function geoAdmin() {  };

geoAdmin.prototype = {
    init: function() {
        this.admin = $("AdminScreens");
        //this.activityLink = $("ActivityLink");
        //this.activityLink.onclick = function() { admin.selectLink(this.id); admin.load(ACTIVITY); return false; };

        if ($("GoLiveLink")) {
            this.goliveLink = $("GoLiveLink");
            this.goliveLink.onclick = function() { admin.selectLink("SettingsLink"); admin.showUpgrades(); return false; };
        }

        this.publishLink = $("PublishLink");
        this.libraryLink = $("LibraryLink");
        this.pagesLink = $("PagesLink");

        if ($("SettingsLink"))
            this.settingsLink = $("SettingsLink");
        if ($("DesignLink"))
            this.designLink = $("DesignLink");
        if ($("AccountLink"))
            this.accountLink = $("AccountLink");
        this.editLink = $("EditModeLink");
        this.layoutLink = $("ChangeLayoutLink");
        this.pagesLink = $("PagesLink");

    },
    screens: [],
    editMode: false,
    load: function(config, parameters) {
        if (this.screens[config.id]) {
            var current = this.screens[config.id];
            if (current.path == config.path && current.parameters == parameters) {
                if (current.visible) {
                    current.close();
                    this.selectLink("none");
                } else {
                    this.admin.style.display = "block";
                    current.setFocus();
                }
                return;
            } else {
                current.close();
            }
        }
        if (this.editMode)
            this.viewSite();
        window.scrollTo(0, 0);
        this.admin.style.display = "block";
        lara.close(MEDIA_LIBRARY);
        this.screens[config.id] = new geoAdminScreen(config, parameters);
    },
    closeAll: function() {
        for (var i in this.screens) {
            if (this.screens[i])
                this.screens[i].close();
        }
        this.selectLink("none");
    },
    close: function(config) {
        if (this.screens[config.id]) {
            this.screens[config.id].close();
            this.selectLink("none");
        }
    },
    selectLink: function(adminId) {
        if (!$("PublishLink"))
            return;

        //$("ActivityLink").className = "aaa aPeople";
        $("PublishLink").className = "aaa aAdd";
        $("LibraryLink").className = "aaa aFile";
        $("PagesLink").className = "aaa aDrop";

        if ($("SettingsLink"))
            $("SettingsLink").className = "aaa aSearch";

        if ($("AccountLink"))
            $("AccountLink").className = "aaa aPeople";

        if ($("MarketingLink"))
            $("MarketingLink").className = "aaa aPeople";

        //if (adminId == "ActivityLink")
        //    $("ActivityLink").className = "aaas aPeople";
        //else {
        if ($(adminId))
            $(adminId).className = "aaas aDrop";

        if (adminId == "PublishLink")
            $("PublishLink").className = "aaas aAdd";

        if (adminId == "SettingsLink")
            $("SettingsLink").className = "aaas aSearch";

        if (adminId == "AccountLink")
            $("AccountLink").className = "aaas aPeople";

        if (adminId == "MarketingLink")
            $("MarketingLink").className = "aaas aPeople";
            
        if (adminId == "LibraryLink")
            $("LibraryLink").className = "aaas aFile";

        //}

    },
    disableAdmin: function(disabled) {
        //$("ActivityLink").disabled = disabled;
        $("PublishLink").disabled = disabled;
        $("LibraryLink").disabled = disabled;
        $("PagesLink").disabled = disabled;
        $("EditModeLink").disabled = disabled;
        $("ChangeLayoutLink").disabled = disabled;
        //$("AddStuffLink").disabled = disabled;

        if ($("SettingsLink"))
            $("SettingsLink").disabled = disabled;
        if ($("DesignLink"))
            $("DesignLink").disabled = disabled;
        if ($("GoLiveLink"))
            $("GoLiveLink").disabled = disabled;
    },
    showEdit: function(display) {
        var editors = $getByClass("FeatureEditBar", "div");
        for (i = 0; i < editors.length; i++) {
            if (display == true) {
                editors[i].style.display = "";
            }
            else
                editors[i].style.display = "none";
        }
    },
    loadDesign: function() {
        admin.disableAdmin(true);

        admin.showEdit(false);
        admin.closeAll();

        $("AdminToolbar").style.display = "none";

        design.panel = $("AdminPanel");
        design.load();
    },
    viewSite: function() {
        if (this.editMode) {
            this.showEdit(false);
            editImg.exitImageEdit();
            this.editMode = false;
            $("EditModeLink").innerHTML = " <span>Edit Page »</span> ";
            $("EditModeLink").title = "Add or change the text, images and other features on the current page.";
            $("ChangeLayoutLink").style.display = "none";
            //$("AddStuffLink").style.display = "none";
            $("PageDetail").style.display = "none";
            //$("ActivityLink").style.display = "";
            $("PagesLink").style.display = "";
            $("LibraryLink").style.display = "";
            if ($("DesignLink"))
                $("DesignLink").style.display = "";
            if ($("SettingsLink"))
                $("SettingsLink").style.display = "";
            if ($("AccountLink"))
                $("AccountLink").style.display = "";
            if ($("MarketingLink"))
                $("MarketingLink").style.display = "";
            $("PublishLink").style.display = "";
            
        }
        else {
            this.closeAll();
            this.showEdit(true);
            this.selectLink("none");
            this.editMode = true;
            $("EditModeLink").innerHTML = " <span>« View Page</span> ";
            $("EditModeLink").title = "Exit edit page mode and view your site.";
            $("ChangeLayoutLink").style.display = "";
            //$("AddStuffLink").style.display = "";
            $("PageDetail").style.display = "";
            //$("ActivityLink").style.display = "none";
            $("PagesLink").style.display = "none";
            $("LibraryLink").style.display = "none";
            if ($("DesignLink"))
                $("DesignLink").style.display = "none";
            if ($("SettingsLink"))
                $("SettingsLink").style.display = "none";
            if ($("AccountLink"))
                $("AccountLink").style.display = "none";
            if ($("MarketingLink"))
                $("MarketingLink").style.display = "none";
            $("PublishLink").style.display = "none";
        }
    },
    loadLayoutEditor: function(addMode) {
        editImg.exitImageEdit();

        siteLayout.header = $("HeaderContent");
        siteLayout.footer = $("FooterContent");
        siteLayout.page = $("PageContent");
        siteLayout.path = $("CurrentPath").value;
        siteLayout.toolbar = $("AdminToolbar");
        siteLayout.info = $("PageDetail").innerHTML;
        siteLayout.wrapper = $("Wrapper");

        siteLayout.closed = function() { admin.exitLayoutEditor(); };

        //$("AddStuffLink").style.display = "none";
        $("ChangeLayoutLink").style.display = "none";
        $("PageDetail").style.display = "none";
        $("EditModeLink").style.display = "none";
        if ($("LaraLogo"))
            $("LaraLogo").style.display = "none";
        if ($("GoLiveLink"))
            $("GoLiveLink").style.display = "none";
        if ($("AccountLink"))
            $("AccountLink").style.display = "none";
        if ($("MarketingLink"))
            $("MarketingLink").style.display = "none";
            
        //Disable menu drop downs, explore etc. 
        ui.disable();

        siteLayout.load(addMode);
    },
    exitLayoutEditor: function() {
        //$("AddStuffLink").style.display = "";  
        $("ChangeLayoutLink").style.display = "";
        $("EditModeLink").style.display = "";
        $("PageDetail").style.display = "";
        if ($("LaraLogo"))
            $("LaraLogo").style.display = "";
        //Re-enable menu drop downs, explore etc.
        ui.init();

    },
    deleteFeature: function(id, locator) {
        if (confirm("Are you sure you want to remove this feature from your page?")) {
            var data = new dataObject();
            data.add("FeatureId", id);
            data.add("Locator", locator);

            lara.request(FEATURE_OPTIONS.path + ":Delete", data, function(result) { admin.processDeleteFeature(result); });
            $(id).parentNode.removeChild($(id));
        }
    },
    processDeleteFeature: function(result) {
        if (!result.success)
            alert("Error: " + result.error);
    },
    editFeature: function(id, locator, editfeaturepath, type) {
        //Close any open image edit windows
        editImg.exitImageEdit();
        if (type == "Image") {

            //Load image controls
            editImg.featureId = id;
            editImg.featurebar = $("FBar" + id);
            editImg.locator = locator;
            editImg.featureOptionsPath = editfeaturepath;
            editImg.pageFeature = $(id);

            if ($("Img" + id))
                editImg.img = $("Img" + id);

            editImg.showTools();

            if ($("ImgSrc" + id))
                editImg.orig = $("ImgSrc" + id).value;
            else
                lara.loadWindow(FEATURE_OPTIONS, editfeaturepath);
        }
        else
            lara.loadWindow(FEATURE_OPTIONS, editfeaturepath);

    },
    cDesign: function() {
        lara.loadWindow(CDESIGN);
    },
    showUpgrades: function() {
        this.close(SITE_SETTINGS);
        admin.load(SITE_SETTINGS);
        this.screens[SITE_SETTINGS.id].onload = function() { ui.showTab("SiteSettings", 4); };
    },
    hide: function() {
        $("AdminPanel").style.display = "none";
        document.body.style.paddingTop = "0";
        editImg.hide();
    },
    show: function() {
        $("AdminPanel").style.display = "";
        document.body.style.paddingTop = "29px";
        editImg.show();
    }
};
var admin = new geoAdmin();

//GEO ADMIN
function geoAdminScreen(config, parameters)
{
    this.id = config.id;
    this.path = config.path;
    this.parameters = parameters;
    
    lara.indicateOn();
                    
    this.screen = $new("div");
    this.screen.id = this.id;
    this.screen.className = "AdmScreen";
    this.screen.style.display = "none";

    var self = this;

    var path = this.path;
    if (parameters)
        path += parameters;
    lara.request(path, null, function(result) { self.load(result); }, true);

};
geoAdminScreen.prototype = {
    load: function(result) {

        if (result.error) {
            this.screen.innerHTML = result.error;
        }
        else {
            this.screen.innerHTML = result;
        }

        admin.admin.appendChild(this.screen);
        this.setFocus();

        //Load javascript for the screen
        lara.include(BASE_URL + this.path.replace("/_ui/", "/_ui/jsw/") + ".js");
        
        if (this.onload) {
            this.onload.call();
            this.onload = null;
        }

        lara.indicateOff();

    },
    setFocus: function() {
        for (var i in admin.screens) {
            var scr = admin.screens[i];
            if (scr != null) {
                if (scr.id == this.id) {
                    scr.screen.style.display = "block";
                    scr.visible = true;
                    if (scr.onfocus)
                        scr.onfocus.call();
                }
                else {
                    scr.screen.style.display = "none";
                    scr.visible = false;
                }
            }
        }
    },
    hide: function() {
        this.screen.style.display = "none";
    },
    close: function() {
        //Check for registered event handler
        if (this.onclose) { this.onclose.call(); }

        lara.exclude(BASE_URL + this.path.replace("/_ui/", "/_ui/jsw/") + ".js");

        lara.adScreens.removeChild(this.screen);
        if (lara.adScreens.getElementsByTagName("div").length == 0)
            lara.adScreens.style.display = "none";

        window.scrollTo(0, 0);
        admin.screens[this.id] = null;
    },
    refresh: function() {
        lara.indicateOn();
        var self = this;
        lara.request(this.path, null, function(result) { self.processRefresh(result); }, true);
    },
    processRefresh: function(result) {
        this.screen.innerHTML = result;

        if (this.onload) {
            this.onload.call();
            this.onload = null;
        }

        lara.indicateOff();
    }
};
var editors = [];
var editModeStyleSheet = window.location.protocol + '//' + window.location.host + "/_ui/css/speck.css";

var features = ["html", "bold", "italic", "underline", "justifyleft", "justifycenter", "justifyright", "insertorderedlist", "insertunorderedlist", "link", "unlink", "formatblock", "fontname", "fontsize", "forecolor", "removeformat", "addfile"];
var featuretext = ["Toggle HTML View", "Bold", "Italic", "Underline", "Align Left", "Align Center", "Align Right", "Insert Ordered List", "Insert Unordered List", "Create Link", "Unlink", "Choose Format", "Choose Font", "Choose Font Size", "Choose Font Color", "Remove Formatting", "Add an image or file from the library"];

var colors = ["006600", "666600", "ccff66", "669933", "ffffff", "eeeeee", "999999", "333333", "000000", "666699", "000033", "000066", "ccffff", "ffff33", "ffcc00", "ffff99", "990000", "330033", "cc3399", "ffcccc", "ffffcc", "996633", "663300", "330000"];

var blockOptions = [];
blockOptions.push("<h1>", "Heading 1");
blockOptions.push("<h2>", "Heading 2");
blockOptions.push("<h3>", "Heading 3");
blockOptions.push("<h4>", "Heading 4");
blockOptions.push("<h5>", "Heading 5");
blockOptions.push("<h6>", "Heading 6");
blockOptions.push("<p>", "Normal");

var fontOptions = [];
fontOptions.push("Verdana", "Verdana");
fontOptions.push("Arial", "Arial");
fontOptions.push("Georgia", "Georgia");
fontOptions.push("Garamond", "Garamond");
fontOptions.push("Trebuchet", "Trebuchet");
fontOptions.push("Courier New", "Courier");
fontOptions.push("Times New Roman", "Times");

var fontSizes = [];
fontSizes.push("1", "Small");
fontSizes.push("3", "Medium");
fontSizes.push("5", "Large");
fontSizes.push("7", "Largest");

function closeEditor()
{
    for(var i in editors)
    {
        try {
            editors[i].IF.contentWindow.document.designMode = "off";
        } catch (err) {}
    }
};
function loadEditor(callback)
{    
    TAs = document.getElementsByTagName('textarea');
    var found = false;
    for(i=0;i<TAs.length;i++)
    {
		var TA = TAs[i];
		if (TA.className == "iEdit") {

		    new speck(TA.id, callback);
		    found = true;
		}
    }   
    if (!found)
    {
        if (callback)
            callback.call();
    }
	return true;
};

function speck(taId, callback)
{
    this.theId = taId;
    editors[taId] = this;
    
	this.TA = $(taId);
	
	if (callback)
	    this.loaded = callback;
	
	if (this.TA.style.width.indexOf("%") >= 0)
	{
        if (document.addEventListener)
            this.width = this.TA.clientWidth;
        else
            this.width = (this.TA.clientWidth + 19); 
     }
     else{ this.width = parseInt(this.TA.style.width); }

    //this.height = this.TA.clientHeight;
    this.height = parseInt(this.TA.style.height);
    this.TA.style.display = "none";
    
	this.Container = document.createElement("div");
	this.Container.id = taId + 'container';	
	
	this.TB = document.createElement("div");
	this.TB.id = taId + "toolbar";
	this.TB.className = "speckToolbar";
    this.TB.style.width = this.width + 'px';
    this.TB.style.height = "32px";

	
	for(var i=0;i<features.length;i++)
	{
	    this.addEditFeature(features[i], featuretext[i]);
	}	
	
    this.Status = document.createElement("div");
      
    this.IF = document.createElement("div");
    
    this.TA.style.height = (this.height-32) + 'px';    
    this.TA.parentNode.replaceChild(this.Container, this.TA);
    this.Container.appendChild(this.TB);
    this.Container.appendChild(this.HBar);
    this.Container.appendChild(this.FBar);
    this.Container.appendChild(this.SBar);
    this.Container.appendChild(this.CBar);
    this.Container.appendChild(this.LBar);    
	this.Container.appendChild(this.IF);    
	this.Container.appendChild(this.TA);    
	this.Container.appendChild(this.Status);   
    
    this.initEdit();
    
//    var self = this;
//	setTimeout(function() { self.initEdit(); }, 1);
//	this.initEdit(this.TA.value);
	

};
speck.prototype.initEdit = function(content) {
    this.Container.removeChild(this.IF);
    this.Container.removeChild(this.Status);

    //Create the iframe
    this.IF = document.createElement("iframe");
    this.IF.id = this.TA.id + "iframe";
    this.IF.className = "speckFrame";
    this.IF.frameBorder = "0";
    this.IF.style.width = (this.width - 2) + 'px';
    this.IF.style.height = (this.height - 32) + 'px';
    this.Container.appendChild(this.IF);

    content = this.protectContent(this.TA.value);
    content = content.replace(/safetextarea/g, "textarea");

    var styleSheet = "";
    if ($("ThemeStyle"))
        var styleSheet = "<link id='ThemeStyle' href='" + $("ThemeStyle").href + "' type='text/css' rel='stylesheet' />";
        
    this.IF.contentWindow.document.open();
    this.IF.contentWindow.document.write("<html><head>" + styleSheet + "</head><body style='background:#fff url();color:#000;'>" + content + "</body></html>");
    this.IF.contentWindow.document.close();

    this.enterDesignMode();

    return true;
};
speck.prototype.enterDesignMode = function()
{
    var self = this;
    
    if (!this.IF.contentWindow.document.body) //Firefox needs a little time for this.
    {
	    setTimeout(function() { self.enterDesignMode(); }, 1);
	    return;
	}
	this.IF.contentWindow.document.designMode = "on";
    
    //add paste detection
	if (typeof document.addEventListener == "function")
	    this.IF.contentWindow.document.addEventListener("keydown", function(e){self.detectPaste(e); return true;}, false);
	else
	    this.IF.contentWindow.document.onkeydown = function(e){ self.detectPaste(e); return true;};
	 
	this.Status = document.createElement("div");
	this.Status.style.height = "16px";
	this.Status.style.fontSize = "8pt";
	this.Container.appendChild(this.Status);
	
	this.wysiwyg = true;

    if (this.loaded)
        this.loaded.call();
};

speck.prototype.addEditFeature = function(action, text)
{
    switch (action)
    {
        case "formatblock": 
	        this.HBar = document.createElement("div");
	        this.HBar.id = this.theId + "Hbar";       
            this.addBar(this.HBar, "formatblock", blockOptions, text);
            break;
        case "fontname": 
	        this.FBar = document.createElement("div");
	        this.FBar.id = this.theId + "Fbar";        
            this.addBar(this.FBar, "fontname", fontOptions, text);
        
            //this.addSelect("fontname", fontOptions);
            break;
        case "fontsize": 
	        this.SBar = document.createElement("div");
	        this.SBar.id = this.theId + "Sbar";        
            this.addBar(this.SBar, "fontsize", fontSizes, text);
            break;
        case "forecolor": 
            this.addColor("forecolor", colors, text);
            break;            
        case "link":
            this.addLinkBar("link", text);    
            break;
        case "addfile":
            this.TB.appendChild(this.getButton(action, text));        
            break;        
        default:
            this.TB.appendChild(this.getButton(action, text));      
            break;
    }
};
speck.prototype.getButton = function(action, text)
{
    var button = document.createElement("input");
    button.type = "button";
    button.id = action + "Button";
    button.title = text;
    button.className = "speckButton";
    //button.title = action;
    button.editor = this.theId;
    button.action = action;
    button.onclick = execToolbarCommand;  
    return button;
};
speck.prototype.addColor = function(action, options, text)
{
	var button = document.createElement("input");
    button.type = "button";
    button.id = action + "Button";
    button.title = text;
    button.className = "speckButton";
    //button.title = action;    
    button.editor = this.theId;
    
    var self = this;
    //button.onclick = function() { self.selection = self.getSelectionRange(); showSelect(this); };
    button.onclick = function() { showSelect(this); };
    
	var bar = document.createElement("div");
	bar.id = action + "Select";
	bar.className = "speckColorBar";
    bar.style.width = this.width + 'px';
    bar.style.display = 'none'; 	
	for (var i=0;i<options.length;i++)
	{
		var option = document.createElement("input");
		//option.value = options[i];
		option.val = options[i];
		option.type = "button";
		option.style.backgroundColor = "#" + option.val;
		option.action = action;
		option.editor = this.theId;
		option.className = "speckColor";
    	option.onclick = execToolbarCommand;
		
		bar.appendChild(option);
	}
	this.CBar = bar;
    button.selectMenuId = bar.id;
    this.TB.appendChild(button);
	return true;
};
speck.prototype.addLinkBar = function(action, text)
{
	var button = document.createElement("input");
    button.type = "button";
    button.id = action + "Button";
    button.title = text;
    button.className = "speckButton";
    button.editor = this.theId;
    
    var self = this;
    //button.onclick = function() { self.selection = self.getSelectionRange(); showSelect(this); };
    button.onclick = function() { showSelect(this); };
    
	var bar = document.createElement("div");
	bar.id = action + "linkbar";
	bar.className = "speckLinkbar";
    bar.style.width = this.width + 'px';
    bar.style.display = 'none'; 	

	this.linkUrl = document.createElement("input");
	this.linkUrl.id = this.theId + "link";
    this.linkUrl.style.width = (this.width - 60) + 'px';
    this.linkUrl.value = "http://";
        
    var link = document.createElement("input");
    link.type = "button";
    link.id = "linkingButton";
    link.value = "link";    
    link.className = "linkbarButton";
    link.editor = this.theId;
    link.action = "createlink";
    link.onclick = execToolbarCommand;
    bar.appendChild(this.linkUrl);
    bar.appendChild(link);

	this.LBar = bar;
    button.selectMenuId = bar.id;
    this.TB.appendChild(button);
	return true;
};
speck.prototype.addBar = function(bar, action, options, text)
{
	var button = document.createElement("input");
    button.type = "button";
    button.id = action + "Button";
    button.title = text;
    button.className = "speckButton";
    //button.title = action;    
    button.editor = this.theId;
    
    var self = this;
    //button.onclick = function() { self.selection = self.getSelectionRange(); showSelect(this); };
    button.onclick = function() { showSelect(this); };
    
	bar.className = "speckBar";
    bar.style.width = this.width + 'px';
    bar.style.display = 'none'; 
    
  	for (var i=0;i<options.length;i+=2)
	{
		var option = document.createElement("input");
		//var text = document.createTextNode(options[i + 1]);
		option.val = options[i];
		option.value = options[i + 1];
		option.type = "button";
		option.action = action;
		option.editor = this.theId;
		option.className = "speckOption";
    	option.onclick = execToolbarCommand;
		//option.appendChild(text);
		
		bar.appendChild(option);
	}
    button.selectMenuId = bar.id;
    this.TB.appendChild(button);
	return true;
};

function showSelect(selector)
{
       
    var selectMenu = $(selector.selectMenuId);
    theSpeck = editors[selector.editor];
    
    if (selectMenu.style.display == "block")
    {
        theSpeck.hideSelects();
        return;
    }
    else
        theSpeck.hideSelects();
        
    theSpeck.IF.style.height = (theSpeck.height-63) + 'px';
    theSpeck.TA.style.height = (theSpeck.height-63) + 'px';
    //selectMenu.style.left = pos.x + "px";
    //selectMenu.style.top =  (pos.y + selector.offsetHeight) + "px";
    selectMenu.style.display = "block";

    if (selector.selectMenuId.indexOf("link") >= 0) {
        var range = theSpeck.getSelection();
        if (range.startContainer)
            if (range.startContainer.parentNode.href)
            theSpeck.linkUrl.value = range.startContainer.parentNode.getAttribute("href");
    }
};

speck.prototype.getSelection = function() {
    var userSelection;
    if (this.IF.contentWindow.getSelection) {
        userSelection = this.IF.contentWindow.getSelection();
    }
    else if (document.selection) { // should come last; Opera!
        userSelection = this.IF.document.selection.createRange();
    }
    if (document.createRange)
        return getRangeObject(userSelection);
    else
        return userSelection;
};
function getRangeObject(selectionObject) {
    if (selectionObject.getRangeAt)
        return selectionObject.getRangeAt(0);
    else { // Safari!
        var range = document.createRange();
        range.setStart(selectionObject.anchorNode, selectionObject.anchorOffset);
        range.setEnd(selectionObject.focusNode, selectionObject.focusOffset);
        return range;
    }
};
speck.prototype.hideSelects = function()
{
    var buttons = this.TB.childNodes;
    for(var i=0;i<buttons.length;i++)
    {
        var button = buttons[i];
        if (button.selectMenuId)
        {
            var selectMenu = $(button.selectMenuId);
            selectMenu.style.display = "none";
        }
    }
    this.LBar.style.display = "none";
    this.IF.style.height = (theSpeck.height-32) + 'px';
    this.TA.style.height = (theSpeck.height-32) + 'px';
};
speck.prototype.addLinkbar = function()
{
	this.LBar = document.createElement("div");
	this.LBar.id = this.theId + "linkbar";
	this.LBar.className = "speckLinkbar";
    this.LBar.style.width = this.width-10 + 'px';
    this.LBar.style.display = 'none'; 
	
	this.linkUrl = document.createElement("input");
	this.linkUrl.id = this.theId + "link";
    this.linkUrl.style.width = (this.width - 60) + 'px';
    this.linkUrl.value = "http://";
        
    var link = document.createElement("input");
    link.type = "button";
    link.id = "linkingButton";
    link.value = "link";    
    link.className = "linkbarButton";
    link.editor = this.theId;
    link.action = "createlink";
    link.onclick = execToolbarCommand;
    this.LBar.appendChild(this.linkUrl);
    this.LBar.appendChild(link);
};

//speck.prototype.getSelection = function() {

//    var userSelection;
//    if (window.getSelection) {
//        userSelection = window.getSelection();
//    }
//    else if (document.selection) { // should come last; Opera!
//        userSelection = document.selection.createRange();
//    }
//    var selectedText = userSelection;
//    if (userSelection.text)
//        selectedText = userSelection.text;

//    alert(selectedText);
//}

speck.prototype.toggleLinkbar = function() {

    if (this.LBar.style.display == 'none') {

        this.getSelection();

        this.LBar.style.display = 'block';
        this.IF.style.height = (this.height - 64) + "px";
        //this.selection = this.getSelectionRange(); 
    }
    else {
        this.LBar.style.display = 'none';
        this.IF.style.height = (this.height - 32) + "px";
    }
};
//speck.prototype.getSelectionRange = function()
//{
//    var userSelection;
//    if (window.getSelection) {
//	    userSelection = this.IF.contentWindow.getSelection();
//        try
//        {
//	        userSelection = getRangeObject(userSelection);    
//	    }catch (err) {}
//    }
//    else if (document.selection) { // should come last; Opera!
//	    userSelection = this.IF.contentWindow.document.selection.createRange();
//    }
//    return userSelection;    
//}

//function getRangeObject(selectionObject) {
//	if (selectionObject.getRangeAt)
//		return selectionObject.getRangeAt(0);
//	else { // Safari!
//		var range = document.createRange();
//		range.setStart(selectionObject.anchorNode,selectionObject.anchorOffset);
//		range.setEnd(selectionObject.focusNode,selectionObject.focusOffset);
//		return range;
//	}
//}

function execToolbarCommand()
{
    theSpeck = editors[this.editor];
    
//    if (theSpeck.wysiwyg && theSpeck.selection)
//    {
//        if (theSpeck.selection.select) //reselect selection in IE
//        {
//            if (theSpeck.selection != null)
//                theSpeck.selection.select();
//        }
//        
//    }
    
	switch (this.action)
	{
		case "createlink":
		    if (theSpeck.linkUrl.value != "")
		    { 
                theSpeck.IF.contentWindow.document.execCommand(this.action, false, theSpeck.linkUrl.value);
                theSpeck.toggleLinkbar();                
            }
            break;
		case "formatblock":
		case "fontsize":
		case "forecolor":
		case "fontname":
		    theSpeck.IF.contentWindow.document.execCommand(this.action, false, this.val);	
//		    if (theSpeck.selection != null)
//		        if (theSpeck.selection.select)
//		            theSpeck.selection.select();	
            break;
        case "addfile":
            lara.loadWindow(MEDIA_LIBRARY, "?mode=select&selectaction=AddSpeck&target=" + theSpeck.theId);
            break;
        case "link":
            theSpeck.toggleLinkbar();
            break;
        case "html":
            theSpeck.toggleMode();
            break;            
		default:
		    theSpeck.IF.contentWindow.document.execCommand(this.action, false, null);
            break;
    }
    theSpeck.selection = null;
    //theSpeck.hideSelects();
    
    if (this.parentNode.className == "editorselect")
    {
        this.parentNode.style.display = "none";
        return false;
    }
        
    theSpeck.setFocus();    
};

speck.prototype.StatusText = function(Text)
{
	this.Status.innerHTML = Text;
};
speck.prototype.protectContent = function(Html)
{
    this.scripts = new Array();
    var self = this;
    
    //put scripts into inputs
    Html = Html.replace(/<script((.|\n|\r)*?)<\/script>/g, function(match){ 
                                                            scriptId = self.scripts.length; 
                                                            self.scripts.push(match);
                                                            return "<input type='text' scriptId='" + scriptId + "' class='scriptProtect' value=\"Embedded Script\"/>"; });

    Html = Html.replace(/<object((.|\n|\r)*?)<\/object>/g, function(match){ 
                                                            scriptId = self.scripts.length; 
                                                            self.scripts.push(match);
                                                            return "<input type='text' scriptId='" + scriptId + "' class='scriptProtect' value=\"Embedded Object\"/>"; });

	//IE STYLE ISSUE duplicate style properties with property called iestyle
	Html = Html.replace(/(style|STYLE|Style)='.+?'/g, function(match){ return match + " ie" + match; });
	Html = Html.replace(/(style|STYLE|Style)=".+?"/g, function(match){ return match + " ie" + match; });
	
	return Html;
};

// Check for pasted content 
speck.prototype.detectPaste = function(e)
{
	if (!e) var e = this.IF.contentWindow.event;
	
	if (e.ctrlKey && e.keyCode == 86 && this.wysiwyg)
	{
		var self = this;
		
		//this.updateEditor();
		this.pasteCache = this.IF.contentWindow.document.getElementsByTagName("body")[0].innerHTML;

        this.StatusText("Processing pasted information.  Please wait...");
        
		// Because Mozilla can't access the clipboard directly, must rely on timeout to check pasted differences in main content
		setTimeout(function(){self.cleanPaste(); return true;}, 10);

	}
	return true;
};
// Clean pasted content
speck.prototype.cleanPaste = function()
{
	var matchedHead = "";
	var matchedTail = "";
	var newContent = this.IF.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
	var newContentStart = 0;
	var newContentFinish = 0;
	var newSnippet = "";
    
	/* Find start of both strings that matches */
	for (newContentStart = 0; newContent.charAt(newContentStart) == this.pasteCache.charAt(newContentStart); newContentStart++)
	{
		matchedHead += this.pasteCache.charAt(newContentStart);
	}
	/* If newContentStart is inside a HTML tag, move to opening brace of tag */
	for (var i = newContentStart; i >= 0; i--)
	{
		if (this.pasteCache.charAt(i) == "<")
		{
			newContentStart = i;
			matchedHead = this.pasteCache.substring(0, newContentStart);
			
			break;
		}
		else if(this.pasteCache.charAt(i) == ">")
		{
			break;
		}
	}
	newContent = newContent.reverse();
	this.pasteCache = this.pasteCache.reverse();
	
	/* Find end of both strings that matches */

	for (newContentFinish = 0; newContent.charAt(newContentFinish) == this.pasteCache.charAt(newContentFinish); newContentFinish++)
	{
		matchedTail += this.pasteCache.charAt(newContentFinish);
	}
	
	/* If newContentFinish is inside a HTML tag, move to closing brace of tag */
	for (var i = newContentFinish; i >= 0; i--)
	{
		if (this.pasteCache.charAt(i) == ">")
		{
			newContentFinish = i;
			matchedTail = this.pasteCache.substring(0, newContentFinish);
			
			break;
		}
		else if(this.pasteCache.charAt(i) == "<")
		{
			break;
		}
	}
	matchedTail = matchedTail.reverse();

	/* If there's no difference in pasted content */
	if (newContentStart == newContent.length - newContentFinish)
	{
	    this.StatusText("");
		return;
	}
	newContent = newContent.reverse();
	newSnippet = newContent.substring(newContentStart, newContent.length - newContentFinish);
    
    var SnipCache = newSnippet;
    
	newSnippet = newSnippet.replace(/<!--(\w|\W)+?-->/g,"");	
	newSnippet = newSnippet.replace(/<title>(\w|\W)+?<\/title>/g,"");
	newSnippet = newSnippet.replace(/\s?(class|type|style)=\w+/g,"");
	newSnippet = newSnippet.replace(/\s+style='[^']+'/g,"");
	newSnippet = newSnippet.replace(/(<[^>]+>)+&nbsp;(<\/\w+>)+/g,"");
	newSnippet = newSnippet.replace(/\s+v:\w+=""[^""]+""/g,"");
	newSnippet = newSnippet.replace(/(\n\r){2,}/g,"");
	newSnippet = newSnippet.replace(/<\/?xml[^>]*>/g, "");
	newSnippet = newSnippet.replace(/<(\/?st\d|\/?span|\/?SPAN|\/?font|\/?o:|\/?w:|\/?meta|\/?link|\/?div|\/?head|\/?body)(.*?)>/g, "");
	newSnippet = newSnippet.replace(/style="(.*?)"/g, "");
	newSnippet = newSnippet.replace(/style='(.*?)'/g, "");

    if (newSnippet != SnipCache)  //only refresh the editor if something happened.
    {
	    this.IF.contentWindow.document.getElementsByTagName("body")[0].innerHTML = matchedHead + newSnippet + matchedTail;
	    this.updateEditor();
	    this.initEdit(this.TA.value);
    }	    
    this.StatusText("");
  	return;

};

speck.prototype.setFocus = function()
{
	if (this.wysiwyg == true)
	{
		this.IF.contentWindow.focus();
	}
	else
	{
		this.TA.focus();
	}
};
speck.prototype.updateEditor = function()
{
    if (this.wysiwyg)
    {
        var theBody = this.IF.contentWindow.document.body.cloneNode(true);
        var theHTML = innerXML(theBody);

        inputs = theBody.getElementsByTagName('INPUT');
        for(var i=0;i<inputs.length;i++)
        {
            if (inputs[i].className == "scriptProtect")
            {
            	theHTML = theHTML.replace(/<input((.|\n|\r)+?)class="scriptProtect"((.|\n|\r)+?)\/>/, this.scripts[parseInt(inputs[i].getAttribute("scriptId"))]);
            }
        }
        this.TA.value = theHTML;
    }
};

speck.prototype.toggleMode = function()
{
    this.hideSelects();
    if (this.wysiwyg)
    {
        this.updateEditor();
        this.TA.style.display = 'block';
        this.IF.style.display = 'none';
        this.wysiwyg = false;
    }
    else
    {
        this.TA.style.display = 'none';
    	this.initEdit(this.TA.value);
        //this.IF.style.display = 'block';
        this.wysiwyg = true;
    }
};
speck.prototype.html = function()
{
    this.updateEditor();
    return this.TA.value;
};


//Functions for maintaining XML instead of HTML
if(!window.Node || !Node.ELEMENT_NODE){
    Node = {ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5,  ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10, DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12};
};

//Returns the innerXML of an HTML DOM node
function innerXML(oNode)
{
    var s = "";
    
    var nodes = oNode.childNodes;
    for(var i=0; i < nodes.length; i++)
    {
        var node = nodes[i];
        var nodeType = node.nodeType;
        if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE || nodeType == Node.DOCUMENT_FRAGMENT_NODE)
        {
            s += xml(node, "");
        } else
        {            
            //if (node.data.replace(/\n/g, "").replace(/\s/g, "") != "")            
                s += node.data; //.replace(/^\s+|\s+$/g,"").replace(/^\n+|\n+$/g,"");
        } 
    }
    return s;
};
//Returns outerXML of the node.
function xml(oNode, indent)
{
    var s = "";
            
    var nodes = oNode.childNodes;
    
    if (nodes.length == 0 && (oNode.nodeName=="INPUT" || oNode.nodeName=="IMG" || oNode.nodeName=="HR" || oNode.nodeName=="BR" || oNode.nodeName=="FEATURE" ))
    {
        if (!oNode.getAttribute("_moz_editor_bogus_node")){
            s += indent + "<" + oNode.nodeName.toLowerCase() + getAttributes(oNode) + " />";
        }
    }
    else
    {  
        if (isEmptyNode(oNode))
            return s;
        
        var tagName = oNode.nodeName.toLowerCase();
//        if (tagName == "font")
//            tagName = "span";
            
        s += indent + "<" + tagName + getAttributes(oNode) + ">";
        for(var i=0; i < nodes.length; i++)
        {
            var node = nodes[i];
            var nodeType = node.nodeType;
            
            if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE || nodeType == Node.DOCUMENT_FRAGMENT_NODE)
            {
                s += xml(node, indent + "");
            } else
            {            
                //if (node.data.replace(/\n/g, "").replace(/\s/g, "") != "")            
                    s += indent + node.data; //.replace(/^\s+|\s+$/g,"").replace(/^\n+|\n+$/g,"");
            }                  
        }
        s += indent + "</" + tagName + ">";
    }
    return s;
};
function getAttributes(oNode)
{
    var s = "";
    var atts = oNode.attributes;
    for(var i=0; i < atts.length; i++)
    {
        var att = atts[i];
        if (validAttribute(att, oNode.nodeName))
        {
            //att = convertAtt(att);

            //style attributes are called iestyle to protect from IE changes
            if (att.nodeName.toLowerCase() == "iestyle")
            {
                if (document.all) //ie check
                    s += " style=\"" + att.nodeValue + "\" ";
            } else {
                var val = att.nodeValue;
                if (att.nodeName == "href")
                    val = val.replace("about:/", "/");
                    
                s += " " + att.nodeName + "=\"" + val + "\" ";
            }
            
        }
    }
    return s;
};
function validAttribute(att, tag)
{
    if (att.nodeName == "start") 
        return false;    
    //IE adds extra attributes - remove them.
    if (att.nodeValue == null || att.nodeValue == '' || att.nodeValue == "inherit" || att.nodeValue == "_moz")
    {
        return false;
    }
    if (att.nodeName == "colSpan" || att.nodeName == "rowSpan")
    {
        if (att.nodeValue == "1") { return false; }
    }
    if (att.nodeName == "class")
    {
        if (att.nodeValue == "Apple-style-span") { return false; }
    }
    if (tag == "INPUT")
    {
        if (att.nodeName == "height" || att.nodeName == "maxLength" || att.nodeName == "loop")
        {
            return false;
        }
    }
    if (tag == "IMG")
    {
        if (att.nodeName == "start" || att.nodeName == "loop")
        {
            return false;
        }
    }
    return true;
};
function isEmptyNode(oNode)
{
    var nodes = oNode.childNodes;
    for(var i=0; i < nodes.length; i++)
    {
        var node = nodes[i];
        var nodeType = node.nodeType;
        
        if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE || nodeType == Node.DOCUMENT_FRAGMENT_NODE)
        {
            return false;
        } else {
            if  (node.data.replace(/^\s+|\s+$/g,"").replace(/^\n+|\n+$/g,"") != "")
                return false;
        }
    }
    return true;
};
function convertAtt(att)
{
    if (att.nodeName.toLowerCase() == "size")
    {  
        var newAtt = document.createAttribute("style");
        switch(att.nodeValue)
        {
            case "1":
                newAtt.nodeValue = "font-size: 8px;";
                break;
            case "3":
                newAtt.nodeValue = "font-size: 13px;";
                break;
            case "5":
                newAtt.nodeValue = "font-size: 30px;";
                break;
            case "7":
                newAtt.nodeValue = "font-size: 50px;";
                break;
        }
        return newAtt;
    }
    if (att.nodeName.toLowerCase() == "face")
    {  
        var newAtt = document.createAttribute("style");
        newAtt.nodeValue = "font-family:" + att.nodeValue + ";";
        return newAtt;
    }
    if (att.nodeName.toLowerCase() == "color")
    {  
        var newAtt = document.createAttribute("style");
        newAtt.nodeValue = "color:" + att.nodeValue + ";";
        return newAtt;
    }    
    return att;
    
        
};

String.prototype.reverse = function()
{
	var theString = "";
	
	for (var i = this.length - 1; i >= 0; i--)
	{
		theString += this.charAt(i);
	}
	
	return theString;
};//Library
function geoLibrary() { };

geoLibrary.prototype = {
    path: MEDIA_LIBRARY.path,
    init: function () {
        this.itemMenu = $("LibraryItemMenu");
        this.folderMenu = $("LibraryFolderMenu");
        this.itemStatus = $("LibraryItemStatus");
        this.editMenu = $("LibraryEditMenu");

        this.crumb = $("FolderCrumb");
        this.contents = $("FolderContents");

        this.statusIcon = $("SelectedIcon");
        this.statusCount = $("SelectedCount");
        this.statusTitle = $("SelectedTitle");
        this.statusDesc = $("SelectedDescription");
        this.statusURI = $("SelectedURI");

        //Clipboard output
        this.clipdiv = $("LibraryClipBoard");
        this.clipItems = $("LibraryClipBoardItems");
        this.clipboard = [];
        this.multiselect = [];

        //What to do if we choose something
        this.action = $("SelectAction").value;
        if ($("SelectActionTarget").value.length > 0)
            this.target = $($("SelectActionTarget").value);
    },
    newFolder: function () {
        library.indicateOn();
        var data = new dataObject();
        data.add("FolderId", this.folder.id);
        lara.request(this.path + ":NewFolder", data, function (result) { library.processNewFolder(result); });
    },
    processNewFolder: function (result) {
        if (result.success) {

            this.items = result.items;
            this.folder.count = result.count;
            this.renderContents();

            //this.showStatus(this.folder);

            //$("CurrentFolderStatus").innerHTML = result.ItemStatus;        

            this.select(null, result.newId);

        }
        else {
            alert(result.error);
        }
        library.indicateOff();
    },
    indicateOn: function () {
        $("FolderContentsCell").className = "LibraryIndicator";
    },
    indicateOff: function () {
        $("FolderContentsCell").className = "";
    },
    showUpload: function (uploadType) {
        if (uploadType == "Single") {
            $("SingleFileUploadChoice").checked = true;
            $("MultiFileUploadChoice").checked = false;
            $("UploadSingleFileForm").style.display = "block";
            $("UploadMultiFileForm").style.display = "none";
        }
        else {
            $("SingleFileUploadChoice").checked = false;
            $("MultiFileUploadChoice").checked = true;
            $("UploadSingleFileForm").style.display = "none";
            $("UploadMultiFileForm").style.display = "block";
            this.showAddFile();
        }
    },
    showAddFile: function () {
        if ($("UploadMultiFileForm").style.display != "none") {
            var up1 = new SWFObject("/_ui/flash/FlashFileUpload.swf", "single", "600", "310", "7");
            up1.addParam("allowScriptAccess", "sameDomain");
            up1.addParam("wmode", "transparent");
            up1.addParam("FlashVars", "uploadPage=/_ui/libraryupload?FolderId=" + this.folder.id + "&completeFunction=FlashUploadsComplete()");
            up1.addVariable("width", "595");
            up1.addVariable("height", "250");
            up1.addVariable("name", "fileUpload");
            up1.write("uploader");
        }
    },
    browse: function (folderId) {
        library.indicateOn();
        //        if (isRoot) {
        //            curFolderId = $("CurrentRootFolderId").value;
        //            if ($("R" + folderId)) {    
        //                $("R" + curFolderId).className = "RootFolder";
        //                $("R" + folderId).className = "RootFolderSelected";
        //            }
        //            $("CurrentRootFolderId").value = folderId;   
        //        }   
        //this.folder.id = folderId;   
        lara.request(this.path + ":Browse", "FolderId=" + folderId, function (result) { library.processBrowse(result); });
    },
    processBrowse: function (result) {
        if (result.success) {

            this.items = result.items;
            this.renderContents();

            //            $("LibrarySizeStatus").innerHTML = result.librarySize;
            //            if (result.disableLibrary == "true") {
            //                $("LibraryExceeded").innerHTML = result.librarySize;
            //                $("LibraryExceeded").style.display = "block";
            //                $("UploadMultiFileForm").style.display = "none";
            //                $("AddMediaFileButton").disabled = true;
            //            }

            this.folder = result.folder;
            this.folder.count = result.count;
            this.showStatus(this.folder);

            this.crumb.innerHTML = result.folder.crumb;

            this.selected = null;

            //$("SelectedItemId").value = "0";
            this.itemMenu.style.display = "none";
            this.folderMenu.style.display = "block";
            this.itemStatus.style.display = "block";
            this.editMenu.style.display = "none";

            //Reset uploading (so flash gets the correct folder)
            library.showUpload("Single");
        }
        else {
            alert(result.error);
        }
        library.indicateOff();
    },
    renderContents: function () {

        //Clear folder contents
        this.contents.innerHTML = "";

        //Show empty
        if (this.items.length == 0)
            this.contents.innerHTML = "This folder is emtpy.";

        for (var i = 0; i < this.items.length; i++) {
            var item = this.items[i];
            item.div = $new("div");
            item.div.id = "I" + item.id;
            item.div.className = "SmallIcon";
            item.div.onclick = function (e) { library.select(e, this.id.substring(1)); };

            //Table is required for proper vertical align.
            item.div.innerHTML = "<table style=\"width:100%;\" class=\"CleanTable\"><tr><td class='LibraryIconSmall'><img src='" + item.smallicon + "' /></td></tr></table>";
            item.titlediv = $new("div");
            item.titlediv.innerHTML = item.title;
            item.div.appendChild(item.titlediv);

            this.contents.appendChild(item.div);
        }
    },
    choose: function () {
        if (this.selected.filetype == "Folder") {
            this.browse(this.selected.id);
        }
        else {

            var selectedURI = this.selected.uri;
            if ($("SelectActionExtension"))
                selectedURI = selectedURI.substring(0, selectedURI.length - 4) + $("SelectActionExtension").value;

            switch (this.action) {
                case "Eval":
                    eval($("SelectActionTarget").value);
                    lara.hide(MEDIA_LIBRARY);
                    break;
                case "AddIcon":
                    this.actionAddIcon();
                    break;
                case "SetValue":
                    this.target.value = selectedURI;
                    lara.hide(MEDIA_LIBRARY);
                    break;
                case "AddVirPath":
                    this.target.value += this.selected.virpath + ";";
                    lara.hide(MEDIA_LIBRARY);
                    break;
                case "AddSpeck":
                    this.actionAddSpeck();
                    lara.hide(MEDIA_LIBRARY);
                    break;
            }

        }
    },
    getItem: function (id) {
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].id == id)
                return this.items[i];
        }
        return null;
    },
    select: function (e, id) {
        e = (e) ? e : window.event;

        //Find new item
        var item = this.getItem(id);

        //Unselect the old item
        if (this.selected) {
            this.selected.div.className = this.folder.view;
            this.selected.div.onclick = function (e) { library.select(e, this.id.substring(1), this); };
        }

        //Show in status bar
        this.showStatus(item);

        //Show item menu
        this.itemMenu.style.display = "block";
        this.folderMenu.style.display = "none";
        this.editMenu.style.display = "none";

        //Highlight and modify action - another click means choose this item
        item.div.className = this.folder.view + "Selected";
        item.div.onclick = function (e) { library.choose(); };

        //save
        this.selected = item;

        //Prevent click of folder
        if (e)
            e.cancelBubble = true;
    },
    showStatus: function (item) {
        this.statusIcon.src = item.icon;
        this.statusTitle.innerHTML = item.title;
        this.statusDesc.innerHTML = item.description;
        this.statusURI.innerHTML = "<a href=\"" + item.uri + "\" target=\"_blank\">" + item.uri + "</a>";
        if (item.count)
            this.statusCount.innerHTML = item.count;
        else
            this.statusCount.innerHTML = "";
    },
    unSelect: function () {
        //Unselect the old item
        if (this.selected) {
            this.selected.div.className = this.folder.view;
            this.selected.div.onclick = function (e) { library.select(e, this.id.substring(1), this); };
        }
        this.selected = null;

        this.showStatus(this.folder);

        //Show folder menus
        this.itemMenu.style.display = "none";
        this.folderMenu.style.display = "block";
        this.itemStatus.style.display = "block";
        this.editMenu.style.display = "none";

    },
    edit: function () {
        this.editMode = "data";

        $("SelectedTitle").innerHTML = "<input style='width:300px;' class='MediumTextBox' id='TitleEdit' type='text' value='" + this.selected.title + "' />";
        $("SelectedDescription").innerHTML = "<input style='width:300px;' class='MediumTextBox' id='DescriptionEdit'  type='text' value='" + this.selected.description + "' />";

        $("LibraryEditMenu").style.display = "block";
        $("LibraryItemMenu").style.display = "none";
    },
    editPath: function () {

        this.editMode = "path";

        var path = this.selected.uri.substr(this.selected.uri.indexOf("/_library/") + 9);

        $("SelectedTitle").innerHTML = "<input style='width:300px;' class='MediumTextBox' id='LibraryPathEdit' type='text' value='" + path +"' />";
        $("SelectedDescription").innerHTML = "Warning, changing the path can cause broken links if this item is in use.";

        $("LibraryEditMenu").style.display = "block";
        $("LibraryItemMenu").style.display = "none";
    },
    save: function () {
        if (this.editMode == "path")
            return this.saveEditPath();

        this.selected.title = $("TitleEdit").value;
        this.selected.description = $("DescriptionEdit").value;
        this.selected.titlediv.innerHTML = this.selected.title;

        var data = new dataObject();
        data.add("ItemId", this.selected.id);
        data.add("Title", this.selected.title);
        data.add("Description", this.selected.description);

        lara.request(this.path + ":Update", data, function (result) { library.processSave(result); });
        this.cancelEdit();
    },
    saveEditPath: function () {

        var data = new dataObject();
        data.add("ItemId", this.selected.id);
        data.add("Path", $("LibraryPathEdit").value);

        lara.indicateOn();
        lara.request(this.path + ":UpdatePath", data, function (result) { library.processSavePath(result); });

    },
    processSave: function (result) {
        if (result.error)
            alert(result.error);
    },
    processSavePath: function (result) {
        if (result.success) {
            this.selected.uri = result.uri;
            this.statusURI.innerHTML = "<a href=\"" + result.uri + "\" target=\"_blank\">" + result.uri + "</a>";
            this.cancelEdit();
        }
        else {
            alert(result.error);
        }
        lara.indicateOff();
    },
    cancelEdit: function () {
        this.showStatus(this.selected);
        $("LibraryEditMenu").style.display = "none";
        $("LibraryItemMenu").style.display = "block";
    },
    deleteItem: function (silent) {
        if (!silent)
            if (confirm("Are you sure you want to delete this item?") == false)
                return false;

        library.indicateOn();

        var data = new dataObject();
        data.add("FolderId", this.folder.id);
        data.add("ItemId", this.selected.id);

        lara.request(this.path + ":Delete", data, function (result) { library.processDelete(result); });
    },
    processDelete: function (result) {
        if (result.success) {

            this.selected.div.parentNode.removeChild(this.selected.div);
            this.folder.count = result.count;

            this.unSelect();
        }
        else {
            alert(result.error);
        }
        library.indicateOff();
    },
    addMediaFile: function () {

        if ($('MediaFile').value) {
            library.indicateOn();

            //when the frame finishes loading our upload is complete.
            var UploadFrame = $('AddMediaUploadFrame');

            if (typeof document.addEventListener == "function")
                UploadFrame.addEventListener("load", function () { AddMediaFileUploadComplete(); return true; }, false);
            else
                UploadFrame.attachEvent("onload", function () { AddMediaFileUploadComplete(); return true; }); //ie

            $('UploadMediaFile').action = BASE_URL + "/_ui/libraryupload?FolderId=" + this.folder.id;
            $('AddMediaFileButton').disabled = true;

            try {
                $('UploadMediaFile').submit();
            }
            catch (e) {
                //sometimes IE gives a "access denied" error.  Wait 1/4 second and try again.
                setTimeout(function () { $('UploadMediaFile').submit(); return true; }, 250);
            }
            $("UploadSingleFileForm").style.display = "none";
            $("UploadProgress").style.display = "block";
        }
    },
    cut: function () {
        this.clipboard.push(this.selected.id);

        this.selected.div.style.display = "none";

        this.clipItems.innerHTML += " (" + this.selected.title + ")";
        this.clipdiv.style.display = "block";

    },
    paste: function () {

        library.indicateOn();

        //serialize clipboard items        
        var pasteItems = "";
        for (var i = 0; i < this.clipboard.length; i++) {
            pasteItems += this.clipboard[i] + ",";
        }

        var data = new dataObject();
        data.add("FolderId", this.folder.id);
        data.add("Items", pasteItems);

        lara.request(this.path + ":Paste", data, function (result) { library.processPaste(result); });

    },
    processPaste: function (result) {
        if (result.success) {

            this.items = result.items;
            this.renderContents();

            this.folder.count = result.count;

            this.unSelect();

            this.clipboard = [];
            this.clipItems.innerHTML = "";
            this.clipdiv.style.display = "none";
        }
        else {
            alert(result.error);
        }
        library.indicateOff();
    },
    cancelPaste: function () {

        for (var i = 0; i < this.clipboard.length; i++) {
            var item = this.getItem(this.clipboard[i]);
            if (item)
                item.div.style.display = "block";
        }
        this.clipboard = [];
        this.clipItems.innerHTML = "";
        this.clipdiv.style.display = "none";

    },
    actionAddIcon: function () {
        var display = $new("div");
        display.id = "SI" + this.selected.id;
        display.className = "SelectedIcon";
        display.innerHTML = "<table class='CleanTable'><tr><td class='LibraryIcon'><img onclick=\"mediaEdit.selectImage('SI" + this.selected.id + "');\" src='" + this.selected.icon + "' /></td></tr><tr><td><div class='SelectedImageTitle'>" + this.selected.title + "</div></td></tr></table>";

        var sel = $new("input");
        sel.type = "hidden";
        sel.value = this.selected.uri;
        display.appendChild(sel);
        this.target.appendChild(display);
        lara.hide(MEDIA_LIBRARY);
    },
    actionAddSpeck: function () {
        var targetSpeck = editors[$("SelectActionTarget").value];

        if (this.selected.filetype == "Image") {
            if (targetSpeck.wysiwyg) {
                var newImage = targetSpeck.IF.contentWindow.document.createElement("img");

                newImage.src = this.selected.uri;
                targetSpeck.IF.contentWindow.document.body.appendChild(newImage);
            }
            else {
                targetSpeck.TA.value += "<img src='" + this.selected.uri + "' />";
            }
        }
        else {
            if (targetSpeck.wysiwyg) {
                var newItem = targetSpeck.IF.contentWindow.document.createElement("a");

                newItem.href = this.selected.uri;
                newItem.innerHTML = this.selected.title;
                targetSpeck.IF.contentWindow.document.body.appendChild(newItem);
            }
            else {
                targetSpeck.TA.value += "<a href='" + this.selected.uri + "'>" + this.selected.title + "</a>";
            }
        }


    }
};
var library = new geoLibrary();

function FlashUploadsComplete() {
    ui.showTab("BrowseScreen", 0);
    library.browse(library.folder.id);
    library.showUpload("Single");
};

function AddMediaFileUploadComplete() {
    if ($('AddMediaUploadFrame').contentWindow.document.body) {
        result = $('AddMediaUploadFrame').contentWindow.document.body.innerHTML;
        if (result.indexOf('Error') >= 0)
            alert(result);
    }

    ui.showTab("BrowseScreen", 0);
    library.browse(library.folder.id);

    $('UploadMediaFile').reset();
    $('AddMediaFileButton').disabled = false;
    $("UploadSingleFileForm").style.display = "block";
    $("UploadProgress").style.display = "none";
};

function CheckContentKey(e) {
    var keynum;
    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    if (keynum == 46) //del key
        DeleteSelected();

};


/* BEGIN CDESIGN */


function cDesign() { };

cDesign.prototype = {
    serverPath: "/_ui/cdesign",
    version: 0,
    load: function () {
        admin.closeAll();
        this.editWindow = lara.windows[CDESIGN.id];
        this.editWindow.onclose = function () { admin.show(); };

        //        var textareas = $getByClass("css");
        //        for (var i = 0; i < textareas.length; i++) {
        //            var styleId = textareas[i].id.replace("CSS", "Style");
        //            this.replaceStyle(styleId, "");
        //        }
        this.applyStyle();
        if ($("ThemeStyle"))
            $("ThemeStyle").parentNode.removeChild($("ThemeStyle"));

        this.home = $("DesignHome");
        this.browse = $("BrowseStyle");
        this.addStyle = $("AddStylesheetForm");
        this.publishButton = $("DesignPublish");
        this.selectFile = $("UploadSelectFileForm");
        this.selectFile.style.zIndex = 21;

        this.loaded = true;
    },
    editMaster: function (styleId) {
        if (!this.loaded)
            this.load();

        lara.indicateOn();
        this.editMasterId = styleId;

        var data = new dataObject();
        data.add("styleId", styleId);

        lara.request(this.serverPath + ":EditMaster", data, function (result) { cdesign.processEditMaster(result); });
    },
    processEditMaster: function (result) {
        if (result.success) {
            $("EditMaster").innerHTML = result.html;
            this.editCompId = result.compId;
            this.home.style.display = "none";
            $("EditMaster").style.display = "block";
            this.cancelMakeMaster();
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    cancelMaster: function () {
        $("EditMaster").innerHTML = "";
        $("EditMaster").style.display = "none";
        this.home.style.display = "block";
    },
    saveMaster: function () {

        lara.indicateOn();
        var data = new dataObject();
        data.add("compId", this.editCompId);
        data.add("title", $("CompTitle").value);
        data.add("css", $("CompCSS").value);

        //Stylesets
        var stylesets = "";
        var styleBoxes = $("StyleSets").getElementsByTagName("input");
        for (i = 0; i < styleBoxes.length; i++) {
            var styleBox = styleBoxes[i];
            if (styleBox.checked) {
                stylesets += styleBox.value + ",";
            }
        }
        data.add("stylesets", stylesets);

        lara.request(this.serverPath + ":SaveMaster", data, function (result) { cdesign.processSaveMaster(result); });
    },
    processSaveMaster: function (result) {
        if (result.success) {
            this.cancelMaster();
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    deleteMaster: function () {
        if (!confirm("Are you sure you want to delete this master style?"))
            return;

        var data = new dataObject();
        data.add("compId", this.editCompId);

        lara.request(this.serverPath + ":DeleteMaster", data, function (result) { cdesign.processSaveMaster(result); });
    },
    addVariant: function (id) {
        var data = new dataObject();
        data.add("compId", id);
        lara.indicateOn();
        lara.request(this.serverPath + ":AddVariant", data, function (result) { cdesign.processEditVariant(result); });
    },
    deleteVariant: function (id) {
        var data = new dataObject();
        data.add("variantId", id);
        lara.indicateOn();
        lara.request(this.serverPath + ":DeleteVariant", data, function (result) { cdesign.processEditVariant(result); });
    },
    editVariant: function (variantId) {
        $("EditMasterButtons").style.display = "none";
        $("Variants").style.display = "none";
        $("StyleSets").style.display = "none";
        $("VariantEdit" + variantId).style.display = "block";
    },
    okVariant: function (variantId) {
        var data = new dataObject();
        data.add("variantId", variantId);
        data.add("display", $("Edit" + variantId + "0").value);
        data.add("value1", $("Edit" + variantId + "1").value);
        data.add("value2", $("Edit" + variantId + "2").value);
        data.add("value3", $("Edit" + variantId + "3").value);
        data.add("value4", $("Edit" + variantId + "4").value);
        data.add("value5", $("Edit" + variantId + "5").value);
        data.add("value6", $("Edit" + variantId + "6").value);
        data.add("value7", $("Edit" + variantId + "7").value);
        data.add("value8", $("Edit" + variantId + "8").value);

        lara.indicateOn();
        lara.request(this.serverPath + ":SaveVariant", data, function (result) { cdesign.processEditVariant(result); });

    },
    cancelVariant: function (variantId) {
        $("EditMasterButtons").style.display = "block";
        $("Variants").style.display = "block";
        $("StyleSets").style.display = "block";
        $("VariantEdit" + variantId).style.display = "none";
    },
    processEditVariant: function (result) {
        if (result.success) {
            $("Variants").innerHTML = result.variants;
            $("VariantEditors").innerHTML = result.variantEditors;
            if (result.variantId)
                this.cancelVariant(result.variantId);
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    removeMasterImage: function (id) {
        var data = new dataObject();
        data.add("imageId", id);
        lara.indicateOn();
        lara.request(this.serverPath + ":RemoveMasterImage", data, function (result) { cdesign.processChangeMasterImage(result); });
    },
    processChangeMasterImage: function (result) {
        if (result.success) {
            $("ImageList" + result.variantId).innerHTML = result.images;
        }
        else {
            alert("Error: " + result.error);
        }
        this.selectFile.style.display = "none";
        lara.indicateOff();
    },
    deleteStyle: function (styleId) {
        if (!confirm("Are you sure you want to delete this stylesheet?"))
            return;

        lara.indicateOn();
        var data = new dataObject();
        data.add("styleId", styleId);

        lara.request(this.serverPath + ":DeleteStyleSheet", data, function (result) { cdesign.processDeleteStyle(result); });
    },
    processDeleteStyle: function (result) {
        if (result.success) {
            $("StyleSheetList").innerHTML = result.styleList;
            $("Style" + result.styleId).parentNode.removeChild($("Style" + result.styleId));
            $("Component" + result.styleId).parentNode.removeChild($("Component" + result.styleId));
        }
        else {
            alert("Error: " + result.error);
        }
        this.addStyle.style.display = "none";
        this.home.style.display = "block";
        lara.indicateOff();
    },
    editStyle: function (styleId) {
        if (!this.loaded)
            this.load();

        this.editStyleId = styleId;
        this.editStylePage = $("Component" + styleId);
        this.editCss = $("CSS" + styleId);

        this.home.style.display = "none";
        this.editStylePage.style.display = "block";
        this.cancelEditCSS = this.editCss.value;
    },
    cancelStyle: function () {
        this.editStylePage.style.display = "none";
        this.home.style.display = "block";
        this.editCss.value = this.cancelEditCSS;
        this.applyStyle();
    },
    browseStyle: function (styleId) {
        if (!this.loaded)
            this.load();

        lara.indicateOn();
        this.browseStyleId = styleId;
        this.browseStyleSetId = 1;

        var data = new dataObject();
        data.add("styleId", styleId);

        lara.request(this.serverPath + ":BrowseStyle", data, function (result) { cdesign.processBrowse(result); });
    },
    processBrowse: function (result) {
        if (result.success) {

            //            this.home.style.display = "none";
            //            this.browse.style.display = "block";

            this.editWindow.hide();
            admin.hide();

            this.toolbox = document.createElement("div");
            this.toolbox.id = "sDesignToolbox";
            this.toolbox.className = "sDesignTools";
            this.toolbox.innerHTML = result.html;
            document.body.appendChild(this.toolbox);
            this.moveTools();

            window.onscroll = function () { cdesign.moveTools(); };
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    moveTools: function () {
        if (!this.toolbox)
            return;

        //this.toolbox.style.top =  ((document.documentElement.clientHeight-400)/2) + document.documentElement.scrollTop + "px";
        if (this.alignment == "0") {
            this.toolbox.style.left = "";
            this.toolbox.style.right = 0;
        }
        else {
            this.toolbox.style.left = 0;
            this.toolbox.style.right = "";
        }

        if (this.toolbox.offsetHeight > document.documentElement.clientHeight) {
            this.toolbox.style.top = 0 + "px";
            return;
        }

        this.toolbox.style.top = (document.documentElement.clientHeight - this.toolbox.offsetHeight) / 2 + lara.scrollTop() + "px";
    },
    loadStyle: function (colorId) {
        lara.indicateOn();

        var data = new dataObject();
        data.add("colorId", colorId);
        data.add("styleId", $("BrowseStyleId").value);

        lara.request(this.serverPath + ":LoadStyle", data, function (result) { cdesign.processLoadStyle(result); });
    },
    processLoadStyle: function (result) {
        if (result.success) {
            $("SelectedColorId").value = result.colorId;
            this.replaceStyle(result.id, result.css);
            //            this.replaceId = result.id;
            //            this.replaceCSS = result.css;
            //            this.applyStyle();
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    cancel: function () {
        lara.close(CDESIGN);
    },
    publish: function () {
        if (!this.loaded)
            this.load();

        var data = new dataObject();
        data.add("id", $("SelectTheme").value);

        lara.indicateOn();
        lara.request(this.serverPath + ":Publish", data, function (result) { cdesign.processLoadTheme(result); });

    },
    cancelSelectedStyle: function () {
        this.editWindow.show();
        admin.show();
        document.body.removeChild(this.toolbox);
        this.replaceId = "";
        this.replaceCSS = "";
        this.applyStyle();
    },
    saveSelectedStyle: function () {

        if (!confirm("Overwrite existing style with this style?"))
            return;

        lara.indicateOn();
        var data = new dataObject();
        data.add("colorId", $("SelectedColorId").value);
        data.add("styleId", $("BrowseStyleId").value);

        lara.request(this.serverPath + ":SaveSelectedStyle", data, function (result) { cdesign.processSaveSelectedStyle(result); });
    },
    processSaveSelectedStyle: function (result) {
        if (result.success) {

            var editPage = $("Component" + result.styleId);
            var div = $new("div");
            div.innerHTML = result.styleEdit;
            editPage.parentNode.replaceChild(div, editPage);

            $("StyleSheetList").innerHTML = result.styleList;

            this.cancelSelectedStyle();
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    saveStyle: function () {

        this.applyStyle();

        var data = new dataObject();
        data.add("Id", this.editStyleId);
        data.add("CSS", this.editCss.value);

        lara.request(this.serverPath + ":SaveStyle", data, function (result) { cdesign.processSaveStyle(result); });

        this.editStylePage.style.display = "none";
        this.home.style.display = "block";
        this.publishButton.style.display = "";
    },
    processSaveStyle: function (result) {
        if (result.success) {
            var nothing = "";
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    preview: function (link) {

        this.editWindow.preview(link, false);

        this.applyStyle();
    },
    applyStyle: function () {
        var textareas = $getByClass("css");
        var first = true;
        for (var i = 0; i < textareas.length; i++) {
            var css = textareas[i].value;
            var styleId = textareas[i].id.replace("CSS", "");
            var ctypeId = $("ComponentTypeId" + styleId).value;
            if (ctypeId == "3" && !first) {
                css = this.modifyFeatureCss(css, styleId);
                first = false;
            }
            var img = $("Images" + styleId);
            var imageList = img.value.split(',');
            for (var j = 0; j < imageList.length; j++) {
                if (imageList[j].length > 0) {
                    css = css.replace(new RegExp(imageList[j], 'g'), "url(" + $("ImagePath").value + imageList[j] + "?v=" + this.version + ")");
                }
            }
            this.replaceStyle(textareas[i].id.replace("CSS", ""), css);
        }
    },
    modifyFeatureCss: function (css, styleId) {
        css = css.replace(/.Feature/g, ".Feature" + styleId);
        css = css.replace(/.FContent/g, ".F" + styleId + "Content");
        css = css.replace(/.FHeader/g, ".F" + styleId + "Header");
        css = css.replace(/.FTL/g, ".F" + styleId + "TL");
        css = css.replace(/.FTR/g, ".F" + styleId + "TR");
        css = css.replace(/.FTitle/g, ".F" + styleId + "Title");
        css = css.replace(/.FText/g, ".F" + styleId + "Text");
        css = css.replace(/.FBL/g, ".F" + styleId + "BL");
        css = css.replace(/.FBR/g, ".F" + styleId + "BR");
        return css;
    },
    replaceStyle: function (id, css) {
        var styleId = "Style" + id;
        var style = $new("style");
        style.id = styleId;
        style.type = "text/css";
        if (style.styleSheet) style.styleSheet.cssText = css;
        else style.appendChild($text(css));
        if ($(styleId))
            $(styleId).parentNode.removeChild($(styleId));
        document.getElementsByTagName("head")[0].appendChild(style);
    },
    clearStyle: function () {
        var styles = document.getElementsByTagName("head")[0].getElementsByTagName("style");
        var styleIds = new Array();
        for (var i = 0; i < styles.length; i++) {
            styleIds.push(styles[i].id);
        }
        for (var j = 0; j < styleIds.length; j++) {
            $(styleIds[j]).parentNode.removeChild($(styleIds[j]));
        }
    },
    loadTheme: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("id", $("SelectTheme").value);

        lara.request(this.serverPath + ":LoadTheme", data, function (result) { cdesign.processLoadTheme(result); });
    },
    showMakePublic: function (id) {
        if (!this.loaded)
            this.load();

        var makePublic = $("MakePublic");
        makePublic.parentNode.removeChild(makePublic);
        document.body.appendChild(makePublic);

        makePublic.style.display = "block";
        ui.centerElement("MakePublic");

        dragdrop.makeDraggable($("MakePublic"), $("MakePublicHeader"));
    },
    cancelMakePublic: function () {
        $("NewPublicName").value = "";
        $("NewPublicDescription").value = "";
        $("MakePublic").style.display = "none";
    },
    makePublic: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $("NewPublicName").value);
        data.add("description", $("NewPublicDescription").value);
        data.add("id", $("SelectTheme").value);

        lara.request(this.serverPath + ":MakePublic", data, function (result) { cdesign.processMakePublic(result); });

    },
    processMakePublic: function (result) {

        if (result.success) {
            ui.showTab('DesignHome', 2);
            $("PublicThemes").innerHTML = result.themes;
        }
        else {
            alert("Error: " + result.error);
        }
        this.cancelMakePublic();
        lara.indicateOff();
    },
    showMakeMaster: function (id) {
        if (!this.loaded)
            this.load();

        var makeMaster = $("MakeMaster");
        makeMaster.parentNode.removeChild(makeMaster);
        document.body.appendChild(makeMaster);

        makeMaster.style.display = "block";
        ui.centerElement("MakeMaster");

        dragdrop.makeDraggable($("MakeMaster"), $("MakeMasterHeader"));
        $("MakeMasterId").value = id;
    },
    cancelMakeMaster: function () {
        $("MakeMasterId").value = "";
        $("NewMasterName").value = "";
        $("MakeMaster").style.display = "none";
    },
    makeMaster: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $("NewMasterName").value);
        data.add("id", $("MakeMasterId").value);

        lara.request(this.serverPath + ":MakeMaster", data, function (result) { cdesign.processEditMaster(result); });

    },
    showCopyTheme: function () {
        if (!this.loaded)
            this.load();

        var copyTheme = $("CopyTheme");
        copyTheme.parentNode.removeChild(copyTheme);
        document.body.appendChild(copyTheme);

        copyTheme.style.display = "block";
        copyTheme.style.zIndex = 21;
        ui.centerElement("CopyTheme");

        dragdrop.makeDraggable($("CopyTheme"), $("CopyThemeHeader"));

    },
    cancelCopyTheme: function () {
        $("NewThemeName").value = "";
        $("CopyTheme").style.display = "none";
    },
    deleteTheme: function () {
        if (!confirm("Are you sure you want to delete this theme?"))
            return;

        lara.indicateOn();

        var data = new dataObject();
        data.add("id", $("SelectTheme").value);

        lara.request(this.serverPath + ":DeleteTheme", data, function (result) { cdesign.processLoadTheme(result); });

    },
    copyTheme: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $("NewThemeName").value);
        data.add("id", $("SelectTheme").value);

        lara.request(this.serverPath + ":CopyTheme", data, function (result) { cdesign.processLoadTheme(result); });

    },
    processLoadTheme: function (result) {

        if (result.success) {
            $("DesignTabData1").innerHTML = result.themes;
            $("StyleEditPages").innerHTML = result.editPages;
            if (result.status == "1")
                $("DeleteTheme").style.display = "none";
            else
                $("DeleteTheme").style.display = "block";

            this.clearStyle();
            this.applyStyle();
        }
        else {
            alert("Error: " + result.error);
        }
        this.cancelCopyTheme();
        lara.indicateOff();
    },
    showNewStylesheet: function () {
        if (!this.loaded)
            this.load();

        var addStyle = $("AddStylesheet");
        addStyle.parentNode.removeChild(addStyle);
        document.body.appendChild(addStyle);

        addStyle.style.display = "block";
        addStyle.style.zIndex = 21;
        ui.centerElement("AddStylesheet");

        dragdrop.makeDraggable($("AddStylesheet"), $("AddStylesheetHeader"));

    },
    cancelNewStylesheet: function () {
        $("AddStylesheet").style.display = "none";
    },
    styleTypeSelected: function () {
        $("NewStyleTitle").value = $("NewStyleType").options[$("NewStyleType").selectedIndex].text;
    },
    saveNewStylesheet: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $("NewStyleTitle").value);
        data.add("ctypeId", $("NewStyleType").value);
        data.add("themeId", $("SelectTheme").value);

        lara.request(this.serverPath + ":AddStyleSheet", data, function (result) { cdesign.processAddStyleSheet(result); });

    },
    processAddStyleSheet: function (result) {

        if (result.success) {
            $("StyleSheetList").innerHTML = result.styleList;
            var div = $new("div");
            div.innerHTML = result.styleEdit;
            $("StyleEditPages").appendChild(div);
            this.replaceStyle(result.styleId, "");
        }
        else {
            alert("Error: " + result.error);
        }
        this.cancelNewStylesheet();
        lara.indicateOff();
    },
    addImage: function () {
        $("UploadImageColorId").value = "";
        $("UploadImageThemeId").value = $("SelectTheme").value;
        this.selectFile.style.display = "block";
    },
    addComponentImage: function (id) {
        $("UploadImageThemeId").value = "";
        $("UploadImageColorId").value = id;
        this.selectFile.style.display = "block";
    },
    cancelUpload: function () {
        $("UploadImageColorId").value = "";
        $("UploadImageThemeId").value = "";
        this.selectFile.style.display = "none";
    },
    uploadImage: function () {
        var form = $("UploadComponentImage");
        var selector = $("ComponentImage");

        if (selector.value) {
            lara.indicateOn();
            form.submit();
        }
    },
    uploadComplete: function () {

        var filename = $("AddComponentUploadFrame").contentWindow.document.body.innerHTML;
        if (filename.indexOf("A file by that name already exists") >= 0) {
            alert(filename);
            lara.indicateOff();
            return;
        }
        if (filename == "")
            return;

        if ($("UploadImageColorId").value != "") {
            var data = new dataObject();
            data.add("variantId", $("UploadImageColorId").value);
            lara.request(this.serverPath + ":LoadComponentImages", data, function (result) { cdesign.processChangeMasterImage(result); });
            return;
        }

        if (!this.editStyleId)
            return;

        var data = new dataObject();
        data.add("filename", filename);
        data.add("styleId", this.editStyleId);

        lara.request(this.serverPath + ":SaveImage", data, function (result) { cdesign.processSaveImage(result); });
    },
    processSaveImage: function (result) {
        if (result.success) {
            $("ImageList" + this.editStyleId).innerHTML = result.imageList;
        }
        else {
            alert("Error: " + result.error);
        }
        this.selectFile.style.display = "none";
        lara.indicateOff();
    },
    removeImage: function (filename) {

        lara.indicateOn();

        var data = new dataObject();
        data.add("filename", filename);
        data.add("styleId", this.editStyleId);

        lara.request(this.serverPath + ":RemoveImage", data, function (result) { cdesign.processSaveImage(result); });
    },
    loadStyleSet: function (styleSetId) {
        this.browseStyleSetId = styleSetId;
        this.loadPage(1);
    },
    loadPage: function (page) {

        lara.indicateOn();

        var data = new dataObject();
        data.add("page", page);
        data.add("styleId", this.browseStyleId);
        data.add("styleSetId", this.browseStyleSetId);

        lara.request(this.serverPath + ":BrowsePage", data, function (result) { cdesign.processLoadPage(result); });
    },
    processLoadPage: function (result) {
        if (result.success) {
            var selectors = $getByClass("StyleSelection");
            for (var i = 0; i < selectors.length; i++) {
                selectors[i].style.display = "none";
            }
            $("StyleSelection" + this.browseStyleSetId).innerHTML = result.html;
            $("StyleSelection" + this.browseStyleSetId).style.display = "block";
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    viewStyles: function (id) {

        if ($("ShowStyleOpen" + id)) {
            $("PublicThemeStyles" + id).innerHTML = "";
            return;
        }

        lara.indicateOn();
        var data = new dataObject();
        data.add("themeId", id)
        lara.request(this.serverPath + ":ShowStyles", data, function (result) { cdesign.processShowStyles(result); });
    },
    processShowStyles: function (result) {
        if (result.success) {
            $("PublicThemeStyles" + result.id).innerHTML = result.styles;
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    previewPublic: function (id) {
        lara.indicateOn();
        var data = new dataObject();
        data.add("themeId", id)
        lara.request(this.serverPath + ":PreviewPublic", data, function (result) { cdesign.processPreviewPublic(result); });
    },
    processPreviewPublic: function (result) {
        if (result.success) {
            this.clearStyle();
            this.replaceStyle(999, result.css);
            this.editWindow.preview($(result.linkId), false, function () { cdesign.exitPreviewPublic(); });
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    exitPreviewPublic: function (id) {
        this.clearStyle();
        this.applyStyle();
    },
    deletePublic: function (id) {
        if (!confirm("Delete this public theme?"))
            return;

        lara.indicateOn();
        var data = new dataObject();
        data.add("themeId", id)
        lara.request(this.serverPath + ":DeletePublic", data, function (result) { cdesign.processMakePublic(result); });
    },
    loadPublic: function (id) {
        lara.indicateOn();
        var data = new dataObject();
        data.add("themeId", id)
        lara.request(this.serverPath + ":LoadPublic", data, function (result) { cdesign.processLoadPublic(result); });
    },
    processLoadPublic: function (result) {
        if (result.success) {
            this.processLoadTheme(result);
            ui.showTab("DesignHome", 1);
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    insertTab: function (event, obj) {
        this.setBoxHeight(obj);

        var tabKeyCode = 9;
        if (event.which)
            var keycode = event.which; // mozilla
        else
            var keycode = event.keyCode; //ie
        if (keycode == tabKeyCode) {
            if (event.type == "keydown") {
                if (obj.setSelectionRange) {
                    // mozilla
                    var s = obj.selectionStart;
                    var e = obj.selectionEnd;
                    obj.value = obj.value.substring(0, s) + "    " + obj.value.substr(e);
                    obj.setSelectionRange(s + 4, s + 4);
                    obj.focus();
                } else if (obj.createTextRange) {
                    // ie
                    document.selection.createRange().text = "    ";
                    obj.onblur = function () { this.focus(); this.onblur = null; };
                }
            }
            if (event.returnValue)
                event.returnValue = false;
            if (event.preventDefault)
                event.preventDefault();
            return false;
        }
        return true;
    },
    setBoxHeight: function (TA) {
        Lines = TA.value.split("\n");
        var height = ((Lines.length * 16) + 50);
        if (height < 300)
            height = 300;
        TA.style.height = height + "px";
    }
};

var cdesign = new cDesign();//Page Layout

function sLayout(){};

sLayout.prototype = {
    serverPath: "/_ui/sitelayout",
    load: function(addMode) {

        lara.indicateOn();
        if (this.header) {
            this.headerCancel = this.header.cloneNode(false);
            this.headerCancel.innerHTML = this.header.innerHTML;
            this.footerCancel = this.footer.cloneNode(false);
            this.footerCancel.innerHTML = this.footer.innerHTML;
        }
        this.pageCancel = this.page.cloneNode(false); //No deep clone because IE 7 crashes with embedded scripts
        this.pageCancel.innerHTML = this.page.innerHTML;
        this.addMode = addMode;
        lara.request(this.serverPath + ":LoadEditor", "Path=" + this.path, function(result) { siteLayout.processLoad(result); });
    },
    processLoad: function(result) {
        if (result.success) {
            //Setup the admin menu items (undo)        
            this.adminTools = document.createElement("div");
            this.adminTools.className = "sLayoutTools";
            this.undoLink = this.getToollink("UndoLayoutLink", "aaa aDrop", "Undo", function() { siteLayout.undo(); return false; }, "80px");
            this.undoLink.style.display = "none";
            this.adminTools.appendChild(this.undoLink);
            this.infoBar = document.createElement("span");
            this.infoBar.innerHTML = this.info;
            this.infoBar.className = "sInfoBar";
            this.adminTools.appendChild(this.infoBar);

            //Main Admin Menu Functions (save, preview, html, cancel)
            this.actionTools = document.createElement("div");
            this.actionTools.className = "sLayoutActions";
            this.saveLink = this.getToollink("SaveLayoutLink", "aaa aSave", "Save", function() { siteLayout.save(); return false; }, "70px");
            this.actionTools.appendChild(this.saveLink);
            this.previewLink = this.getToollink("PreviewLayoutLink", "aaa aLight", "Preview", function() { siteLayout.preview(); return false; }, "70px");
            this.actionTools.appendChild(this.previewLink);
            this.htmlLink = this.getToollink("HtmlLayoutLink", "aaa aLight", "Html", function() { siteLayout.editHtml(); return false; }, "70px");
            this.actionTools.appendChild(this.htmlLink);
            this.cancelLink = this.getToollink("CancelLayoutLink", "aaa aCancel", "Cancel", function() { siteLayout.cancel(); return false; }, "70px");
            this.actionTools.appendChild(this.cancelLink);

            this.toolbar.appendChild(this.actionTools);
            this.toolbar.appendChild(this.adminTools);

            this.groups = result.Features;
            this.layouts = result.Layouts;

            this.toolbox = document.createElement("div");
            this.toolbox.id = "sDesignToolbox";
            this.toolbox.className = "sLayoutToolbox";
            this.tools = document.createElement("div");
            this.tools.className = "sLayoutToolboxTools";
            this.toolbox.appendChild(this.tools);

            window.onscroll = function() { siteLayout.moveTools(); };

            //            this.featureBar = document.createElement("div");
            //            this.featureBar.className = "sFeatureBar";
            //            if (!this.addMode)
            //                this.featureBar.style.display = "none";

            //            var featureBar = "";  //this.getOption("Layout Tools", "FeatureOptions", !this.addMode, "siteLayout.loadTools();") + "<span/><span/>";
            //            
            //            var firstCheck = true;
            //            for(var j=0;j<this.groups.length;j++)
            //            {
            //                featureBar += this.getOption(this.groups[j].title, "FeatureOptions", firstCheck, "siteLayout.showFeatures('" + this.groups[j].title + "');");
            //                firstCheck = false;
            //            }
            //            this.featureBar.innerHTML = featureBar;

            this.showFeatures(true);
            this.loadTools();

            document.body.appendChild(this.toolbox);

            //this.toolbar.appendChild(this.featureBar);       
            if (this.header) {
                this.header.innerHTML = result.HeaderLayout;
                this.footer.innerHTML = result.FooterLayout;
            }
            this.page.innerHTML = result.PageLayout;

            this.featureData = result.FeatureData; //stored features

            this.refresh();

            this.moveTools();

            lara.indicateOff();
        }
        else {
            alert("Error: " + result.error);
        }
    },
    getOption: function(text, name, checked, click) {
        var check = "";
        if (checked) {
            check = 'checked="true"';
            this.selectedFeatures = text;
        }

        return '<input type="radio" name="' + name + '" onclick="' + click + '" ' + check + ' />' + text;

    },
    setUndo: function() {
        if (this.header) {
            this.undoHeader = this.header.cloneNode(true);
            this.undoFooter = this.footer.cloneNode(true);
        }
        this.undoPage = this.page.cloneNode(true);
        this.undoPage.innerHTML = this.page.innerHTML;
        this.undoLink.style.display = "";
    },
    undo: function() {
        if (this.header) {
            this.header.parentNode.replaceChild(this.undoHeader, this.header);
            this.header = this.undoHeader;
            this.footer.parentNode.replaceChild(this.undoFooter, this.footer);
            this.footer = this.undoFooter;
        }
        this.page.parentNode.replaceChild(this.undoPage, this.page);
        this.page = this.undoPage;

        this.refresh();
    },
    getToollink: function(id, className, text, click, width) {
        var toolLink = document.createElement("a");
        toolLink.className = className;
        toolLink.id = id;
        toolLink.href = "/" + text;
        toolLink.innerHTML = "<span>" + text + "</span>";
        toolLink.onclick = click;
        toolLink.style.width = width;
        return toolLink;
    },
    loadTools: function() {
        //        this.addFeaturesLink.className = "aaa aAdd";
        //        this.layoutLink.className = "aaas aSave";

        var groupTitle = document.createElement("div");
        groupTitle.className = "LayoutGroupTitle";
        groupTitle.innerHTML = "Change Layout";

        //Toggle collapse/expand
        this.layoutOptions = document.createElement("div");
        this.layoutOptions.className = "FeatureGroupOptions";
        this.layoutOptions.style.display = "none";
        groupTitle.onclick = function() {
            if (siteLayout.layoutOptions.style.display == "none") {
                if (!this.selectedRow) {
                    var rows = siteLayout.masterRows(siteLayout.page);
                    if (rows.length > 0)
                        siteLayout.selectRow(rows[0]);
                }

                //Close Feature Options
                var options = $getByClass("FeatureGroupOptions");
                for (var i = 0; i < options.length; i++) {
                    options[i].style.display = "none";
                }
                siteLayout.layoutOptions.style.display = "";
            }
            else
                siteLayout.layoutOptions.style.display = "none";
        };

        this.tools.appendChild(groupTitle);
        this.tools.appendChild(siteLayout.layoutOptions);

        this.mode = "layout";
        //this.featureBar.style.display = "none";
        siteLayout.layoutOptions.innerHTML = "<div class=\"sToolsTitle\">Select row and click layout</div>";
        for (var i = 0; i < this.layouts.length; i++) {
            var layout = this.layouts[i];
            var option = document.createElement("div");
            option.className = "LayoutSelector";
            var layoutIcon = document.createElement("img");
            layoutIcon.src = layout.icon;
            layoutIcon.title = layout.title + " - click to apply.";
            layoutIcon.value = layout.html;
            layoutIcon.onclick = function() { siteLayout.changeLayout(this.value); };
            option.appendChild(layoutIcon);
            siteLayout.layoutOptions.appendChild(option);
        }
        var addRow = document.createElement("a");
        addRow.id = "AddRowLink";
        addRow.href = "/addrow";
        addRow.title = "Add Row";
        addRow.innerHTML = "Row";
        addRow.onclick = function() { siteLayout.addRow(); return false; };
        siteLayout.layoutOptions.appendChild(addRow);

        var delRow = document.createElement("a");
        delRow.id = "DeleteRowLink";
        delRow.href = "/deleterow";
        delRow.title = "Delete Row";
        delRow.innerHTML = "Row";
        delRow.onclick = function() { siteLayout.deleteRow(); return false; };
        siteLayout.layoutOptions.appendChild(delRow);

        this.addDelBox();
    },
    moveTools: function() {
        if (!this.toolbox)
            return;

        //Don't move toolbox if it is larger than the client area.
        if ((this.toolbox.offsetHeight + 35) > (document.documentElement.clientHeight))
            return;

        //this.toolbox.style.top =  ((document.documentElement.clientHeight-400)/2) + document.documentElement.scrollTop + "px";
        this.toolbox.style.top = 35 + lara.scrollTop() + "px";

        if (this.toolsRight) {
            this.toolbox.style.left = "";
            this.toolbox.style.right = 0;
        }
        else {
            this.toolbox.style.left = 0;
            this.toolbox.style.right = "";
        }

        //this.toolbox.style.height = document.documentElement.clientHeight-100 + "px";
        //this.tools.style.height = document.documentElement.clientHeight-200 + "px";
    },
    refresh: function() {
        this.fitPage();

        dragdrop.clearDropTargets();

        this.clearResizers();

        var selectedId = null;
        if (this.selectedRow)
            selectedId = this.selectedRow.id;

        if (this.header) {
            this.refreshSection(this.header);
            this.refreshSection(this.footer);
        }
        this.refreshSection(this.page);

        if (selectedId != null)
            this.selectRow($(selectedId));


    },
    clearResizers: function() {
        //Remove column resizers
        var resizers = $getByClass("ColumnResizer");
        for (var i = 0; i < resizers.length; i++) {
            document.body.removeChild(resizers[i]);
        }
    },
    refreshSection: function(section) {
        this.convert(section);
        this.enableDragging(section);
        this.enableDropping(section);
        this.setBorders(section, "solid 1px #bbb");
        this.highlight(section);
    },
    //Makes sure the toolbox has room on the left by narrowing the page
    fitPage: function() {
        if (!this.wrapper)
            return;
        var pageWidth = this.wrapper.offsetWidth;
        var pos = ui.findPos(this.wrapper);
        var toolsWidth = this.toolbox.offsetWidth;
        var clientWidth = document.documentElement.clientWidth;

        if (pos.x == 0 && pageWidth < clientWidth)
            this.toolsRight = true;

        if (clientWidth < (pageWidth + (toolsWidth * 2))) {
            if (!this.toolsRight)
                this.wrapper.style.marginLeft = toolsWidth + 10 + "px";

            if (clientWidth < (pageWidth + toolsWidth + 10))
                this.wrapper.style.width = pageWidth - 30 - toolsWidth + "px";
        }

    },
    //Used to ensure data is in the correct format
    convert: function(section) {
        //Convert each row to a table, tables can not be nested, and can only contain one row
        //content can not exist outside of a row
        //var newSection = section.cloneNode(true);

        //section.innerHTML = "";

        //var rows = newSection.getElementsByTagName("tr");
        //        for (var i = 0; i < rows.length; i++) {
        //            var row = rows[i];

        //            var newTable = document.createElement("table");
        //            newTable.className = "CleanTable";
        //            newTable.style.width = "100%";
        //            newTable.setAttribute("safestyle", "width:100%;");
        //            var newTBody = document.createElement("tbody");
        //            newTBody.appendChild(row.cloneNode(true));

        //            newTable.appendChild(newTBody);

        //            section.appendChild(newTable);
        //        }
    },
    enableDragging: function(section) {
        var features = section.getElementsByTagName("div");
        for (var i = 0; i < features.length; i++) {
            dragdrop.makeDraggable(features[i], features[i], function(dragItem, dropTarget) { siteLayout.activeDrop(dragItem, dropTarget); }, function() { siteLayout.startDrag(); });
        }
    },
    startDrag: function() {
        this.setUndo();

        this.deselectAllRows();
    },
    setBorders: function(section, borderStyle) {
        var rows = section.getElementsByTagName("table");
        for (var i = 0; i < rows.length; i++) {
            var tds = rows[i].getElementsByTagName("td");
            for (var j = 0; j < tds.length; j++) {
                tds[j].style.borderTop = borderStyle;
                tds[j].style.borderLeft = borderStyle;
                if (i == rows.length - 1)
                    tds[j].style.borderBottom = borderStyle;

                if (j == tds.length - 1)
                    tds[j].style.borderRight = borderStyle;
            }
        }
    },
    enableDropping: function(section) {
        var tds = section.getElementsByTagName("td");
        for (var i = tds.length; i >= 0; i--) {
            dragdrop.makeDroppable(tds[i]);
        }
        if (this.delBox)
            dragdrop.makeDroppable(this.delBox);
    },
    highlight: function(section) {
        var features = section.getElementsByTagName("div");
        for (var i = 0; i < features.length; i++) {
            features[i].className = "LayoutFeature";
        }

        if (section.childNodes.length == 0)
            return;

        var rows = this.masterRows(section);
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            row.id = section.id + "Row" + i;
            row.setAttribute("section", section.id);
            row.style.cursor = "Pointer";
            row.title = "Click to change column layout.";
            row.onclick = function(e) {
                siteLayout.selectRow(this);
                if (!e) var e = window.event;
                e.cancelBubble = true;
                if (e.stopPropagation) e.stopPropagation();
            };

            if (row.id == this.selectedRow)
                row.style.backgroundColor = "#999";

            //var children = row.childNodes;
            var cols = row.cells;  //getElementsByTagName("td");
            //alert(children.length + " " + cols.length);
            for (var j = 0; j < cols.length; j++) {

                var col = cols[j];
                //col.style.verticalAlign = "top";
                col.className = "FeatureContainer";
                col.style.backgroundColor = "";

                if (col.getElementsByTagName("div").length == 0)
                    col.innerHTML = "&nbsp;";

                if (section.id == "PageContent")
                    col.style.height = "150px";
                else
                    col.style.height = "80px";

                //If we are not on the first column, add a resizer
                if (j != 0) {
                    var resizer = $new("div");
                    resizer.className = "ColumnResizer";
                    resizer.title = "Click and drag to resize columns.";
                    var pos = ui.findPos(col);
                    resizer.style.top = pos.y + "px";
                    resizer.style.left = (pos.x - 3) + "px";
                    resizer.style.height = col.offsetHeight + "px";
                    resizer.leftCol = cols[j - 1];
                    resizer.rightCol = cols[j];

                    resizer.onmousedown = function(ev) {

                        //Setup the move and drop events
                        siteLayout.resizing = true;
                        siteLayout.activeResizer = this;

                        siteLayout.startPos = ui.findPos(this);

                        siteLayout.startLeft = this.leftCol.offsetWidth;
                        siteLayout.startRight = this.rightCol.offsetWidth;

                        siteLayout.startMouse = dragdrop.mousePos(ev);
                        ui.disableSelection();
                        document.onmousemove = function(ev) { siteLayout.mouseMove(ev); };
                        document.onmouseup = function(ev) { siteLayout.mouseUp(ev); };
                        return false;
                    };

                    document.body.appendChild(resizer);


                }


            }
        }
    },
    mouseMove: function(ev) {
        ev = ev || window.event;

        var pos = dragdrop.mousePos(ev);

        if (this.resizing) {
            var xMove = this.startMouse.x - pos.x;

            var leftWidth = (siteLayout.startLeft - xMove);
            if (leftWidth > 0)
                this.activeResizer.leftCol.style.width = leftWidth + "px";

            var rightWidth = (siteLayout.startRight + xMove);
            if (rightWidth > 0)
                this.activeResizer.rightCol.style.width = rightWidth + "px";

            //All the columns in a row can be affected by adjusting the size.  We must reposition all resizers in the row
            //to ensure accuracy.  
            var resizers = $getByClass("ColumnResizer");
            for (var i = 0; i < resizers.length; i++) {
                pos = ui.findPos(resizers[i].rightCol);
                resizers[i].style.left = (pos.x - 3) + "px";
            }

            return false;
        }
    },
    mouseUp: function(ev) {
        ev = ev || window.event;

        if (this.resizing) {
            this.resizing = false;

            //calculate % width, in case page is resized later.  
            var row = this.activeResizer.leftCol.parentNode;

            var cols = row.getElementsByTagName("td");
            for (var j = 0; j < cols.length; j++) {

                //remove existing width
                var style = cols[j].getAttribute("safestyle");
                style = style.replace(/width:.+?;/g, "");
                style += "width:" + Math.round(cols[j].offsetWidth / row.offsetWidth * 100) + "%;";
                cols[j].setAttribute("safestyle", style)
            }

            document.onmousemove = null;
            document.onmouseup = null;
            ui.enableSelection();
        }
    },
    masterRows: function(section) {
        return section.getElementsByTagName("tr");
    },
    activeDrop: function(dragItem, dropTarget) {

        if (dropTarget.id == "DeleteContainer") {
            dragItem.parentNode.removeChild(dragItem);
            return;
        }
        if (dropTarget.getElementsByTagName("div").length == 0)
            dropTarget.innerHTML = "";

        dragItem.style.position = "relative";
        dragItem.style.left = "0px";
        dragItem.style.top = "0px";
        dropTarget.appendChild(dragItem);

        this.refresh();
    },
    selectRow: function(row) {
        this.deselectAllRows();
        this.selectedRow = row;
        this.section = $(row.getAttribute("section"));

        row.style.backgroundColor = "#ddd";

        //Show Layout Tools and Close Feature Options
        var options = $getByClass("FeatureGroupOptions");
        for (var i = 0; i < options.length; i++) {
            options[i].style.display = "none";
        }
        siteLayout.layoutOptions.style.display = "";
    },
    deselectAllRows: function() {
        if (this.header) {
            this.deselectRows(this.header);
            this.deselectRows(this.footer);
        }
        this.deselectRows(this.page);
    },
    deselectRows: function(section) {
        var rows = this.masterRows(section);
        for (var i = 0; i < rows.length; i++) {
            rows[i].style.backgroundColor = "";
        }
    },
    addRow: function() {
        this.setUndo();

        var newTable = document.createElement("table");
        var newTbody = document.createElement("tbody");
        var newRow = document.createElement("tr");
        var newTD = document.createElement("td");
        newTable.className = "lt";
        //        newTable.cellPadding = "0";
        //        newTable.cellSpacing = "0";
        //        newTable.style.width = "100%";
        //        newTable.setAttribute("safestyle", "width:100%;");

        newRow.appendChild(newTD);
        newTbody.appendChild(newRow);
        newTable.appendChild(newTbody);

        this.section.appendChild(newTable);
        this.refresh();

    },
    deleteRow: function() {
        if (this.selectedRow != null) {
            if (confirm("Are you sure you want to remove the selected row?"))
                this.selectedRow.parentNode.removeChild(this.selectedRow);

            this.selectedRow = null;
        }
        this.refresh();
    },
    featureDrop: function(dragItem, dropTarget) {
        if (dropTarget.id == "DeleteContainer")
            return;

        this.setUndo();

        newFeature = document.createElement("div");
        var html = dragItem.getAttribute("html");


        //Protect style in IE
        html = html.replace(/(style|STYLE|Style)=".+?"/g, function(match) { return match + " safe" + match; });
        html = html.replace(/(style|STYLE|Style)=".+?"/g, function(match) { return match + " safe" + match; });

        newFeature.innerHTML = html;
        if (dropTarget.getElementsByTagName("div").length == 0)
            dropTarget.innerHTML = "";

        dropTarget.appendChild(newFeature.firstChild);

        this.refresh();

    },
    changeLayout: function(html) {
        if (!this.selectedRow)
            return;

        this.setUndo();

        var newLayout = document.createElement("div");

        //Protect style in IE
        html = html.replace(/(style|STYLE|Style)=".+?"/g, function(match) { return match + " safe" + match; });
        html = html.replace(/(style|STYLE|Style)=".+?"/g, function(match) { return match + " safe" + match; });

        newLayout.innerHTML = html;

        //Get columns
        var cols = this.selectedRow.getElementsByTagName("td");
        var newCols = newLayout.getElementsByTagName("td");
        var newCol = 0;
        for (var i = 0; i < cols.length; i++) {
            if (cols[i].className == "FeatureContainer") {
                //Move contents
                var colContents = cols[i].childNodes;
                for (var j = 0; j < colContents.length; j++) {
                    newCols[newCol].appendChild(colContents[j].cloneNode(true));
                }
                if (newCols[newCol].innerHTML == "")
                    newCols[newCol].innerHTML = "&nbsp;";

                if (newCol < (newCols.length - 1))
                    newCol++;

            }
        }
        var newRow = newLayout.getElementsByTagName("tr")[0];
        this.selectedRow.parentNode.replaceChild(newRow, this.selectedRow);

        this.refresh();
    },
    showFeatures: function(isLoading) {
        //        this.addFeaturesLink.className = "aaas aAdd";
        //        this.layoutLink.className = "aaa aSave";
        this.mode = "add";
        //this.featureBar.style.display = "block";
        this.selectedFeatures = groupTitle;
        //this.tools.innerHTML = "";

        var first = true;
        for (var j = 0; j < this.groups.length; j++) {
            var group = document.createElement("div");
            group.className = "FeatureGroup";
            var groupTitle = document.createElement("div");
            groupTitle.className = "FeatureGroupTitle";
            groupTitle.innerHTML = this.groups[j].title;
            group.appendChild(groupTitle);
            group.groupOptions = document.createElement("div");
            group.groupOptions.className = "FeatureGroupOptions";
            //Toggle collapse/expand
            group.onclick = function() {
                siteLayout.deselectAllRows();
                siteLayout.layoutOptions.style.display = "none";
                if (this.groupOptions.style.display == "none")
                    this.groupOptions.style.display = "";
                else
                    this.groupOptions.style.display = "none";
            };

            for (var i = 0; i < this.groups[j].features.length; i++) {
                var feature = this.groups[j].features[i];

                var option = document.createElement("div");
                option.className = "NewLayoutFeature";
                option.value = feature.description;
                option.title = "Drag this item to your page.";
                option.setAttribute("html", feature.html);
                //option.onmouseover = function() { siteLayout.hoverArea.style.display = ""; $("DeleteInfo").style.visibility = "hidden"; siteLayout.hoverIcon.src = this.firstChild.src; siteLayout.hoverTitle.innerHTML = "<br />" + this.value; };
                //option.onmouseout = function() { siteLayout.hoverArea.style.display = "none"; $("DeleteInfo").style.visibility = ""; };

                var featureIcon = document.createElement("img");
                featureIcon.src = feature.icon;

                var featureTitle = document.createElement("span");
                featureTitle.innerHTML = feature.title;

                option.appendChild(featureIcon);
                option.appendChild(featureTitle);

                dragdrop.makeCreatable(option, option, function(dragItem, dropTarget) { siteLayout.featureDrop(dragItem, dropTarget); }, function() { siteLayout.startDrag(); });

                group.groupOptions.appendChild(option);
            }
            if (!first)
                group.groupOptions.style.display = "none";

            group.appendChild(group.groupOptions);
            this.tools.appendChild(group);
            first = false;
        }

        this.addDelBox();

        this.hoverArea = document.createElement("div");
        this.hoverArea.className = "sHoverInfo";
        this.hoverArea.style.display = "none";
        this.hoverIcon = document.createElement("img");
        this.hoverTitle = document.createElement("span");
        this.hoverArea.appendChild(this.hoverIcon);
        this.hoverArea.appendChild(this.hoverTitle);
        this.toolbox.appendChild(this.hoverArea);

        if (!isLoading)
            this.refresh();
    },
    addDelBox: function() {
        if (!this.delBox) {
            this.delBox = document.createElement("div");
            this.delBox.id = "DeleteContainer";
            this.toolbox.appendChild(this.delBox);
            this.delInfo = document.createElement("div");
            this.delInfo.id = "DeleteInfo";
            this.delInfo.innerHTML = "Drop items here to remove them from your page.";
            this.toolbox.appendChild(this.delInfo);
            dragdrop.makeDroppable(this.delBox);
        }
    },
    cancel: function() {
        if (this.header) {
            this.header.parentNode.replaceChild(this.headerCancel, this.header);
            this.footer.parentNode.replaceChild(this.footerCancel, this.footer);
        }
        this.page.parentNode.replaceChild(this.pageCancel, this.page);

        this.exit();
    },
    exit: function() {
        this.adminTools.parentNode.removeChild(this.adminTools);
        //this.featureBar.parentNode.removeChild(this.featureBar);
        this.toolbox.parentNode.removeChild(this.toolbox);
        this.actionTools.parentNode.removeChild(this.actionTools);
        if (this.wrapper) {
            this.wrapper.style.width = ""; //fitpage
            this.wrapper.style.marginLeft = ""; //fitpage
        }
        this.toolbar.style.height = "31px";
        dragdrop.clearDropTargets();
        this.clearResizers();
        this.delBox = null;
        window.onscroll = null;
        this.closed.call();
    },
    preview: function() {
        if (this.inPreview) {
            this.htmlLink.style.display = "";
            //            if (this.mode == "add")
            //                this.featureBar.style.display = "block";
            this.toolbox.style.display = "block";
            this.adminTools.style.display = "block";

            this.previewLink.innerHTML = "<span>Preview</span>";
            this.previewLink.style.width = "70px";
            if (this.header) {
                this.header.parentNode.replaceChild(this.headerPreview, this.header);
                this.footer.parentNode.replaceChild(this.footerPreview, this.footer);
                this.header = this.headerPreview;
                this.footer = this.footerPreview;
            }
            this.page.parentNode.replaceChild(this.pagePreview, this.page);
            this.page = this.pagePreview;

            this.refresh();
            this.inPreview = false;
            lara.request(this.serverPath + ":CancelPreview", null, function(result) { result = result; });
        }
        else {
            this.updateHtml();
            lara.indicateOn();
            this.inPreview = true;
            if (this.header) {
                this.headerPreview = this.header.cloneNode(true);
                this.footerPreview = this.footer.cloneNode(true);
            }
            this.pagePreview = this.page.cloneNode(true);

            this.htmlLink.style.display = "none";
            //this.featureBar.style.display = "none";
            this.toolbox.style.display = "none";
            this.adminTools.style.display = "none";
            this.clearResizers();

            if (this.wrapper) {
                this.wrapper.style.width = ""; //fitpage
                this.wrapper.style.marginLeft = ""; //fitpage
            }
            
            this.previewLink.innerHTML = "<span>Exit Preview</span>";
            this.previewLink.style.width = "100px";

            var data = new dataObject();
            data.add("Layout", this.pageHtml);
            if (this.header) {
                data.add("Header", this.headerHtml);
                data.add("Footer", this.footerHtml);
            }
            data.add("Path", this.path);

            lara.request(this.serverPath + ":Preview", data.serialize() + this.featureData, function(result) { siteLayout.processPreview(result); });
        }
    },
    processPreview: function(result) {
        lara.indicateOff();
        if (result.success) {
            if (this.header) {
                this.header.innerHTML = result.HeaderHtml;
                this.footer.innerHTML = result.FooterHtml;
            }
            this.page.innerHTML = result.html;
        }
        else {
            alert("Error: " + result.error);
        }
    },
    save: function() {
        if (this.editHtmlMode) //Exit edit html mode
            this.editHtml();

        if (this.inPreview) //Exit preview mode
            this.preview();

        this.updateHtml();
        lara.indicateOn();

        var data = new dataObject();
        data.add("Layout", this.pageHtml);
        if (this.header) {
            data.add("Header", this.headerHtml);
            data.add("Footer", this.footerHtml);
        }
        data.add("Path", this.path);

        lara.request(this.serverPath + ":Save", data.serialize() + this.featureData, function(result) { siteLayout.processSave(result); });
    },
    processSave: function(result) {
        lara.indicateOff();
        if (result.success) {
            if (this.header) {
                this.header.innerHTML = result.HeaderHtml;
                this.footer.innerHTML = result.FooterHtml;
            }
            this.page.innerHTML = result.html;

            this.exit();
        }
        else {
            alert("Error: " + result.error);
        }
    },
    editHtml: function() {
        if (this.editHtmlMode) {
            this.cancelLink.style.display = "";
            this.saveLink.style.display = "";
            this.previewLink.style.display = "";
            //            if (this.mode == "add")
            //                this.featureBar.style.display = "block";
            this.toolbox.style.display = "block";
            this.adminTools.style.display = "block";
            this.htmlLink.innerHTML = "<span>Html</span>";
            this.htmlLink.style.width = "70px";

            this.editHtmlMode = false;
            if (this.header) {
                this.header.innerHTML = this.renderHtml(this.headerView.value);
                this.footer.innerHTML = this.renderHtml(this.footerView.value);
            }
            this.page.innerHTML = this.renderHtml(this.pageView.value);
            this.refresh();
        }
        else {
            this.clearResizers();
            this.editHtmlMode = true;
            this.updateHtml();
            this.headerView = document.createElement("textarea");
            this.headerView.value = this.headerHtml;
            this.headerView.style.height = "300px";
            this.headerView.style.width = "95%";
            this.headerView.wrap = "off";
            this.header.innerHTML = "";
            this.header.appendChild(this.headerView);

            this.pageView = document.createElement("textarea");
            this.pageView.value = this.pageHtml;
            this.pageView.style.height = "600px";
            this.pageView.style.width = "95%";
            this.pageView.wrap = "off";
            this.page.innerHTML = "";
            this.page.appendChild(this.pageView);

            this.footerView = document.createElement("textarea");
            this.footerView.value = this.footerHtml;
            this.footerView.style.height = "300px";
            this.footerView.style.width = "95%";
            this.footerView.wrap = "off";
            this.footer.innerHTML = "";
            this.footer.appendChild(this.footerView);

            this.cancelLink.style.display = "none";
            this.saveLink.style.display = "none";
            this.previewLink.style.display = "none";
            //this.featureBar.style.display = "none";
            this.toolbox.style.display = "none";
            this.adminTools.style.display = "none";
            this.htmlLink.innerHTML = "<span>Exit Html</span>";
            this.htmlLink.style.width = "100px";
        }
    },
    renderHtml: function(html) {
        //Protect style with IE
        html = html.replace(/(style|STYLE|Style)=".+?"/g, function(match) { return match + " safe" + match; });
        html = html.replace(/<feature /g, "<div ");
        html = html.replace(/<\/feature>/g, "</div>");

        return html;
    },

    updateHtml: function() {
        if (this.header) {
            this.headerHtml = this.getHtml(this.header);
            this.footerHtml = this.getHtml(this.footer);
        }
        this.pageHtml = this.getHtml(this.page);
    },
    getHtml: function(section) {
        //Get rid of <SPAN> drag triggers
        var features = section.getElementsByTagName("div");
        for (var i = 0; i < features.length; i++) {
            if (features[i].firstChild.innerHTML)
                features[i].innerHTML = features[i].firstChild.innerHTML;
        }

        var content = section.cloneNode(true);
        var html = this.cleanHtml(content);
        html = html.replace(/border="1"/g, "border=\"0\"");
        html = html.replace(/div/g, "feature");

        return html;

    },
    //Returns the innerXML of an HTML DOM node
    cleanHtml: function(oNode) {
        var s = "";
        var nodes = oNode.childNodes;
        for (var i = 0; i < nodes.length; i++) {

            var node = nodes[i];
            var nodeType = node.nodeType;

            //ElementNode, DocumentNode, DocumentFragmentNode
            if (nodeType == 1 || nodeType == 9 || nodeType == 11) {
                s += this.xml(node, "");
            }
            else {
                //If Node not empty
                if (node.data.replace(/\n/g, "").replace(/\s/g, "") != "")
                    s += node.data.replace(/^\s+|\s+$/g, "").replace(/^\n+|\n+$/g, ""); //Remove empty space
            }

        }
        return s;
    },
    //Returns outerXML of the node.
    xml: function(oNode, indent) {

        var s = "";
        var nodes = oNode.childNodes;

        //Write out single close tags
        if (nodes.length == 0 && (oNode.nodeName == "INPUT" || oNode.nodeName == "IMG" || oNode.nodeName == "HR" || oNode.nodeName == "BR" || oNode.nodeName == "FEATURE")) {
            if (!oNode.getAttribute("_moz_editor_bogus_node")) {
                s += indent + "<" + oNode.nodeName.toLowerCase() + this.getAttributes(oNode) + " />\n";
            }
        }
        else {

            var tagName = oNode.nodeName.toLowerCase();
            s += indent + "<" + tagName + this.getAttributes(oNode) + ">\n";

            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                var nodeType = node.nodeType;

                //ElementNode, DocumentNode, DocumentFragmentNode
                if (nodeType == 1 || nodeType == 9 || nodeType == 11) {
                    s += this.xml(node, indent + "  ");
                }
                else {
                    //If Node not empty
                    if (node.data.replace(/\n/g, "").replace(/\s/g, "") != "")
                        s += indent + node.data.replace(/^\s+|\s+$/g, "").replace(/^\n+|\n+$/g, "") + "\n"; //Remove empty space
                }

            }
            s += indent + "</" + tagName + ">\n";
        }
        return s;
    },
    getAttributes: function(oNode) {

        var s = "";
        var atts = oNode.attributes;

        for (var i = 0; i < atts.length; i++) {
            var att = atts[i];

            if (this.validAttribute(att, oNode.nodeName)) {

                //style attributes are called safestyle to protect from changes
                if (att.nodeName.toLowerCase() == "safestyle") {
                    s += " style=\"" + att.nodeValue + "\"";
                } else {
                    s += " " + att.nodeName + "=\"" + att.nodeValue + "\"";
                }

            }
        }
        return s;
    },
    validAttribute: function(att, tag) {

        //IE adds extra attributes - remove them.
        if (att.nodeValue == null || att.nodeValue == "" || att.nodeValue == "inherit") {
            return false;
        }
        //Style is always saved in safestyle
        if (att.nodeName == "style" || att.nodeName == "valign" || att.nodeName == "vAlign") {
            return false;
        }
        if (att.nodeName.toLowerCase() == "colspan" || att.nodeName.toLowerCase() == "rowspan") {
            if (att.nodeValue == "1") { return false; }
        }
        if (tag == "INPUT") {
            if (att.nodeName == "start" || att.nodeName == "height" || att.nodeName.toLowerCase() == "maxlength" || att.nodeName == "loop")
                return false;
        }
        if (tag == "IMG") {
            if (att.nodeName == "start" || att.nodeName == "loop")
                return false;
        }
        if (tag == "TR") {
            if (att.nodeName == "title" || att.nodeName == "id")
                return false;
        }
        //        if (tag == "TD") {
        //            if (att.nodeName == "class") {
        //                if (att.nodeValue == "FeatureContainer")
        //                    return false;
        //            }
        //        }           
        if (att.nodeName == "section") //Remove section marker
            return false;

        return true;
    }
};    
var siteLayout = new sLayout();







function getFeatureOptions(featureObj, settings) {
        
    switch(featureObj) {
        case "SignIn":
            if ($("SignInFullView").checked)
                settings.add("view", 0); 
            if ($("SignInWindowView").checked)
                settings.add("view", 1);
            return;

        case "SignUp":
            if ($("SignUpEmailView").checked)
                settings.add("view", 2);
            if ($("SignUpButtonView").checked)
                settings.add("view", 3);
            settings.add("buttontext", $("SignUpButtonText").value);
            settings.add("contentbuttontext", $("ContentButtonText").value);
            settings.add("buttonstyle", $("SignUpButtonStyle").value);
            settings.add("signuptext", $("EditSignUpText").value);
            settings.add("signedintext", $("EditSignedInText").value);
            settings.add("showaddcontent", $("SignUpShowAddContent").checked);
            settings.add("showsignin", $("SignUpShowSignIn").checked);
            settings.add("createuser", $("SignUpCreateUser").checked);
            return;

        case "PopularityList":
            settings.add("count", $("MediaListCount").value);
            settings.add("showrss", $("MediaListShowRSS").checked);
            settings.add("showheaderimage", $("MediaListShowHeaderImage").checked);
            return;

        case "PageInPage":
            settings.add("pagepath", $("PageInPagePath").value);
            return;
            
        case "GoogleEarthRegion":
            settings.add("googlekey", $("GoogleEarthKey").value);
            settings.add("regionid", $("ParentRegionId").value);
            settings.add("startid", $("StartRegionId").value);
            return;
            
        case "GoogleEarth":
            settings.add("googlekey", $("GoogleEarthKey").value);
            settings.add("mapwidth", $("MapWidth").value);
            settings.add("mapheight", $("MapHeight").value);
            settings.add("heading", $("MapHeading").value);
            settings.add("tilt", $("MapTilt").value);
            settings.add("latitude", $("MapLat").value);
            settings.add("longitude", $("MapLong").value);
            settings.add("range", $("MapRange").value);
            settings.add("nav", $("MapNav").checked);
            return;                         

        case "Payment":
            settings.add("account", $("PaymentEditAccount").value);
            settings.add("username", $("PaymentEditUserName").value);
            settings.add("key", $("PaymentEditKey").value);
            settings.add("email", $("PaymentEditEmail").value);
            settings.add("gateway", $("PaymentEditGateway").value);
            settings.add("live", $("PaymentEditLive").checked);
            settings.add("headerformat", $("PaymentEditHeader").value);
            settings.add("payfields", $("PaymentEditFields").value);
            settings.add("descriptiontext", $("PaymentEditDescription").value);
            return;

        case "PageField":
            settings.add("fieldpath", $("EditFieldPath").value);
            return;
            
        case "ShowSpot":
            settings.add("portal", $("ShowSpotPortal").checked);
            settings.add("portalroot", $("ShowSpotRoot").value);
            settings.add("datasource", $("ShowSpotData").value);
            return;

        case "PlanetsNu":
            settings.add("datasource", $("PlanetsNuData").value);
            return;                        
            
        case "MediaList":
            if ($("MediaListFullView").checked)
                settings.add("view", 1);
            if ($("MediaListIconView").checked)
                settings.add("view", 2);
            if ($("MediaListTitleView").checked)
                settings.add("view", 3);
//            if ($("MediaListSlideView").checked)
//                settings.add("view", 4);
//            if ($("MediaListExploreView").checked)
//                settings.add("view", 5);
            if ($("MediaListFullFeatureView").checked)
                settings.add("view", 6);
                
            if ($("MediaListDateOrder").checked)
                settings.add("orderby", 0);
            if ($("MediaListTitleOrder").checked)
                settings.add("orderby", 1);
//            if ($("MediaListPopularityOrder").checked)
//                settings.add("orderby", 2);                

            settings.add("listcolumns", $("MediaListListColumns").value);
            settings.add("listpadding", $("MediaListListPadding").value);

            if ($("MediaListListView").checked) {
                settings.add("showheaderimage", $("MediaListShowHeaderImage").checked);
                settings.add("showimage", $("MediaListShowImage").checked);
                settings.add("showdescription", $("MediaListShowDescription").checked);
                settings.add("showdate", $("MediaListShowDate").checked);
                settings.add("showlocation", $("MediaListShowLocation").checked);
                //settings.add("showviews", $("MediaListShowViews").checked);
                settings.add("showuser", $("MediaListShowUser").checked);
                settings.add("showtopics", $("MediaListShowTopics").checked);
                settings.add("showspecific", $("MediaListShowTypeSpecific").checked);
                settings.add("showborder", $("MediaListShowBorder").checked);
                settings.add("showlisttitle", $("MediaListShowTitle").checked);
                settings.add("showmoredetails", $("MediaListShowMoreDetails").checked);
                settings.add("listtitleformat", $("MediaListListTitleFormat").value);
                settings.add("imagesize", $("MediaListImageSizeSelector").value);
                settings.add("squareimages", $("MediaListSquareImages").checked);
            }
            settings.add("count", $("MediaListCount").value);
            settings.add("starton", $("MediaListStartOn").value);

            if ($("UseSearchTitle")) {
                settings.add("usesearchtitle", $("UseSearchTitle").checked);
                settings.add("enablepaging", $("EnablePaging").checked);
                settings.add("showresultcount", $("ShowSearchResultCount").checked);
                settings.add("showsearchpath", $("ShowSearchPath").checked);
                settings.add("showsortoptions", $("ShowSortOptions").checked);
            }
            else {
                featureEdit.readContentSelection(settings);
            }
            settings.add("showrss", $("MediaListShowRSS").checked);
            return;     

        case "Forum":
            settings.add("forumchannel", $("ForumChannel").value);
            settings.add("forumtitle", $("ForumTitle").value);
            settings.add("description", $("ForumDescription").value);
            settings.add("bottommargin", $("ForumBottomMargin").checked);
            settings.add("showtableheader", $("ForumShowTableHeader").checked);
            return;
            
        case "Download":
            settings.add("src", $("EditDownloadSource").value);
            settings.add("buttontext", $("DownloadButtonText").value);
            settings.add("counter", $("DownloadCounterName").value);
            settings.add("showcount", $("DownloadShowCount").checked);
            settings.add("showbutton", $("DownloadShowButton").checked);
            return;
            
        case "BuildSite":
            settings.add("rootdomain", $("BuildSiteRootDomain").value);
            settings.add("startup", $("BuildSiteStartup").value);
            settings.add("realestate", $("BuildSiteRealEstateStartup").value);
            return;
                    
        case "EditStyle":
            settings.add("designurl", $("EditStyleDesignUrl").value);
            return;

        case "StyleRender":
            settings.add("designurl", $("EditStyleDesignUrl").value);
            return;

        case "ThemeList":
            settings.add("designurl", $("EditStyleDesignUrl").value);
            return;            

        case "ShowMedia":
            if ($("PicViewNone").checked)
                settings.add("picview", 0);        
            if ($("PicViewHorizontal").checked)
                settings.add("picview", 1);
            if ($("PicViewVertical").checked)
                settings.add("picview", 2);    
            if ($("PicViewSlideshow").checked)
                settings.add("picview", 3);
            if ($("ContentViewFull").checked)
                settings.add("view", 1);
            if ($("ContentViewShort").checked)
                settings.add("view", 2);
            if ($("ContentViewFeature").checked)
                settings.add("view", 3);
            if ($("ContentViewFeature").checked)
                settings.add("view", 3);
            settings.add("showdate", $("ShowMediaShowDate").checked);
            return;

        case "Image":
            settings.add("showborder", $("FeatureImageShowBorder").checked);
            settings.add("src", $("EditImageSource").value);
            settings.add("version", $("FeatureImageVersion").value);
            settings.add("caption", $("FeatureImageCaption").value);
            settings.add("link", $("ImageLink").value);
            if ($("ImageLinkTarget").checked)
                settings.add("linktarget", "_blank");
            
            if ($("ImageAlignLeft").checked)
                settings.add("align", "left");
            if ($("ImageAlignCenter").checked)
                settings.add("align", "center");
            if ($("ImageAlignRight").checked)
                settings.add("align", "right");            
            return;

        case "Video":
            settings.add("src", $("EditVideoSource").value);
            settings.add("videowidth", $("EditVideoWidth").value);
            settings.add("videoheight", $("EditVideoHeight").value);
            if ($("VideoAlignLeft").checked)
                settings.add("align", "left");
            if ($("VideoAlignCenter").checked)
                settings.add("align", "center");
            if ($("VideoAlignRight").checked)
                settings.add("align", "right");
            return;       
            
        case "Audio":
            settings.add("src", $("EditAudioSource").value);
            if ($("AudioAlignLeft").checked)
                settings.add("align", "left");
            if ($("AudioAlignCenter").checked)
                settings.add("align", "center");
            if ($("AudioAlignRight").checked)
                settings.add("align", "right");
            return;       

        case "Tree":
            settings.add("treeroot", $("TreeEditSelectorPath").value);
            settings.add("roottitle", $("TreeRootTitle").checked);
            settings.add("showroot", $("TreeShowRoot").checked);

            if ($("TreeSizeSmall").checked)
                settings.add("treesize", 1);
            if ($("TreeSizeNormal").checked)
                settings.add("treesize", 2);
            if ($("TreeSizeBig").checked)
                settings.add("treesize", 3);

            featureEdit.readContentSelection(settings);
            
            return;
            
        case "Map":                  
            settings.add("mapheight", $("MapHeight").value);
            settings.add("mapwidth", $("MapWidth").value);
            settings.add("zoom", $("MapZoom").value);
            settings.add("address", $("MapAddress").value);
            settings.add("markers", $("MapMarkers").value);
            settings.add("showcontrols", $("MapShowControls").checked);  
            return;  
            
        case "Comments":
            settings.add("requireapproval", $("CommentsRequireApproval").checked);
            settings.add("showwebsite", $("CommentsShowWebsite").checked);
            settings.add("showlocation", $("CommentsShowLocation").checked);
            settings.add("buttonstyle", $("CommentButtonStyle").value);
            if ($("CommentBoxVerticalView").checked)
                settings.add("view", 0);
            if ($("CommentBoxHorizontalView").checked)
                settings.add("view", 1);
            return;
            
        case "BackNext": 
            settings.add("showitemtitle", $("BackNextShowItemTitle").checked);

            if ($("BackNextHor").checked)
                settings.add("view", 0);
            if ($("BackNextVert").checked)
                settings.add("view", 1);
            return;                       
    
        case "MediaActions":
            settings.add("showpromote", $("ActionsShowPromote").checked);
            settings.add("showemail", $("ActionsShowEmail").checked);
            settings.add("showenquire", $("ActionsShowEnquire").checked);
            settings.add("showdelicious", $("ActionsShowDelicious").checked);
            settings.add("showdigg", $("ActionsShowDigg").checked);
            settings.add("showstumble", $("ActionsShowStumble").checked);
            settings.add("showdownload", $("ActionsShowDownload").checked);
            return;
            
        case "PropertySearch":
            settings.add("fieldwidth", $("FieldWidth").value);
            settings.add("propertiesfor", $("PropertiesForOption").value);
            settings.add("showforoption", $("ShowForOption").checked);
            settings.add("showminprice", $("ShowMinPrice").checked);
            settings.add("showmaxprice", $("ShowMaxPrice").checked);
            settings.add("showbedrooms", $("ShowBedrooms").checked);
            settings.add("showbathrooms", $("ShowBathrooms").checked);
            settings.add("showsize", $("ShowSize").checked);
            settings.add("showlandsize", $("ShowLandSize").checked);        
            settings.add("showbuiltafter", $("ShowBuiltAfter").checked);        
            return;
            
        case "ContactBox":
            settings.add("toemail", $("ContactBoxEditToEmail").value);
            settings.add("boxheight", $("ContactBoxEditHeight").value);
            settings.add("buttonstyle", $("ContactBoxButtonClass").value);
            settings.add("buttontext", $("ContactBoxButtonText").value);
            settings.add("suggested", $("ContactBoxEditSuggested").value);
            settings.add("showphone", $("ContactBoxShowPhone").checked);
            settings.add("showmessage", $("ContactBoxShowMessage").checked);
            settings.add("showchecks", $("ContactBoxSuggestedChecks").checked);
            if ($("ContactBoxVerticalView").checked)
                settings.add("view", 0);
            if ($("ContactBoxHorizontalView").checked)
                settings.add("view", 1);
            return;

        case "BasicForm":
            settings.add("toemail", $("BasicFormEditToEmail").value);
            settings.add("formfields", $("BasicFormFormFields").value);
            settings.add("boxwidth", $("BasicFormBoxWidth").value);
            settings.add("titlewidth", $("BasicFormTitleWidth").value);
            settings.add("buttonstyle", $("BasicFormButtonClass").value);
            settings.add("buttontext", $("BasicFormButtonText").value);
            settings.add("navigateto", $("BasicFormNavigateTo").value);
            settings.add("createuser", $("BasicFormCreateUser").checked);
            settings.add("captcha", $("BasicFormShowCaptcha").checked);
            return;
            
        case "RSS":
            settings.add("feedurl", $("RSSFeedUrl").value);
            settings.add("blockwords", $("RSSBlockwords").value);
            settings.add("listtitleformat", $("RSSListTitleFormat").value);
            settings.add("showlink", $("RSSShowLink").checked);
            settings.add("showenclosure", $("RSSShowEnclosure").checked);
            settings.add("showdescription", $("RSSShowDescription").checked);
            settings.add("showdate", $("RSSShowDate").checked);
            settings.add("count", $("RSSCount").value);       
            return;
            
        case "SlideShow":
            settings.add("images", $("SlideshowImages").value);
            settings.add("imageheight", $("SlideshowHeight").value);
            settings.add("imagewidth", $("SlideshowWidth").value);
            settings.add("delay", $("SlideshowDelay").value);
            return;
            
        case "BuyCredit":
            if ($("LaraAccountStore").checked)
                settings.add("store", "lara");
            if ($("MailAccountStore").checked)
                settings.add("store", "mail");
            return;

        case "CreateAccount":
            if ($("LaraAccountStore").checked)
                settings.add("store", "lara");
            if ($("MailAccountStore").checked)
                settings.add("store", "mail");
            return;
    }   
};

     
function laraImage() {  };

laraImage.prototype = {
    serverPath: "/_ui/editimage",
    showTools: function() {
        this.open = true;
                        
        //Show Action Bar (Style classes are in slayout.css)
        var pos = ui.findPos(this.featurebar);
        this.actionBar = $new("div");
        this.actionBar.className = "FeatureActionBar";
        this.actionBar.style.top = (pos.y) + "px";
        this.actionBar.style.left = (pos.x) + "px";
        
        this.actionMenu = $new("div");
        
        var settings = $new("a");
        settings.className = "FeatureActionLink";
        settings.innerHTML = "Settings";
        settings.onclick = function() { editImg.showSettings(); };        
        var resize = $new("a");
        resize.className = "FeatureActionLink";
        resize.innerHTML = "Resize";
        resize.onclick = function() { editImg.resize(); };
        var revert = $new("a");
        revert.className = "FeatureActionLink";
        revert.innerHTML = "Full Size";
        revert.onclick = function() { editImg.revert(); };        
        var save = $new("a");
        save.className = "FeatureActionLink";        
        save.onclick = function() { editImg.exitImageEdit(); };
        save.innerHTML = "OK";       
            
        this.actionMenu.appendChild($text("Image Tools: "));
        this.actionMenu.appendChild(settings);
        this.actionMenu.appendChild($text(" - "));        
        this.actionMenu.appendChild(resize);
        this.actionMenu.appendChild($text(" - "));
        this.actionMenu.appendChild(revert);        
        this.actionMenu.appendChild($text(" - "));
        this.actionMenu.appendChild(save);
    
        //Action Save Menu
        this.saveMenu = $new("div");
        this.saveMenu.style.display = "none";
        this.saveMenuText =  $new("span");
        this.saveMenuText.innerHTML = "Action: ";
        
        this.saveMenuSave = $new("a");
        this.saveMenuSave.className = "FeatureActionLink";
        this.saveMenuSave.innerHTML = "Save";
        this.saveMenuCancel = $new("a");
        this.saveMenuCancel.className = "FeatureActionLink";        
        this.saveMenuCancel.innerHTML = "Cancel";            
            
        this.saveMenu.appendChild(this.saveMenuText);
        this.saveMenu.appendChild(this.saveMenuSave);
        this.saveMenu.appendChild($text(" - "));                
        this.saveMenu.appendChild(this.saveMenuCancel);
        
        this.actionBar.appendChild (this.actionMenu);
        this.actionBar.appendChild(this.saveMenu);
        document.body.appendChild(this.actionBar);    
        
        if (this.actionBar.offsetWidth < this.featurebar.offsetWidth)
            this.actionBar.style.width = this.featurebar.offsetWidth - 8 + "px"; //-8 for padding and borders
        
    },
    refresh: function() {
        if (!this.featureId)
            return;
            
        this.pageFeature = $(this.featureId);
        this.img = $("Img" + this.featureId); 
        this.featurebar = $("FBar" + this.featureId);
        
        //reposition (in case size changed)
        var pos = ui.findPos(this.featurebar);
        this.actionBar.style.top = (pos.y) + "px";
        this.actionBar.style.left = (pos.x) + "px";        
        this.actionBar.style.width = "";
        
        if (this.actionBar.offsetWidth < this.featurebar.offsetWidth)
            this.actionBar.style.width = this.featurebar.offsetWidth - 8 + "px"; //-8 for padding and borders

    },
    hide: function() {
        if (this.actionBar)
            this.actionBar.style.display = "none";
    },
    show: function() {
        if (this.actionBar)
            this.actionBar.style.display = "block";
    },    
    exitImageEdit: function() {
        if (this.open) {
            if (this.frame)
                this.resizeCancel();

            document.body.removeChild(this.actionBar);
                
            this.open = false;
            this.featureId = null;
        }
    },  
    showSettings: function() {
        lara.loadWindow(FEATURE_OPTIONS, this.featureOptionsPath);  
    },   
    revert: function() {
        if (!this.img)
            return;
                
        //already on base image.
        if (this.img.src == this.orig)
            return;
            
        if (!confirm("Are you sure you want to go back to the original image?  All image edits will be undone."))
            return;
                                    
        var data = new dataObject();
        data.add("FeatureId", this.featureId);
        data.add("Locator", this.locator);
        data.add("SourceImage", this.orig);
        data.add("PreviousImage", this.img.src);
        data.add("Save", "true");
        
        this.displayWidth = this.pageFeature.offsetWidth;
        if ($("ImgContainer" + this.featureId))
            this.displayWidth = $("ImgContainer" + this.featureId).offsetWidth;
        data.add("Width", this.displayWidth);
        
        lara.indicateOn();

        lara.request(this.serverPath + ":AutoResize",  data, function(result) { editImg.processRevert(result); });                                        
    },        
    processRevert: function(result) {     
        if (result.success) {
            this.img.src = result.src;
            this.img.style.height = "";
            this.img.style.width = "";         
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();         
    },       
    autoResize: function(featureId, locator, oldsrc, src, width) {
    
        var data = new dataObject();
        data.add("FeatureId", featureId);
        data.add("Locator", locator);
        data.add("SourceImage", src);
        data.add("PreviousImage", oldsrc);
        data.add("Width", width);

        lara.request(this.serverPath + ":AutoResize",  data, function(result) { featureEdit.autoResizeComplete(result); });    
    },
    resize: function() {
        
        if (!this.img)
            return;
        
        this.saveMenuText.innerHTML = "Resize: ";
        this.saveMenuSave.onclick = function() { editImg.resizeSave(); };
        this.saveMenuCancel.onclick = function() { editImg.resizeCancel(); };

        //Show save menu
        this.actionMenu.style.display = "none";
        this.saveMenu.style.display = "block";

        this.size = { width: this.img.offsetWidth, height: this.img.offsetHeight };

        this.frame = $new("div");
        this.frame.className = "ImageResizerFrame";
        this.frame.style.width = this.size.width + "px";
        this.frame.style.height = this.size.height + "px";

        this.positionFrame();
    
        var mleft = $new("div");
        mleft.className = "MarqueeLeft MarqueeVert";
        var mright = $new("div");
        mright.className = "MarqueeRight MarqueeVert";
        var mtop = $new("div");
        mtop.className = "MarqueeTop MarqueeHor";
        var mbottom = $new("div");
        mbottom.className = "MarqueeBottom MarqueeHor";
        this.frame.appendChild(mleft);
        this.frame.appendChild(mright);
        this.frame.appendChild(mtop);
        this.frame.appendChild(mbottom);
    
        this.resizer = $new("div");
        this.resizer.className = "ImageResizer";

        this.maxWidth = this.pageFeature.offsetWidth;
        if ($("ImgContainer" + this.featureId))
            this.maxWidth = $("ImgContainer" + this.featureId).offsetWidth;

	    this.resizer.onmousedown = function(ev){
		    
	        //Setup the move and drop events
	        editImg.resizing = true;
	        editImg.startpos = dragdrop.mousePos(ev);
            ui.disableSelection();
		    document.onmousemove = function(ev) { editImg.mouseMove(ev); };
            document.onmouseup = function(ev) { editImg.mouseUp(ev); }; 		
		    return false;
	    };
	    
	    this.frame.appendChild(this.resizer);
        document.body.appendChild(this.frame);
    
    },
    positionFrame: function() {
        var pos = ui.findPos(this.img);
        
        this.frame.style.top = pos.y + "px";
        this.frame.style.left = pos.x + "px";
                    
    },
    resizeCancel: function() {
        this.img.style.width = "";
        this.img.style.height = "";
        this.saveMenu.style.display = "none";
        this.actionMenu.style.display = "block";
        if (this.frame)
            document.body.removeChild(this.frame);
        this.frame = null;
    },
    resizeSave: function() {
       
        var data = new dataObject();
        data.add("FeatureId", this.featureId);
        data.add("Locator", this.locator);
        data.add("SourceImage", this.orig);
        data.add("CurrentImage", this.img.src);
        data.add("Width", this.size.width);
        data.add("Height", this.size.height);

        lara.indicateOn();        
        lara.request(this.serverPath + ":Resize",  data, function(result) { editImg.processSaveResize(result); });
              
    },
    processSaveResize: function(result)
    {     
        if (result.success) {
        
            this.img.src = result.src;
            
            this.saveMenu.style.display = "none";
            this.actionMenu.style.display = "block";
            document.body.removeChild(this.frame);    
            this.frame = null;          
//            this.img.style.height = "";
//            this.img.style.width = "";            
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();         
    },    
    mouseMove: function(ev){
	    ev = ev || window.event;
	    
	    var pos = dragdrop.mousePos(ev);
        
	    if (this.resizing)
	    {
	        //we resize based on the width for equal
	        //always maintaining aspect ratio
	        //if (this.size.width >= this.size.height) {
    	        var ratio = this.size.height/this.size.width;            
                var width = this.size.width - (this.startpos.x-pos.x);
                
                //Don't resize past the width of the feature area.
                if (width > this.maxWidth)
                    width = this.maxWidth;
                    
                var height = width * ratio;
//	        } else {
//    	        var ratio = this.size.width/this.size.height;            
//                var height = this.size.height - (this.startpos.y-pos.y);
//                var width = height * ratio;
//	        }

            this.curSize = { width: width, height:height };

            this.img.style.width = width + "px";
            this.img.style.height = height + "px";
        
            this.frame.style.width = width + "px";
            this.frame.style.height = height + "px";            
            this.positionFrame();

		    return false;
	    }		
    },
    mouseUp: function(ev){
	    ev = ev || window.event;
	    
	    if (this.resizing)  {
	        this.size = this.curSize;
    	    this.resizing = false;
	        document.onmousemove = null;
            document.onmouseup = null;
            ui.enableSelection();   	
        }
    }         
};
var editImg = new laraImage();

