var nextId = 0;
var starters = new Object();

var storage = null;
var googleStorage;
var starterCookie;
var noLoginCookie;
var starterTarget = "_blank";

var speedySettings = {
  SpeedySize: "SpeedySize",
  SpeedyTarget: "SpeedyTarget",
  SpeedyBackground: "SpeedyBackground"
}


function setup() {
    if (navigator.userAgent.indexOf("MSIE") >= 0 && $("IeMsg")) {
      $("IeMsg").style.display = "block";
      var index = navigator.userAgent.indexOf("MSIE");
      if (navigator.userAgent.charAt(index + 5) < '7') {
        $("IE6").style.display = "block";
      }
    }
    noLoginCookie = new Cookie("SpeedyNoLogin");
    googleStorage = new GoogleStorage("speedymarks", "http://speedymarksstorage.appspot.com/");
    googleStorage.onError = function(error) {
      alert(error);
    }
    googleStorage.checkLogin(null, afterCheck); 
}    
    
function afterCheck(login, url) {
    if (login && noLoginCookie.get() != "true") {
      storage = googleStorage;
      $("Login").style.display = "none";
      $("Logout").style.display = "block";
      $("LoginMenuLink").style.display = "none";
      $("LogoutMenuLink").style.display = "inline";
      storage.reload(reload);
    }
    else {    
      storage = new CookieStorage();
      $("Login").style.display = "block";
      $("Login").url = url;
      $("Logout").style.display = "none";
      $("LoginMenuLink").style.display = "inline";
      $("LogoutMenuLink").style.display = "none";
      reload();
    }
}

function login() {
  noLoginCookie.store("false");
  if ($("Login").url) {
    location.href = $("Login").url;
  }
  else {
    location.reload();    
  }  
}      

function logout() {
  if ($("RemoveAll").checked && confirm("Do you really want to remove all your SpeedyMarks from the server?")) {
    googleStorage.removeAll();
  }
  noLoginCookie.store("true");
  googleStorage.logout(null, function() {
    location.reload();
  });
  $("Starters").style.display = "none"; 
  $("MainLoadingText").innerHTML = "Logging out...";
  $("MainLoading").style.visibility = "visible";
}

function showGoogleAccountMore() {
  $("GoogleAccountMore").style.display = "block";
  $("ShowGoogleAccountMore").style.display = "none";
}      

function reload() {
    var sizeCookie = storage.get(speedySettings.SpeedySize);
    if (sizeCookie != "false") {
      $("EditToggleSize").checked = true;
    }
    sizeToggled();

    var targetCookie = storage.get(speedySettings.SpeedyTarget);
    if (targetCookie != "false") {
      $("EditToggleTarget").checked = true;
    }
    targetToggled();

    var colors = $("BackgroundSelect");
    var colorCookie = storage.get(speedySettings.SpeedyBackground);
    if (colorCookie) {
      colors.value = colorCookie;
    }
    for(var i =0; i < colors.options.length; i ++) {
    	if (true) {
    	  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;
    $("Body").style.backgroundColor = colors.value;
      
    starterCookie = "Speedy-IDs";
    var ids = null;
    try {
      ids = eval(storage.get(starterCookie));
      reloadStarters(ids);
    }
    catch (e) {
      ids = null;
      //load defaults
    }    
    if (ids == null || ids.length <= 1) {      
      createDefaultStarters();
    }
    
    updatePreview();
    $("MainLoading").style.visibility = "hidden";

    if (location.href.indexOf("#syndication") >= 0) {
      showAboutSection();
    }
    
    var search = location.search;
    if (search && search.length > 0) {
      if (search.indexOf("download") >= 0) {
        showAboutSection();
      }
      var index = search.indexOf("add=");
      if (index >= 0) {
        var index2 = search.indexOf("&", index);
        if (index2 < 0) {
          index2 = search.length;
        }
        var url = search.substring(index + 4, index2);
        $("UrlInputField").value = decodeURIComponent(url);
        updatePreview();
        index = search.indexOf("title=");
        if (index >= 0) {
          var index2 = search.indexOf("&", index);
          if (index2 < 0) {
            index2 = search.length;
          }
          $("TitleInputField").value = decodeURIComponent(search.substring(index + 6, index2));
        }
        showAddSection();
      }
    } 
}

function createDefaultStarters() {
  var starter = null; 
  starter = createNewStarter("http://en.wikipedia.org", "Wikipedia", false);
  starter = createNewStarter("http://www.youtube.com", "YouTube", false);
  starter = createNewStarter("http://www.flickr.com", "Flickr");
  starter = createNewStarter("http://www.imdb.com", "Internet Movie DB");
  starter = createNewStarter("http://www.ebay.com", "eBay", false);
  starter = createNewStarter("http://www.amazon.com/gp/redirect.html?ie=UTF8&location=http%3A%2F%2Fwww.amazon.com%2F&tag=iphon-20&linkCode=ur2&camp=1789&creative=9325", "Amazon", false);
  starter = createNewStarter("http://www.wunderground.com/", "Weather", false);
  starter = createNewStarter("http://www.digg.com", "Digg", false);
  starter = createNewStarter("http://www.microsoft.com", "Microsoft", false);
  starter = createNewStarter("http://www.apple.com", "Apple", false);
  starter = createNewStarter("http://www.ubuntu.com", "Ubuntu Linux", false);
  starter = createNewStarter("http://www.widgetop.com", "Widgetop", false);
}

function reloadStarters(ids) {
  for (var i = 0; i < ids.length; i++) {
  	var cookie = "Speedy" + ids[i];
  	try {
  	  var text = storage.get(cookie);
    	if (text != null) {
      	var settings = eval("new Object(" + text + ")");
    	  var starter = createStarter(ids[i], settings.url, settings.title, settings.usePath);    	    
    	  starter.cookie = cookie;
    	}
    	nextId = Math.max(nextId, ids[i]);
  	}
  	catch (e) {
  	  alert("Reloading starter " + ids[i] + " failed: " + e);
  	  storage.remove(cookie);
  	}  
  }
  saveStarterIds();
  nextId++;
}

function saveStarterIds() {
  var text = "[";
  var container = $("Starters");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  text += divs[i].starter.id + ",";
  	}  
  }
  text += "null]";
  storage.store(starterCookie, text);
}

function saveStarter(starter) {
  var text = "{"
  text += "url:'" + starter.url + "',"
  text += "title:'" + starter.title + "',";
  text += "usePath:" + starter.usePath + ",";
  text += "empty:null}";
  storage.store(starter.cookie, text);
}

function readUrl() {
  var url = $("UrlInputField").value;
  return url;
}

function getImageUrl(url, usePath) {
  var result = url;
  if (!usePath) {
    var index = url.indexOf(":");
    if (index >= 0) {
      index = url.indexOf("/", index + 3);
      if (index >= 0) {
        result = url.substring(0, index);
      }
    }
  }
  return result;
}

function updatePreview() {
  var usePath = $("UsePathInput").checked;
  var url = readUrl();
  $("PreviewImage").src = "loading.gif";
  if (url && url.indexOf("widgetop") >= 0) {
    $("PreviewImage").src = "widgetop.png";    
  }
  else {
    $("PreviewImage").src = "http://images.websnapr.com/?size=S&url=" + getImageUrl(readUrl(), usePath);
  }
  $("Preview").style.display = "block";
}

function openDirect() {
  var url = readUrl();
  window.open(url);  
}

function addNewStarter() {
  var title = $("TitleInputField").value;
  if (title.length == 0) {
    title = readUrl();
    if (title.length > 28) {
      title = title.substring(0, 26) + "..";
    }
  }
  createNewStarter(readUrl(), title, $("UsePathInput").checked);
  $("AddSection").style.display = "none";    
}

function createNewStarter(url, title, usePath) {
  var id = nextId++;
  var starter = createStarter(id, url, title, usePath);
  saveStarterIds();
  starter.cookie = "Speedy" + id;
  saveStarter(starter);
  return starter;
}  

function createStarter(id, url, title, usePath) {
  var starter = document.createElement("div");
  starter.id = "Starter" + id;
  starter.className = "starter";
  //starter.width = 320;

  //starter.style.display = "block";
  starter.onmouseover = function() {
    starterMouseOver(this);
  }   
  starter.onmouseout = function() {
    starterMouseOut(this);
  }  
  var template = $("StarterTemplate").innerHTML;
  starter.innerHTML = template.replace(/\$ID\$/g, id);
  $("Starters").appendChild(starter);
  $("StarterImage" + id).src = "loading.gif";
  if (url && url.indexOf("widgetop") >= 0) {
    $("StarterImage" + id).src = "widgetop.png";    
  }
  else {
    $("StarterImage" + id).src = "http://images.websnapr.com/?url=" 
      + getImageUrl(url, usePath) 
      + "&size=S";
  }
  $("StarterImage" + id).starter = starter;
  if (title == null || title.length == 0) {
    title = url;
  }

  var starterObj = setupStarter(id, starter, url, title, usePath);
  starter.starter = starterObj;

  $("StarterLink" + id).innerHTML = title;
  $("StarterLink" + id).starter = starter;
  $("StarterUrl" + id).title = url;
  if (url.length > 28) {
    url = url.substring(0, 26) + "..";
  }
  $("StarterUrl" + id).innerHTML = url;
  $("StarterUrl" + id).starter = starter;
  
  $("CloseButton" + id).starter = starter;
  $("LeftButton" + id).starter = starter;
  $("RightButton" + id).starter = starter;

  addToStarters(starter);
  return starterObj;
}

function addToStarters(starter) {
  var container = $("Starters");
  container.appendChild(starter);
}

function setupStarter(id, element, url, title, usePath) {
  var starter = new Object();
  starter.id = id;
  starter.element = element;
  starter.url = url;
  starter.title = title;
  starter.usePath = usePath;
  starters["" + id] = starter;
  return starter;
}

function starterMouseOver(starterElement) {
  var closeBtn = $("CloseButton" + starterElement.starter.id);
  closeBtn.style.display = "block";
  $("LeftButton" + starterElement.starter.id).style.display = "block";
  $("RightButton" + starterElement.starter.id).style.display = "block";
}

function starterMouseOut(starterElement) {
  var closeBtn = $("CloseButton" + starterElement.starter.id);
  closeBtn.style.display = "none";
  $("LeftButton" + starterElement.starter.id).style.display = "none";
  $("RightButton" + starterElement.starter.id).style.display = "none";
}

function closeStarter(closeElement) {
  var starterElement = closeElement.starter;
  if (!window.confirm("Remove " + starterElement.starter.title + "?")) {
    return;
  }  
  delete starters["" + starterElement.starter.id];
  var startersElement = $("Starters");
  startersElement.removeChild(starterElement);
  storage.remove(starterElement.starter.cookie);
  saveStarterIds();
}

function moveStarterLeft(moveElement) {
  var starters = $("Starters");
  var starterElement = moveElement.starter;
  var previous = starterElement.previousSibling;
  if (previous != null) {
    starters.removeChild(starterElement);
    starters.insertBefore(starterElement, previous);
  }
  saveStarterIds();
}

function moveStarterRight(moveElement) {
  var starters = $("Starters");
  var starterElement = moveElement.starter;
  var next = starterElement.nextSibling;
  if (next != null) {
    starters.removeChild(next);
    starters.insertBefore(next, starterElement);
  }
  saveStarterIds();
}

function openStarter(starterElement) {
  window.open(starterElement.starter.url, starterTarget);
}

function showAllEdits() {
  var container = $("Starters");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  starterMouseOver(divs[i]);
  	}  
  }
  $("EditShowAll").onclick = hideAllEdits;
  $("EditShowAll").innerHTML = "Hide Edit";
}

function hideAllEdits() {
  var container = $("Starters");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  starterMouseOut(divs[i]);
  	}  
  }
  $("EditShowAll").onclick = showAllEdits;
  $("EditShowAll").innerHTML = "Edit Starters";
}

function sizeToggled() {
  var small = $("EditToggleSize").checked;
  if (small) {
    $("StarterCss").href = "starterSmall.css";
  }
  else {
    $("StarterCss").href = "starterNormal.css";    
  }
  storage.store(speedySettings.SpeedySize, small + "");
}

function targetToggled() {
  var blank = $("EditToggleTarget").checked;
  if (blank) {
    starterTarget = "_blank";
  }
  else {
    starterTarget = "_self";
  }
  storage.store(speedySettings.SpeedyTarget, blank + "");
}

function closeAdd() {
  $("AddSection").style.display = "none";
}

function closeAbout() {
  $("AboutSection").style.display = "none";
}                

function closeEdit() {
  $("EditSection").style.display = "none";
}

function backgroundChanged() {
  var color = $("BackgroundSelect").value;
  $("BackgroundSelect").style.backgroundColor = color;  
  $("Body").style.backgroundColor = color;
  storage.store(speedySettings.SpeedyBackground, color + "");
}

function showAddSection() {
  $("AddSection").style.display = "block";
  $("EditSection").style.display = "none";
  $("AboutSection").style.display = "none";
  //window.open("#AddSection", "_self");
  scrollTo(0, 0);
}

function showEditSection() {
  $("AddSection").style.display = "none";
  $("EditSection").style.display = "block";
  $("AboutSection").style.display = "none";
  //window.open("#AddSection", "_self");
  scrollTo(0, 0);
}                  

function showAboutSection() {
  $("AddSection").style.display = "none";
  $("EditSection").style.display = "none";
  $("AboutSection").style.display = "block";
  //window.open("#AddSection", "_self");
  scrollTo(0, $("AboutSection").offsetTop);
}

function tellFriend() {
  var body = "Hi,<br><br>I just stumbled upon the SpeedyMarks applications:" +
      "<br><br>http://www.speedymarks.com" +
      "<br><br>Best regards";
  window.open("mailto:?subject=SpeedyMarks&body=" + body, "_self");  
}
                                    