var App = new Class({
    Extends: BaseApp,

    initialize: function(registerOnly, inviteOnly) {
	this.parent();

        this.registerOnly = registerOnly;
        this.inviteOnly = inviteOnly;

        this.activeDesktopID;          // will be a unique ID
        this.tabs = new Object();     // assoc array of desk/tab ID -> Tab object
        this.desktops = new Object(); // assoc array of desk/tab ID -> Desktop object
        this.widgets = new Object(); // assoc array of element.id -> widget object which wraps the element
        this.widgetParams = new Object(); // assoc array of widgetID -> parameters loaded from DB
        this.isLoggedIn = false;      // are we logged in?
        this.launchers = new Object();    // assoc array
	this.fileBrowsers = new Array();

        //should be an object
        this.cookieName = 'schmedleyData';
        this.cookieData = JSON.decode(Cookie.read(this.cookieName));

        // figure out a base URL to use
        var regex = /https{0,1}:\/\/([^\/]+)(.*)$/;
        var matches = regex.exec(location.href);
        this.domain = matches[1];
        this.baseURL = this.domain + matches[2];

        this.widgetsCount = 0;

	// chrome needs special cases because it's transparency handling sucks.
	if (navigator.userAgent.toLowerCase().match(/chrome/)) {
	    Browser.Engine.chrome = true;
	}

        // browser check
        if (Browser.Engine.trident5
	    || Browser.Engine.chrome){
	    this.useFade = false;
        }
        else {
            this.useFade = true;
        }

        var self = this;

	// powered by
	if (wLabel){
	    var powered = $('powered');
	    powered.setStyle('display', 'block');
	}

        // "Set" button

        var suButton = new Element('div', {
            'class': 'butb signup',
            'id': 'signup'
        });

        suButton.set('html', '<div class="butl"></div><div class="butc">' + gls('but7') + '</div><div class="butr"></div>');
        suButton.inject($('infobox'));
        suButton.setStyles({position: 'absolute', top: '14px', left: '35px', height: '25px', display: 'block', overflow: 'hidden'});

        suButton.addEvent('mousedown', function(e) {
            e = new Event(e).stop();
            this.setProperty('class', 'bdown');
        })
            .addEvent('mouseup', function(e) {
		e = new Event(e).stop();
		this.setProperty('class', 'butb signup');
            })
            .addEvent('click', function(e) {
		e = new Event(e).stop();
		self.launchSignup();
            });


        $('signin').set('html', gls('but8'));


        this.bo = new Element('div', {
            'class': 'blackout'
        });

        this.bos = new Element('div', {
            'class': 'blackoutSemi',
            'opacity': .9
        });
        this.bos.set('html', '&nbsp;');
        this.bos.injectInside(this.bo);

        this.bo.injectInside(document.body);

        this.colorLaunch = $('color');
        this.colorLaunch.addEvent('click', this.manageColor.bindWithEvent(this));


    },

    run: function() {
        var signin = $('signin');
        if (signin){
            this.shimmyLogin(signin);

            signin.removeEvents('click');
            signin.addEvent('click', this.launchLogin.bindWithEvent(this));
        }

        if (this.registerOnly) {
            this.launchSignup();
        }
        else {
            wf = new WidgetFactory();         // used to instantiate schmidgets
            lf = new LauncherFactory();

            this.verifyLogin();
        }

    },

    activate: function() {
        var flag = $('flag');
        if (flag) {
            flag.removeEvents('click');
            flag.addEvent('click', function(e) {
                alert('international support is coming soon...');
            });
        }

        var info = $('info');
        if (info) {
            info.removeEvents('click');
            info.addEvent('click', this.schmedleyInfo.bindWithEvent(this));
        }

        var home = $('home');
        if (home) {
            home.removeEvents('click');
            home.addEvent('click', this.homeInstructions.bindWithEvent(this));
        }

        var copyright = $('copy');
        copyright.removeEvents('click');
        copyright.addEvent('click', this.copyrightLink.bindWithEvent(this));


        var g1 = $('grad1');
        g1.removeEvents('click');
        g1.addEvent('click', function(e) {
            e = new Event(e).stop();
            toggleGradient(1);
        });

        var g2 = $('grad2');
        g2.removeEvents('click');
        g2.addEvent('click', function(e) {
            e = new Event(e).stop();
            toggleGradient(2);
        });

        var desk = $('dsktp');
        if (desk) {
            desk.removeEvents('click');
            desk.addEvent('click', this.desktopPics.bindWithEvent(this));
        }


        var bugreport = $('buggy');
        bugreport.removeEvents('click');
        bugreport.addEvent('click', this.bugReport.bindWithEvent(this));
        this.bugreport = bugreport;

        this.attachDockEvents();

        this.attachTabEvents();
    },

    desktopPics: function() {
	var self = this;

        if  ($('BGpicker')) {
            // do nothing
	    var BGpicker = $('BGpicker');
        }
        else {
            var BGpicker = new Element('div', {
                'id': 'BGpicker'
            })
		.adopt(new Element('h1', {'html': 'desktop backgrounds'}))
		.adopt(new Element('div').setStyles({'position': 'absolute', 'right': '24px', 'top': '24px'})
                       .adopt(new Element('div', {'class': 'butb', 'html': '<div class="butl"></div><div class="butc">Remove Current Background</div><div class="butr"></div>'})
                              .addEvent('click', function() {
				  var desk = self.getActiveDesk();
				  if (desk) desk.setBGImage('');
                              })
                             )
                      );
	    
	    BGpicker.inject($('ColourMod'), 'after');
            BGpicker.setOpacity(1);
	    
            schmedley.addDialogClose(BGpicker);
            schmedley.fade('in', BGpicker);
	    
            BGpicker.makeDraggable();
	}
	
        // adjust the display of the "tabs" and the thumbnail grids when one is clicked
	
        function switchStuff() {
            var labels = $$('a.bglabel');
            var grids = $$('div.bggrid');
	    
            labels.each(function(e) {
                e.removeClass('actvlabel');
            });
	    
            grids.each(function(e) {
                e.setStyle('display', 'none');
            });
	    
            $(schmedley.bgpage).setStyle('display', 'block');
            $(schmedley.bgpage + 'Label').addClass('actvlabel');
        };
	
	var url = "/getBGImages.php?c=" + this.getActiveTab().categoryID;

	var req = new Request.JSON({url: url,
				    method: 'get',
				    onComplete: function(message){
					if (message.status == 'success'){
					    var pageCount = 0;
					    for(var pageIndex in message.data){

						var page = message.data[pageIndex];
						if (pageCount == 0) schmedley.bgpage = page.bgPageName;

						var bgPage = new Element('div', {'id': page.bgPageName, 'class': 'bggrid'});
						var pageTab = new Element('a', {'href': "#", 'id': page.bgPageName + 'Label', 'class': 'bglabel', 'html': page.bgPageDesc })
						    .addEvent('click', function () {
							schmedley.bgpage = this.id.substring(0, this.id.length - 5);
							switchStuff();
							return false;
						    });
						
						if (!page.bgImages) continue;

						for(var i = 0; i < page.bgImages.length; i++){
						    var bgi = page.bgImages[i];
						    if (bgi.isWallpaper == 1){
							var className = 'wpthumb';
							var dir = '/css/img/bg/wp/';
						    }
						    else {
						    var className = 'bgthumb';
							var dir = '/css/img/bg/desktops/';
						    }

						    bgPage.adopt(new Element('div', {'class': className})
								 .adopt(new Element('img', {'src': dir + bgi.bgImage}))
								 .adopt(new Element('br'))
								 .appendText(bgi.bgImageName)
								 .addEvent('click', function(e) {
								     e = new Event(e).stop();
								     
								     var src = this.getFirst().src.toString();
								     var desk = schmedley.getActiveDesk();
								     
								     if (desk) {
									 desk.setBGImage(src);
								     }
								 })
								);
						}

						bgPage.adopt(new Element('div', {'class': 'bgcredits'})
							     .adopt(new Element('a', {href: page.bgCreditURL})
								    .appendText(page.bgCredit)
								   )
							    );



						BGpicker.adopt(pageTab);
						BGpicker.adopt(bgPage);
						pageCount++;
					    }
					    switchStuff();
					}
					

				    }
				   });
	req.send(null);

    },

    schmedleyInfo: function() {
        if  ($('infoDialog')) {
            // do nothing
        }
        else {
            var infoDialog = new Element('div', {
                'id': 'infoDialog'
            });
            infoDialog.set('html', '<a style="font-size: 17px;" href="http://blog.schmedley.com/" target="_new">blog<span style="margin-left: 4px; margin-right: 3px;">/</span>news</a>'
                           + '&nbsp;&nbsp; <a style="font-size: 14px;" href="http://blog.schmedley.com/vote/" target="_new">polls<span style="margin-left: 4px; margin-right: 3px;">/</span>surveys</a>&nbsp;&nbsp;'
                           + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; '
                           + '&nbsp;&nbsp; <a style="font-size: 14px;" href="http://help.schmedley.com/" target="_new">help<span style="margin-left: 4px; margin-right: 3px;">/</span>support</a>'
                           + '&nbsp;&nbsp; <a style="font-size: 11px;" href="http://help.schmedley.com/discussions" target="_new">forums<span style="margin-left: 4px; margin-right: 3px;">/</span>discussion</a>'
                           + '&nbsp;&nbsp; <a href="http://help.schmedley.com/faqs" target="_new">FAQs<span style="margin-left: 4px; margin-right: 3px;">/&nbsp;</span> <span style="font-size: 12px;">knowledge&nbsp;base</span></a>&nbsp;&nbsp;'
                           + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; '
                           + '&nbsp;&nbsp; <a href="http://blog.schmedley.com/about/" target="_new">about</a>'
                           + '&nbsp;&nbsp; <a href="http://blog.schmedley.com/contact/" target="_new">contact</a>'
                           + '&nbsp;&nbsp; <a href="http://blog.schmedley.com/team/" target="_new">team</a>'
                           + '&nbsp;&nbsp; <a href="http://blog.schmedley.com/partners/" target="_new">partners</a>&nbsp;&nbsp;'
                           + ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; '
                           + '<a style="font-size: 11px;" href="http://blog.schmedley.com/about/privacy-policy/" target="_new">privacy policy</a><br />'
                           + '<a style="font-size: 11px;" href="http://blog.schmedley.com/about/terms-of-use/" target="_new">terms of use</a>');
            infoDialog.inject($('rite'));
            infoDialog.setOpacity(0);

            schmedley.addDialogClose(infoDialog);

	    schmedley.fade('in', infoDialog);
	    
	    (function () {
                schmedley.fade('out', infoDialog);
	    }).delay(20000);
	    
	    (function () {
                $('infoDialog').destroy();
	    }).delay(21000);

        }
    },

    copyrightLink: function() {
        window.open('http://blog.schmedley.com/about/','','');
    },

    homeInstructions: function() {
        var self = this;
        var browser;

        if (Browser.Engine.trident == true) {
            document.body.style.behavior='url(#default#homepage)';
            document.body.setHomePage('http://www.schmedley.com');
        }
        else {
            if (Browser.Engine.gecko == true) {
                browser = 'Firefox';
            }
            else if (Browser.Engine.webkit == true) {
                browser = 'Safari';
            }
            else { }

            new Confirm(gls('acp5') + ' ' + browser + '.<br />' + gls('acp6'), function() {
                if (browser == 'Firefox') {
                    window.open('http://support.mozilla.com/en-US/kb/How+to+set+the+home+page');
                }
                else if (browser == 'Safari') {
                    window.open('http://helposx.apple.com/leopard/safarihelphelpr1/English.lproj/pgs/9268.html');
                }
                else { }
            });
        }
    },

    postInit: function(){
        this.adjustLayout();

        new Asset.images(['css/img/dialog-tab.png', 'css/img/dialog-log.png', 'css/img/dialog-sup.png', 'css/img/dialog-bug.png', 'css/img/dialog-info.png', 'css/img/promptBox350.png']);

        var self = this;

        // try again as asset with onload event !!

        /*        new Asset.javascript('js/schmedleyMore.js', { 'id': 'schmedMore',
                                                      'onComplete':
                                                      self.run
                                                    }); */
        this.dock = new Dock();

	window.addEvent('resize', this.dock.sizeIcons.bind(this.dock));

        if (!this.registerOnly
            && (typeof Widget) == 'undefined'){
            new Request({'url': 'js/schmedleyMore.js',
                         'onSuccess': function(response){
                             eval(response);
                             self.run();
                         } }).get();
        }
        else {
            self.run();
        }

        if ($('signup')) {
            var subw = $('signup').getFirst().getNext().clientWidth + 20;        // button width
            $('signup').setStyle('left', ((135 - subw) / 2) + 'px');            // button left
        }

        // load the ads
	/*	var req = new Request({'url': 'ads.php',
			       'onSuccess': function(text, xml){
				   var adSpace = $('adSpace');
				   if (adSpace){
				       adSpace.innerHTML = text;
				       self.adjustLayout.delay(1000, self);
				   }
			       }
                              });
        req.get();
	*/

    },

    registerInDock: function(name)
    {
        var i = new Element('img', {
            'id': name,
            'src': 'css/img/dock/' + name + '.png',
            'alt': upperFirst(name)
        });

        i.inject('dock');
    },

    addDesktop: function(id, tabObj, categoryID)
    {
        var deskName = tabObj.name;
        var bgcolor = tabObj.bgcolor;
        var bgimage = tabObj.bgimage;
        var gradState = tabObj.gradient;
        var setActive =  tabObj.active;
        var isWidgetTab =  tabObj.isWidgetTab;
        var privacy = tabObj.privacy;
        var tabURLName = tabObj.tabURLName;
        var defaultTab = tabObj.defaultTab;
        var indexTab  = tabObj.indexTab;

        var color;

        if (bgcolor && bgcolor != ''){
            color = bgcolor;
        }
        else {
            color = dfbg;
        }


        if (isWidgetTab == 1) {
            var newDesk = new Desktop(id, this, '', '', gradState);

            // this doesn't seem to work for meebo even though I defined it in main.css
            // also we need to have the dsktp class on the div or it won't hide.
            // newDesk.el.set('class', deskName + 'Desk');

            // i'd prefer not to have special cases here, but oh well....
            switch(deskName){
            case 'meeboTab':
                // Safari no likey...
                // newDesk.el.setStyle('background', 'url(apps/meebo/img/meebo-bg.png) 0 0 repeat-x');

                // instead...
                newDesk.el.setStyles({
                    'background-image': 'url(apps/meebo/img/meebo-bg.png)',
                    'background-position': '0px 0px',
                    'background-repeat': 'repeat-x'
                });

                var meebo = new Element('iframe', {
                    'id': 'schmeebo',
                    'src': 'https://www.meebo.com',
                    'scrolling': 'auto',
                    'frameborder': 0
                });
                meebo.injectInside(newDesk.el);

                var maskdiv = new Element('div', {
                    'style': 'position: absolute; top: 97px; left: 19px; width: 1px; height: 3px; background: #7094c8;'
                });
                maskdiv.injectInside(newDesk.el);
            }
        }
        else {
            var newDesk = new Desktop(id, this, color, bgimage, gradState);
        }

        this.desktops[id] = newDesk;

        var newTab = new Tab(deskName, newDesk, isWidgetTab, privacy, tabURLName, defaultTab);
        newTab.indexTab = indexTab;
	newTab.categoryID = categoryID;

        this.tabs[id] = newTab;

        if (setActive == 1){
            this.selectTab(newTab, true);
        }

        return newDesk;
    },

    attachTabEvents: function(){
        var tabAdd = $('tabAdd');
        tabAdd.removeEvents('click'); // so these don't pile up during login/logout cycles

        var self = this;
        tabAdd.addEvent('click', function(){
            self.newTab(true, '', 0);
        });
    },

    attachDockEvents: function()
    {
        $$('#dock img').each(function(item, index, array){
            item.removeEvents('click');
            if (item.className == 'widgetTab'){ // for meebo
                item.addEvent('click', this.confirmWidgetTab.bindWithEvent(this));
            }
            else if (item.className == 'launcher'){
                item.addEvent('click', this.widgetLauncherClick.bindWithEvent(this));
            }
	    else if (item.className == 'link'){
		item.addEvent('click', this.openDockLink.bindWithEvent(this));
	    }
            else {
                item.addEvent('click', this.widgetIconClick.bindWithEvent(this));
            }
        }, this);
    },

    removeDockEvents: function(){
        $$('#dock img').each(function(item, index, array){
            item.removeEvents('click');
        }, this);
    },

    widgetIconClick: function(e){
        this.newWidget(e.target.id);
    },

    openDockLink: function(ev){
	window.open(dockLinks[ev.target.id]);
    },

    newWidget: function(widgetName, params){
        if (!this.isWidgetLoaded(widgetName))
        {
            this.widgetLoad(widgetName, params); // createWidget will be called upon script load
        }
        else
        {
            this.createWidget(widgetName, params);
        }
    },

    widgetLauncherClick: function(e){
        widgetName = e.target.id;

        // ok to use the widgetLoaded method
        if (!this.isWidgetLoaded(widgetName)){
            this.launcherLoad(widgetName); // createWidget will be called upon script load
        }
        else{
            this.createLauncher(widgetName);
        }
    },

    confirmWidgetTab: function(e){
        widgetName = e.target.id;

        var self = this;

        new Confirm(widgetName + ' will be launched in its own tab.  Is that OK?', function(){ self.widgetTabClick(widgetName) } );
    },


    widgetTabClick: function(widgetName){
        this.newTab(false, widgetName, 1);
    },


    //--------------------------------------------------

    //--------------------------------------------------

    selectTab: function(tab) {
        var desk = tab.desk;
        for(var i in this.tabs){
            var unTab = this.tabs[i];
            unTab.active(false);
        }

	this.fileBrowsers.each(function(e){
	    if (e.tabID == desk.dbID) {
		e.show();
	    }
	    else {
		e.hide();
	    }
	});


        tab.active(true);

        if ($('cmDefault')) {
            closeColor();            // if the bg color picker is open, close it
        }

        this.activeDesktopID = tab.dbID;
        this.updateColors();

        // tab.adjustTabFontColor();
        if (tab.isWidgetTab == 1) {
            this.dock.hide();
            $$('#color, #grad1, #grad2', '#dsktp', '#toolbar').setStyle('display', 'none');
        }
        else {
            this.dock.show();
            $$('#color, #grad1, #grad2', '#dsktp', '#toolbar').setStyle('display', 'block');
        }

        this.setPrivacyStyles(tab.privacy, true);
	
	this.adjustLayout();
    },

    setPrivacyStyles: function(privacy, useTween){
	if (wLabel) return false;
	
        // see if we're already in public mode
        var logo = $('logo');
        var logoImg = $('logoImg');
        var logoEnv = $('logoEnv');
        var tabs = $('tabs');

        var startLogoPos = logo.getStyle('left');
        var startTabsPos = tabs.getStyle('left');

        if (privacy == 'public'){
            var size = window.getSize();
            var width = 151;
            var height = 65;

            var logoX = size.x - width - 9;
            var logoY = 3;
            var newTabsX = 20;
            //            var newTabsY = 1;

            var envX = 15;
            var envY = 61;
            var envAlign = 'center';

        }
        else {
            var logoX = 0;
            var logoY = 0;
            var newTabsX = 230;
            //            var newTabsY = -8;
            var width = 210;
            var height = 90;

            var envX = 175;
            var envY = 75;
            var envAlign = 'left';

        }

        if (useTween){
            var fx = new Fx.Morph(logo);
            var ifx = new Fx.Morph(logoImg);
            var tfx = new Fx.Morph(tabs);
            var efx = new Fx.Morph(logoEnv);

            tfx.start({
                'left': newTabsX + 'px'
                //                    'top': newTabsY + 'px'
            })
		.chain(function(){
                    fx.start({
			'left': logoX,
			'top': logoY
                    })
			.chain(function(){
			    ifx.start({
				'width': width + 'px',
				'height': height + 'px'
			    })
				.chain(function(){
				    fx.start({
					'width': width + 'px',
					'height': height + 'px'
				    })
				})
			})
		});

            efx.start({
                'left': envX + 'px',
                'top': envY + 'px',
                'text-align': envAlign
            });

        }
        else {
            logo.setStyles({'left': logoX,
                            'top': logoY
                           });
            tabs.setStyles({
                'left': newTabsX
                //                'top': newTabsY
            }
                          );
        }
    },




    // this is to create one that doesn't exist yet
    // (not in DB)
    // params should only be passed for new widgets, these are for initialization
    // 'z' is a reserved parameter

    createWidget: function(widgetName, params)
    {
        /*if (widgetName == 'yahooMail') {
            alert("Under Construction.");
            return;
        }*/

        // need to talk to the DB
        var app = this;

        var currentDesk = this.desktops[this.activeDesktopID];
        var coords = currentDesk.getOpenPosition(widgetName);
        var x = coords[0];
        var y = coords[1];
        var z = currentDesk.widgets.length + 1;

        var pendingDiv = this.showPending(currentDesk, widgetName, x, y, z);
        // insert a Z param so it will be parsed after widget creation
        if (!params){
            params = new Object();
        }
        params['x'] = x + 'px';
        params['y'] = y + 'px';
        params['z'] = z;


        var req = new Request.JSON({'url': "addSchmidget.php",
				    'async': true,
				    'onComplete': function(response){
					if (response.status == 'success'){
					    var widgetID = response.data.tabWidgetID;

					    // add shared/permanent params that come back from the server
					    if (response.data.widgetParams){
						for(paramName in response.data.widgetParams){
						    params[paramName] = response.data.widgetParams[paramName];
						}
					    }

					    app.widgetParams[widgetID] = params;

					    currentDesk.addWidget(widgetName, widgetID, pendingDiv);
					}
					else {
					    app.alert("Failed to add Schmidget.");
					    pendingDiv.destroy();
					}
				    }});
        req.send('n=' + widgetName+ '&t=' + app.activeDesktopID + '&p=' +  JSON.encode(params));
    },

    getDimensions: function(type) {
	switch (type){
	case 'title': return {'w': 160, 'h': 80};
        case 'text': return {'w': 540, 'h': 340};
        case 'photo': return {'w': 320, 'h': 400};
        case 'music': return {'w': 340, 'h': 115};
        case 'video': return {'w': 320, 'h': 400};
        case 'embed': return {'w': 320, 'h': 400};
        case 'comments': return {'w': 540, 'h': 340};
        case 'search': return {'w': 240, 'h': 80};
        case 'images': return {'w': 280, 'h': 280};
        case 'weather': return {'w': 260, 'h': 305};
        case 'showtimes': return {'w': 285, 'h': 335};
        case 'previews': return {'w': 200, 'h': 280};
        case 'asteroids': return {'w': 440, 'h': 380};
        case 'frogger': return {'w': 410, 'h': 480};
        case 'youtube': return {'w': 370, 'h': 470};
        case 'lastfm': return {'w': 220, 'h': 220};
        case 'maps': return {'w': 490, 'h': 425};
        case 'stocks': return {'w': 250, 'h': 125};
        case 'amazon': return {'w': 240, 'h': 125};
        case 'feed': return {'w': 300, 'h': 300};
        case 'stickyNotes': return {'w': 250, 'h': 230};
        case 'clock': return {'w': 260, 'h': 130};
        case 'calendar': return {'w': 220, 'h': 220};
        case 'todoList': return {'w': 250, 'h': 195};
        case 'bookmarks': return {'w': 250, 'h': 105};
        case 'facebook': return {'w': 330, 'h': 330};
        case 'myspace': return {'w': 300, 'h': 320};
        case 'twitter': return {'w': 320, 'h': 320};
        case 'friendFeed': return {'w': 320, 'h': 320};
        case 'contacts': return {'w': 280, 'h': 300};
        case 'gmail': return {'w': 350, 'h': 295};
        case 'yahooMail': return {'w': 350, 'h': 295};
        case 'hotmail': return {'w': 350, 'h': 295};
        case 'mobileMe': return {'w': 350, 'h': 295};
        case 'aolMail': return {'w': 350, 'h': 295};
        case 'genericMail': return {'w': 350, 'h': 500};        
	    
        default: return {'w': 250, 'h': 250};
	}
    },

    showPending: function(desk, widgetName, x, y, z) {
        var w = this.getDimensions(widgetName).w;
        var h = this.getDimensions(widgetName).h;

        var pendingDiv = new Element('div', {'html': '&nbsp;', 'class': 'pendingWidget'});
        pendingDiv.setStyles({'left': (x + 9) + 'px', 'top': (y + 4) + 'px', 'width': (w - 20) + 'px', 'height': (h - 20) + 'px', 'z-index': z});
        pendingDiv.setOpacity(0);
        pendingDiv.injectInside(desk.el);
        pendingDiv.set('tween', {duration: 'short'});
        this.fade('in', pendingDiv);

        return pendingDiv;
    },

    isWidgetLoaded: function(widgetName)
    {
        var headContents = document.head.innerHTML.toString();
        return (headContents.indexOf(widgetName + 'JS') >= 0);
    },

    widgetLoad: function(widgetName, params)
    {
        new Asset.css('apps/' + widgetName + '/' + widgetName + comp + '.css', {'id': widgetName + 'CSS'});
        new Asset.javascript('apps/' + widgetName + '/' + widgetName + comp + '.js', {'id': widgetName + 'JS', 'onload':
                                                                                      function(e){
                                                                                          this.createWidget(widgetName, params);
                                                                                      }.bindWithEvent(this)
                                                                                     });
    },

    launcherLoad: function(launcherName){
        new Asset.css('apps/' + launcherName + '/' + launcherName + comp + '.css', {'id': launcherName + 'CSS'});
        new Asset.javascript('apps/' + launcherName + '/' + launcherName + comp + '.js', {'id': launcherName + 'JS', 'onload':
                                                                                          function(e){
                                                                                              this.createLauncher(launcherName);
                                                                                          }.bindWithEvent(this)
                                                                                         });
    },

    createLauncher: function(launcherName){
        if (this.launchers[launcherName]) return false;
        lf.getInstance(launcherName);

    },

    removeLauncher: function(launcherName){
        delete(this.launchers[launcherName]);
    },


    //    onAssetLoad: function(e, widgetName, params)
    //  {
    //     console.log('onAsssetLoad');
    //        console.log(widgetName);
    //    console.log(params);
    //    this.createWidget(widgetName, params);
    // },

    /**
    * check that our session is valid
    * returns a JSON object of desktop data if logged in
    * null if not logged in
    **/
    verifyLogin: function(){
        var app = this;
        var req = new Request.JSON({'url': "verifyLogin.php", 'async': false, 'onComplete': function(response){
            if (response.status == 'success'){
                app.removeAllTabs();

                // we're registered and logged in so do the normal
                // or we don't care about invites

                if (response.data.isRegistered == 1
                    || !app.inviteOnly){

                    //                    app.configureDesktops.delay(1, app, response.data.desktop);
                    app.configureDesktops(response.data.desktop);

                    app.activate();

                    if (response.data.forceNewPass == 1){
                        app.forceNewPass();
                    }
                }

                // need this whether registered or not
                // all users have a userID
                app.userID = response.data.id;

                // if we are logged in and registered show it
                if (response.data.isRegistered == 1 ){
                    app.isRegistered = true;

                    app.userName = response.data.userName;
                    app.email = response.data.email;

                    app.statusLoggedIn(response.data.userName);
                    app.bugreport.setStyle('visibility', 'visible');
                }
                // if we're only accepting registered and we're not than show login.
                else {
                    app.bugreport.setStyle('visibility', 'hidden');

                    if (app.inviteOnly){
                        app.launchLogin();
                    }
                    app.isRegistered = false;
                    app.userName = '';

                    // show a tooltip
		    if (showTips){ // defined globally
			var dockhint = new Element('div', {'class': 'dockhint',
							   'html': 'Move your mouse over the icons below to display their names and get a better idea of their function.<br />Clicking on the icons will launch new schmidgets (widgets / applications) onto your current desktop.'});
			$(document.body).adopt(dockhint);
			dockhint.setStyle('display', 'block');
			app.addDialogClose(dockhint, null, {top: -9, left: 14} );
			
			(function(){ schmedley.fade('out', dockhint) }).delay(20000);
		    }

                }

            }
            else {
                app.showError("There was an error retrieving data from the Server.");
            }
        }});
        req.get();            // no parameters
    },

    configureDesktops: function(appConfig){
        if (appConfig.tabs instanceof Array) return; // should be an object if we have tab data.

        var activeID = 0;

        for(var tabID in appConfig.tabs){
            var tab = appConfig.tabs[tabID];
            var desk = this.addDesktop(tabID, tab, tab.categoryID);
            if (tab.active == 1) {
                activeID = tabID;
                this.activeDesktopID = activeID; // need this so we know whether to fadein the widgets or not.
            }
        }

        for(var i = 0; i < 2; i++){ // 0 = active, 1 = non-active
            for(var tabID in appConfig.tabs){
                var tab = appConfig.tabs[tabID];

                // do the active first, then the non-active
                if (i == 0 && tab.active != 1) continue;
                if (i == 1 && tab.active == 1) continue;

                // we expect an object (assoc array), but we get an Array if widgets is empty
                // so just continue;
                if (tab.widgets instanceof Array) continue;

                var desk = this.desktops[tabID];

                for(var tabWidgetID in tab.widgets){ // widgets
                    var widget = tab.widgets[tabWidgetID]; // the data object
                    this.widgetParams[tabWidgetID] = widget.widgetParams; // save for later, after instantiation
                    desk.addWidget(widget.widgetName, tabWidgetID); // the actual schmidget element
                }
            }
        }

        // make sure we set the active tab again after all tabs are added.
        if (activeID > 0) {
            var activeTab = this.tabs[activeID];
            if (activeTab) this.selectTab(activeTab);
        }
        else {                  // if not active tab, set the first one active
            for(var i in this.tabs){
                var tab = this.tabs[i];
                tab.selectTab();
                break;
            }
        }

        this.updateColors();      // will set the tab font colors

	this.adjustLayout();
    },

    newTab: function(checkReg, tabName, isWidgetTab){
        // close tab edit dialogs
        var t = this.getActiveTab();
        t.closeTabDialogs();

        // if not logged in new destop launches registration.
        if (checkReg && !this.isLoggedIn){
            if (this.newTabRegConfirm) {
                return; // don't open multiple
            }

            var self = this;

            this.newTabRegConfirm = this.showConfirm(gls('acp0') + '<br />&nbsp;<br />' + gls('acp1'), this.launchSignup.bindWithEvent(this), function(){ self.newTabRegConfirm = null });
            return;
        }

        var self = this;
        var req = new Request.JSON({'url': "addTab.php",
				    'async': true,
				    'onComplete': function(response){
					if (response){
					    if (response.status == 'success'){
						var tabID = response.data.tabID;
						response.data['gradient'] = 0;
						response.data['active'] = true;
						response.data['name'] = response.data['tabName'];

						self.addDesktop(tabID, response.data, response.data.categoryID);
					    }
					    else {
						self.alert(response.data.reason);
					    }
					}
					else {
					    self.alert("Unable to add Tab/Desktop");
					}
				    }});

        if (!tabName || tabName == ''){
            tabName = gls('tab1');
        }

        req.get({'tn': tabName, 'bg': dfbg, 'iwt': isWidgetTab });
    },

    /*    addTab: function(tabID, tabName, bgcolor) {
    var newDesktop = new Element('div', {    // create a new desktop (<div> element)
    'id': 'desk' + tabID,            // assign it an id - "tab" + the number
    'class': 'dsktp'
    });
    newDesktop.injectBefore('tabs');
    newDesktop.setStyle('height', window.getHeight() + "px");

    this.selectTab(newDesktop);

    return newDesktop;        // return a reference to the desktop
    },*/

    addTabZero: function() {
        this.addDesktop(0, {'name': gls('tab0'),
                            'bgcolor': dfbg,
                            'gradient': 0,
                            'active': true}
                       );
    },

    /*    addCSStoHead: function(x, color) { // x = the number of the new tab that was just created via the addTab function
        var newCSS = new Element('style', { // creates a new temporary CSS (<style>) element in the <head> for the benefit of the bg color picker
        'id': 'css' + x,
        'type': 'text/css'
        });
        if (Browser.Engine.trident5 == true) { // loads the appropriate text/style info inside the newly created <style> tag
            newCSS.styleSheet.cssText = '#desk' + x + ' {background: ' + color + '; height: 100%}'; // for IE7
        }
        else {
            newCSS.textContent = '#desk' + x + ' {background: ' + color + '; height: 100%}'; // for Firefox & Safari
        }
        newCSS.injectInside(document.head);
    },
*/
    getElWidget: function(el){
        if (this.widgets[el.id]){
            return this.widgets[el.id];
        }
        else while(el.getParent()){
            el = el.getParent();
            if (this.widgets[el.id]){
                return this.widgets[el.id];
            }
        }
        return null;
    },

    getElTab: function(tabID){
        if (this.tabs[tabID]){
            return this.tabs[tabID];
        }
        return null;
    },

    logout: function(){
        var app = this;
        var req = new Request({'url': 'logout.php', 'async': false, 'onComplete': function(response){

            app.statusLoggedOut();
            app.verifyLogin();

        }});
        req.get();

        // don't allow launch after logout
        if (this.inviteOnly){
            this.removeDockEvents();
            var tabAdd = $('tabAdd');
            tabAdd.removeEvents('click');
        }

    },

    retrieveUserPass: function() {
        if (this.loginDialog) this.fade('out', this.loginDialog);

        this.upDialog = new Element('div', {
            'id': 'upDialog',
            'class': 'fupdlg'
        });

        this.upDialog.setOpacity(0.0);
        this.upDialog.injectInside(this.horizon);

        var h1 = new Element('h1', {'html': gls('rup0') + ' / ' + gls('rup1')});
        h1.injectInside(this.upDialog);

        var p = new Element('p', {'html': gls('sup3') + '&nbsp;:&nbsp;&nbsp;'});
        p.setStyles({'margin-left': '74px', 'margin-top': '40px'});
        p.injectInside(this.upDialog);

        var email = new Element('input', {'type': 'text',
					  'value': '',
					  'id': 'upEmail'
					 });
        email.injectInside(p);

        p = new Element('p', {'html': gls('sup12') + '&nbsp;:&nbsp;&nbsp;'});
        p.setStyles({'margin-left': '55px', 'margin-top': '25px'});
        p.injectInside(this.upDialog);

        var captchaImg = new Element('img', {'src': 'captcha.php?r=' + Math.random(),
					     'id': 'forgotCaptchaImg'
					    });
        captchaImg.setStyles({'width': '160px', 'height': '40px', 'border': '0px'});
        captchaImg.injectInside(p);

        p = new Element('p');
        p.setStyles({'margin-top': '-10px', 'margin-left': '163px'});
        p.injectInside(this.upDialog);

        var captcha = new Element('input', {'type': 'text',
					    'value': '',
					    'id': 'captcha'
					   });
        captcha.setStyles({'width': '90px'});
        captcha.injectInside(p);
        captcha.addEvent('keypress', this.stopReturn);

        p.appendText('\u00A0');

        var retry = new Element('a', {'href': '#', 'html': gls('sup13')});
        retry.setStyles({'margin-left': 7, 'font-size': 10});
        retry.addEvent('click', function() {
            captchaImg.set('src', 'captcha.php?r=' + Math.random());
            return false;
        });
        retry.injectInside(p);

        var self = this;

        this.upSpinner = new Element('img', {'src': 'css/img/spinner-bt.gif'});
        this.upSpinner.setStyles({'position': 'absolute', 'left': '225px', 'top': '250px', 'display': 'none'});
        this.upSpinner.injectInside(this.upDialog);

        var but = new Button('i', this.upDialog, 'upUsername', 'b', 42, 250, gls('rup0'), null, '');
        but.onClick = function(){
            self.sendUsername(email.value, captcha.value);
        }

        but = new Button('i', this.upDialog, 'upPassword', 'b', 331, 250, gls('rup1'), null, '');
        but.onClick = function(){
            self.sendPassword(email.value, captcha.value);
        }

        this.addDialogClose(this.upDialog);

        this.fade('in', this.upDialog);

        email.focus();


    },

    sendUsername: function(email, captcha){
        if (email == '') {
            alert ('You need to provide an email address');
            return false;
        }

        this.upSpinner.setStyle('display', 'block');

        var self = this;

        var req = new Request.JSON({'url' : 'sendUsername.php', 'onComplete' : function(response){
            if (response.status == 'success'){
                if (self.upDialog){
                    self.fade('out', self.upDialog);
                    self.upDialog.destroy.bindWithEvent(self.upDialog).delay(1000);
                }
                alert("An Email containing your username has been sent to " + email);
            }
            else if (response.status == 'error'){
                self.upSpinner.setStyle('display', 'none');
                alert(response.data.reason);
            }
        } });

        req.send("e=" + email + '&c=' + captcha);

        this.launchLogin.delay(1000, this);

    },

    sendPassword: function(email, captcha){
        if (email == '') {
            alert ('You need to provide an email address');
            return false;
        }

        this.upSpinner.setStyle('display', 'block');

        var self = this;

        var req = new Request.JSON({'url' : 'sendPassword.php', 'onComplete' : function(response){
            if (response.status == 'success'){
                if (self.upDialog){
                    self.fade('out', self.upDialog);
                    self.upDialog.destroy.bindWithEvent(self.upDialog).delay(1000);
                }
                alert("An Email containing your new password has been sent to " + email);
            }
            else if (response.status == 'error'){
                self.upSpinner.setStyle('display', 'none');
                alert(response.data.reason);

            }
        } });

        req.send("e=" + email + '&c=' + captcha);

        this.launchLogin.delay(1000, this);
    },

    forceNewPass: function(){
        var self = this;
        new Prompt('Please enter a new schmedley password.', true, self.setNewPass.bindWithEvent(this), {'password': true, 'confirm password': true}, true);
    },

    setNewPass: function(fields){
        if (!this.validatePass(fields[0].value, fields[1].value)){
            fields[0].focus();
            return false;
        }

        var self = this;
        var req = new Request.JSON({'url' : 'setPassword.php', 'onComplete' : function(response){
            if (response.status == 'success'){
                alert("Your password has been changed.");
            }
            else if (response.status == 'error'){
                alert(response.data.reason);
            }
            self.blackOut('out');
        } });

        req.send("p=" + fields[0].value);

        return true;
    },

    login: function() {
        var login = this.loginDialog;
        var userName = document.getElementById('un');
        var pass = document.getElementById('pw').value;
        var app = this;
	
        var req = new Request.JSON({'url' : 'login.php', 'onComplete' : function(response){
            if (response.status == 'success'){
                app.fade('out', login);
                login.destroy.bindWithEvent(login).delay(1000);
		
                app.removeAllTabs();
                app.statusLoggedIn(response.data.userName);
                app.configureDesktops(response.data.desktop);

                app.activate();

                if (response.data.forceNewPass == 1){
                    app.forceNewPass();
                }

                app.isRegistered = true;
                app.userID = response.data.id;
                app.userName = response.data.userName;
                app.email = response.data.email;

                $('buggy').setStyle('visibility', 'visible');
		
            }
            else {            // how do we show login errors? do we have a mac-like shake?
                alert("Login Failed.<br/>" + response.data.reason);
            }
        }});
        req.get({'u': userName.value, 'p': pass});

    },

    signUp: function(e, button) {
        button.disable(); // prevent multiple clicks

        // do sign up
        // verify form fields
        var signup = $('signupDialog');

        var form = $('signupForm'); // promote to full element

        var fields = ['firstname', 'lastname', 'email', 'username', 'password'];

        var message = '';
        for(var i = 0; i < fields.length; i++){
            if (form[fields[i]].value.trim() == ''){
                message += "Please provide a value for " + fields[i] + "<br />";
            }
        }
        if (message != ''){
            alert(message);
            button.enable();
            return false;
        }

        unLimit = 16;
        if (form.username.value.length > unLimit){
            form.username.value = form.username.value.substring(0, unLimit);
            alert('Sorry, usernames are limited to ' + unLimit + ' characters.');
	    button.enable();
            return false;
        }

	var reserved = new Array(/^apps$/, /^css$/, /^js$/, /^lang$/, /.*\.php/, /^admin/);
	for(var i = 0; i < reserved.length; i++){
	    if (form.username.value.match(reserved[i])){
		alert('Sorry, the username "' + form.username.value + '" is not available.');
		button.enable();
		return false;
	    }
	}

        // email check
        var emailReg = /^[A-Z0-9._%-\+]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
        var emailVal = form.email.value;
        if (!emailVal.match(emailReg)){
            alert("Please Enter a valid Email Address.");
            form.email.focus();
            button.enable();
            return false;
        }

	// escape the plus sign
	emailVal = emailVal.replace('+', '%2b');

        // password check
        var passVal = form.password.value;
        var confirmVal = form.confirm.value;

        if (!this.validatePass(passVal, confirmVal)){
            button.enable();
            return false;
        }

        var date = new Date();
        if (!form.dobMonth.value.match(/[0-9]{1,2}/)
            || form.dobMonth.value > 12){
            alert("DOB Month is invalid.");
            button.enable();
            return false;
        }
        if (!form.dobDay.value.match(/[0-9]{1,2}/)
            || form.dobDay.value > 31){
            alert("DOB Day is invalid.");
            button.enable();
            return false;
        }
        if (!form.dobYear.value.match(/[0-9]{4}/)
            || form.dobYear.value > date.getFullYear()
            || form.dobYear.value < date.getFullYear() - 110){
            alert("DOB Year is invalid.");
            button.enable();
            return false;
        }
        if (!form.agree.checked){
            alert('To complete you registration, you must check the box signifying that you agree with our "Privacy Policy" and "Terms of Use".');
            button.enable();
            return false;
        }


        var self = this;

        var req = new Request.JSON({'url' : 'register.php', 'onComplete' : function(response){
            if (response.status == 'success'){
                self.fade('out', signup);
                signup.destroy.bindWithEvent(signup).delay(1000);

                alert("Thanks for signing up.  You'll receive a confirmation email shortly.");
            }
            else if (response.status == 'error'){
                if (response.data.scope == 'register_username_inuse'){
                    form.username.focus();
                }
                if (response.data.scope == 'register_email_inuse'){
                    form.email.focus();
                }

                alert(response.data.reason);
                button.enable();
                return false;
            }
        }});

        var sex = '';
        for(var i = 0; i < form.sex.length; i++){
            if (form.sex[i].checked) sex = form.sex[i].value;
        }

        req.post({'firstName': form.firstname.value,
                  'lastName': form.lastname.value,
                  'email': emailVal,
                  'sex': sex,
                  'dob': form.dobYear.value + '-' + form.dobMonth.value + '-' + form.dobDay.value,
                  'userName': form.username.value,
                  'password': passVal,
                  'captcha': form.captcha.value
                 });

    },

    validatePass: function(pass1, pass2){
        if (pass1.length < 8){
            alert("Password must be at least 8 characters.");
            return false;
        }

        if (pass1 != pass2){
            alert("Passwords do not match.");
            button.enable();
            return false;
        }
        return true;
    },

    removeAllTabs: function(){
        var idRegEx = /^tab([0-9]*)$/;
        //    for(var i = 0; i < this.tabs.length; i++){
        for (var tabNum in this.tabs){
            var tab = this.tabs[tabNum];
            //        var matches = idRegEx.exec(tab.id);
            //    if (matches){
            //        var tabNum = matches[1];
            var xdesk = "desk" + tabNum;
            var xcss = 'css' + tabNum;
            var xdialog = 'dialog' + tabNum;

            $(xdesk).destroy();
            if ($(xcss)) $(xcss).destroy();
            if ($(xdialog)) $(xdialog).destroy();
            tab.destroy();
        }
        this.tabs = new Object();
        this.desktops = new Object();
        //    }
    },

    getActiveTab: function(){
        var active = this.tabs[this.activeDesktopID];

        if (!active){
            for(var i in this.tabs){
                active = this.tabs[i];
                this.activeDesktopID = i;
                break;
            }
        }
        return active;
    },


    statusLoggedIn: function(userName){
        // set the log in to say logged in
        var signin = document.getElementById('signin');
        signin.destroy();       // start over with no listeners

        signin = new Element('div', {'id': 'loggedin',
                                     'html': userName })
            .injectTop($('infobox'));

        var signup = $('signup');
        signup.destroy();

        var logout = new Button('i', 'infobox', 'logout', 'b', 35, 14, gls('but9'), this.logout.bindWithEvent(this), '');

        this.isLoggedIn = true;

        var self = this;
        self.shimmyLogin(signin);

    },

    hideFlashWidgets: function(){
        for(var i in this.widgets){
            var widget = this.widgets[i];
            if (widget.isFlash){
                widget.el.setStyle('visibility', 'hidden');
            }
        }
    },

    restoreFlashWidgets: function(){
        var activeDesk = this.getActiveDesk();
        for(var i in this.widgets){
            var widget = this.widgets[i];
            if (widget.isFlash
                && widget.desk == activeDesk){
                widget.el.setStyle('visibility', 'visible');
            }
        }

    },

    alert: function(errorText){
        this.hideFlashWidgets();
        this.showError(errorText);
    },

    showError: function(errorText){
        new Alert(errorText, this.restoreFlashWidgets.bind(this));
    },

    showConfirm: function(confirmText, onOK, onCancel){
        return new Confirm(confirmText, onOK, onCancel);
    },

    blackOut: function(dir){
        if (dir == 'in'){
            this.hideFlashWidgets();
            this.bo.setStyles({'opacity': 0,
                               'visibility': 'visible',
                               'display': 'block',
                               'height': window.getHeight(),
                               'width': window.getWidth()
                              });

            this.bos.setStyles({'display': 'block',
                                'visibility': 'visible',
                                'height': window.getHeight(),
                                'width': window.getWidth()
                               });
            this.fade(dir, this.bo);
        }
        else {
            this.restoreFlashWidgets();
            this.fade(dir, this.bo);
            this.hideBlackOut.bindWithEvent(this).delay(400);
        }

    },

    hideBlackOut: function(){
        this.bo.setStyles({'display': 'none'});
    },

    getNumTabs: function(){
        var tabCount = 0;
        for(var i in this.tabs){
            tabCount++;
        }
        return tabCount;
    },

    canDeleteTab: function(){
        if (this.getNumTabs() <= 1){
            return false;
        }
        return true;
    },

    removeTabRef: function(tab){
        if (this.tabs[tab.dbID]){
            delete this.tabs[tab.dbID];
        }
    },


    adjustLayout: function() {
        $$('div.dsktp').setStyle('height', '100%');
	
        var h  = window.getHeight();
        var sh = window.getScrollSize().y;
	
        var safariHeight = document.body.scrollHeight;
	
        var w  = window.getWidth();

	// adjust the BG images
	for(var i in this.desktops){
	    this.desktops[i].layoutBG(true);
	};

        adjustAds();

/*	var aDesk = this.getActiveDesk();
	if (aDesk) var aHeight = aDesk.getHeight();
	else {
	var aHeight = 0;
	 } */

	if (Browser.Engine.webkit) {
            $$('div.dsktp').setStyle('height', Math.max(h, safariHeight));
            if (safariHeight > h) {
                $('rite').setStyle('left', (w-160) + 'px');                // sets the position of the right column w/ the infobox and ads
            }
            else {
                $('rite').setStyle('left', (w-145) + 'px');
            }
        }
        else {
	    var newHeight = Math.max(h, sh);

	    for(var i in this.desktops){
		var desk = this.desktops[i];
		desk.el.setStyle('height', newHeight);
	    }
	    
	    $('rite').setStyle('left', (w-145) + 'px');
	}
	    
        $('rite').style.display = "block"; // display the right column after the position has been set above

        $('tabs').style.width = (w - 400) + "px"; // sets the width of the tabs container to window width - 400 (the width of the logo and schpaces tab)

        schmedley.horizon.style.top = (h/2) + "px";      // add later
        schmedley.horizon.style.width = (w-40) + "px"; // add later

        // alert(h);

        function adjustAds() {
            allOn();

            var desk = schmedley.getActiveDesk();

            //if (desk) {
            //    desk.el.setStyle('height', h);
            //}

            if (h < 1020) {
                var ad5 = $('ad5');
                if (ad5) ad5.setStyle('display', 'none');
            }
            if (h < 875) {
                var ad4 = $('ad4');
                if (ad4) ad4.setStyle('display', 'none');
            }
            if (h < 730) {
                var ad3 = $('ad3');
                if (ad3) ad3.setStyle('display', 'none');
            }
            else { }

            var ad1 = $('ad1');
            var adSpace = $('adSpace');

            if (ad1 && adSpace) adSpace.setStyles({
                'display': 'block',
                'visibility': 'visible'
            });
        }

        function allOn() {
            for(var i = 1; i <= 5; i++){
                $$('#ad1, #ad2, #ad3, #ad4, #ad5').setStyle('display', 'block');
            }
        }

        var active = schmedley.getActiveTab();
        if (active) {
            schmedley.setPrivacyStyles(active.privacy, false);
        }

    },

    bugReport: function(){
        window.open("http://bugs.schmedley.com?user=" + this.userName + '&email=' + this.email);
    },
    /*        if (this.bugDialog && $('bug')) this.bugDialog.setStyle('display', 'block');
        else {
            var newDialog = new Element('div', {    // create the signup dialog box (<div> element)
                'id': 'bug',                // assigns it an id - "signup"
                'class': 'bugdlg'                // assigns the CSS class (supdlg = signup dialog)
                });

            newDialog.setOpacity(0.0);
            newDialog.injectInside($('horizon'));

            newDialog.set('html','<h1>' + gls('bug0') + '</h1><form id="bugForm"><p style="line-height: 29px; text-align: center;">' + gls('bug1') + ':<br /><textarea name="bugDesc" style="width: 328px; height: 234px; resize: none;"></textarea></p></form><img src="css/img/bug.png" alt="bug" style="position: absolute; top: -22px; right: -21px;" />');

            this.addDialogClose(newDialog);

            var self = this;

            var but = new Button('i', 'bug', 'bugGo', 'b', 210, 355, gls('but6'), null, '');                 // makes the "Submit" button

            but.onClick = function(){
                self.sendBugReport();
            }

            this.fade('in', newDialog);

            this.bugDialog = newDialog;
        }

    },

    sendBugReport: function(){
        var form = $('bugForm');
        if (form.bugDesc.value == ''){
            alert(gls('bugA'));
            return false;
        }

        new Request.JSON({'url': 'bugReport.php',
                          'onComplete': function(message){
                              if (message && message.status == 'success'){
                                  if (this.bugDialog) {
                                      this.fade('out', this.bugDialog);
                                      this.bugDialog.destroy();
                                      alert(gls('bugB'));
                                  }
                              }
                          }.bindWithEvent(this),
                          'onFailure': function(message){
                              alert(gls('bugC'));
                          }
                         }).send('bugDesc=' + form.bugDesc.value);

    },
  */
    closeColor: function() {
        var colorMod = $('ColourMod');
        if (colorMod) colorMod.empty();                    // dump the contents of the 'ColourMod' <div>

        for(var i in this.desktops){
            var desk = this.desktops[i];
            desk.colorOpen = false;
        }

        this.updateColors();
    },

    updateColors: function(){
        var tab = this.tabs[this.activeDesktopID];
	
        if (tab) {
            tab.adjustTabFontColor();
        }

	this.parent();
    },

    draggingWidget: function(isDragging){
        this.isDragging  = isDragging;
    },

    manageColor: function(e) {
        var activeDesk = this.getActiveDesk();

        if (!activeDesk) return;

        if (activeDesk.colorOpen) return;

        activeDesk.colorOpen = true;

        var ev = new Event(e);
        var x = ev.target;

        var cmod = new Element('div', {        // creates the bg color picker <div> (cmod = ColourMod)
            'id': 'cmDefault'                // ColourMod Default
        });

        // create the HTML for the color picker...

        cmod.set('html', '<div id="cmColorBox"></div>'
                 + '<div id="cmSatValBg"></div>'
                 + '<img src="css/img/colour-bg.png" id="cmOverlay" alt="" />'
                 + '<div id="cmTop"></div>'
                 + '<div id="cmSatValBox"><div id="cmDot" class="cmDot"></div></div>'
                 + '<div id="cmHueBox"><div id="cmArrow" class="cmArrow"></div></div>'
                 + '<h1>' + gls('gui0') + '</h1>'
                 + '<input type="text" name="cmHex" id="cmHex" value="" maxlength="6" />'
                 + '<a id="cmClose" src="css/img/but-x.png" alt="Close" title="Close" /></a>'
                 + '<div id="cmHueValBox"><input type="text" name="cmHue" id="cmHue" value="0" maxlength="3" /></div>');


        var theColor = activeDesk.el.getStyle('background-color');        // gets the background color of the active desktop
        var hexColor = theColor.replace(/#/, '');                        // removes the "#", leaving the 6-character hex code

        // the color picker only likes 6-digit hex codes
        // IE7 sometimes returns shorthand (3-digit) color codes, so we need to convert those to 6-digit codes...

        if (hexColor.length == 3) {
            var r = hexColor.substring(0, 1) + '';
            var g = hexColor.substring(1, 2) + '';
            var b = hexColor.substring(2, 3) + '';
        }

        cmod.injectInside($('ColourMod'));

        pickColor('#desk' + schmedley.activeDesktopID, 'background', x);    // (element we're working with), (which style we're affecting), (triggering element to position near)

        $('cmHex').value = hexColor;        // sets the text field in the color picker to the 6-character hex code
        hexUpdate();                // updates the color picker's color display per the 'cmHex' value defined above
    },

    /**
* @param {String} type the type of widgets that need notification
* @param {String} url the url of the file that was deleted
*/
    notifyDelete: function(type, url){
	for(var i in this.widgets){
	    var w = this.widgets[i];
	    if (w.type == type){
		w.notifyDelete(url);
	    }
	}
    },

    regFileBrowser: function(fb){
	this.fileBrowsers.push(fb);
    },

    unregFileBrowser: function(fb){
	this.fileBrowsers.erase(fb);
    }

    
});




