var nextId = 0;
var starters = new Object();

var storage = null;
var googleStorage;
var starterCookie;
var noLoginCookie;

function setup() {
    window.setTimeout(function() {window.scrollTo(0, 1)}, 1);    

    noLoginCookie = new Cookie("SpeedyNoLogin");
    googleStorage = new GoogleStorage("iphonemarks", "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 showGoogleAccountMore() {
  $("GoogleAccountMore").style.display = "block";
  $("ShowGoogleAccountMore").style.display = "none";
}      

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 showLogin() {
  $("ShowLoginSection").style.display = "none";
  $("LoginSection").style.display = "block";
}

function hideLogin() {
  $("ShowLoginSection").style.display = "block";
  $("LoginSection").style.display = "none";
}

function reload() {
    starterCookie = "Starter-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();
    }
    var sizeCookie = storage.get("StarterSize");
    if (sizeCookie != "false") {
      $("EditToggleSize").checked = true;
      sizeToggled();
    }
    
    updateUrlPreview();
    
    $("MainLoading").style.visibility = "hidden";

    var search = location.search;
    if (search && search.length > 0) {
      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);
        var title = url;
        index = search.indexOf("title=");
        if (index >= 0) {
          var index2 = search.indexOf("&", index);
          if (index2 < 0) {
            index2 = search.length;
          }
          title = decodeURIComponent(search.substring(index + 6, index2));
        }
        createNewStarter(url, title, true);
        location.search = "";
      }
    } 
}

function createDefaultStarters() {
  var starter = createNewStarter("http://www.apple.com/startpage", "Apple Startpage", true);
  starter = createNewStarter("http://en.wikipedia.org", "Wikipedia", 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://iphoneapplicationlist.com/", "IPhone Apps List", false);
  starter = createNewStarter("http://www.widgetop.com/mobile.html", "Widgetop", false);
}

function reloadStarters(ids) {
  for (var i = 0; i < ids.length; i++) {
  	var cookie = "Starter" + 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 = $("ProtocolInput").value;
  url += $("SubDomainInput").value;
  url += ".";
  url += $("DomainInput").value;
  url += ".";
  url += $("TopLevelInput").value;
  url += "/";
  url += $("PathInput").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 updateUrlPreview() {
  $("UrlPreview").innerHTML = readUrl();
}

function updatePreview() {
  var usePath = $("UsePathInput").checked;
  var url = readUrl();
  if (url && url.indexOf("widgetop") >= 0) {
    $("PreviewImage").src = "widgetopMobile.png";    
  }
  else {
    $("PreviewImage").src = getThumbUrl(getImageUrl(readUrl(), usePath), 200);
  }  
  $("Preview").style.display = "block";
}

function getThumbUrl(url, width) {
  var thumbs = "0";//$("ThumbSelect").value;
  if (thumbs == "1") {
    return "http://images.websnapr.com/?url=" 
      + encodeURIComponent(getImageUrl(url)) 
      + "&size=S";
  }
  return "http://api.thumbalizr.com/?url=" + encodeURIComponent(url) + "&width=" + width;  
}

function openDirect() {
  var url = readUrl();
  window.open(url);  
}

function addPredefined(select, inputId, add) {
  if (select.selectedIndex == 0) {
    return;
  }
  if (add) {
    $(inputId + "Input").value += select.value;
  }
  else {
    $(inputId + "Input").value = select.value;
  }
  select.selectedIndex = 0;
  updateUrlPreview();
}

function addNewStarter() {
  createNewStarter(readUrl(), readUrl(), $("UsePathInput").checked);    
}

function createNewStarter(url, title, usePath) {
  var id = nextId++;
  var starter = createStarter(id, url, title, usePath);
  saveStarterIds();
  starter.cookie = "Starter" + id;
  saveStarter(starter);
  return starter;
}  

function createStarter(id, url, title, usePath) {
  var starter = document.createElement("div");
  starter.id = "Starter" + id;
  starter.className = "starter";
  //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);
  if (url && url.indexOf("widgetop") >= 0) {
    $("StarterImage" + id).src = "widgetopMobile.png";    
  }
  else {
    $("StarterImage" + id).src = getThumbUrl(getImageUrl(url, usePath), 200);
  }    
  if (title == null || title.length == 0) {
    title = url;
  }
  $("StarterLink" + id).innerHTML = title;

  var starterObj = setupStarter(id, starter, url, title, usePath);
  starter.starter = starterObj;

  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";
}

function starterMouseOut(starterElement) {
  var closeBtn = $("CloseButton" + starterElement.starter.id);
  closeBtn.style.display = "none";
}

function closeStarter(starterElement) {
  delete starters["" + starterElement.starter.id];
  var startersElement = $("Starters");
  startersElement.removeChild(starterElement);
  storage.remove(starterElement.starter.cookie);
  saveStarterIds();
}

function openStarter(starterElement) {
  window.open(starterElement.starter.url);
}

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";    
  }
  var cookie = "StarterSize";
  storage.store(cookie, small + "");
}

function searchDigg() {
  var url = "http://www.digg.com/search?s=";
  url += encodeURIComponent($("sbi").value);
  window.open(url, "_blank");
}

function searchWikipedia() {
  var url = "http://en.wikipedia.org/wiki/Special:Search?search=";
  url += encodeURIComponent($("sbi").value);
  window.open(url, "_blank");
}

function searchAmazon() {
  var url = "http://www.amazon.com/gp/search?ie=UTF8&tag=iphon-20&index=blended&linkCode=ur2&camp=1789&creative=9325&keywords=";
  url += encodeURIComponent($("sbi").value);
  window.open(url, "_blank");
}

function tellFriend() {
  var body = "Hi,<br><br>I just stumbled upon this SpeedyMarks application:" +
      "<br><br>http://m.speedymarks.com<br><br>" +
      "SpeedyMarks makes it easy to open and to bookmark your favorite" +
			" web sites on the iPhone. It's the iPhone version of the visual bookmark" +
			" site:" +
      "<br><br>http://www.speedymarks.com<br><br>" +
      "Best regards";
  window.open("mailto:?subject=SpeedyMarks on the iPhone&body=" + body, "_self");  
}  

