/*
 * Copyright 2006 OST-SYSTEMS. All rights reserved.
 */

var StorageClass = KeyStorage;

function Controls() {
}

Controls.fillCategoryList = function(list) {  
  var selector = $("CategorySelector");
  if (list == null) {
    if (selector != null) {
      selector.disabled = true;
    }  
    dir.getPathList(Controls.fillWidgetsList, null);
  }
  else {  
    selector.disabled = false;
    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, "Top50", "Top Widgets"); 
    //addOptionElement(selector, "", "-----------------"); 
    if (list.length > 0) {
      group = document.createElement("optgroup");
      group.setAttribute("label", "Category");
      selector.appendChild(group);

      for (var i = 0; i < list.length; i++) {      
        addOptionElement(group, list[i].category, list[i].category + " (" + list[i].count + ")");
      }
    }    
    dir.getPathList(Controls.fillWidgetsList, "Favourites");
  }
}

Controls.fillWidgetsList = function(dirs) {
  var selector = $("WidgetSelector");
  selector.innerHTML = "";
  for (var i = 0; i < dirs.length; i++) {
    var option = document.createElement("option");
    option.setAttribute("value", dirs[i].path);
    option.appendChild(document.createTextNode(dirs[i].title));
    selector.appendChild(option);
  }
  if (selector.length > 0) {
    Controls.widgetInfoChanged();
  }
}

Controls.categoryChanged = function() {
  var widgetInfo = $("ControlsWidgetInfoSection");
  if (widgetInfo) {
    widgetInfo.style.display = "none";
  }
  var selector = $("CategorySelector");
  if (selector.value != null && selector.value.length > 0) {
    dir.getPathList(Controls.fillWidgetsList, selector.value);  
  }  
}

Controls.widgetInfoChanged = function() {  
  var selector = $("WidgetSelector");
  dir.getWidgetInfo(Controls.setWidgetInfo, selector.value);  
}

Controls.setWidgetInfo = function(info) {
  var widgetInfo = $("ControlsWidgetInfoSection");  
  if (widgetInfo) {
    widgetInfo.style.display = "inline";
    var summary = $("WidgetInfoSummary");
    if (info.summary) {
      summary.innerHTML = info.summary;
    }
    else {
      summary.innerHTML = "No summary";
    }    
    var icon = $("WidgetInfoIcon");
    icon.setAttribute("src", widgetsPath + info.path + "/Icon.png");
    $("WidgetInfoScreenshotImage").src = widgetsPath + info.path + "/_hectorScreenshot.png"    
  }  
}

Controls.addWidget = function(openWidget) {
  var select = $("WidgetSelector");
  var value =  select.value;
  if (openWidget) {
    MobileWindow.afterAddCallback = function(id) {
      MobileWindow.afterAddCallback = null;
      Desktop.showWidget($("DesktopWidget" + id));
    }
  }
  addNewWidget(value);
  if (openWidget) {
    showSection("WidgetsSection");
  }
}

Controls.openSingleWidget = function() {
  var select = $("WidgetSelector");
  var value =  select.value;
  window.open("mobileSingle.html?widget=" + value, "_blank");  
}

Controls.showSingleWidgetHelp = function() {
  var text = "Opens the widget as a separate application which stores its " +
      "settings in a local cookie. The widget can be added to the home screen " +
      "but there can only be one instance per widget type.";
  alert(text);
}

function Rss() {  
}

Rss.searchRssFeeds = function() {
  $("RssFeedSearchResults").style.display = "none";
  $("RssFeedSearchResultsClose").style.display = "none";
  $("RssFeedSearchResults").innerHTML = "";
  $("RssFeedSearchResults").selected = null;
  var search = $("RssFeedSearchInput").value;
  if (search.length == 0) {
    $("RssFeedSearchResults").style.display = "block";
    $("RssFeedSearchResults").innerHTML = "<p />&nbsp;&nbsp;<b>Nothing to search</b><p />";        
    return;
  }
  $("RssFeedSearchLoading").style.display = "block";
  google.feeds.findFeeds(search, function(result) {
    $("RssFeedSearchLoading").style.display = "none";
    $("RssFeedSearchResults").style.display = "block";
    $("RssFeedSearchResultsClose").style.display = "inline";
    if (!result.error) {
      if (result.entries.length > 0) {
        for (var i = 0; i < Math.min(12, 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.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.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("div");
        	div.appendChild(add);
        	add.className = "glassButton rssFeedSearchResultButton";
        	add.innerHTML = "<img src='widgets/AHectorSingleRSS/Icon.png' width='14' style='vertical-align:text-top'> Open Widget";//"Open Widget";
        	add.link = entry.url;
        	add.style.display = "none";
        	add.onclick = function() {
        	  Rss.addFeedWidget(this.link);
        	}
        	title.addButton = add;
        }
      }
      else {
        $("RssFeedSearchResults").innerHTML = "<p /><b>No results</b><p />";        
      }  
    }
    else {
      $("RssFeedSearchResults").innerHTML = "<p /><b>Error:</b> " + result.error.message + "<p />";
    }
  });
}

Rss.hideSearchResults = function() {
  $("RssFeedSearchResults").style.display = "none";
  $("RssFeedSearchResultsClose").style.display = "none";
  window.scrollTo(0, 1);  
}

Rss.addRssFeed = function() {
  var url = $("RssFeedSearchInput").value;
  if (url.length == 0) {
    $("RssFeedSearchResults").style.display = "block";
    $("RssFeedSearchResults").innerHTML = "<p />&nbsp;&nbsp;<b>Nothing to add</b><p />";        
    return;
  }  
  google.feeds.lookupFeed(url, function(result) {
    if (result.error) {
      Rss.addFeedWidget(url);
    }
    else {
      Rss.addFeedWidget(result.url);
    }  
  });
}

Rss.addFeedWidget = function(url) {
  MobileWindow.afterAddCallback = function(id) {
    keyStorage.store("widget", "com.pietjonas.hector.SingleRSS", id + "-feed", url);
    MobileWindow.afterAddCallback = null;
    Desktop.showWidget($("DesktopWidget" + id));
  }
  addNewWidget("AHectorSingleRSS");
  showSection("WidgetsSection");
  sendServerTest(null, "/addFeedWidget.mobile");    
}


function Desktop() {
  Desktop.placeHolder = $("DesktopPlaceHolder");
  Desktop.desktop = $("Desktop");
}

Desktop.addNewWidget = function(path) {
  if (!path) {
    path = widgetsHelper.getWidgetValue(selectedWidgetId, "path");
  }  
  MobileWindow.afterAddCallback = function(id) {
    MobileWindow.afterAddCallback = null;
    Desktop.showWidget($("DesktopWidget" + id));
  }
  addNewWidget(path);
  showSection("WidgetsSection");
}

Desktop.showWidget = function(iconElement) {
  if (!isSupportedEngine()) {
    Desktop.showInfo("Unsupported Browser", "mobile/mobileUnsupportedFeature.html");
    return;
  }
  var loaded = selectWidget(iconElement.iconId);
  showSection("WidgetsSection");
  if (!loaded) {
    showWidget(iconElement.iconId, iconElement.plist, iconElement.widgetPath);
    $("DesktopIcon" + iconElement.iconId).className = "desktopIcon desktopIconHighlight";
    $("DesktopListWidget" + iconElement.iconId).className = "desktopListWidget desktopListWidgetHighlight";
  }  
}

Desktop.back = function() {
  if (selectedWidgetId) {
    var title = widgetsHelper.getWidgetValue(selectedWidgetId, "title");
    if (title) {
      $("DesktopTitle" + selectedWidgetId).innerHTML = title;
      $("DesktopListTitle" + selectedWidgetId).innerHTML = title;
    }
  }    
  selectWidget(null); 
  showSection('DesktopSection');
}

Desktop.closeSelectedWidget = function() {
  if (selectedWidgetId) {
    var icon = $("DesktopIcon" + selectedWidgetId);
    icon.className = "desktopIcon";
    var item = $("DesktopListWidget" + selectedWidgetId);
    item.className = "desktopListWidget";
    var title = widgetsHelper.getWidgetValue(selectedWidgetId, "title");
    if (title) {
      $("DesktopTitle" + selectedWidgetId).innerHTML = title;
      $("DesktopListTitle" + selectedWidgetId).innerHTML = title;
    }  
  }
  closeSelectedWidget();  
  showSection("DesktopSection");
}

Desktop.removeSelectedWidget = function() {
  Desktop.removeWidget(selectedWidgetId);
  selectedWidgetId = null;
}

Desktop.removeWidget = function(id) {
  if (!confirm("Do you really want to remove that widget?")) {
    return;
  }
  if (id) {
    var icon = $("DesktopWidget" + id);
    $("Desktop").removeChild(icon);
    var item = $("DesktopListWidget" + id);
    item.onclick = null;
    $("DesktopList").removeChild(item);
    removeWidget(id);  
  }
  showSection("DesktopSection");
}

Desktop.flipSelectedWidget = function() {
  if (selectedWidgetId) {
    var widget = $(widgetIdPrefix + selectedWidgetId);
    var currentWidget = frames["Frame" + widget.frameId];
    if (currentWidget != null) {
      if (currentWidget.widget) {
        var w = currentWidget.widget;
        if (w.isFront) {
          if (w.mobile && w.mobile.showBack) {
            w.mobile.showBack();
          }
          else if (currentWidget.window.showBack) {
            currentWidget.window.showBack(null);
          }            
          else if (currentWidget.window.showPrefs) {
            currentWidget.window.showPrefs(null);
          }
        }
        else {
          if (w.mobile && w.mobile.hideBack) {
            w.mobile.hideBack();
          }
          else if (currentWidget.window.hideBack) {
            currentWidget.window.hideBack(null);
          }        
          else if (currentWidget.window.showFront) {
            currentWidget.window.showFront(null);
          }        
          else if (currentWidget.window.hidePrefs) {
            currentWidget.window.hidePrefs(null);
          }            
        }
        currentWidget.window.scrollTo(0, 1);
      }
    }
  }
}

Desktop.reloadWidgets = function() {
  var desktop = $("Desktop");
  //var placeHolder = $("DesktopPlaceHolder");
  //desktop.removeChild(placeHolder);
  desktop.innerHTML = "";
  $("DesktopList").innerHTML = "";
  //desktop.appendChild(placeHolder);
  reloadWidgets(false);
}

Desktop.switchViews = function() {
  var desktop = $("Desktop");
  var list = $("DesktopList");
  if (desktop.style.display == "none") {
    desktop.style.display = "block";    
    list.style.display = "none";    
  }
  else {
    desktop.style.display = "none";    
    list.style.display = "block";        
  }
}

Desktop.showHelp = function() {
  Desktop.showInfo("Help", "mobile/mobileHelp.html");
}

Desktop.showAbout = function() {
  Desktop.showInfo("About Widgetop", "mobile/mobileAbout.html");
}

Desktop.showInfo = function(title, url) {
  $("ControlsLoading").style.visibility = "visible";
  var request = createXMLHttpRequest();
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      if (request.status == 200 || request.status == 0) {
        $("InfoTitle").innerHTML = title;
        $("InfoText").innerHTML = request.responseText;
        showSection("InfoSection");
      }
      $("ControlsLoading").style.visibility = "hidden";
    }
  }
  request.open("GET", url);
  request.send(null);
}

Desktop.mouseDown = function(event, iconElement) {
  Desktop.placeHolder = $("DesktopPlaceHolder");
  Desktop.desktop = $("Desktop");
  Desktop.draggedIcon = iconElement;
  iconElement.style.position = "absolute";
  Desktop.dragx = event.pageX - iconElement.offsetLeft;
  Desktop.dragy = event.pageY - iconElement.offsetTop;
  Desktop.placeHolder.style.zIndex = "1000";    
}

Desktop.mouseUp = function(iconElement) {
  if (Desktop.draggedIcon == iconElement) {
    //stop dragging
    iconElement.style.position = null;
    iconElement.style.top = null;
    iconElement.style.left = null;
    iconElement.parentNode.removeChild(iconElement);
    Desktop.desktop.insertBefore(iconElement, Desktop.placeHolder);
    Desktop.draggedIcon = null;
    Desktop.placeHolder.style.display = "none";    
  }
}

Desktop.mouseMove = function(event, iconElement) {
  if (Desktop.draggedIcon == iconElement) {
    //start dragging
    var posx = document.all ? window.event.clientX : event.pageX;
    var posy = document.all ? window.event.clientY : event.pageY;
    if (posx - Desktop.dragx >= 0) {
      iconElement.style.left = (posx - Desktop.dragx) + "px";
    }  
    if (posy - Desktop.dragy >= 0) {
      iconElement.style.top = (posy - Desktop.dragy) + "px";
    }  
  }    
}

Desktop.mouseOver = function(iconElement) {
  addError(iconElement.id);
  if (Desktop.draggedIcon != null) {
    Desktop.placeHolder.parentNode.removeChild(Desktop.placeHolder);
    Desktop.desktop.insertBefore(Desktop.placeHolder, iconElement);    
  }
}

Desktop.tellFriend = function() {
  var body = "Hi,<br><br>I just stumbled upon Widgetop, which lets you run Dashboard" +
      " widgets on your iPhone: " + 
      "<br><br>http://m.widgetop.com<br><br>" +
      "and in your desktop browser:" +
      "<br><br>http://www.widgetop.com<br><br>" +
      "Best regards";
  window.open("mailto:?subject=Widgetop on iPhone&body=" + body, "_self");
  sendServerTest(null, "/tellAFriend.mobile");
}

var loginObj;
var started = false;

function setup() {
  widgetsHelper = new WidgetsHelper();
  widgetsHelper.group = "mobile";
  widgetContext = new WidgetContext("mobilePage");
  widgetContext.showErrors = false;
  widgetsPath = getPath();
  var forceOnDevice = false;
  if (location.search.indexOf("ForceOnDevice") >= 0) {
    forceOnDevice = true;
  }
  if (forceOnDevice || (screen.width > 300 && screen.height > 300)) {
    $("IconsCSS").href = "mobile/mobileBigIcons.css";  
  }
  if (!forceOnDevice && screen.width > 700) {
    //on desktop browser 
    MobileWidget.onDevice = false;
    $("DeviceCSS").href = "mobile/mobileBrowser.css";
    /*
    $("Phone").className = "offPhone";
    $("InnerPhone").className = "offInnerPhone";
    $("PhoneTurn").style.display = "block";
    */
    widgetContext.showErrors = true;
    $("Header").innerHTML = 
      '<iframe src="mobile/mobileHeader.html" frameborder="no" width="100%" height="140px" scrolling="no"><h1>Widgetop - Mobile Demo</h1></iframe>'
    $("Footer").innerHTML = 
      '<iframe src="mobile/mobileFooter.html" frameborder="no" width="100%" height="1200px" scrolling="no"></iframe>'      
  }
  else {
    //on device
    if (!isSupportedEngine() && !forceOnDevice) {
      if (location.search.indexOf("force=true") < 0) {
        window.open("mobile/mobileUnsupported.html", "_top");
        return;
      }
      myBrowser.supported = true;
    }
    var availWidth = screen.availWidth;
    var availHeight = screen.availHeight;
    if (forceOnDevice) {
      if (window.innerWidth) {
        availWidth = window.innerWidth - 20;
        availHeight = window.innerHeight;
      }
      else {
        availWidth = document.documentElement.clientWidth - 20;
        availHeight = document.documentElement.clientHeight;
      }  
    }
    $("Body").style.width = availWidth + "px";    
    //$("Body").style.height = screen.availHeight + "px";    
    window.onresize = resized;
    resized();
  }
  if (location.protocol == "file:") {
    dir = new FirefoxLocalDir(widgetsPath);
    keyStorage = new StorageClass();
    favourites = new CookieFavourites(dir, favouritesLoaded);
    addDefaultWidgets();
    isLocal = true;
    isOffline = true;
    dir.getPathList(Controls.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 resized() {
  var availWidth = screen.availWidth;
  if (window.orientation && window.orientation != 0) {
    availWidth = window.innerWidth;
  }
  //alert("Here: " + availWidth + " " + window.innerWidth + " " + screen.availWidth);
  if (window.orientation == undefined) {
    $("Body").style.width = "100%";    
  }
  else {
    $("Body").style.width = availWidth + "px";
  }  
  MobileWidget.screenWidth = availWidth;          
  MobileWidget.screenHeight = screen.availHeight;
  selectWidget(selectedWidgetId);            
  setTimeout(function() {window.scrollTo(0, 1)}, 1); 
}

function start() {
  widgetContext.restoreBackground();
  widgetContext.showErrors = true;  
  if (window.netscape) {
    /*netscape.security.PrivilegeManager.
         enablePrivilege("UniversalBrowserRead");*/
  }
  window.onblur = function(e) {
    keyStorage.saveAll();
  }      
  window.onunload = function(e) {
    hideAllWidgets();
    keyStorage.saveAll();
  }
  setupWidgets();
  Desktop.reloadWidgets();
  $("StartupLoading").style.display = "none";
  $("Board").style.display = "block";
  showSection("DesktopSection");
  dir.getCategoryList(Controls.fillCategoryList);
  started = true;
}

function onServerTest(request) {
  keyStorage = new StorageClass();
  if (request.status == 200) {
    myBrowser.hasProxy = true;
    dir = new ServerDir("commands", $("ControlsLoading"));
    loginObj = new Login($("ControlsLoading"), afterLogin, null);
    loginObj.checkAutoLogin();
  }
  else {
    //HFS
    isOffline = true;
    dir = new ServerDir("myWidgets.txt", $("ControlsLoading"));
    favourites = new CookieFavourites(dir, favouritesLoaded);
    start();
  }
}

function addDefaultWidgets() {
  if (window.startupWidgets) {
    for (var i = 0; i < startupWidgets.length; i++) {      
      var id = widgetsHelper.addWidget(startupWidgets[i].title, startupWidgets[i].path);
      widgetsHelper.storeWidgetKey(id, "top", "0px");  
      widgetsHelper.storeWidgetKey(id, "left", "0px");
      widgetsHelper.storeWidgetKey(id, "type", startupWidgets[i].type);
      if (startupWidgets[i].title) {
        widgetsHelper.storeWidgetKey(id, "title", startupWidgets[i].title);
      }  
      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]);
        }              	
      }
    }
  }
}

function afterLogin(success) {  
  widgetContext.restoreBackground();
  if (success) {
    favourites = new ServerFavourites(dir, favouritesLoaded);
  }
  else {
    favourites = new CookieFavourites(dir, favouritesLoaded);
    if (keyStorage.get(widgetsHelper.group, "list", "all") == null) {
      addDefaultWidgets();
    }              
  }  
  if (!started) {
    start();
  }
  else {
    Desktop.reloadWidgets();
  }  
}

/***
  Add widgets section code
***/

function addOptionElement(selector, value, text) {
  var option = document.createElement("option");
  option.setAttribute("value", value);
  option.appendChild(document.createTextNode(text));
  selector.appendChild(option);
}

function openBackgroundWidget() {
  addNewWidget("AHectorBackground");
}

function showLogin() {
  loginObj.showLogin();
}

function login() {
  if (!isSupportedEngine()) {
    Desktop.showInfo("Unsupported Browser", "mobile/mobileUnsupportedFeature.html");
    return;
  }
  loginObj.doLogin();
}

function logout() {
  loginObj.doLogout();
}

function newUser() {
  if (!isSupportedEngine()) {
    Desktop.showInfo("Unsupported Browser", "mobile/mobileUnsupportedFeature.html");
    return;
  }
  loginObj.newUser();
}

function removeUser() {
  loginObj.doRemoveUser();
}

function closePopout() {
  showSection("DesktopSection");
}

function loginDone(user) {
  $("DesktopLogin").style.display = "none";
  $("DesktopLogout").style.display = "inline";
  $("DesktopTestWarning").style.display = "none";
}

function logoutDone() {
  $("DesktopLogin").style.display = "inline";
  $("DesktopLogout").style.display = "none";
  $("DesktopTestWarning").style.display = "block";
}

/*
 * Mobile specific functions
 */
 
var sections = new Array("WidgetsSection", "ControlsSection", "DesktopSection", "LoginSection", "NewUserSection", "InfoSection", "RssSection");

function showSection(section) {
  hideTooltip();
  for (var i = 0; i < sections.length; i++) {
    if (sections[i] == section) {
      if (sections[i] == "WidgetsSection" && myBrowser.needsDockHiddenMethod) {
        $("WidgetsSection").style.visibility = "visible";
      }
      else {
        $(sections[i]).style.display = "block";
      }        
    }
    else {
      if (sections[i] == "WidgetsSection" && myBrowser.needsDockHiddenMethod) {
        $("WidgetsSection").style.visibility = "hidden";
      }
      else {
        $(sections[i]).style.display = "none";      
      }  
    }
  }
  setTimeout(function() {window.scrollTo(0, 1)}, 1); 
}

function showTooltip(element) {
  if (myBrowser.noMouseOver) {
    return;
  }  
  var text = element.title;
  var tooltip = $("Tooltip");
  tooltip.innerHTML = text;
  tooltip.style.display = "inline";
}

function hideTooltip() {
  var tooltip = $("Tooltip");
  tooltip.innerHTML = "";
  tooltip.style.display = "none";
}

function turnPhone() {
  var turn = $("PhoneTurn");
  if (turn.horizontal) {
    turn.title = "Turn Horizontal";
    turn.className = "phoneTurnHorizontal";
    turn.horizontal = false;
    $("PhoneTurnImage").className = "phoneTurnImageHorizontal";
    $("Phone").className = "phone";
    $("InnerPhone").className = "innerPhone";
  }
  else {
    turn.title = "Turn Vertical";
    turn.className = "phoneTurnVertical";
    turn.horizontal = true;
    $("PhoneTurnImage").className = "phoneTurnImageVertical";
    $("Phone").className = "phoneHorz";
    $("InnerPhone").className = "innerPhoneHorz";    
  }
}

var currentWidget;
function flipWidget() {
}           