/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

var loginObj;
var started = false;
var StorageClass = GlobalStorage;

function setup() {
  if (!isSupportedEngine()) {
    var search = location.search;
    if (!search || search.indexOf("ForceBrowser") < 0) {     
      window.open("unsupported.html", "_top");
      return;
    }  
  }
  widgetsHelper = new WidgetsHelper();
  widgetContext = new WidgetContext("dashboard");
  widgetContext.showErrorPage(false);  
  widgetsPath = getPath();
  if (location.protocol == "file:") {
    dir = new FirefoxLocalDir(widgetsPath);
    keyStorage = new StorageClass();
    favourites = new CookieFavourites(dir, favouritesLoaded);
    isLocal = true;
    isOffline = true;
    dir.getPathList(fillWidgetsList);
    start();
  }
  else {
    sendServerTest(onServerTest);
  }
  /*  
  if (location.protocol == "file:") {
    dir = new FirefoxLocalDir(path);
    dir.getPathList(fillWidgetsList);
  }
  else {
    dir = new ServerDir("commands", $("WidgetsLoading"));
    dir.getCategoryList(fillCategoryList);
  } 
  */ 
}

function start() {
  widgetContext.restoreBackground();
  restoreFavouritesDock();
  if (window.netscape) {
    //netscape.securty.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  }
  window.onblur = function(e) {
    keyStorage.saveAll();
  }      
  window.onunload = function(e) {
    hideAllWidgets();
    keyStorage.saveAll();
  }
  setupWidgets();
  reloadWidgets();
  $("Board").style.display = "block";
  $("StartupLoading").style.display = "none";
  Desktop.hideBusyGlassPane();
  dir.getCategoryList(fillCategoryList);
  dir.getWidgetsCount(fillWidgetsCount);
  started = true;

  //Add Widget from url parameter
  var params = location.search;
  if (params != null && params.length > 0) {
    //Add Widget
    var index = params.indexOf("add=");
    if (index >= 0) {
      var path = params.substring(index + 4);
      index = path.indexOf("&");
      if (index >= 0) {
        path = path.substring(0, index);
      }
      if (path.length > 0) {
        addNewWidget(path);
      }  
    }
    //Add YourMini
    var index = params.toLowerCase().indexOf("addyourmini=");
    if (index >= 0) {
      var path = params.substring(index + 12);
      index = path.indexOf("&");
      if (index >= 0) {
        path = path.substring(0, index);
      }
      if (path.length > 0) {
        addYourMini(decodeURIComponent(path));
      }  
    }
    //Add Gadget
    var index = params.indexOf("addGadget=");
    if (index >= 0) {
      var path = params.substring(index + 10);
      index = path.indexOf("&");
      if (index >= 0) {
        path = path.substring(0, index);
      }
      if (path.length > 0) {
        addGadget(decodeURIComponent(path));
      }  
    }
    //AddImage
    var index = params.indexOf("addImage=");
    if (index >= 0) {
      var path = params.substring(index + 9);
      index = path.indexOf("&");
      if (index >= 0) {
        path = path.substring(0, index);
      }
      if (path.length > 0) {
        var title = "Picture";
        index = params.indexOf("title=");
        if (index >= 0) {
          title = params.substring(index + 6);
          index = title.indexOf("&");
          if (index >= 0) {
            title = title.substring(0, index);
          }
        }
        var refresh = null;  
        index = params.indexOf("refresh=");
        if (index >= 0) {
          refresh = params.substring(index + 8);
          index = refresh.indexOf("&");
          if (index >= 0) {
            refresh = refresh.substring(0, index);
          }
        }
        addImageWidget(decodeURIComponent(path), decodeURIComponent(title), refresh);
      }  
    }
    //AddFeed
    var index = params.indexOf("addFeed=");
    if (index >= 0) {
      var path = params.substring(index + 8);
      index = path.indexOf("&");
      if (index >= 0) {
        path = path.substring(0, index);
      }
      if (path.length > 0) {
        var refresh = null;  
        index = params.indexOf("refresh=");
        if (index >= 0) {
          refresh = params.substring(index + 8);
          index = refresh.indexOf("&");
          if (index >= 0) {
            refresh = refresh.substring(0, index);
          }
        }
        addFeedWidget(decodeURIComponent(path), refresh);
      }  
    }
    //AddSlideshow
    var index = params.indexOf("addSlideshow=");
    if (index >= 0) {
      var path = params.substring(index + 8);
      index = path.indexOf("&");
      if (index >= 0) {
        path = path.substring(0, index);
      }
      if (path.length > 0) {
        addSlideShowWidget(decodeURIComponent(path));
      }  
    }
    //AddCountdown
    var index = params.indexOf("addCountdown=");
    if (index >= 0) {
      var title = Desktop.getParameter(params, "addCountdown", "");
      var time = Desktop.getParameter(params, "time", "");
      var zone = Desktop.getParameter(params, "timeZone", "");
      var repeat = Desktop.getParameter(params, "repeat", "0");
      var url = Desktop.getParameter(params, "url", "");
      var logo = Desktop.getParameter(params, "logo", "");
      var sound = Desktop.getParameter(params, "alert", "");
      addCountdownWidget(decodeURIComponent(title), decodeURIComponent(time), 
                         decodeURIComponent(zone), repeat, 
                         decodeURIComponent(url), decodeURIComponent(logo), 
                         decodeURIComponent(sound));
    }
    //AddCalCountdown
    var index = params.indexOf("addCalCountdown=");
    if (index >= 0) {
      var url = Desktop.getParameter(params, "addCalCountdown", "");
      var logo = Desktop.getParameter(params, "logo", "");
      var sound = Desktop.getParameter(params, "alert", "");
      addCalCountdownWidget(decodeURIComponent(url), decodeURIComponent(logo), 
                         decodeURIComponent(sound));
    }
    //AddWorldClock
    var index = params.indexOf("addWorldClock=");
    if (index >= 0) {
      var city = Desktop.getParameter(params, "addWorldClock", "");
      var lat = Desktop.getParameter(params, "lat", "0");
      var lng = Desktop.getParameter(params, "long", "0");
      var zone = Desktop.getParameter(params, "timeZone", "0");
      var dst = Desktop.getParameter(params, "dst", "false");
      addWorldClockWidget(decodeURIComponent(city), lat, lng, zone, dst);
    }
  }
}

Desktop = function() {  
}

Desktop.getParameter = function (src, key, defaultValue) {
  if (src.indexOf("&amp;") >= 0) {
    src = src.replace(/\&amp\;/g, "&");
  }
  var index = src.indexOf("&" + key + "=");
  if (index < 0) {
    index = src.indexOf("?" + key + "=");
  }
  if (index >= 0) {
    var index2 = src.indexOf("&", index + 1);
    if (index2 >= 0) {
      return Desktop.decode(src.substring(index + key.length + 2, index2));
    }
    return Desktop.decode(src.substring(index + key.length + 2));
  }
  return defaultValue;   
}

Desktop.decode = function (value) {
  var result = decodeURIComponent(value);
  return result.replace(/(\+)/g, " ");
}

/*
 * Busy Glasspane functions
 */
 
Desktop.showBusyGlassPane = function(title, content, hideLoading) {
  closePopout();
  if (hideLoading) {
    $("BusyLoading").style.display = "none";
  }
  else {
    $("BusyLoading").style.display = "block";    
  }
  $("BusyTitle").innerHTML = title;
  $("BusyContent").innerHTML = content;
  var pane = $("BusyGlassPane");
  if (!myBrowser.isIE) {
    pane.style.width = window.innerWidth + "px";
    pane.style.height = window.innerHeight + "px";
  }
  else {
    pane.style.width = document.body.clientWidth + "px";
    pane.style.height = document.body.clientHeight + "px";
  }
  var background = $("BusyBackground");
  var opacity = 0.1;
  background.style.opacity = "" + opacity;
  var darken = function() {
    opacity += 0.05;
    background.style.opacity = opacity + "";
    if (opacity < 0.6) {
      setTimeout(darken, 50);  
    }
  }
  setTimeout(darken, 50);
  pane.style.height="5000px";  
  pane.style.display = "block"; 
  window.scrollTo(0, 0); 
}

Desktop.hideBusyGlassPane = function() {
  $("BusyGlassPane").style.display = "none";
}

Desktop.reshowBusyGlassPane = function() {
  closePopout();
  $("BusyGlassPane").style.display = "block";  
} 

function onServerTest(request) {
  keyStorage = new StorageClass();
  if (request.status == 200) {
    myBrowser.hasProxy = true;
    dir = new ServerDir("commands", $("ControlsLoading"));
    loginObj = new Login($("WidgetsLoading"), function(success) {
      afterLogin(success);
    }, null);
    var page = Desktop.getParameter(location.search, "page");
    if (page) {
      keyStorage = new KeyStorage(); //in memory storage
      loadPage(page);
    }
    else {
      loginObj.checkAutoLogin();
    }  
  }
  else {
    //HFS
    isOffline = true;
    dir = new ServerDir("myWidgets.txt", $("ControlsLoading"));
    favourites = new CookieFavourites(dir, favouritesLoaded);
    start();
  }
}

function loadPage(page) {
  var password = Desktop.getParameter(location.search, "password");
  Sharing.loadPage(function(page, result, error) {
    pageLoaded(page, result, error);
  }, "widgets", page, password);   
}

function pageLoaded(page, result, error) {
  if (page) {
    Desktop.page = page;
    updateSharingIcon(page)
  }
  if (result != null && error == null) {
    widgetsHelper.clearList();
    for (var i = 0; i < result.length; i++) {
      keyStorage.store(result[i][0], result[i][1], result[i][2], result[i][3]);          
    }
  }
  afterLogin(false);  
}

function afterLogin(success) {  
  widgetContext.restoreBackground();
  if (success) {
    favourites = new ServerFavourites(dir, favouritesLoaded);
  }
  else {
    favourites = new CookieFavourites(dir, favouritesLoaded);
    if (keyStorage.get("widgets", "list", "all") == null) {
      addDefaultWidgets();
    }      
  }  
  Desktop.hideBusyGlassPane();
  if (!started) {
    start();
    if (!success) {
      Desktop.showBusyGlassPane("<img src='images/WidgetopLogo.png'> Welcome to Widgetop", $("StartupTemplate").innerHTML, true);
      if (myBrowser.isExperimental) {
        $("StartupBrowserExperimental").style.display = "block";
      }
      if (!myBrowser.supported) {
        $("StartupBrowserUnsupported").style.display = "block";
      }
    }
  }
  else {
    reloadWidgets();
  }  
}

function addDefaultWidgets() {
  if (startupWidgets) {
    for (var i = 0; i < startupWidgets.length; i++) {      
      var id = widgetsHelper.addWidget(startupWidgets[i].title, startupWidgets[i].path);
      widgetsHelper.storeWidgetKey(id, "top", startupWidgets[i].top + "px");  
      widgetsHelper.storeWidgetKey(id, "left", startupWidgets[i].left + "px");
      widgetsHelper.storeWidgetKey(id, "type", startupWidgets[i].type);
      if (startupWidgets[i].settings) {
        var settings = startupWidgets[i].settings;
        for (var property in settings) {
          var key = property;
          if (key.indexOf("#ID") >= 0) {
            key  = key.replace(/\#ID/, id);
          }
          keyStorage.store("widget", startupWidgets[i].type, key, settings[property]);
        }              	
      }
    }
  }
}

/***
  Popup Section code
***/

function openPopout(id) {
  closePopoutSection();
  $("PopoutSectionWrapper").style.display = "block";
  var section = $(id);
  section.style.display = "block";
}

function closePopoutSection() {
  var popup = $("PopoutSection");
  var sections = popup.getElementsByTagName("div");
  for (var i = 0; i < sections.length; i++) {
  	if (sections[i].className.indexOf("popoutSection") >= 0) {
  	  sections[i].style.display = "none";
  	}
  }
}

function closePopout() {
  closePopoutSection();
  $("PopoutSectionWrapper").style.display = "none";  
}

/***
  Add gadgets section code
***/

function showAddGadgets() {
  openPopout("GadgetsAddSection");
}

function copyGadgetDemoCode() {
  $("GadgetCodeInput").value = '<script src="http://gmodules.com/ig/ifr?url=http://abowman.googlepages.com/spider.xml&amp;synd=open&amp;w=320&amp;h=200&amp;title=Spider&amp;border=%23ffffff%7C3px%2C1px+solid+%23999999&amp;output=js"></script>';
}

function addGadget(code) {
  if (code == null) {
    code = $("GadgetCodeInput").value;
  }  
  var index = code.indexOf('http://gmodules.com');
  if (index >= 0) {
    var last = code.indexOf('"', index);
    if (last < 0) {
      last = code.length;
    }
    code = code.substring(index, last);
    var path = "AGoogleGadgetWidget";
    var id = widgetsHelper.addWidget("Google Gadget", path);
    widgetsHelper.storeWidgetKey(id, "top", "0px");  
    widgetsHelper.storeWidgetKey(id, "left", "0px");
    var type = "com.pietjonas.hector.GoogleGadget";
    widgetsHelper.storeWidgetKey(id, "type", type);
    keyStorage.store("widget", type, id + "-src", code);
    reloadWidget(id, path);    
  }  
}

function clearAddGagdet() {
  $("GadgetCodeInput").value = "";
}

/***
  Add yourminis section code
***/

function showAddYourMinis() {
  openPopout("YourMinisAddSection");
}

function copyYourMiniDemoCode() {
  $("YourMiniCodeInput").value = '<embed pluginspage="http://www.adobe.com/go/getflashplayer" src="http://www.yourminis.com/Dir/GetContainer.api?uri=yourminis/yourminis/mini:youtube" FlashVars="height=270&xheight=280&xwidth=370&width=360&uri=yourminis%2Fyourminis%2Fmini%3Ayoutube&swfurl=%2Fwidget%5Fyoutube%2Eswf&" type="application/x-shockwave-flash" allowScriptAccess="always" wmode="transparent" width="370" height="280"></embed>';
}

function addYourMini(code) {
  if (code == null) {
    code = $("YourMiniCodeInput").value;
  }  
  var path = "AYourMinisWidget";
  var id = widgetsHelper.addWidget("YourMinis Widget", path);
  widgetsHelper.storeWidgetKey(id, "top", "0px");  
  widgetsHelper.storeWidgetKey(id, "left", "0px");
  var type = "com.pietjonas.hector.YourMinis";
  widgetsHelper.storeWidgetKey(id, "type", type);
  keyStorage.store("widget", type, id + "-src", code);
  reloadWidget(id, path);    
}

function clearAddYourMini() {
  $("YourMiniCodeInput").value = "";
}

/***
  Add RSS section code
***/

function showAddRss() {
  openPopout("RssAddSection");
}

function addRssFeed(slideshow) {
  var url = $("RssFeedSearchInput").value;
  google.feeds.lookupFeed(url, function(result) {
    if (result.error) {
      if (slideshow) {
        addSlideShowWidget(url);
      }
      else {  
        addFeedWidget(url);
      }  
    }
    else {
      if (slideshow) {
        addSlideShowWidget(result.url);
      }
      else {  
        addFeedWidget(result.url);
      }  
    }  
  });
}

function searchRssFeeds() {
  $("RssFeedSearchResults").style.display = "none";
  $("RssFeedSearchLoading").style.display = "block";
  $("RssFeedSearchResults").innerHTML = "";
  $("RssFeedSearchResults").selected = null;
  var search = $("RssFeedSearchInput").value;
  google.feeds.findFeeds(search, function(result) {
    $("RssFeedSearchLoading").style.display = "none";
    $("RssFeedSearchResults").style.display = "block";
    if (!result.error) {
      if (result.entries.length > 0) {
        for (var i = 0; i < Math.min(8, result.entries.length); i++) {
        	var entry = result.entries[i];
        	var div = document.createElement("div");
        	$("RssFeedSearchResults").appendChild(div);
        	div.className = "rssFeedSearchResult";
        	if (i % 2 != 0) {
          	div.className = "rssFeedSearchResult rssFeedSearchResultEven";      	  
        	}
        	var title = document.createElement("div");
        	div.appendChild(title);
        	title.className = "rssFeedSearchResultTitle";
        	title.innerHTML = entry.title;
        	title.onclick = function() {
        	  if ($("RssFeedSearchResults").selected) {
        	    $("RssFeedSearchResults").selected.addButton.style.display = "none";
        	    $("RssFeedSearchResults").selected.addSsButton.style.display = "none";
        	    $("RssFeedSearchResults").selected.content.style.display = "none";
        	    $("RssFeedSearchResults").selected.link.style.display = "none";
        	    $("RssFeedSearchResults").selected.parentNode.style.backgroundColor = "";
        	  }
        	  if ($("RssFeedSearchResults").selected != this) {
        	    this.addButton.style.display = "inline";
        	    this.addSsButton.style.display = "inline";
        	    this.content.style.display = "block";
        	    this.link.style.display = "block";
       	      this.parentNode.style.backgroundColor = "#202020";
        	    $("RssFeedSearchResults").selected = this;
        	  }
        	  else {
        	    $("RssFeedSearchResults").selected = null;      	    
        	  }  
        	}
        	var content = document.createElement("div");
        	div.appendChild(content);
        	content.className = "rssFeedSearchResultContent";
        	content.innerHTML = entry.contentSnippet;
        	content.style.display = "none";
        	title.content = content;      	
        	var link = document.createElement("a");
        	div.appendChild(link);
        	link.className = "widgetInfoLink rssFeedSearchResultLink";
        	link.innerHTML = entry.link;
        	link.style.display = "none";
        	link.href = entry.link;
        	link.target = "_blank";      	
        	title.link = link;      	
        	var add = document.createElement("button");
        	div.appendChild(add);
        	add.className = "rssFeedSearchResultButton";
        	add.innerHTML = "Add Feed";
        	add.link = entry.url;
        	add.style.display = "none";
        	add.onclick = function() {
        	  addFeedWidget(this.link);
        	}
        	title.addButton = add;
        	//slideshow
        	var addSs = document.createElement("button");
        	div.appendChild(addSs);
        	addSs.className = "rssFeedSearchResultButton";
        	addSs.innerHTML = "Add Slideshow";
        	addSs.link = entry.url;
        	addSs.style.display = "none";
        	addSs.onclick = function() {
        	  addSlideShowWidget(this.link);
        	}
        	title.addSsButton = addSs;
        }
      }
      else {
        $("RssFeedSearchResults").innerHTML = "<p /><b>No results</b><p />";        
      }  
    }
    else {
      $("RssFeedSearchResults").innerHTML = "<p /><b>Error:</b> " + result.error.message + "<p />";
    }
  });
}

/***
  Add image widget setion code
***/

function addImageWidget(url, title, refresh) {
  if (url.length >= 0) {
    var path = "AHectorPictureFrame";
    var id = widgetsHelper.addWidget("Picture Frame", path);
    widgetsHelper.storeWidgetKey(id, "top", "0px");  
    widgetsHelper.storeWidgetKey(id, "left", "0px");
    var type = "com.pietjonas.hector.PictureFrame";
    widgetsHelper.storeWidgetKey(id, "type", type);
    keyStorage.store("widget", type, id + "-url", url);
    keyStorage.store("widget", type, id + "-title", title);
    if (refresh != null) {
      refresh = parseInt(refresh);
      if (refresh != NaN) {
        keyStorage.store("widget", type, id + "-refresh", refresh * 60);
      }
    }
    reloadWidget(id, path);    
  }  
}

 
/***
  Add countdown widgets section code
***/

function addCountdownWidget(title, timeString, zone, repeat, url, logo, sound) {
  var path = "AHectorCountdown";
  var id = widgetsHelper.addWidget("Countdown", path);
  widgetsHelper.storeWidgetKey(id, "top", "0px");  
  widgetsHelper.storeWidgetKey(id, "left", "0px");
  var type = "com.pietjonas.hector.AHectorCountdown";
  widgetsHelper.storeWidgetKey(id, "type", type);
  if (title.length > 0) {
    keyStorage.store("widget", type, id + "-title", title);
  }
  if (timeString.length > 0) {  
    var numbers = timeString.split("_");
    var time = new Date(parseInt(numbers[0]), parseInt(numbers[1]) - 1, parseInt(numbers[2]), parseInt(numbers[3]), parseInt(numbers[4]));
    if (zone.length > 0) {
      var timeZone = parseInt(zone);
      var zone = time.getTimezoneOffset();
      time.setMinutes(time.getMinutes() - zone - 60*timeZone);
    }  
    keyStorage.store("widget", type, id + "-time", "" + time.getTime());
  }  
  if (repeat != null) {
    repeat = parseInt(repeat);
    if (repeat != NaN) {
      keyStorage.store("widget", type, id + "-repeat", repeat);
    }
  }
  if (url.length > 0) {
    keyStorage.store("widget", type, id + "-url", url);
  }
  if (logo.length > 0) {
    keyStorage.store("widget", type, id + "-logo", logo);
  }
  if (sound.length > 0) {
    keyStorage.store("widget", type, id + "-sound", sound);
  }
  reloadWidget(id, path);    
}

function addCalCountdownWidget(url, logo, sound) {
  var path = "AGoogleCountdown";
  var id = widgetsHelper.addWidget("Countdown", path);
  widgetsHelper.storeWidgetKey(id, "top", "0px");  
  widgetsHelper.storeWidgetKey(id, "left", "0px");
  var type = "com.pietjonas.hector.AGoogleCountdown";
  widgetsHelper.storeWidgetKey(id, "type", type);
  if (url.length > 0) {
    keyStorage.store("widget", type, id + "-calUrl", url);
  }
  if (logo.length > 0) {
    keyStorage.store("widget", type, id + "-logo", logo);
  }
  if (sound.length > 0) {
    keyStorage.store("widget", type, id + "-sound", sound);
  }
  reloadWidget(id, path);    
}

/***
  Add feed widget section code
***/

function addFeedWidget(url, refresh) {
  if (url.length >= 0) {
    var path = "AHectorSingleRSS";
    var id = widgetsHelper.addWidget("RSS Feed", path);
    widgetsHelper.storeWidgetKey(id, "top", "0px");  
    widgetsHelper.storeWidgetKey(id, "left", "0px");
    var type = "com.pietjonas.hector.SingleRSS";
    widgetsHelper.storeWidgetKey(id, "type", type);
    keyStorage.store("widget", type, id + "-feed", url);
    if (refresh != null) {
      refresh = parseInt(refresh);
      if (refresh != NaN) {
        keyStorage.store("widget", type, id + "-refresh", refresh);
      }
    }
    reloadWidget(id, path);
    sendServerTest(null, "/addFeedWidget.desktop");    
  }  
}
 

/***
  Add slideshow widget section code
***/

function addSlideShowWidget(url) {
  if (url.length >= 0) {
    var path = "AHectorSlideshow";
    var id = widgetsHelper.addWidget("Slideshow", path);
    widgetsHelper.storeWidgetKey(id, "top", "0px");  
    widgetsHelper.storeWidgetKey(id, "left", "0px");
    var type = "com.pietjonas.hector.Slideshow";
    widgetsHelper.storeWidgetKey(id, "type", type);
    keyStorage.store("widget", type, id + "-site", "0");
    keyStorage.store("widget", type, id + "-url", url);
    reloadWidget(id, path);
    sendServerTest(null, "/addSlideshowWidget.desktop");    
  }  
}
 

/***
  Add WorldClock widget section code
***/

function addWorldClockWidget(city, lat, lng, zone, dst) {
  if (url.length >= 0) {
    var path = "AHectorClock";
    var id = widgetsHelper.addWidget("World Clock", path);
    widgetsHelper.storeWidgetKey(id, "top", "0px");  
    widgetsHelper.storeWidgetKey(id, "left", "0px");
    var type = "com.pietjonas.hector.AHectorWorldClock";
    widgetsHelper.storeWidgetKey(id, "type", type);
    keyStorage.store("widget", type, id + "-location", city);
    lat = parseFloat(lat);
    if (lat != NaN) {
      keyStorage.store("widget", type, id + "-lat", lat);
    }
    lng = parseFloat(lng);
    if (lng != NaN) {
      keyStorage.store("widget", type, id + "-long", lng);
    }
    zone = parseInt(zone);
    if (zone != NaN) {
      keyStorage.store("widget", type, id + "-zone", zone);
    }
    if (dst == "true") {
      keyStorage.store("widget", type, id + "-dst", true);      
    }
    reloadWidget(id, path);    
  }  
}
 

/***
  Add widgets section code
***/

function showAddWidgets() {
  openPopout("WidgetsAddSection");
}

function addOptionElement(selector, value, text) {
  var option = document.createElement("option");
  option.setAttribute("value", value);
  option.appendChild(document.createTextNode(text));
  selector.appendChild(option);
}

function fillWidgetsCount(count) {
  $("WidgetCount").innerHTML = count;
}

function fillCategoryList(list) { 
  var selector = $("CategorySelector");  
  if (list == null) {
    if ($("CategorySelectorBox") != null) {
      $("CategorySelectorBox").style.display = "none";
    }  
    $("CategorySelectorEmpty").style.display = "block";
    dir.getPathList(fillWidgetsList, null);
  }
  else {  
    $("CategorySelectorBox").style.display = "block";
    //selector.style.display = "block";
    $("CategorySelectorEmpty").style.display = "none";
    var group = document.createElement("optgroup");
    group.setAttribute("label", "Special");
    selector.appendChild(group);
    addOptionElement(group, "Favourites", "My Favourites"); 
    addOptionElement(group, "LastAdded", "Last Added"); 
    addOptionElement(group, "LastUpdated", "Last Updated"); 
    addOptionElement(group, "Featured", "Featured"); 
    addOptionElement(group, "Top50", "Top Widgets"); 
    addOptionElement(group, "Widgetop", "Widgetop"); 
    if (list.length > 0) {
      group = document.createElement("optgroup");
      group.setAttribute("label", "Category");
      selector.appendChild(group);
      //addOptionElement(selector, "", "-----------------"); 
      for (var i = 0; i < list.length; i++) {      
        addOptionElement(group, list[i].category, list[i].category + " (" + list[i].count + ")");
      }
    }  
    selector.selectedIndex = -1;
    fillWidgetsList(null);  
  }
}

function fillWidgetsList(dirs) {
  var selector = $("WidgetSelector");
  selector.innerHTML = "";
  if (dirs == null || dirs.length == 0) {
    $("WidgetSelectorEmpty").style.display = "block";
    $("WidgetSelectorBox").style.display = "none";
    setWidgetInfo(null);
    return;
  }
  if (myBrowser.isIE) {
    //strange bug fix
    $("WidgetSelectorBox").style.display = "none";
    $("WidgetSelectorEmpty").style.display = "block";
  }  
  $("WidgetSelectorEmpty").style.display = "none";
  $("WidgetSelectorBox").style.display = "block";
  /*
  while (selector.firstChild) {
    selector.removeChild(selector.lastChild);
  }
  */
  for (var i = 0; i < dirs.length; i++) {
    var option = document.createElement("option");
    option.setAttribute("value", dirs[i].path);
    var title = dirs[i].title;
    if (dirs[i].featured) {
      title = "*" + title;
    }
    option.appendChild(document.createTextNode(title));
    selector.appendChild(option);
  }
}

function categoryChanged() {
  setWidgetInfo(null);
  var selector = $("CategorySelector");
  if (selector.value != null && selector.value.length > 0) {
    var widgets = $("WidgetSelector");
    widgets.innerHTML = "<optgroup label='Loading...'></optgoup>";    
    $("WidgetSelectorEmpty").style.display = "none";
    $("WidgetSelectorBox").style.display = "block";
    dir.getPathList(fillWidgetsList, selector.value);  
  }  
}

function widgetInfoChanged() {  
  var selector = $("WidgetSelector");
  dir.getWidgetInfo(setWidgetInfo, selector.value);  
}

function setWidgetInfo(info) {
  var widgetInfo = $("WidgetInfo");  
  if (info == null) {
    widgetInfo.style.display = "none";
    $("WidgetInfoEmpty").style.display = "block";
    return;
  }
  $("WidgetInfoEmpty").style.display = "none";
  if (widgetInfo) {
    widgetInfo.style.display = "inline";
    var title = $("WidgetInfoTitle");
    title.innerHTML = info.title;
    if (info.featured) {
      $("WidgetInfoFeatured").style.display = "block";
    }
    else {
      $("WidgetInfoFeatured").style.display = "none";      
    }
    var description = $("WidgetInfoDescription");
    description.innerHTML = "<b>Click for full description & screenshot...</b>";
    if (info.description) {
      description.title = info.description;
    }
    else {
      description.title = "No description";
    }
    var summary = $("WidgetInfoSummary");
    if (info.summary) {
      summary.innerHTML = info.summary;
    }
    else {
      summary.innerHTML = "No summary";
    }    
    var version = $("WidgetInfoVersion");
    version.innerHTML = info.version;
    var icon = $("WidgetInfoIcon");
    icon.setAttribute("src", widgetsPath + info.path + "/Icon.png");    
    var modified = $("WidgetInfoModified");
    if (info.updated) {
      var date = new Date();
      date.setTime(info.updated);
      modified.innerHTML = date.toLocaleString();
    }  
    var icoImage = new Image();
    icoImage.onerror = function() {
      var imagePath = getHectorPath() + "images/";
      icon.setAttribute("src", imagePath + "defaultIcon.png");
    };
    icoImage.src = icon.src;
    var developer = $("WidgetInfoCompany");
    developer.innerHTML = info.companyName;
    developer.href = info.companyUrl;
  }  
}

function showWidgetInfoDescription() {
  var description = $("WidgetInfoDescription");
  var screenshot = $("WidgetInfoIcon").src;
  screenshot = screenshot.substring(0, screenshot.length - 8) + "_hectorScreenshot.png";
  Desktop.showBusyGlassPane(
    $("WidgetInfoTitle").innerHTML,
    "<p style='text-align: center'><img id='WidgetInfoScreenshot' src='" + screenshot +"'></p>" +
    "<p style='font-size: 13px'>" + description.title + "</p>" +
    "<p style='text-align: center'>" +
    "<button onclick='Desktop.hideBusyGlassPane();addCommand()'>Add Widget</button>" +
    "&nbsp;&nbsp;&nbsp;<button onclick='Desktop.hideBusyGlassPane()'>Close</button>" +
    "</p>", true);
  description.innerHTML = description.title;
  $("WidgetInfoScreenshot").width = "";
  var img = new Image();
  img.src = screenshot;
  img.onload = function() {
    var width = img.width;
    if (width > 360) {
      width = 360;
    }
    $("WidgetInfoScreenshot").width = width;
  }
}

/***
  Background settings function 
***/
var settings;
function showSettings() {
  if (settings == null) {
    settings = new Settings();
  }
  openPopout("SettingsSection");
  settings.fillColors();
  settings.updateSettings();
}

function Settings() {
  this.setup = function() {
    this.fillColors();
    $("BgRepeat").onchange = function() {
      widgetContext.setBackgroundAttribute("Repeat", 
        $("BgRepeat").value);
    }
    $("BgHPosition").onchange = function() {
      settings.positionUpdated();
    }
    $("BgVPosition").onchange = function() {
      settings.positionUpdated();
    }
    this.updateSettings();
    this.urlUpdated();
  }
  
  this.updateSettings = function() {
    this.selectOption($("BgColor"), 
               widgetContext.getBackgroundAttribute("Color"));
    $("BgUrl").value = "";
    var value = widgetContext.getBackgroundAttribute("Image");
    if (value.length > 0) {
      var index = value.indexOf("url(");
      if (index == 0) {
        $("BgUrl").value = value.substring(4, value.length - 1);
      }  
    }
    this.urlUpdated();  
    this.selectOption($("BgRepeat"), 
                 widgetContext.getBackgroundAttribute("Repeat"));
    var position = widgetContext.getBackgroundAttribute("Position");
    
    if (position != null) {
      position = position.split(" ", 2);
      for(var i = 0; i < position.length; i++) {
        this.selectOption($("BgHPosition"), position[i]);
        this.selectOption($("BgVPosition"), position[i]);   
      }
    }               
  }
  
  this.updateBackground = function() {
    background.style.background = widgetContext.getBackground();  
  }
  
  this.fillColors = function() {
    var colors = $("BgColor");
    for(var i =0; i < colors.options.length; i ++) {
    	if (myBrowser.supportsListColor) {
    	  colors.options[i].style.backgroundColor = colors.options[i].value;
    	  colors.options[i].style.color = colors.options[i].value;
    	}
    	else {
    	  colors.options[i].innerHTML = colors.options[i].value;
    	}  
    }
    colors.style.backgroundColor = colors.value;  
    colors.onchange = this.colorsChanged;
  }
  
  this.colorsChanged = function() {
    var colors = $("BgColor");
    colors.style.backgroundColor = colors.value;
    widgetContext.setBackgroundAttribute("Color", colors.value);
  }
  
  this.urlUpdated = function() {
    var url = $("BgUrl").value;
    if (url == null || url.length == 0) {
      /*
      var rows = $("SettingsBgUrlTable").rows;
      for (var i = 0; i < rows.length; i++) {
      	if (rows[i].className.indexOf("settingsBgUrlExtra") >= 0) {
      	  rows[i].style.visibility = "hidden";
      	}
      }
      */
    }
    else {
      /*
      var rows = $("SettingsBgUrlTable").rows;
      for (var i = 0; i < rows.length; i++) {
      	if (rows[i].className.indexOf("settingsBgUrlExtra") >= 0) {
      	  rows[i].style.visibility = "visible";
      	}
      }
      */
      widgetContext.setBackgroundAttribute("Image", "url(" + url + ")");    
    }
  }
  
  this.positionUpdated = function() {
    var horizontal = $("BgHPosition").value;
    var vertical = $("BgVPosition").value;
    var repeat = $("BgRepeat").value;
    var value = horizontal + " ";
    value += vertical;
    widgetContext.setBackgroundAttribute("Position", value);
  }
  
  this.selectOption = function(selector, value) {
    for(var i=0; i<selector.options.length; i++) {
    	if (selector.options[i].value == value) {
    	  selector.options[i].selected = true;
    	  break;
    	}
    }
  }

  this.setup();
}




function showLogin() {
  Desktop.hideBusyGlassPane();
  loginObj.showLogin();
}

function login() {
  if (loginObj.doLogin()) {
    Desktop.showBusyGlassPane("Login...", "");    
  }
}

function logout() {
  Desktop.showBusyGlassPane("Logout...", "");
  loginObj.doLogout();
}

function removeUser() {
  loginObj.doRemoveUser();
}

function newUser() {
  if (loginObj.newUser()) {
    Desktop.showBusyGlassPane("Create User...", "");    
  }
}

function closeLogin() {
  loginObj.closeLogin();
}      

function showNewUser() {
  Desktop.hideBusyGlassPane();
  loginObj.showNewUser();
}

function changeUserName() {
  loginObj.changeUserName();
}

function changePassword() {
  loginObj.changePassword();
}

function loginDone(user) {
  $("LoginButton").style.display = "none";
  $("LogoutButton").style.display = "inline";
  $("SharingButton").style.display = "inline";
  $("PagesCancel_").style.display = "none";
  $("PagesReplace_").style.display = "none";
  $("RemoveButton").style.display = "inline";
  $("DeveloperButton").style.display = "inline";
  $("ChangeSection").style.display = "block";
  $("ChangeName").value = user;
  $("HeaderSection").className = "headerSection headerSectionOnline";  
  Desktop.hideBusyGlassPane();
  Sharing.loadSharedPage(onSharedLoad, "dashboard");  
}

function logoutDone() {
  $("LoginButton").style.display = "inline";
  $("LogoutButton").style.display = "none";
  $("SharingButton").style.display = "none";
  $("PagesCancel_").style.display = "inline";
  $("PagesReplace_").style.display = "inline";
  $("RemoveButton").style.display = "none";
  var logoutButton = $("DeveloperButton");
  //logoutButton.style.display = "none";
  $("ChangeSection").style.display = "none";
  $("HeaderSection").className = "headerSection headerSectionOffline";  
  Desktop.hideBusyGlassPane();
  Desktop.page = null;
}

function openFeed() {
  var path = location.protocol + "//" + location.host + location.pathname;
  lastSlash = path.lastIndexOf("/");
  if (lastSlash >= 0) {
    path = path.substring(0, lastSlash) + "/";
  }
  window.sidebar.addPanel("New Widgets", path + "rss/widgets.rss", "");
}

/*
 * Sharing functions
 */

function showSharing() {  
  var template = $("SharingTemplate").innerHTML;
  template = template.replace(/\_/g, "");
  Desktop.showBusyGlassPane("<img src='images/sharing2.png'> Desktop Sharing <span class='betaTag'>Beta</span>", template, true);
  if (!Desktop.page) {
    $("SharingLoadSection").style.display = "block";
    Sharing.loadSharedPage(onSharedLoad, "dashboard");
  }
  else {
    updateSharing();
  }  
}

function onSharedLoad(page, status, error) {
  if (!error && status == "success") {
    if (page == null) {
      page = new Object();
      page.status = 2;
      page.desktop = "dashboard";
    }
    Desktop.page = page;
    updateSharingIcon(page)
    updateSharing();
  }
  else {
    $("SharingError").innerHTML = error ? error : status;
    $("SharingLoadSection").style.display = "none";
    $("SharingErrorSection").style.display = "block";
  }    
}

function updateSharingIcon(page) {
  switch (page.status) {
    case 0:
      $("SharingButtonIcon").src = "images/sharingIconPublic.png";
      break;
    case 1:
      $("SharingButtonIcon").src = "images/sharingIconPrivate.png";
      break;
    default:
      $("SharingButtonIcon").src = "images/sharingIcon.png";
      break;    
  }  
}

function updateSharing() {
  if (!$("SharingLoadSection")) {
    return;
  }
  $("SharingLoadSection").style.display = "none";
  $("SharingChangeSection").style.display = "none";
  var page = Desktop.page;
  if (page.status == 2) {
    $("SharingNoInfoSection").style.display = "block";
    $("SharingInfoSection").style.display = "none";
  }
  else {
    $("SharingInfoSection").style.display = "block";
    $("SharingNoInfoSection").style.display = "none";
    $("SharingInfoId").innerHTML = page.path;
    if (page.status == 0) {
      $("SharingInfoPublic").style.display = "inline";
      $("SharingInfoPrivate").style.display = "none";
    }
    else {  
      $("SharingInfoPublic").style.display = "none";
      $("SharingInfoPrivate").style.display = "inline";
    }
    var param = "?page=" + page.path;
    if (page.status == 1 && page.password && page.password.length > 0) {
      param += "&password=" + page.password;
    }
    $("SharingInfoShared").href = "shared.html" + param;
    $("SharingInfoShared").innerHTML = "http://www.widgetop.com/shared.html" + param;  
    $("SharingInfoDesktop").href = param;  
    $("SharingInfoDesktop").innerHTML = "http://www.widgetop.com" + param;  
  }  
}

function showSharingChange() {
  var page = Desktop.page;
  $("SharingChangeTitle").value = page.title ? page.title : "";
  $("SharingChangeDescription").value = page.description ? page.description : "";
  $("SharingChangePublic").checked = page.status == 0;
  publicSharingChanged();
  $("SharingChangePassword").value = page.password ? page.password : "";    
  $("SharingChangeSection").style.display = "block";
  $("SharingInfoSection").style.display = "none";
  $("SharingNoInfoSection").style.display = "none";
}

function publicSharingChanged() {
  if ($("SharingChangePublic").checked) {
    $("SharingChangePublicHelp").style.display = "inline";    
    $("SharingChangePrivateHelp").style.display = "none";    
    $("SharingChangePrivate").style.display = "none";    
  }
  else {
    $("SharingChangePublicHelp").style.display = "none";    
    $("SharingChangePrivateHelp").style.display = "inline";    
    $("SharingChangePrivate").style.display = "inline";    
  }  
}

function sharingChanged() {
  var page = Desktop.page;
  var title = $("SharingChangeTitle").value;
  if (title.length < 3) {
    alert("Title is too short");
    return;
  }
  var description = $("SharingChangeDescription").value;
  if (description.length > 1024) {
    if (confirm("Description too long. Trim it?")) {
      $("SharingChangeDescription").value = description.substring(0, 1024);
    }
    return;  
  }
  page.title = title;
  page.description = description;
  page.status = 0;
  if (!$("SharingChangePublic").checked) {
    page.status = 1;
    page.password = $("SharingChangePassword").value;
  }
  $("SharingLoadSection").style.display = "block";
  $("SharingChangeSection").style.display = "none";
  Sharing.updateSharedPage(onSharedLoad, Desktop.page);
}

function removeSharing() {
  if (!confirm("Really remove the sharing of your desktop?")) {
    return;
  }
  Desktop.page.status = 2;
  $("SharingLoadSection").style.display = "block";
  $("SharingChangeSection").style.display = "none";
  Sharing.removeSharedPage(onSharedLoad, Desktop.page, "dashboard");
}

function closeSharing() {
  Desktop.hideBusyGlassPane();
  Desktop.pane = null;
}

/*
 * Pages functions
 */

function showPages() {
  var template = $("PagesTemplate").innerHTML;
  template = template.replace(/\_/g, "");
  Desktop.showBusyGlassPane("Public Desktops <span class='betaTag'>Beta</span>", template, false);
  if (Desktop.page) {
    Pages.currentPage = Desktop.page;
    $("PagesCancel").style.display = $("PagesReplace").style.display;
  }
  else {
    $("PagesCancel").style.display = "none";
  }  
  Pages.loadPagesInfo(function(error) {
    Desktop.hideBusyGlassPane();
    alert(error);
  });
}

function replaceWithPage(page, done) {
  if (!page) {
    return;
  }
  Sharing.loadPage(function(page, result, error) {
    pageLoaded(page, result, error);
    if (!error && !done) {
      Desktop.reshowBusyGlassPane();      
    }
  }, page.desktop, page.path, page.password);  
}

function backToDefault() {
  Pages.backToDefault();
  Desktop.hideBusyGlassPane();
}

function openDesktop() {
  window.open("desktop.html" + location.search, "_top");
}              
