/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

var keyStorage = null;
var dir = null;
var favourites = null;
var isLocal = false;
var isOffline = false;
var widgetsPath;
var widgetIdPrefix = "Widget";
var lastFrameId = new Date().getTime();

function setupWidgets() {
  if (window.netscape) {
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
  }
  widgetsPath = getPath();
  setupWindow();
}

function getPath() {
  var path = location.protocol + "//" + location.host + location.pathname;
  lastSlash = path.lastIndexOf("/");
  if (lastSlash >= 0) {
    path = path.substring(0, lastSlash) + "/widgets/";
  }
  return path;  
}  

function openBackgroundWidget() {
  addNewWidget("AHectorBackground");
}

/***
  widgets code
***/

function modifyIButtonImageURL(img) {
  if (img == null) {
    return null;
  }  
  var path = getHectorPath() + "/scripts/HectorClasses/Images/";

  var ibutton = img.indexOf("/System/Library/WidgetResources/");
  if (ibutton >= 0) {
    ibutton = img.lastIndexOf("/");
    img = img.substring(ibutton + 1);
    addError("Modify image url to " + path + img);
    return path + img;
  }
  return null;
}  

function modifyIButtonImage(style) {
  if (style && style.backgroundImage) {
    var img = style.backgroundImage;
    if (img.indexOf("url(file:") >= 0 || img.indexOf("url(/System") >= 0) {
      img = modifyIButtonImageURL(img);
      if (img != null) {
        style.backgroundImage = "url(" + img;
      }
    }
  }  
}

function modifyCSS(styles) {
  for (var i = 0; i < styles.length; i++) {
    var rules = null;
    try {
      styles[i].cssRules; //check for security exception
    }
    catch (e) {
      continue;
    }
    if (styles[i].cssRules) {
      rules = styles[i].cssRules;
    }
    else {
      rules = styles[i].rules; //IE     
    }  
    for (var j = 0; j < rules.length; j++) {
      modifyIButtonImage(rules[j].style);
      if (rules[j].styleSheet) {
        for (var k = 0; k < rules[j].styleSheet.cssRules.length; k++) {
          modifyIButtonImage(rules[j].styleSheet.cssRules[k].style);
        }
      }
    }
  }
}

function modifySearchInput(input) {
  var type = input.getAttribute("type");
  if (type == "search" && input.getAttribute("onchange") == null) {
    var onSearch = input.getAttribute("onSearch");
    if (onSearch == null) {
      onSearch = input.getAttribute("onsearch");    
    }
    if (typeof onSearch == "string") {
      input.setAttribute("onchange", onSearch);
    }
    else {
      input.onchange = onSearch;      
    }
    input.style.textIndent = "20px";
    input.style.backgroundImage = "url(" + getHectorPath() + "/images/search.png)";
    input.style.backgroundRepeat = "no-repeat";
    input.style.backgroundPosition = "2px center";
    input.style.color = "gray";
    input.value = input.getAttribute("placeholder");
    var onInputFocus = function() {
      this.value = "";
      this.style.color = null;
      this.removeEventListener("focus", this.onInputFocus, false);
    };
    input.addEventListener("focus", onInputFocus, false);
    input.onInputFocus = onInputFocus;
    var onInputBlur = function() {
      if (this.value == null || this.value.length == 0) {
        this.style.color = "gray";
        this.value = input.getAttribute("placeholder");        
        this.addEventListener("focus", onInputFocus, false);
        this.onInputFocus = onInputFocus;
      }
    };
    input.addEventListener("blur", onInputBlur, false);
  }
}

function modifySearchInputPhone(input) {
  var type = input.getAttribute("type");
  if (type == "search" && input.getAttribute("onchange") == null) {
    var onSearch = input.getAttribute("onSearch");
    if (onSearch == null) {
      onSearch = input.getAttribute("onsearch");    
    }
    if (typeof onSearch == "string") {
      input.setAttribute("onchange", onSearch);
    }
    else {
      input.onchange = onSearch;      
    }
  }
}

function modifyCanvas(canvas) {
  if (canvas.childNodes.length == 0) {
    canvas.appendChild(canvas.ownerDocument.createTextNode("Canvas not supported"));    
    addError("Modifed Canvas " + canvas.id);
  }
}

function modifyScript(script) {
  if (script.getAttribute("src") 
      && script.getAttribute("src").toLowerCase().indexOf("scroller.js") >= 0) {
    var path = getHectorPath() + "scripts/";
    script.src = path + "Scroller.js";
    addError("Modified Script: " + script.src);
  }
}

function modifyDOM(document) {
  var divs = document.getElementsByTagName("div");
  for (var i = 0; i < divs.length; i++) {
    if (divs[i].ownerDocument.defaultView) {
      modifyIButtonImage(divs[i].ownerDocument.defaultView.getComputedStyle(divs[i], ""));
    }
    else {
      modifyIButtonImage(divs[i].currentStyle);      
    }  
  }
  var imgs = document.getElementsByTagName("img");
  for (var i = 0; i < imgs.length; i++) {
    var img = modifyIButtonImageURL(imgs[i].getAttribute("src"));
    if (img != null) {
      imgs[i].setAttribute("src", img);
    }
  }
  var tds = document.getElementsByTagName("td");
  for (var i = 0; i < tds.length; i++) {
    var img = modifyIButtonImageURL(tds[i].getAttribute("background"));
    if (img != null) {
      tds[i].setAttribute("background", img);
    }
  }
  if (!myBrowser.supportsSearchBox) {
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
      if (!myBrowser.isIE) {
        if (myBrowser.supportsSearchBoxPhone) {
          modifySearchInputPhone(inputs[i]);  
        }
        else {  
          modifySearchInput(inputs[i]);  
        }  
      }  
    }
  }
  var canvas = document.getElementsByTagName("canvas");
  for (var i = 0; i < canvas.length; i++) {
    modifyCanvas(canvas[i]);
  }
  var scripts = document.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; i++) {
    //modifyScript(scripts[i]);
  }
  var sheets = document.styleSheets;
  if (sheets.length > 0 && sheets[0].cssRules) {
    sheets[0].insertRule("a img {border: 0px;}", sheets[0].cssRules.length);
  }  
}

function frameLoaded(iframe) {
  var frame = frames[iframe.id];
  //frame.document.getElementsByTagName("body")[0].style.backgroundColor = "transparent";
  if (myBrowser.needsAllowTransparency) {
    frame.document.bgColor = "transparent";
    if (!myBrowser.isIE) {     
      frame.document.getElementsByTagName("body")[0].style.backgroundColor = "transparent";
    }  
  }  
  if (myBrowser.needsWidgetBackgroundColor) {
    frame.document.getElementsByTagName("body")[0].style.backgroundColor = widgetContext.getBackgroundAttribute("Color");
    //frame.document.bgColor = widgetContext.getBackgroundAttribute("Color");
  }
  
  try {
    frameLoaded2(iframe);
  }  
  catch (e) {
    alert(e);
    addError("Widget frameloaded2 failed: " + e);
  }
  try {
    if (!myBrowser.lateOnLoad) {
      if (frame.window.onload) {
        frame.window.onload();
      }
      else {
        var body = frame.document.getElementsByTagName("body");
        if (body[0].onload) {
          //(body[0].onload);
          if (!myBrowser.isIE) {
            body[0].onload();
          }
          else {
            frame.window._hectorStartupFunction = body[0].onload;
            frame.window._hectorStartupFunction();
          }  
        }
      }
      if (frame.window.widget.onshow) {
        frame.window.widget.onshow();
      }
    }
    else {
      frame.window.attachEvent('onload', function() {
        if (frame.window.widget.onshow) {
          frame.window.widget.onshow();
        }
      });
    }
  }  
  catch (e) {
    addError("Widget onload failed: " + e);
    throw e;
  }

  try {
    modifyDOM(frame.document);
  }  
  catch (e) {
    addError("Widget modifyDOM failed: " + e);
  }

  try {
    if (iframe.getAttribute("width") == 0) {
      var style = frame.document.defaultView.getComputedStyle(
        frame.document.getElementsByTagName("body")[0], null);
      
      if (frame.document.getElementsByTagName("body")[0].scrollWidth) {
        frame.window.resizeTo(
          frame.document.getElementsByTagName("body")[0].scrollWidth,
  	    frame.document.getElementsByTagName("body")[0].scrollHeight);
  	  }
  	  else {
  	    frame.window.resizeTo(300, 300);
  	  }
  	  widgetResized(iframe);    
    }
  }  
  catch (e) {
    addError("Widget setSize failed: " + e);
  }

  iframe.setAttribute("scrolling", "no");
  iframe.setAttribute("onload", "frameLoaded2(this);");  

  var id = getWidgetId(iframe.parentNode);  
  if (widgetsHelper.getWidgetValue(id, "status") == "iconify") {
    widgetIconify(iframe.parentNode.parentNode);
  }
  if (window.MobileWidget) {
    frame.window.widget.mobile.removeFrontEvents(frame.window.widget.mobile.front);
  }  
}

function frameLoaded2(iframe) {
  var frame = frames[iframe.id];
  try {
    modifyCSS(frame.window.document.styleSheets);
  }
  catch (e) {
    addError("Modify CSS failed: " + e)
  }  
  var win = new MyWindow(iframe.id);
  frame.window.resizeTo = win.resizeTo;
  frame.window.resizeBy = win.resizeBy;
  frame.window.alert = win.alert;
  
  //Safari fix
  if (myBrowser.needsXMLHttpRequestVariable) {
    var script = frame.window.document.createElement("script");
    script.type = "text/javascript";    
    script.innerHTML = "if (parent.myBrowser.needsXMLHttpRequestVariable) {var XMLHttpRequest;}";
    //script.src = "request.js";
    var heads = frame.window.document.getElementsByTagName("head");
    if (heads.length > 0) {
      heads[0].appendChild(script);
    }  
  }

  var id = getWidgetId(iframe.parentNode);
  var path = widgetsPath + widgetsHelper.getWidgetValue(id, "path");  
  var test = null;
  if (window.XMLHttpRequest) {
    var proxy = 'function ProxyXMLHttpRequest' + id + '() {'
      + 'this.path = "' + path + '/";'
      + 'this.widgetId = "' + id + '";'
      + 'this.request = new XMLHttpRequest();} '
      + 'ProxyXMLHttpRequest' + id + '.prototype = new ' + myBrowser.getXMLHttpRequestName() + '();';
    eval(proxy);
    eval("frame.window.XMLHttpRequest = ProxyXMLHttpRequest" + id + ";");
    //frame.window.XMLHttpRequest = ProxyXMLHttpRequest2;
  }
  else {
    frame.window.XMLHttpRequest = myBrowser.getXMLHttpRequest();
  }  

  frame.window.createGenericButton = createGenericButton;
  frame.window.genericButtonSetEnabled = genericButtonSetEnabled;
  frame.window.AppleButton = HectorButton;
  frame.window.AppleGlassButton = HectorGlassButton;
  frame.window.AppleInfoButton = HectorInfoButton;
  frame.window.AppleAnimation = HectorAnimation;
  frame.window.AppleAnimator = HectorAnimator;
  frame.window.AppleRect = HectorRect;
  frame.window.AppleRectAnimation = HectorRectAnimation;
  frame.window.AppleVerticalScrollbar = HectorVerticalScrollbar;
  frame.window.AppleHorizontalScrollbar = HectorHorizontalScrollbar;
  frame.window.AppleScrollArea = HectorScrollArea;
  //frame.window.AppleSlider = HectorSlider;
  frame.window.AppleVerticalSlider = HectorVerticalSlider;
  frame.window.AppleHorizontalSlider = HectorHorizontalSlider;
  frame.window.Fader = Fader;
  frame.window.Resizer = Resizer;
  frame.window._hectorMyBrowser = myBrowser;
  /* 
  frame.window.scrollerInit = hectorScrollerInit;
  frame.window.calculateAndShowThumb = hectorCalculateAndShowThumb;
  frame.window.SCROLLBAR_DIV_NAME = "myScrollBar";
  frame.window.mouseDownScrollThumb = function() {};
  /* */  
    
  //frame.window.Stretcher = Stretcher;

  if (myBrowser.makeCompatible) {
    myBrowser.makeCompatible(frame.window, frame.window.document);
  }
  
  var widgetId = id;
  if (window.testWidgetId) {
    widgetId = testWidgetId;
  }
  var widget = new Widget(widgetId, widgetsHelper.getWidgetValue(widgetId, "type"), frame.window);
  if (window.MobileWidget) {
    widget.mobile = new MobileWidget(widget, widgetId, frame.window);
  }
  widget.context = widgetContext;
  frame.window.widget = widget;
  //var icon = document.getElementById("IconifyIcon" + widgetIdPrefix + id);
  //icon.setAttribute("src", path + "/Icon.png");
  var defaultImage = document.getElementById("DefaultImage" + widgetIdPrefix + id);
  defaultImage.parentNode.removeChild(defaultImage);
  var loadingImage = document.getElementById("LoadingImage" + widgetIdPrefix + id);
  loadingImage.parentNode.removeChild(loadingImage);
  
  var body = frame.window.document.getElementsByTagName("body")[0];
  if (myBrowser.isIE) {
    body.attachEvent("mouseover", function() {
      widgetBorderHide(document.getElementById(widgetIdPrefix + id));
    });
    body.attachEvent("click", function() {
      widgetToFront(document.getElementById(widgetIdPrefix + id));
    });
  }
  else {  
    body.addEventListener("mouseover", function() {
      widgetBorderHide(document.getElementById(widgetIdPrefix + id));
    }, false);
    body.addEventListener("click", function() {
      widgetToFront(document.getElementById(widgetIdPrefix + id));
    }, false);
  }  
  
  if (myBrowser.loadLocale != false) {
    loadLocale(frame.window);
  }  
  setupDashCode(frame.window);
}

function loadLocale(win) {
  var locale = navigator.language;
  if (locale != null && locale.length > 2) {
    locale = locale.substring(0, 2);
  }
  if (!locale || locale.length == 0) {
    locale = "en";
  }
  loadLocaleStrings(win, locale)
}  
  
function loadLocaleStrings(win, locale) {
  var src = locale + ".lproj/localizedStrings.js";
  try {
    var request = new win.XMLHttpRequest();
    request.open("GET", src, false);
    request.send(null);
    if (request.status == 200 || request.status == 0) {
      var localizedStrings = null;
      eval(request.responseText);
      if (localizedStrings) {
        win.localizedStrings = localizedStrings;
      }
    }
    else {
      addError("Loading locale failed: " + request.statusText);
      if (locale != "en") {
        loadLocaleStrings(win, "en");
      }
    }
  }
  catch(e) {
    addError("Loading locale failed: " + e);    
    if (locale != "en") {
      loadLocaleStrings(win, "en");
    }
  }
}

function createXMLHttpRequest() {
  var xml_request;
		if (window.XMLHttpRequest) {
		  xml_request = new XMLHttpRequest();
		}
		else if (window.ActiveXObject) { // IE
          xml_request = new ActiveXObject("Microsoft.XMLHTTP");
        }
  return xml_request;      
}

function addNewWidget(widgetPath) {
  clearErrors();
  var path = widgetsPath + widgetPath;
  dir.widgetAdded(widgetPath);

  var plistRequest = null;
	if (plistRequest != null)
	{
		plistRequest.abort();
		plistRequest = null;
	}
  if (window.netscape) {
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
  }
  plistRequest = createXMLHttpRequest();
      
	plistRequest.onreadystatechange = function(e) {
	  plistLoaded(e, plistRequest, 0, widgetPath);
	}
	if (plistRequest.overrideMimeType) {
	  plistRequest.overrideMimeType("text/xml");
	}
	url = path + "/Info.plist";
	plistRequest.open("GET", url);
	plistRequest.setRequestHeader("Cache-Control", "no-cache");
	plistRequest.send(null);
}

function reloadWidgets(inSync) {
  if (inSync == null) {
    inSync = false;
  }
  var widgets = document.getElementById("Widgets");
  while (widgets.childNodes.length > 0) {
    widgets.removeChild(widgets.lastChild);
  }
  var id = widgetsHelper.getFirstWidgetId();
  while (id != null) {
    var path = widgetsHelper.getWidgetValue(id, "path");
    addError("Reload: " + id + " from " + path);
    try {
      if (path == null) {
        throw "widget path is null";
      }
      reloadWidget(id, path, inSync);
    }
    catch (e) {
      addError("Reloading widget " + path + " failed: " + e);
      var oldId = id;
      id = widgetsHelper.getNextWidgetId(id);
      widgetsHelper.removeWidget(oldId);
      continue;
    }  
    id = widgetsHelper.getNextWidgetId(id);
  }
}

function clearAllWidgets() {
  var id = widgetsHelper.getFirstWidgetId();
  while (id != null) {
    widgetClose(widgetIdPrefix + id);
    id = widgetsHelper.getFirstWidgetId();
  }
}

function getPListName(plist) {
  var result = plist["CFBundleName"];
  if (!result) {
    result = plist["CFBundleDisplayName"];
    if (!result) {
      result = plist["CFBundleIndentifier"];    
      if (!result) {
        result = "Widget";
      }
    }
  }
  return result;
}

function reloadWidget(id, path, inSync) {
  if (inSync == null) {
    inSync = false;
  }
  if (window.netscape) {
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
  }
  var plistRequest = createXMLHttpRequest();
        
  if (!inSync) {
    plistRequest.onreadystatechange = function(e) {plistLoaded(e, plistRequest, id, path);}
    if (plistRequest.overrideMimeType) {
 	    plistRequest.overrideMimeType("text/xml");
    }
  }  
  url = widgetsPath + path + "/Info.plist";
  plistRequest.open("GET", url, !inSync);
  plistRequest.setRequestHeader("Cache-Control", "no-cache");
  plistRequest.send(null);
  if (inSync) {
    plistLoaded(null, plistRequest, id, path);
  }
}

function getTextContent(element) {
   var children = element.childNodes;
   for (var i = 0; i < children.length; i++) {
     if(children[i].nodeType == 3) {
       return children[i].data;
     }  
   }
   return "";            
}

function plistLoaded(e, plistRequest, id, widgetPath) {
  if (plistRequest.readyState == 4) {
     if (plistRequest.status == 0 
         || plistRequest.status == 200 
         || plistRequest.status == 304) {
        if (window.netscape) {
          //netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
          //netscape.security.PrivilegeManager.enablePrivilege("UniversalFileRead");
        }
        var xmldoc = plistRequest.responseXML;
        var path = widgetsPath + widgetPath;
        var keys = xmldoc.getElementsByTagName("key");
        var plist = new Object();
        for (var i = 0; i < keys.length; i++) {
          var key = getTextContent(keys[i]);
          var element = keys[i];
          while(element.nextSibling.nodeType != 1) {
            element = element.nextSibling;
          }
          if (element.nextSibling.nodeName == "true") {
            plist[key] = true;
          } 
          else if (element.nextSibling.nodeName == "false") {
            plist[key] = false;
          }
          else {            
            var value = getTextContent(element.nextSibling);
            plist[key] = value; 
          }  
        }
        if (!plist.MainHTML) {
          addError("Missing MainHTML parameter in Info.plist");
          plist.MainHTML = widgetPath + ".html";
        }  
        if (!plist.CFBundleIdentifier) {
          addError("Missing CFBundleIdentifier parameter in Info.plist");
        }
        if (id == 0) {
          id = widgetsHelper.addWidget(plist.CFBundleIdentifier, widgetPath);
        }  
        addWidget(id, plist, widgetPath);
        if (favourites && favourites.add(getPListName(plist) ,widgetPath)) {
          addFavouriteIcon(getPListName(plist), widgetPath);
        }
     } else {
        addError('Request failed: ' + plistRequest.status);
        if (window.addErrorCallback) {
          window.addErrorCallback();
        }
     }
     return true;
  }
  return false;
}

function addFrame(widgetElement, plist, path, defaultImage, parentElement) {
  var frame = document.createElement("iframe");
  frame.widgetId = widgetElement.id;
  frame.className = "widgetFrame";
  frame.setAttribute("id", "Frame" + lastFrameId);
  frame.setAttribute("name", "Frame" + lastFrameId);
  widgetElement.frameId = lastFrameId;
  lastFrameId++;
  if (plist["Width"]) {
    frame.setAttribute("width", plist["Width"]);
  }
  else {
    frame.setAttribute("width", defaultImage.width);
  }
  if (plist["Height"]) {  
    frame.setAttribute("height", plist["Height"]);
  }  
  else {
    frame.setAttribute("height", defaultImage.height);
  }
  widgetResized(frame);
  frame.setAttribute("frameborder", "0");
  frame.setAttribute("framespacing", "0");
  frame.setAttribute("border", "0");
  frame.setAttribute("scrolling", "no");
  frame.frameBorder = "no";
  if (myBrowser.needsAllowTransparency) {
    frame.setAttribute("allowtransparency", "true");
    frame.allowTransparency = true;    
  }
  if (myBrowser.isIE) {
    frame.onreadystatechange = function() {
      if (this.readyState == "complete") {
        frameLoaded(this);
      }
      else {
        var frame = frames[this.id];
        myBrowser.makeCompatible(frame, frame.document);
      }  
    }
  }
  else {
    frame.setAttribute("onload", "frameLoaded(this)");    
  }
  frame.onmouseover = function() {widgetBorderHide(document.getElementById(this.widgetId));}
  frame.onmouseout = function() {widgetBorderShow(document.getElementById(this.widgetId))};
  //frame.setAttribute("onfocus", "focus(this.parentNode.parentNode)");
  //frame.setAttribute("onblur", "blur(this.parentNode.parentNode)");
  frame.setAttribute("src", path + plist["MainHTML"]);
  parentElement.appendChild(frame);
  //defaultImage.style.display = "none";
  //widgetBorder.removeChild(defaultImage);
}

function getWidget(widgetElement) {
  var frame = window.frames["Frame" + widgetElement.frameId];
  if (frame) {
    return frame.widget;
  }
  return null;  
}

function addCloseIcon(parent, theClass, id, name, onclick) {
  var imagePath = getHectorPath() + "images/";
  var closeIconImage = document.createElement("img");
  closeIconImage.className = theClass;
  closeIconImage.setAttribute("id", id);
  closeIconImage.setAttribute("alt", "Close");
  closeIconImage.setAttribute("title", "Close " + name);
  closeIconImage.setAttribute("src", imagePath + "closeDisabled.png");
  closeIconImage.onclick = function() {eval(onclick)}; 
  closeIconImage.onmouseover = function() {
    this.setAttribute("src", imagePath + "close.png");
  };    
  closeIconImage.onmouseout = function() {
    this.setAttribute("src", imagePath + "closeDisabled.png");
  };    
  closeIconImage.onmousedown = function() {
    this.setAttribute("src", imagePath + "closePressed.png");
  };    
  closeIconImage.onmouseup = function() {
    this.setAttribute("src", imagePath + "close.png");
  };    
  parent.appendChild(closeIconImage);
  parent.icon = closeIconImage;
}

var lastz = 1;
function widgetToFront(widget) {
  if (widget.style.zindex != lastz) {
    widget.style.zIndex = lastz++;
    widgetsHelper.moveWidgetToEnd(getWidgetId(widget));
  }  
}

function showGlassPane() {
  var glass = document.getElementById("WidgetsGlassPane");
  if (glass) {
    glass.style.display = "block";
    glass.style.zIndex = lastz++;
  }
}

function hideGlassPane() {
  var glass = document.getElementById("WidgetsGlassPane");
  if (glass) {
    glass.style.display = "none";
  }
}

/***
  Favourites Dock code
***/

function loadFavourites() {
  favouritesLoaded(favourites.getAll());
}

function favouritesLoaded(list) {
  var dock = document.getElementById("FavouritesDock");
	if (dock != null) {
	  while (dock.firstChild != null) {
	    dock.removeChild(dock.lastChild);
	  }
	}
  for (var i = 0; i < list.length; i++) {
    addFavouriteIcon(list[i].title, list[i].path);
  }
}

function addFavouriteIcon(title, path) {
  var dock = document.getElementById("FavouritesDock");
	if (dock != null) {
  	var dockIcon = document.createElement("div");
  	dockIcon.className = "favouriteIcon";
  	dockIcon.path = path;
  	dockIcon.setAttribute("title", "Add " + title);
  	dock.appendChild(dockIcon);
    dockIcon.onmouseover = function() { dockMouseOver(this)};
    dockIcon.onmouseout = function() {dockMouseOut(this)};
  	var img = document.createElement("img");
    img.setAttribute("src", widgetsPath + path + "/Icon.png");
    img.setAttribute("width", ICON_WIDTH);
    img.setAttribute("height", ICON_WIDTH);
    img.className = "favouriteIconImage";
    img.style.padding = "1px";
    img.onclick = function() {addFavourite(this.parentNode)};
    dockIcon.appendChild(img);
    dockIcon.img = img;
    var closeIconClass = "favouriteCloseIcon";
    if (myBrowser.isSafari) {
      closeIconClass += " favouriteCloseIconSafari";
    }
    addCloseIcon(dockIcon, closeIconClass, null,
                 title, "removeFavourite(this.parentNode)");
    var icoImage = new Image();
    icoImage.img = img;
    icoImage.onerror = function() {
      var imagePath = getHectorPath() + "images/";
      this.img.setAttribute("src", imagePath + "defaultIcon.png");
    };
    icoImage.src = img.src;
	}
}

function removeFavourite(favourite) {
  favourite.parentNode.removeChild(favourite);
  favourites.remove(favourite.path);
}

function dockMouseOver(dockIcon) {
  //var id = getWidgetId(dockIcon);
  //var icon = document.getElementById("DockCloseIcon" + widgetIdPrefix + id);
  var icon = dockIcon.icon;
  if (icon) {
    icon.style.visibility = "visible";
  }
  var img = dockIcon.img;
  if (img!= null) {
    img.className = "favouriteIconImageHover"
  }  
}

function dockMouseOut(dockIcon) {
  //var id = getWidgetId(dockIcon);
  //var icon = document.getElementById("DockCloseIcon" + widgetIdPrefix + id);
  var icon = dockIcon.icon;
  if (icon) {
    icon.style.visibility = "hidden";
  }  
  var img = dockIcon.img;
  if (img != null) {
    img.className = "favouriteIconImage"
  }  
}


