function geoAdmin() {  };

geoAdmin.prototype = {
    init: function () {
        this.admin = $l("AdminScreens");
        //this.activityLink = $l("ActivityLink");
        //this.activityLink.onclick = function() { admin.selectLink(this.id); admin.load(ACTIVITY); return false; };

        if ($l("GoLiveLink")) {
            this.goliveLink = $l("GoLiveLink");
            this.goliveLink.onclick = function () { admin.selectLink("SettingsLink"); admin.showUpgrades(); return false; };
        }

        this.publishLink = $l("PublishLink");
        this.libraryLink = $l("LibraryLink");
        this.pagesLink = $l("PagesLink");

        if ($l("SettingsLink"))
            this.settingsLink = $l("SettingsLink");
        if ($l("DesignLink"))
            this.designLink = $l("DesignLink");
        if ($l("AccountLink"))
            this.accountLink = $l("AccountLink");
        this.editLink = $l("EditModeLink");
        this.layoutLink = $l("ChangeLayoutLink");
        this.pagesLink = $l("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]) {
                try {
                    this.screens[i].close();
                }
                catch (e) {
                    //invalid screen
                }
            }
        }
        this.selectLink("none");
    },
    close: function (config) {
        if (this.screens[config.id]) {
            this.screens[config.id].close();
            this.selectLink("none");
        }
    },
    selectLink: function (adminId) {
        if (!$l("PublishLink"))
            return;

        //$l("ActivityLink").className = "aaa aPeople";
        $l("PublishLink").className = "aaa aAdd";
        $l("LibraryLink").className = "aaa aFile";
        $l("PagesLink").className = "aaa aDrop";

        if ($l("SettingsLink"))
            $l("SettingsLink").className = "aaa aSearch";

        if ($l("AccountLink"))
            $l("AccountLink").className = "aaa aPeople";

        if ($l("MarketingLink"))
            $l("MarketingLink").className = "aaa aPeople";

        //if (adminId == "ActivityLink")
        //    $l("ActivityLink").className = "aaas aPeople";
        //else {
        if ($l(adminId))
            $l(adminId).className = "aaas aDrop";

        if (adminId == "PublishLink")
            $l("PublishLink").className = "aaas aAdd";

        if (adminId == "SettingsLink")
            $l("SettingsLink").className = "aaas aSearch";

        if (adminId == "AccountLink")
            $l("AccountLink").className = "aaas aPeople";

        if (adminId == "MarketingLink")
            $l("MarketingLink").className = "aaas aPeople";

        if (adminId == "LibraryLink")
            $l("LibraryLink").className = "aaas aFile";

        //}

    },
    disableAdmin: function (disabled) {
        //$l("ActivityLink").disabled = disabled;
        if ($l("PublishLink")) {
            $l("PublishLink").disabled = disabled;
            $l("LibraryLink").disabled = disabled;
            $l("PagesLink").disabled = disabled;
            $l("EditModeLink").disabled = disabled;
            $l("ChangeLayoutLink").disabled = disabled;
            //$l("AddStuffLink").disabled = disabled;
        }
        if ($l("SettingsLink"))
            $l("SettingsLink").disabled = disabled;
        if ($l("DesignLink"))
            $l("DesignLink").disabled = disabled;
        if ($l("GoLiveLink"))
            $l("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();

        $l("AdminToolbar").style.display = "none";

        design.panel = $l("AdminPanel");
        design.load();
    },
    viewSite: function () {
        if (this.editMode) {
            this.showEdit(false);
            editImg.exitImageEdit();
            this.editMode = false;
            $l("EditModeLink").innerHTML = " <span>Edit Page »</span> ";
            $l("EditModeLink").title = "Add or change the text, images and other features on the current page.";
            $l("ChangeLayoutLink").style.display = "none";
            //$l("AddStuffLink").style.display = "none";
            $l("PageDetail").style.display = "none";
            //$l("ActivityLink").style.display = "";
            $l("PagesLink").style.display = "";
            $l("LibraryLink").style.display = "";
            if ($l("DesignLink"))
                $l("DesignLink").style.display = "";
            if ($l("SettingsLink"))
                $l("SettingsLink").style.display = "";
            if ($l("AccountLink"))
                $l("AccountLink").style.display = "";
            if ($l("MarketingLink"))
                $l("MarketingLink").style.display = "";
            $l("PublishLink").style.display = "";

        }
        else {
            this.closeAll();
            this.showEdit(true);
            this.selectLink("none");
            this.editMode = true;
            $l("EditModeLink").innerHTML = " <span>« View Page</span> ";
            $l("EditModeLink").title = "Exit edit page mode and view your site.";
            $l("ChangeLayoutLink").style.display = "";
            //$l("AddStuffLink").style.display = "";
            $l("PageDetail").style.display = "";
            //$l("ActivityLink").style.display = "none";
            $l("PagesLink").style.display = "none";
            $l("LibraryLink").style.display = "none";
            if ($l("DesignLink"))
                $l("DesignLink").style.display = "none";
            if ($l("SettingsLink"))
                $l("SettingsLink").style.display = "none";
            if ($l("AccountLink"))
                $l("AccountLink").style.display = "none";
            if ($l("MarketingLink"))
                $l("MarketingLink").style.display = "none";
            $l("PublishLink").style.display = "none";
        }
    },
    loadLayoutEditor: function (addMode) {
        editImg.exitImageEdit();

        siteLayout.header = $l("HeaderContent");
        siteLayout.footer = $l("FooterContent");
        siteLayout.page = $l("PageContent");
        siteLayout.path = $l("CurrentPath").value;
        siteLayout.toolbar = $l("AdminToolbar");
        siteLayout.info = $l("PageDetail").innerHTML;
        siteLayout.wrapper = $l("Wrapper");

        siteLayout.closed = function () { admin.exitLayoutEditor(); };

        //$l("AddStuffLink").style.display = "none";
        $l("ChangeLayoutLink").style.display = "none";
        $l("PageDetail").style.display = "none";
        $l("EditModeLink").style.display = "none";
        if ($l("LaraLogo"))
            $l("LaraLogo").style.display = "none";
        if ($l("GoLiveLink"))
            $l("GoLiveLink").style.display = "none";
        if ($l("AccountLink"))
            $l("AccountLink").style.display = "none";
        if ($l("MarketingLink"))
            $l("MarketingLink").style.display = "none";

        //Disable menu drop downs, explore etc. 
        ui.disable();

        siteLayout.load(addMode);
    },
    exitLayoutEditor: function () {
        //$l("AddStuffLink").style.display = "";  
        $l("ChangeLayoutLink").style.display = "";
        $l("EditModeLink").style.display = "";
        $l("PageDetail").style.display = "";
        if ($l("LaraLogo"))
            $l("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); });
            $l(id).parentNode.removeChild($l(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 = $l("FBar" + id);
            editImg.locator = locator;
            editImg.featureOptionsPath = editfeaturepath;
            editImg.pageFeature = $l(id);

            if ($l("Img" + id))
                editImg.img = $l("Img" + id);

            editImg.showTools();

            if ($l("ImgSrc" + id))
                editImg.orig = $l("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 () {
        if ($l("AdminPanel")) {
            $l("AdminPanel").style.display = "none";
            document.body.style.paddingTop = "0";
        }
        editImg.hide();
    },
    show: function () {
        if ($l("AdminPanel")) {
            $l("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 = $l(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 ($l("ThemeStyle"))
        var styleSheet = "<link id='ThemeStyle' href='" + $l("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 = $l(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 = $l(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 cleanHtmlResult(s);
};

function cleanHtmlResult(s) {
    //chrome adds these
    s = s.replace(/ style="color: rgb(0, 0, 0); " /g, "");
    s = s.replace(/ color: rgb(0, 0, 0); /g, "");
    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 = $l("LibraryItemMenu");
        this.folderMenu = $l("LibraryFolderMenu");
        this.itemStatus = $l("LibraryItemStatus");
        this.editMenu = $l("LibraryEditMenu");

        this.crumb = $l("FolderCrumb");
        this.contents = $l("FolderContents");

        this.statusIcon = $l("SelectedIcon");
        this.statusCount = $l("SelectedCount");
        this.statusTitle = $l("SelectedTitle");
        this.statusDesc = $l("SelectedDescription");
        this.statusURI = $l("SelectedURI");

        //Clipboard output
        this.clipdiv = $l("LibraryClipBoard");
        this.clipItems = $l("LibraryClipBoardItems");
        this.clipboard = [];
        this.multiselect = [];

        //What to do if we choose something
        this.action = $l("SelectAction").value;
        if ($l("SelectActionTarget").value.length > 0)
            this.target = $l($l("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);

            //$l("CurrentFolderStatus").innerHTML = result.ItemStatus;        

            this.select(null, result.newId);

        }
        else {
            alert(result.error);
        }
        library.indicateOff();
    },
    indicateOn: function () {
        $l("FolderContentsCell").className = "LibraryIndicator";
    },
    indicateOff: function () {
        $l("FolderContentsCell").className = "";
    },
    showUpload: function (uploadType) {
        if (uploadType == "Single") {
            $l("SingleFileUploadChoice").checked = true;
            $l("MultiFileUploadChoice").checked = false;
            $l("UploadSingleFileForm").style.display = "block";
            $l("UploadMultiFileForm").style.display = "none";
        }
        else {
            $l("SingleFileUploadChoice").checked = false;
            $l("MultiFileUploadChoice").checked = true;
            $l("UploadSingleFileForm").style.display = "none";
            $l("UploadMultiFileForm").style.display = "block";
            this.showAddFile();
        }
    },
    showAddFile: function () {
        if ($l("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 = $l("CurrentRootFolderId").value;
        //            if ($l("R" + folderId)) {    
        //                $l("R" + curFolderId).className = "RootFolder";
        //                $l("R" + folderId).className = "RootFolderSelected";
        //            }
        //            $l("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();

            //            $l("LibrarySizeStatus").innerHTML = result.librarySize;
            //            if (result.disableLibrary == "true") {
            //                $l("LibraryExceeded").innerHTML = result.librarySize;
            //                $l("LibraryExceeded").style.display = "block";
            //                $l("UploadMultiFileForm").style.display = "none";
            //                $l("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;

            //$l("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 ($l("SelectActionExtension"))
                selectedURI = selectedURI.substring(0, selectedURI.length - 4) + $l("SelectActionExtension").value;

            switch (this.action) {
                case "Eval":
                    eval($l("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";

        $l("SelectedTitle").innerHTML = "<input style='width:300px;' class='MediumTextBox' id='TitleEdit' type='text' value='" + this.selected.title + "' />";
        $l("SelectedDescription").innerHTML = "<input style='width:300px;' class='MediumTextBox' id='DescriptionEdit'  type='text' value='" + this.selected.description + "' />";

        $l("LibraryEditMenu").style.display = "block";
        $l("LibraryItemMenu").style.display = "none";
    },
    editPath: function () {

        this.editMode = "path";

        var path = this.selected.uri.substr(this.selected.uri.indexOf("/_library/") + 9);

        $l("SelectedTitle").innerHTML = "<input style='width:300px;' class='MediumTextBox' id='LibraryPathEdit' type='text' value='" + path +"' />";
        $l("SelectedDescription").innerHTML = "Warning, changing the path can cause broken links if this item is in use.";

        $l("LibraryEditMenu").style.display = "block";
        $l("LibraryItemMenu").style.display = "none";
    },
    save: function () {
        if (this.editMode == "path")
            return this.saveEditPath();

        this.selected.title = $l("TitleEdit").value;
        this.selected.description = $l("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", $l("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);
        $l("LibraryEditMenu").style.display = "none";
        $l("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 ($l('MediaFile').value) {
            library.indicateOn();

            //when the frame finishes loading our upload is complete.
            var UploadFrame = $l('AddMediaUploadFrame');

            if (typeof document.addEventListener == "function")
                UploadFrame.addEventListener("load", function () { AddMediaFileUploadComplete(); return true; }, false);
            else
                UploadFrame.attachEvent("onload", function () { AddMediaFileUploadComplete(); return true; }); //ie

            $l('UploadMediaFile').action = BASE_URL + "/_ui/libraryupload?FolderId=" + this.folder.id;
            $l('AddMediaFileButton').disabled = true;

            try {
                $l('UploadMediaFile').submit();
            }
            catch (e) {
                //sometimes IE gives a "access denied" error.  Wait 1/4 second and try again.
                setTimeout(function () { $l('UploadMediaFile').submit(); return true; }, 250);
            }
            $l("UploadSingleFileForm").style.display = "none";
            $l("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[$l("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 ($l('AddMediaUploadFrame').contentWindow.document.body) {
        result = $l('AddMediaUploadFrame').contentWindow.document.body.innerHTML;
        if (result.indexOf('Error') >= 0)
            alert(result);
    }

    ui.showTab("BrowseScreen", 0);
    library.browse(library.folder.id);

    $l('UploadMediaFile').reset();
    $l('AddMediaFileButton').disabled = false;
    $l("UploadSingleFileForm").style.display = "block";
    $l("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 ($l("ThemeStyle"))
            $l("ThemeStyle").parentNode.removeChild($l("ThemeStyle"));

        this.home = $l("DesignHome");
        this.browse = $l("BrowseStyle");
        this.addStyle = $l("AddStylesheetForm");
        this.publishButton = $l("DesignPublish");
        this.selectFile = $l("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) {
            $l("EditMaster").innerHTML = result.html;
            this.editCompId = result.compId;
            this.home.style.display = "none";
            $l("EditMaster").style.display = "block";
            this.cancelMakeMaster();
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    cancelMaster: function () {
        $l("EditMaster").innerHTML = "";
        $l("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", $l("CompTitle").value);
        data.add("css", $l("CompCSS").value);

        //Stylesets
        var stylesets = "";
        var styleBoxes = $l("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) {
        $l("EditMasterButtons").style.display = "none";
        $l("Variants").style.display = "none";
        $l("StyleSets").style.display = "none";
        $l("VariantEdit" + variantId).style.display = "block";
    },
    okVariant: function (variantId) {
        var data = new dataObject();
        data.add("variantId", variantId);
        data.add("display", $l("Edit" + variantId + "0").value);
        data.add("value1", $l("Edit" + variantId + "1").value);
        data.add("value2", $l("Edit" + variantId + "2").value);
        data.add("value3", $l("Edit" + variantId + "3").value);
        data.add("value4", $l("Edit" + variantId + "4").value);
        data.add("value5", $l("Edit" + variantId + "5").value);
        data.add("value6", $l("Edit" + variantId + "6").value);
        data.add("value7", $l("Edit" + variantId + "7").value);
        data.add("value8", $l("Edit" + variantId + "8").value);

        lara.indicateOn();
        lara.request(this.serverPath + ":SaveVariant", data, function (result) { cdesign.processEditVariant(result); });

    },
    cancelVariant: function (variantId) {
        $l("EditMasterButtons").style.display = "block";
        $l("Variants").style.display = "block";
        $l("StyleSets").style.display = "block";
        $l("VariantEdit" + variantId).style.display = "none";
    },
    processEditVariant: function (result) {
        if (result.success) {
            $l("Variants").innerHTML = result.variants;
            $l("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) {
            $l("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) {
            $l("StyleSheetList").innerHTML = result.styleList;
            $l("Style" + result.styleId).parentNode.removeChild($l("Style" + result.styleId));
            $l("Component" + result.styleId).parentNode.removeChild($l("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 = $l("Component" + styleId);
        this.editCss = $l("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", $l("BrowseStyleId").value);

        lara.request(this.serverPath + ":LoadStyle", data, function (result) { cdesign.processLoadStyle(result); });
    },
    processLoadStyle: function (result) {
        if (result.success) {
            $l("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", $l("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", $l("SelectedColorId").value);
        data.add("styleId", $l("BrowseStyleId").value);

        lara.request(this.serverPath + ":SaveSelectedStyle", data, function (result) { cdesign.processSaveSelectedStyle(result); });
    },
    processSaveSelectedStyle: function (result) {
        if (result.success) {

            var editPage = $l("Component" + result.styleId);
            var div = $new("div");
            div.innerHTML = result.styleEdit;
            editPage.parentNode.replaceChild(div, editPage);

            $l("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 = $l("ComponentTypeId" + styleId).value;
            if (ctypeId == "3" && !first) {
                css = this.modifyFeatureCss(css, styleId);
                first = false;
            }
            var img = $l("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(" + $l("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 ($l(styleId))
            $l(styleId).parentNode.removeChild($l(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++) {
            $l(styleIds[j]).parentNode.removeChild($l(styleIds[j]));
        }
    },
    loadTheme: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("id", $l("SelectTheme").value);

        lara.request(this.serverPath + ":LoadTheme", data, function (result) { cdesign.processLoadTheme(result); });
    },
    showMakePublic: function (id) {
        if (!this.loaded)
            this.load();

        var makePublic = $l("MakePublic");
        makePublic.parentNode.removeChild(makePublic);
        document.body.appendChild(makePublic);

        makePublic.style.display = "block";
        ui.centerElement("MakePublic");

        dragdrop.makeDraggable($l("MakePublic"), $l("MakePublicHeader"));
    },
    cancelMakePublic: function () {
        $l("NewPublicName").value = "";
        $l("NewPublicDescription").value = "";
        $l("MakePublic").style.display = "none";
    },
    makePublic: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $l("NewPublicName").value);
        data.add("description", $l("NewPublicDescription").value);
        data.add("id", $l("SelectTheme").value);

        lara.request(this.serverPath + ":MakePublic", data, function (result) { cdesign.processMakePublic(result); });

    },
    processMakePublic: function (result) {

        if (result.success) {
            ui.showTab('DesignHome', 2);
            $l("PublicThemes").innerHTML = result.themes;
        }
        else {
            alert("Error: " + result.error);
        }
        this.cancelMakePublic();
        lara.indicateOff();
    },
    showMakeMaster: function (id) {
        if (!this.loaded)
            this.load();

        var makeMaster = $l("MakeMaster");
        makeMaster.parentNode.removeChild(makeMaster);
        document.body.appendChild(makeMaster);

        makeMaster.style.display = "block";
        ui.centerElement("MakeMaster");

        dragdrop.makeDraggable($l("MakeMaster"), $l("MakeMasterHeader"));
        $l("MakeMasterId").value = id;
    },
    cancelMakeMaster: function () {
        $l("MakeMasterId").value = "";
        $l("NewMasterName").value = "";
        $l("MakeMaster").style.display = "none";
    },
    makeMaster: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $l("NewMasterName").value);
        data.add("id", $l("MakeMasterId").value);

        lara.request(this.serverPath + ":MakeMaster", data, function (result) { cdesign.processEditMaster(result); });

    },
    showCopyTheme: function () {
        if (!this.loaded)
            this.load();

        var copyTheme = $l("CopyTheme");
        copyTheme.parentNode.removeChild(copyTheme);
        document.body.appendChild(copyTheme);

        copyTheme.style.display = "block";
        copyTheme.style.zIndex = 21;
        ui.centerElement("CopyTheme");

        dragdrop.makeDraggable($l("CopyTheme"), $l("CopyThemeHeader"));

    },
    cancelCopyTheme: function () {
        $l("NewThemeName").value = "";
        $l("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", $l("SelectTheme").value);

        lara.request(this.serverPath + ":DeleteTheme", data, function (result) { cdesign.processLoadTheme(result); });

    },
    copyTheme: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $l("NewThemeName").value);
        data.add("id", $l("SelectTheme").value);

        lara.request(this.serverPath + ":CopyTheme", data, function (result) { cdesign.processLoadTheme(result); });

    },
    processLoadTheme: function (result) {

        if (result.success) {
            $l("DesignTabData1").innerHTML = result.themes;
            $l("StyleEditPages").innerHTML = result.editPages;
            if (result.status == "1")
                $l("DeleteTheme").style.display = "none";
            else
                $l("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 = $l("AddStylesheet");
        addStyle.parentNode.removeChild(addStyle);
        document.body.appendChild(addStyle);

        addStyle.style.display = "block";
        addStyle.style.zIndex = 21;
        ui.centerElement("AddStylesheet");

        dragdrop.makeDraggable($l("AddStylesheet"), $l("AddStylesheetHeader"));

    },
    cancelNewStylesheet: function () {
        $l("AddStylesheet").style.display = "none";
    },
    styleTypeSelected: function () {
        $l("NewStyleTitle").value = $l("NewStyleType").options[$l("NewStyleType").selectedIndex].text;
    },
    saveNewStylesheet: function () {
        lara.indicateOn();

        var data = new dataObject();
        data.add("title", $l("NewStyleTitle").value);
        data.add("ctypeId", $l("NewStyleType").value);
        data.add("themeId", $l("SelectTheme").value);

        lara.request(this.serverPath + ":AddStyleSheet", data, function (result) { cdesign.processAddStyleSheet(result); });

    },
    processAddStyleSheet: function (result) {

        if (result.success) {
            $l("StyleSheetList").innerHTML = result.styleList;
            var div = $new("div");
            div.innerHTML = result.styleEdit;
            $l("StyleEditPages").appendChild(div);
            this.replaceStyle(result.styleId, "");
        }
        else {
            alert("Error: " + result.error);
        }
        this.cancelNewStylesheet();
        lara.indicateOff();
    },
    addImage: function () {
        $l("UploadImageColorId").value = "";
        $l("UploadImageThemeId").value = $l("SelectTheme").value;
        this.selectFile.style.display = "block";
    },
    addComponentImage: function (id) {
        $l("UploadImageThemeId").value = "";
        $l("UploadImageColorId").value = id;
        this.selectFile.style.display = "block";
    },
    uploadImage: function () {
        var form = $l("UploadComponentImage");
        var selector = $l("ComponentImage");

        if (selector.value) {
            lara.indicateOn();
            form.submit();
        }
    },
    cancelUpload: function () {
        $l("UploadImageColorId").value = "";
        $l("UploadImageThemeId").value = "";
        this.selectFile.style.display = "none";
    },
    uploadComplete: function () {

        var filename = $l("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 ($l("UploadImageColorId").value != "") {
            var data = new dataObject();
            data.add("variantId", $l("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) {
            $l("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";
            }
            $l("StyleSelection" + this.browseStyleSetId).innerHTML = result.html;
            $l("StyleSelection" + this.browseStyleSetId).style.display = "block";
        }
        else {
            alert("Error: " + result.error);
        }
        lara.indicateOff();
    },
    viewStyles: function (id) {

        if ($l("ShowStyleOpen" + id)) {
            $l("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) {
            $l("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($l(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();
function geoMarketing()  {  };

geoMarketing.prototype = {
    path: "/_ui/marketing",

    viewDetails: function (id, stat) {
        var data = new dataObject();
        data.add("campaignId", id);
        data.add("stat", stat);
        lara.indicateOn();
        lara.request(this.path + ":ViewDetails", data, function (result) { marketing.processLoadStat(result); });
    },
    processLoadStat: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("CampaignStatDetails").innerHTML = result.html;
        }
        else {
            alert(result.error);
        }

    },
    viewCampaign: function (id) {
        ui.showTab('Marketing', 2);
        this.loadCampaign(id);
    },
    loadCampaign: function (id) {
        var data = new dataObject();
        data.add("id", id);
        lara.indicateOn();
        lara.request(this.path + ":LoadCampaign", data, function (result) { marketing.processLoadCampaign(result); });
    },
    processLoadCampaign: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("CampaignDetail").innerHTML = result.html;
            $l("SendingHistory").innerHTML = result.list;
            $l("NewsLetterList").innerHTML = result.letters;
            $l("ContactList").innerHTML = result.contacts;
            $l("GroupList").innerHTML = result.groups;
            $l("SelectCampaignTargets").innerHTML = result.targets;
            var pie = new SWFObject(BASE_URL + "/_ui/flash/FCF_Pie2D.swf", "single", "590", "300", "7");
            pie.addParam("wmode", "transparent");
            pie.addVariable("dataURL", BASE_URL + "/_api/tracking/campaign/graph?campaign=" + result.id);
            pie.addVariable("chartWidth", "600");
            pie.addVariable("chartHeight", "300");
            pie.write("piechart");
        }
        else {
            alert(result.error);
        }

    },
    selectContact: function () {

        var selected = this.getSelected();
        if (selected.length > 0)
            $l("ContactActions").style.visibility = "visible";
        else
            $l("ContactActions").style.visibility = "hidden";

    },
    getSelected: function () {

        var checks = $l("Contacts").getElementsByTagName("input");
        var selected = "";
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked)
                selected += checks[i].value + ",";
        }
        return selected;
    },
    selectContacts: function (checked) {
        var checks = $l("Contacts").getElementsByTagName("input");
        for (var i = 0; i < checks.length; i++) {
            checks[i].checked = checked;
        }
        this.selectContact();
    },
    deleteSelected: function () {
        if (!confirm("Are you sure you want to delete these contacts?"))
            return;

        var data = new dataObject();
        data.add("contacts", this.getSelected());
        data.add("groupId", $l("CurrentGroupId").value);
        lara.indicateOn();
        lara.request(this.path + ":DeleteContacts", data, function (result) { marketing.processContactGroupChange(result); });
    },
    removeSelected: function () {
        if (!confirm("Are you sure you want to remove these contacts from this group?"))
            return;

        var data = new dataObject();
        data.add("contacts", this.getSelected());
        data.add("groupId", $l("CurrentGroupId").value);
        lara.indicateOn();
        lara.request(this.path + ":RemoveFromGroup", data, function (result) { marketing.processContactGroupChange(result); });
    },
    addToGroup: function () {
        var data = new dataObject();
        data.add("contacts", this.getSelected());
        data.add("groupId", $l("AddToGroup").value);
        lara.indicateOn();
        lara.request(this.path + ":AddToGroup", data, function (result) { marketing.processGroupChange(result); });
    },
    showAddContact: function () {
        $l("ContactEmail").value = "";
        $l("ContactFirstName").value = "";
        $l("ContactLastName").value = "";
        $l("AddContact").style.display = "block";
        ui.centerElement("AddContact");
        dragdrop.makeDraggable($l("AddContact"), $l("AddContactHeader"));
        $l("UploadContacts").style.display = "none";
    },
    showUploadContacts: function () {
        $l("UploadContacts").style.display = "block";
        ui.centerElement("UploadContacts");
        dragdrop.makeDraggable($l("UploadContacts"), $l("UploadContactHeader"));
        $l("AddContact").style.display = "none";
    },
    addContact: function () {
        var data = new dataObject();
        data.add("email", $l("ContactEmail").value);
        data.add("firstname", $l("ContactFirstName").value);
        data.add("lastname", $l("ContactLastName").value);
        data.add("groupId", $l("CurrentGroupId").value);
        lara.indicateOn();
        lara.request(this.path + ":AddContact", data, function (result) { marketing.processContactGroupChange(result); });
    },
    cancelAddContact: function () {
        $l("AddContact").style.display = "none";
    },
    uploadContacts: function () {
        var form = $l("UploadContactForm");
        var fileUpload = $l("ContactUpload");

        if (fileUpload.value) {
            lara.indicateOn();
            form.submit();
        }
    },
    cancelUploadContacts: function () {
        $l("UploadContacts").style.display = "none";
    },
    uploadContactsComplete: function () {

        var contacts = $l("AddContactUploadFrame").contentWindow.document.body.innerHTML;
        if (contacts.indexOf("Improperly Formed Document") >= 0) {
            alert(contacts);
            lara.indicateOff();
            return;
        }
        if (contacts == "")
            return;

        var data = new dataObject();
        data.add("contacts", escape(contacts));
        data.add("groupid", $l("CurrentGroupId").value);

        lara.request(this.path + ":ContactUploadSuccess", data, function (result) { marketing.processSaveContacts(result); });
    },
    processSaveContacts: function (result) {
        if (result.success) {
            $l("ContactList").innerHTML = result.contacts;
            $l("GroupList").innerHTML = result.groups;
            $l("SelectCampaignTargets").innerHTML = result.targets;
        }
        else {
            alert(result.error);
        }
        this.cancelUploadContacts();
        lara.indicateOff();
    },
    loadGroup: function (id) {
        var data = new dataObject();
        data.add("groupId", id);
        lara.indicateOn();
        lara.request(this.path + ":LoadGroup", data, function (result) { marketing.processContactChange(result); });
    },
    removeGroup: function (id) {
        if (!confirm("Removing this group will not remove the contacts in this group.  Just the group name.  Are you sure you want to remove this group?"))
            return;

        var data = new dataObject();
        data.add("groupId", id);
        lara.indicateOn();
        lara.request(this.path + ":RemoveGroup", data, function (result) { marketing.processContactGroupChange(result); });
    },
    processContactChange: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("AddContact").style.display = "none";
            $l("ContactList").innerHTML = result.html;
        }
        else {
            alert(result.error);
        }

    },
    processContactGroupChange: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("ContactList").innerHTML = result.contacts;
            $l("GroupList").innerHTML = result.groups;
            $l("SelectCampaignTargets").innerHTML = result.targets;
        }
        else {
            alert(result.error);
        }
        this.cancelAddContact();
    },
    addGroup: function () {
        var data = new dataObject();
        data.add("groupName", $l("NewGroupName").value);
        lara.indicateOn();
        lara.request(this.path + ":AddGroup", data, function (result) { marketing.processGroupChange(result); });
    },
    processGroupChange: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("ContactList").innerHTML = result.contacts;
            $l("GroupList").innerHTML = result.groups;
            $l("SelectCampaignTargets").innerHTML = result.targets;
        }
        else {
            alert(result.error);
        }

    },
    showSend: function (path) {
        $l("SendPath").value = path;
        $l("TestTargets").value = "";
        $l("SendNewsletter").style.display = "block";
        ui.centerElement("SendNewsletter");

        dragdrop.makeDraggable($l("SendNewsletter"), $l("SendNewsletterHeader"));
    },
    cancelSend: function () {
        $l("SendNewsletter").style.display = "none";
    },
    send: function () {
        var data = new dataObject();
        data.add("path", $l("SendPath").value);
        if ($l("SendNewsletterTabContent1").style.display == "none") {
            data.add("targets", $l("TestTargets").value);
            data.add("sendtest", true);
            this.sendTest = true;
        }
        else {
            data.add("targets", this.getTargetGroups());
            data.add("sendtest", false);
            this.sendTest = false;
        }
        lara.indicateOn();
        lara.request(this.path + ":Send", data, function (result) { marketing.processSend(result); });
    },
    getTargetGroups: function () {

        var checks = $l("SelectCampaignTargets").getElementsByTagName("input");
        var selected = "";
        for (var i = 0; i < checks.length; i++) {
            if (checks[i].checked)
                selected += checks[i].value + ",";
        }
        return selected;
    },
    processSend: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("SendNewsletter").style.display = "none";
            if (!this.sendTest) {
                this.loadCampaign(result.id);
                ui.showTab('Marketing', 2);
            }
        }
        else {
            alert(result.error);
        }

    },
    addPage: function () {
        $l("NewsLetterTitle").value = "";
        $l("NewsLetterPath").value = "";
        $l("CreateNewsLetter").style.display = "block";
        ui.centerElement("CreateNewsLetter");

        dragdrop.makeDraggable($l("CreateNewsLetter"), $l("CreateNewsLetterHeader"));
    },
    copy: function (path) {
        $l("CopyPath").value = path;
        $l("CreateCopy").innerHTML = "Create a copy of news letter: " + path;
        this.addPage();
    },
    cancelCreate: function () {
        $l("CreateCopy").innerHTML = "";
        $l("CreateNewsLetter").style.display = "none";
    },
    deletePage: function (path) {
        if (!confirm("Are you sure you want to delete this newsletter?  All statistics for this newsletter will also be deleted."))
            return;

        var data = new dataObject();
        data.add("path", path);
        lara.indicateOn();
        lara.request(this.path + ":DeletePage", data, function (result) { marketing.processDeletePage(result); });
    },
    processDeletePage: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("NewsLetterList").innerHTML = result.html;
            $l("CampaignDetail").innerHTML = result.campaign;
            $l("SendingHistory").innerHTML = result.list;
        }
        else {
            alert(result.error);
        }

    },
    createPage: function () {
        var data = new dataObject();
        if ($l("CopyPath").value != "")
            data.add("copypath", $l("CopyPath").value);
        data.add("title", $l("NewsLetterTitle").value);
        data.add("path", $l("NewsLetterPath").value);
        lara.indicateOn();
        lara.request(this.path + ":CreatePage", data, function (result) { marketing.processChange(result); });
    },
    setPath: function () {
        if ($l("NewsLetterPath").value == "") {
            //Try to clean up the path
            var path = "/email/" + $l("NewsLetterTitle").value.toLowerCase().replace(/ /g, "-");
            path = path.replace("//", "/");
            $l("NewsLetterPath").value = path;
        }
    },
    processChange: function (result) {
        lara.indicateOff();
        if (result.success) {
            $l("CreateNewsLetter").style.display = "none";
            $l("NewsLetterList").innerHTML = result.html;
        }
        else {
            alert(result.error);
        }

    },
    subscribe: function () {
        if (this.validate()) {
            lara.indicateOn();

            $l("SubscribeButton").disabled = true;

            var data = new dataObject();

            data.add("first", $l("SubscribeFirst").value);
            data.add("last", $l("SubscribeLast").value);
            data.add("email", $l("SubscribeEmail").value);
            lara.request(this.path + ":Subscribe", data, function (result) { marketing.processSubscribe(result); });
        }
    },
    processSubscribe: function (result) {
        if (result.success) {
            $l("SubscribeForm").innerHTML = result.html;
        }
        else {
            $l("SubscribeButton").disabled = false;
            $l("ValidationStatus").innerHTML = result.error;
        }
        lara.indicateOff();
    },
    validate: function () {

        $l("SubscribeFirst").className = "";
        $l("SubscribeLast").className = "";
        $l("SubscribeEmail").className = "";

        var errClass = "ValidationErr";
        MESSAGE = "Oops!  All fields are required.";
        $l("ValidationStatus").innerHTML = "";

        var passed = true;
        if ($l("SubscribeFirst").value == "") {
            $l("SubscribeFirst").className = errClass;
            $l("ValidationStatus").innerHTML = MESSAGE;
            passed = false;
        }

        if ($l("SubscribeLast").value == "") {
            $l("SubscribeLast").className = errClass;
            $l("ValidationStatus").innerHTML = MESSAGE;
            passed = false;
        }
        if ($l("SubscribeEmail").value == "") {
            $l("SubscribeEmail").className = errClass;
            $l("ValidationStatus").innerHTML = MESSAGE;
            passed = false;
        }

        return passed;
    }
};
    
var marketing = new geoMarketing();



    

//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.header.style.marginTop = 0; //prevent custom styling from making this unusable.
            this.footer.style.marginTop = 0;
        }
        this.pageCancel = this.page.cloneNode(false); //No deep clone because IE 7 crashes with embedded scripts
        this.pageCancel.innerHTML = this.page.innerHTML;
        this.page.style.marginTop = 0;
        $l("Content").style.marginTop = 0;
        $l("MenuContentFrame").style.marginTop = 0;
        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);

            if (!this.emailMode) {
                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";
            if (this.emailMode)
                this.toolbox.className = "sEmailToolbox";
            else
                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();

            this.refresh();
        }
        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.undoLink.style.display = "none";

        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";
        if (!this.emailMode) {
            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);
        }
        else {
            this.layoutOptions = document.createElement("div");
            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.emailMode) {
            this.toolbox.style.top = ui.findPos($l("PageContent")).y + lara.scrollTop() + "px";
            this.toolbox.style.left = (((document.documentElement.clientWidth - 590) / 2) - this.toolbox.offsetWidth - 30) + "px";
        }
        else 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($l(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;

        if (this.emailMode)
            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 = $l(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");

            if (!this.emailMode) {
                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";
                };
            }
            else
                group.className = "EmailFeatureGroup";

            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 = ""; $l("DeleteInfo").style.visibility = "hidden"; siteLayout.hoverIcon.src = this.firstChild.src; siteLayout.hoverTitle.innerHTML = "<br />" + this.value; };
                //option.onmouseout = function() { siteLayout.hoverArea.style.display = "none"; $l("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(); });

                if (!this.emailMode)
                    group.groupOptions.appendChild(option);
                else
                    group.appendChild(option);
            }
            if (!first && !this.emailMode)
                group.groupOptions.style.display = "none";

            if (!this.emailMode)
                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 ($l("SignInFullView").checked)
                settings.add("view", 0); 
            if ($l("SignInWindowView").checked)
                settings.add("view", 1);
            return;

        case "SignUp":
            if ($l("SignUpEmailView").checked)
                settings.add("view", 2);
            if ($l("SignUpButtonView").checked)
                settings.add("view", 3);
            settings.add("buttontext", $l("SignUpButtonText").value);
            settings.add("contentbuttontext", $l("ContentButtonText").value);
            settings.add("buttonstyle", $l("SignUpButtonStyle").value);
            settings.add("signuptext", $l("EditSignUpText").value);
            settings.add("signedintext", $l("EditSignedInText").value);
            settings.add("showaddcontent", $l("SignUpShowAddContent").checked);
            settings.add("showsignin", $l("SignUpShowSignIn").checked);
            settings.add("createuser", $l("SignUpCreateUser").checked);
            return;

        case "PopularityList":
            settings.add("count", $l("MediaListCount").value);
            settings.add("showrss", $l("MediaListShowRSS").checked);
            settings.add("showheaderimage", $l("MediaListShowHeaderImage").checked);
            return;

        case "Calendar":
            settings.add("mediatype", $l("CalendarContent").value);
            settings.add("listsize", $l("CalendarListSize").value);
            return;

        case "PageInPage":
            settings.add("pagepath", $l("PageInPagePath").value);
            settings.add("useslider", $l("UseSlider").checked);
            settings.add("tabtext", $l("TabText").value);
            settings.add("tablocation", $l("TabLocation").value);
            settings.add("topposition", $l("TopPosition").value);
            settings.add("leftposition", $l("LeftPosition").value);
            settings.add("fixedposition", $l("FixPosition").checked);
            settings.add("tabimage", $l("TabImagePath").value);
            settings.add("tabimagewidth", $l("TabImageWidth").value);
            settings.add("tabimageheight", $l("TabImageHeight").value);
            settings.add("mounttoparent", $l("ParentContainer").checked);
            settings.add("mounttobody", $l("BodyContainer").checked);
            settings.add("mounttocustom", $l("CustomContainer").checked);
            settings.add("customparent", $l("CustomSelector").value);
            return;
            
        case "GoogleEarthRegion":
            settings.add("googlekey", $l("GoogleEarthKey").value);
            settings.add("regionid", $l("ParentRegionId").value);
            settings.add("startid", $l("StartRegionId").value);
            return;
            
        case "GoogleEarth":
            settings.add("googlekey", $l("GoogleEarthKey").value);
            settings.add("mapwidth", $l("MapWidth").value);
            settings.add("mapheight", $l("MapHeight").value);
            settings.add("heading", $l("MapHeading").value);
            settings.add("tilt", $l("MapTilt").value);
            settings.add("latitude", $l("MapLat").value);
            settings.add("longitude", $l("MapLong").value);
            settings.add("range", $l("MapRange").value);
            settings.add("nav", $l("MapNav").checked);
            return;                         

        case "Payment":
            settings.add("account", $l("PaymentEditAccount").value);
            settings.add("username", $l("PaymentEditUserName").value);
            settings.add("key", $l("PaymentEditKey").value);
            settings.add("email", $l("PaymentEditEmail").value);
            settings.add("gateway", $l("PaymentEditGateway").value);
            settings.add("live", $l("PaymentEditLive").checked);
            settings.add("headerformat", $l("PaymentEditHeader").value);
            settings.add("payfields", $l("PaymentEditFields").value);
            settings.add("descriptiontext", $l("PaymentEditDescription").value);
            return;

        case "PageField":
            settings.add("fieldpath", $l("EditFieldPath").value);
            return;
            
        case "ShowSpot":
            settings.add("portal", $l("ShowSpotPortal").checked);
            settings.add("portalroot", $l("ShowSpotRoot").value);
            settings.add("datasource", $l("ShowSpotData").value);
            return;

        case "PlanetsNu":
            settings.add("datasource", $l("PlanetsNuData").value);
            return;

        case "Search":
            settings.add("showresults", $l("SearchShowResults").checked);
            settings.add("boxwidth", $l("SearchBoxWidth").value);
            return;

        case "Archive":
            settings.add("mediatype", $l("MediaTypeSelector").value);
            return;

        case "MediaList":
            if ($l("MediaListFullView").checked)
                settings.add("view", 1);
            if ($l("MediaListIconView").checked)
                settings.add("view", 2);
            if ($l("MediaListTitleView").checked)
                settings.add("view", 3);
//            if ($l("MediaListSlideView").checked)
//                settings.add("view", 4);
//            if ($l("MediaListExploreView").checked)
//                settings.add("view", 5);
            if ($l("MediaListFullFeatureView").checked)
                settings.add("view", 6);
                
            if ($l("MediaListDateOrder").checked)
                settings.add("orderby", 0);
            if ($l("MediaListTitleOrder").checked)
                settings.add("orderby", 1);
//            if ($l("MediaListPopularityOrder").checked)
//                settings.add("orderby", 2);                

            settings.add("listcolumns", $l("MediaListListColumns").value);
            settings.add("listpadding", $l("MediaListListPadding").value);

            if ($l("MediaListListView").checked) {
                settings.add("showheaderimage", $l("MediaListShowHeaderImage").checked);
                settings.add("showimage", $l("MediaListShowImage").checked);
                settings.add("showdescription", $l("MediaListShowDescription").checked);
                settings.add("showdate", $l("MediaListShowDate").checked);
                settings.add("showlocation", $l("MediaListShowLocation").checked);
                //settings.add("showviews", $l("MediaListShowViews").checked);
                settings.add("showuser", $l("MediaListShowUser").checked);
                settings.add("showtopics", $l("MediaListShowTopics").checked);
                settings.add("showspecific", $l("MediaListShowTypeSpecific").checked);
                settings.add("showborder", $l("MediaListShowBorder").checked);
                settings.add("showlisttitle", $l("MediaListShowTitle").checked);
                settings.add("showmoredetails", $l("MediaListShowMoreDetails").checked);
                settings.add("listtitleformat", $l("MediaListListTitleFormat").value);
                settings.add("imagesize", $l("MediaListImageSizeSelector").value);
                settings.add("squareimages", $l("MediaListSquareImages").checked);
            }
            settings.add("count", $l("MediaListCount").value);
            settings.add("starton", $l("MediaListStartOn").value);

            if ($l("UseSearchTitle")) {
                settings.add("usesearchtitle", $l("UseSearchTitle").checked);
                settings.add("enablepaging", $l("EnablePaging").checked);
                settings.add("showresultcount", $l("ShowSearchResultCount").checked);
                settings.add("showsearchpath", $l("ShowSearchPath").checked);
                settings.add("showsortoptions", $l("ShowSortOptions").checked);
            }
            else {
                featureEdit.readContentSelection(settings);
            }
            settings.add("showrss", $l("MediaListShowRSS").checked);
            return;     

        case "Forum":
            settings.add("forumchannel", $l("ForumChannel").value);
            settings.add("forumtitle", $l("ForumTitle").value);
            settings.add("description", $l("ForumDescription").value);
            settings.add("bottommargin", $l("ForumBottomMargin").checked);
            settings.add("showtableheader", $l("ForumShowTableHeader").checked);
            return;
            
        case "Download":
            settings.add("src", $l("EditDownloadSource").value);
            settings.add("buttontext", $l("DownloadButtonText").value);
            settings.add("counter", $l("DownloadCounterName").value);
            settings.add("showcount", $l("DownloadShowCount").checked);
            settings.add("showbutton", $l("DownloadShowButton").checked);
            return;
            
        case "BuildSite":
            settings.add("rootdomain", $l("BuildSiteRootDomain").value);
            settings.add("startup", $l("BuildSiteStartup").value);
            settings.add("realestate", $l("BuildSiteRealEstateStartup").value);
            return;
                    
        case "EditStyle":
            settings.add("designurl", $l("EditStyleDesignUrl").value);
            return;

        case "StyleRender":
            settings.add("designurl", $l("EditStyleDesignUrl").value);
            return;

        case "ThemeList":
            settings.add("designurl", $l("EditStyleDesignUrl").value);
            return;            

        case "ShowMedia":
            if ($l("PicViewNone").checked)
                settings.add("picview", 0);        
            if ($l("PicViewHorizontal").checked)
                settings.add("picview", 1);
            if ($l("PicViewVertical").checked)
                settings.add("picview", 2);    
            if ($l("PicViewSlideshow").checked)
                settings.add("picview", 3);
            if ($l("ContentViewFull").checked)
                settings.add("view", 1);
            if ($l("ContentViewShort").checked)
                settings.add("view", 2);
            if ($l("ContentViewFeature").checked)
                settings.add("view", 3);
            if ($l("ContentViewFeature").checked)
                settings.add("view", 3);
            settings.add("showdate", $l("ShowMediaShowDate").checked);
            return;

        case "Image":
            settings.add("showborder", $l("FeatureImageShowBorder").checked);
            settings.add("src", $l("EditImageSource").value);
            settings.add("version", $l("FeatureImageVersion").value);
            settings.add("caption", $l("FeatureImageCaption").value);
            settings.add("link", $l("ImageLink").value);
            if ($l("ImageLinkTarget").checked)
                settings.add("linktarget", "_blank");
            
            if ($l("ImageAlignLeft").checked)
                settings.add("align", "left");
            if ($l("ImageAlignCenter").checked)
                settings.add("align", "center");
            if ($l("ImageAlignRight").checked)
                settings.add("align", "right");            
            return;

        case "Video":
            settings.add("src", $l("EditVideoSource").value);
            settings.add("videowidth", $l("EditVideoWidth").value);
            settings.add("videoheight", $l("EditVideoHeight").value);
            if ($l("VideoAlignLeft").checked)
                settings.add("align", "left");
            if ($l("VideoAlignCenter").checked)
                settings.add("align", "center");
            if ($l("VideoAlignRight").checked)
                settings.add("align", "right");
            return;       
            
        case "Audio":
            settings.add("src", $l("EditAudioSource").value);
            if ($l("AudioAlignLeft").checked)
                settings.add("align", "left");
            if ($l("AudioAlignCenter").checked)
                settings.add("align", "center");
            if ($l("AudioAlignRight").checked)
                settings.add("align", "right");
            return;       

        case "Tree":
            settings.add("treeroot", $l("TreeEditSelectorPath").value);
            settings.add("roottitle", $l("TreeRootTitle").checked);
            settings.add("showroot", $l("TreeShowRoot").checked);

            if ($l("TreeSizeSmall").checked)
                settings.add("treesize", 1);
            if ($l("TreeSizeNormal").checked)
                settings.add("treesize", 2);
            if ($l("TreeSizeBig").checked)
                settings.add("treesize", 3);

            featureEdit.readContentSelection(settings);
            
            return;
            
        case "Map":                  
            settings.add("mapheight", $l("MapHeight").value);
            settings.add("mapwidth", $l("MapWidth").value);
            settings.add("zoom", $l("MapZoom").value);
            settings.add("address", $l("MapAddress").value);
            settings.add("markers", $l("MapMarkers").value);
            settings.add("showcontrols", $l("MapShowControls").checked);  
            return;  
            
        case "Comments":
            settings.add("requireapproval", $l("CommentsRequireApproval").checked);
            settings.add("showwebsite", $l("CommentsShowWebsite").checked);
            settings.add("showlocation", $l("CommentsShowLocation").checked);
            settings.add("buttonstyle", $l("CommentButtonStyle").value);
            if ($l("CommentBoxVerticalView").checked)
                settings.add("view", 0);
            if ($l("CommentBoxHorizontalView").checked)
                settings.add("view", 1);
            return;
            
        case "BackNext": 
            settings.add("showitemtitle", $l("BackNextShowItemTitle").checked);

            if ($l("BackNextHor").checked)
                settings.add("view", 0);
            if ($l("BackNextVert").checked)
                settings.add("view", 1);
            return;                       
    
        case "MediaActions":
            settings.add("showpromote", $l("ActionsShowPromote").checked);
            settings.add("showemail", $l("ActionsShowEmail").checked);
            settings.add("showenquire", $l("ActionsShowEnquire").checked);
            settings.add("showdelicious", $l("ActionsShowDelicious").checked);
            settings.add("showdigg", $l("ActionsShowDigg").checked);
            settings.add("showstumble", $l("ActionsShowStumble").checked);
            settings.add("showdownload", $l("ActionsShowDownload").checked);
            return;
            
        case "PropertySearch":
            settings.add("fieldwidth", $l("FieldWidth").value);
            settings.add("propertiesfor", $l("PropertiesForOption").value);
            settings.add("showforoption", $l("ShowForOption").checked);
            settings.add("showminprice", $l("ShowMinPrice").checked);
            settings.add("showmaxprice", $l("ShowMaxPrice").checked);
            settings.add("showbedrooms", $l("ShowBedrooms").checked);
            settings.add("showbathrooms", $l("ShowBathrooms").checked);
            settings.add("showsize", $l("ShowSize").checked);
            settings.add("showlandsize", $l("ShowLandSize").checked);        
            settings.add("showbuiltafter", $l("ShowBuiltAfter").checked);        
            return;
            
        case "ContactBox":
            settings.add("toemail", $l("ContactBoxEditToEmail").value);
            settings.add("boxheight", $l("ContactBoxEditHeight").value);
            settings.add("buttonstyle", $l("ContactBoxButtonClass").value);
            settings.add("buttontext", $l("ContactBoxButtonText").value);
            settings.add("suggested", $l("ContactBoxEditSuggested").value);
            settings.add("showphone", $l("ContactBoxShowPhone").checked);
            settings.add("showmessage", $l("ContactBoxShowMessage").checked);
            settings.add("showchecks", $l("ContactBoxSuggestedChecks").checked);
            if ($l("ContactBoxVerticalView").checked)
                settings.add("view", 0);
            if ($l("ContactBoxHorizontalView").checked)
                settings.add("view", 1);
            return;

        case "BasicForm":
            settings.add("toemail", $l("BasicFormEditToEmail").value);
            settings.add("formfields", $l("BasicFormFormFields").value);
            settings.add("boxwidth", $l("BasicFormBoxWidth").value);
            settings.add("titlewidth", $l("BasicFormTitleWidth").value);
            settings.add("buttonstyle", $l("BasicFormButtonClass").value);
            settings.add("buttontext", $l("BasicFormButtonText").value);
            settings.add("navigateto", $l("BasicFormNavigateTo").value);
            settings.add("createuser", $l("BasicFormCreateUser").checked);
            settings.add("captcha", $l("BasicFormShowCaptcha").checked);
            return;
            
        case "RSS":
            settings.add("feedurl", $l("RSSFeedUrl").value);
            settings.add("blockwords", $l("RSSBlockwords").value);
            settings.add("listtitleformat", $l("RSSListTitleFormat").value);
            settings.add("showlink", $l("RSSShowLink").checked);
            settings.add("showenclosure", $l("RSSShowEnclosure").checked);
            settings.add("showdescription", $l("RSSShowDescription").checked);
            settings.add("showdate", $l("RSSShowDate").checked);
            settings.add("count", $l("RSSCount").value);       
            return;
            
        case "SlideShow":
            settings.add("images", $l("SlideshowImages").value);
            settings.add("imageheight", $l("SlideshowHeight").value);
            settings.add("imagewidth", $l("SlideshowWidth").value);
            settings.add("delay", $l("SlideshowDelay").value);
            return;

        case "Gallery":
            settings.add("images", $l("GalleryImages").value);
            settings.add("imageheight", $l("GalleryHeight").value);
            settings.add("imagewidth", $l("GalleryWidth").value);
            settings.add("delay", $l("GalleryDelay").value);
            settings.add("theme", $l("GalleryTheme").value);
            settings.add("showthumbs", $l("GalleryShowThumbs").checked);
            return;

        case "BuyCredit":
            if ($l("LaraAccountStore").checked)
                settings.add("store", "lara");
            if ($l("MailAccountStore").checked)
                settings.add("store", "mail");
            return;

        case "CreateAccount":
            if ($l("LaraAccountStore").checked)
                settings.add("store", "lara");
            if ($l("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 = $l(this.featureId);
        this.img = $l("Img" + this.featureId); 
        this.featurebar = $l("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 ($l("ImgContainer" + this.featureId))
            this.displayWidth = $l("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 ($l("ImgContainer" + this.featureId))
            this.maxWidth = $l("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();


