var nextId = 0;
var webcams = new Object();
var current = null;

var webcamCookie;
var cycle = false;
var cycleTimer = null;
var updateTimer = null;
var allUpdateTimer = null;
var fadeTimer = null;
var fadeElement = null;
var defferTimer = null;

var width = 320;
var height = 400;

var predefined = null;

var noLoginCookie;
var loginUrlCookie;
var googleStorage;
var storage;

function setup() {
    setTimeout(function() {window.scrollTo(0,1)}, 1);
    try {
      var request = new XMLHttpRequest();
      request.open("GET", "predefined.js", false);
      request.send(null);
      var result = request.responseText;
      predefined = eval(result);
      for (var i = 0; i < predefined.length; i++) {
        var optgroup = document.createElement("optgroup");
        optgroup.label = predefined[i][0];
        $("Examples").appendChild(optgroup);
        for (var j = 0; j < predefined[i][1].length; j++) {
          var option = document.createElement("option");
          option.innerHTML = predefined[i][1][j][0];
          option.cam = predefined[i][1][j];
          optgroup.appendChild(option);
        }    	
      }
    }
    catch (e) {
    }
    noLoginCookie = new Cookie("WorldWatchrLogin");
    googleStorage = new GoogleStorage("worldwatchr", "http://speedymarksstorage.appspot.com/");
    googleStorage.onError = function(error) {
      alert(error);
    }
    loginUrlCookie = new Cookie("WorldWatchrLoginUrl");
    if (noLoginCookie.get() == "false" || !loginUrlCookie.get()) {
      googleStorage.checkLogin(null, afterCheck);
    }
    else {
      afterCheck(false, loginUrlCookie.get());
    }   
}    
    
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;
      //loginUrlCookie.store(url);
      $("Logout").style.display = "none";
      $("LoginMenuLink").style.display = "inline";
      $("LogoutMenuLink").style.display = "none";
      reload();
    }
}

function login() {
  noLoginCookie.store("false");
  loginUrlCookie.remove();
  if ($("Login").url) {
    location.href = $("Login").url;
  }
  else {
    location.reload();    
  }  
}      

function logout() {
  if ($("RemoveAll").checked && confirm("Do you really want to remove all your Webcams from the server?")) {
    googleStorage.removeAll();
  }
  noLoginCookie.store("true");
  googleStorage.logout(null, function() {
    location.reload();
  });
  $("WebCams").style.display = "none"; 
  $("MainLoadingText").innerHTML = "Logging out...";
  $("MainLoading").style.display = "block";
}

function showLogin() {
  $("ShowLoginSection").style.display = "none";
  $("LoginSection").style.display = "block";
}

function hideLogin() {
  $("ShowLoginSection").style.display = "block";
  $("LoginSection").style.display = "none";
}

function showGoogleAccountMore() {
  $("GoogleAccountMore").style.display = "block";
  $("ShowGoogleAccountMore").style.display = "none";
}      

function reload() {    
    $("WebCams").innerHTML = "";
    webcamCookie = "WebCam-IDs";
    var ids = null;
    try {
      ids = eval(storage.get(webcamCookie));
      reloadWebCams(ids);
    }
    catch (e) {
      //alert(e)
      ids = null;
      //load defaults
    }
    if (ids == null || ids.length <= 1) {      
      createDefaultWebCams();
    }
    $("EditSection").style.display = "block";
    
    $("MainLoading").style.display = "none";

    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 = decodeURIComponent(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));
        }
        createNewWebCam(url, title, true);
        location.search = "";
      }
    } 
}

function createDefaultWebCams() {
  if (predefined) {
    for (var i = 0; i < predefined.length; i++) {
      for (var j = 0; j < predefined[i][1].length; j++) {
      	createNewWebCam(predefined[i][1][j][1], predefined[i][1][j][0]);
      }    	
    }
  }
}

function reloadWebCams(ids) {
  for (var i = 0; i < ids.length; i++) {
  	var cookie = "WebCam" + ids[i];
  	try {
  	  var text = storage.get(cookie);
    	if (text != null) {
      	var settings = eval("new Object(" + text + ")");
    	  var webcam = createWebCam(ids[i], settings.url, settings.title, settings.usePath);    	    
    	  webcam.cookie = cookie;
    	}
    	nextId = Math.max(nextId, ids[i]);
  	}
  	catch (e) {
  	  //alert("Reloading webcam " + ids[i] + " failed: " + e);
  	  storage.remove(cookie);
  	}  
  }
  saveWebCamIds();
  nextId++;
}

function saveWebCamIds() {
  var text = "[";
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  text += divs[i].webcam.id + ",";
  	}  
  }
  text += "null]";
  storage.store(webcamCookie, text);
}

function saveWebCam(webcam) {
  var text = "{"
  text += "url:'" + webcam.url + "',"
  text += "title:'" + webcam.title + "',";
  text += "usePath:" + webcam.usePath + ",";
  text += "empty:null}";
  storage.store(webcam.cookie, text);
}

function readUrl() {
  var url = $("CamUrl").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() {
  $("PreviewImageError").style.display = "none";
  var url = readUrl();
  $("PreviewImage").src = "loading.gif";
  $("Preview").style.display = "block";
  var img = new Image();
  img.onload = function() {
    $("PreviewImage").src = img.src;
  }
  img.onerror = function() {
    $("PreviewImage").src = null;
    $("PreviewImageError").style.display = "block";
  }
  img.src = url;
}

function addExample() {
  var example = $("Examples").options[$("Examples").selectedIndex];
  if (example.cam) {
    $("CamTitle").value = example.cam[0];
    $("CamUrl").value = example.cam[1];
    updatePreview();
  }
  $("Examples").selectedIndex = 0;  
}

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;
}

function addNewWebCam() {
  var title = $("CamTitle").value;
  if (title.length == 0) {
    title = readUrl();
  }
  createNewWebCam(readUrl(), title); 
  $("AddSection").style.display = "none";
}

function createNewWebCam(url, title) {
  var id = nextId++;
  var webcam = createWebCam(id, url, title);
  saveWebCamIds();
  webcam.cookie = "WebCam" + id;
  saveWebCam(webcam);
  return webcam;
}  

function createWebCam(id, url, title) {
  var webcam = document.createElement("div");
  webcam.id = "WebCam" + id;
  webcam.className = "webcam";
  //webcam.style.display = "block";
  webcam.onmouseover = function() {
    //webcamMouseOver(this);
  }   
  webcam.onmouseout = function() {
    //webcamMouseOut(this);
  }  
  var template = $("WebCamTemplate").innerHTML;
  webcam.innerHTML = template.replace(/\$ID\$/g, id);
  $("WebCams").appendChild(webcam);
  if (title == null || title.length == 0) {
    title = url;
  }
  webcam.title = title;

  var webcamObj = setupWebCam(id, webcam, url, title);
  webcam.webcam = webcamObj;

  addToWebCams(webcam);
  loadImage(id, url);
  return webcamObj;
}

function addToWebCams(webcam) {
  var container = $("WebCams");
  container.appendChild(webcam);
}

function setupWebCam(id, element, url, title) {
  var webcam = new Object();
  webcam.id = id;
  webcam.element = element;
  webcam.url = url;
  webcam.title = title;
  webcams["" + id] = webcam;
  return webcam;
}

function webcamMouseOver(webcamElement) {
  var closeBtn = $("CloseButton" + webcamElement.webcam.id);
  closeBtn.style.display = "block";
}

function webcamMouseOut(webcamElement) {
  var closeBtn = $("CloseButton" + webcamElement.webcam.id);
  closeBtn.style.display = "none";
}

function closeWebCam(webcamElement) {
  delete webcams["" + webcamElement.webcam.id];
  var webcamsElement = $("WebCams");
  webcamsElement.removeChild(webcamElement);
  storage.remove(webcamElement.webcam.cookie);
  saveWebCamIds();
}

function openWebCam(webcamElement) {
  current = webcamElement.webcam;
  
  $("WebCamTitle").innerHTML = current.title;
  $("WebCam").title = current.title;
  $("WebCam").src = $("WebCamImage" + current.id).src;
  setOptSize(document.images["WebCamImage" + current.id]);  
  
  $("Heading").style.display = "none";
  $("Content").style.display = "none";
  $("Footer").style.display = "none";
  $("WebCamSection").style.display = "block";
  cycle = false;
  $("WebCamCycle").src = "play.png";
  stopAllAutoUpdate();
  startAutoUpdate();
  defferFadeOut();
  setTimeout(function() {window.scrollTo(0,1)}, 1);
}

function showAllEdits() {
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  webcamMouseOver(divs[i]);
  	}  
  }
  $("EditShowAll").onclick = hideAllEdits;
  $("EditShowAll").innerHTML = "Hide Edit";
}

function hideAllEdits() {
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  webcamMouseOut(divs[i]);
  	}  
  }
  $("EditShowAll").onclick = showAllEdits;
  $("EditShowAll").innerHTML = "Edit";
}

function toggleControls() {
  var shown = $("WebCamControls").style.display == "block";
  if (shown) {
    startFadeOut($("WebCamControls"));
    //$("WebCamControls").style.display = "none";
  }
  else {
    $("WebCamControls").style.display = "block";
    defferFadeOut();
  }
}

function closeWebCamView() {
  $("Heading").style.display = "block";
  $("Content").style.display = "block";
  $("Footer").style.display = "block";
  $("WebCamSection").style.display = "none";
  stopCycling();
  stopAutoUpdate();
  startAllAutoUpdate();
  setTimeout(function() {window.scrollTo(0,1)}, 1);
}

function getUrl(url) {
  var key = new Date().getTime();
  if (url.indexOf("?") >= 0) {
    return url + "&" + key;
  }
  else {
    return url + "?" + key;  
  }    
}

function updateWebCam() {
  if ($("WebCamCycle").checked) {
    updateAllWebCams();
  }
  else {
    loadImage(current.id, getUrl(current.url));
  }  
}

function updateAllWebCams() {
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	loadImage(divs[i].webcam.id, getUrl(divs[i].webcam.url));
  }
}

function loadImage(id, url) {
  var element1 = $("WebCam");
  var element2 = $("WebCamImage" + id);
  element1.src = "loading.gif";
  element2.src = "loading.gif";
  var img = new Image();  
  img.onload = function() {    
    element1.src = img.src;
    element2.src = img.src;
    document.images[element2.id].orgWidth = img.width;
    document.images[element2.id].orgHeight = img.height;
    setOptSize(document.images[element2.id])
  }
  img.onerror = function() {
    element1.src = "error.png";
    element2.src = "error.png";
    document.images[element2.id].orgWidth = 320;
    document.images[element2.id].orgHeight = 240;
    setOptSize(document.images[element2.id])
  }
  img.src = url;
}

function setOptSize(image) {
  var img = $("WebCam");
  var imgWidth = width;//$("WebCamSection").clientWidth;
  var imgHeight = height;//$("WebCamSection").clientHeight;
  var x = 0;
  var y = 0;
  if (height > 0) {
    if (image.orgWidth * imgHeight > image.orgHeight * imgWidth) {
      img.width = imgWidth;
      img.height = imgWidth * image.orgHeight / image.orgWidth;
      y = (imgHeight - imgWidth * image.orgHeight / image.orgWidth) / 2
    }
    else {
      img.width = imgHeight * image.orgWidth / image.orgHeight;
      img.height = imgHeight;      
      x = (imgWidth - imgHeight * image.orgWidth / image.orgHeight) / 2;
    }
  }
  else {
    img.width = width;
    img.height = width * image.orgHeight / image.orgWidth;
  }
  img.style.left = x + "px";
  img.style.top = y + "px";
}

function toggleCycling() {
  if (!cycle) {
    startCycling();
  }
  else {
    stopCycling();
  }
}

function nextCam() {
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].webcam == current) {
  	  var index = i + 1;
  	  if (index >= divs.length) {
  	    index = 0;
  	  }
      current = divs[index].webcam;
      $("WebCamTitle").innerHTML = current.title;
      $("WebCam").src = $("WebCamImage" + current.id).src;
      $("WebCam").title = current.title;
      setOptSize(document.images["WebCamImage" + current.id]);
      break;
  	}  
  }  
}

function previousCam() {
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].webcam == current) {
  	  var index = i - 1;
  	  if (index < 0) {
  	    index = divs.length - 1;
  	  }
      current = divs[index].webcam;
      $("WebCamTitle").innerHTML = current.title;
      $("WebCam").src = $("WebCamImage" + current.id).src;
      $("WebCam").title = current.title;
      setOptSize(document.images["WebCamImage" + current.id]);
      break;
  	}  
  }  
}

function cycling() {
  nextCam();
  startCycling();
}

function startCycling() {
  stopCycling();
  cycle = true;
  $("WebCamCycle").src = "pause.png";
  cycleTimer = setTimeout(cycling, 8000);
}

function stopCycling() {
  if (cycleTimer) {
    clearTimeout(cycleTimer);    
  }
  cycleTimer = null;
  cycle = false;
  $("WebCamCycle").src = "play.png";
}

function autoUpdate() {
  updateWebCam();
  startAutoUpdate();
}

function startAutoUpdate() {
  stopAutoUpdate();
  var time = $("AutoUpdate").value;
  if (time > 0) {
    updateTimer = setTimeout(autoUpdate, time * 60000);
  }
}

function stopAutoUpdate() {
  if (updateTimer) {
    clearTimeout(updateTimer);    
  }
  updateTimer = null;  
}

function allAutoUpdate() {
  updateAllWebCams();
  startAllAutoUpdate();
}

function startAllAutoUpdate() {
  stopAllAutoUpdate();
  var time = $("AllAutoUpdate").value;
  if (time > 0) {
    allUpdateTimer = setTimeout(allAutoUpdate, time * 60000);
  }
}

function stopAllAutoUpdate() {
  if (allUpdateTimer) {
    clearTimeout(allUpdateTimer);    
  }
  allUpdateTimer = null;  
}

function toggleAdd() {
  if ($("AddSection").style.display == "block") {
    hideAdd();
  }
  else {  
    $("AddSection").style.display = "block";
    window.open("#AddSection", "_self");
  }    
}

function hideAdd() {
  $("AddSection").style.display = "none";
  $("Preview").style.display = "none";
  window.open("#WebCams", "_self");
}

function fade() {
  fadeElement.style.opacity -= 0.1;
  if (fadeElement.style.opacity <= 0) {
    stopFadeOut();
  }
  else {
    fadeTimer = setTimeout(fade, 50);
  }  
}

function startFadeOut(element) {
  if (defferTimer) {
    clearTimeout(defferTimer);
    defferTimer = null;
  }
  stopFadeOut();
  fadeElement = element;
  fadeElement.style.opacity = 1.0;
  fadeTimer = setTimeout(fade, 100);
}

function stopFadeOut() {
  if (fadeTimer) {
    clearTimeout(fadeTimer);
  }
  if (fadeElement) {
    fadeElement.style.display = "none";
    fadeElement.style.opacity = 1.0;
    fadeTimer = null;
    fadeElement = null;
  }  
}

function defferFadeOut() {
  stopFadeOut();
  $("WebCamControls").style.display = "block";
  if (defferTimer) {
    clearTimeout(defferTimer);
    defferTimer = null;
  }
  defferTimer = setTimeout(function() {
    if (defferTimer != null && $("WebCamControls").style.display == "block") {
      startFadeOut($("WebCamControls"));
    }  
  }, 4000);      
}

function openExternal() {
  if (current) {
    var sourceWindow = window.open("about:blank"); 
    var newDoc = sourceWindow.document; 
    newDoc.open(); 
    newDoc.write("<html><head><title>" + current.title 
      + "</title><meta name=\"viewport\" id=\"viewport\" content=\"initial-scale=1.0;" 
      + "width=" + document.images["WebCamImage" + current.id].orgWidth 
      + "\"/><script>function do_onload()" 
      + "{setTimeout(function(){window.scrollTo(0,1);},100);}if(navigator.userAgent.indexOf" + "(\"iPhone\")!=-1)window.onload=do_onload;</script>"
      + "<style>body {margin:0;border:0;padding:0}</style>"
      + "</head><body></body></html>"); 
    newDoc.close(); 
    var img = newDoc.body.appendChild(newDoc.createElement("img"));
    img.src = current.url;
  }
}

function showAllWebCamsView() {
  $("AllWebCams").innerHTML = "";
  $("Heading").style.display = "none";
  $("Content").style.display = "none";
  $("Footer").style.display = "none";
  $("AllWebCamsSection").style.display = "block";
  var container = $("WebCams");
  var divs = container.childNodes;
  for (var i = 0; i < divs.length; i++) {
  	if (divs[i].nodeType == 1) {
  	  var img = document.createElement("img");
  	  img.className = "allWebCamsImage";
  	  img.src = getUrl(divs[i].webcam.url);
  	  img.width = window.innerWidth;
  	  $("AllWebCams").appendChild(img);;
  	  var title = document.createElement("div");
  	  title.className = "allWebCamsTitle";
  	  title.innerHTML = divs[i].webcam.title;
 	    $("AllWebCams").appendChild(title);
  	}  
  }
  window.onscroll = function() {
    $("AllWebCamsControls").style.top = window.pageYOffset + "px";      
  }
  $("AllWebCamsControls").style.top = window.pageYOffset + "px";  
  setTimeout(function() {window.scrollTo(0,1)}, 1);
}

function closeAllWebCamsView() {
  $("Heading").style.display = "block";
  $("Content").style.display = "block";
  $("Footer").style.display = "block";
  $("AllWebCamsSection").style.display = "none";
  window.onscroll = null;  
  setTimeout(function() {window.scrollTo(0,1)}, 1);
}

function emailWebCam() {
  if (current) {
    window.open("mailto:?subject=WorldWatchr: " + current.title 
    + "&body=Add to WorldWatchr: " 
    + encodeURIComponent("http://www.worldwatchr.com?add=" + encodeURIComponent(current.url) + "&title=" + encodeURIComponent(current.title))
    + "<br><br>Add to iPhone: "
    + encodeURIComponent("http://m.worldwatchr.com?add=" + encodeURIComponent(current.url) + "&title=" + encodeURIComponent(current.title)), 
    "_self");
  }
}

function tellFriend() {
  var body = "Hi,<br><br>I just stumbled upon this iPhone Webcams application:" +
      "<br><br>http://m.worldwatchr.com<br><br>" +
      "Monitor webcams on your iPhone or on your desktop:" +
      "<br><br>http://www.worldwatchr.com<br><br>" +
      "Best regards";
  window.open("mailto:?subject=WorldWatchr Webcams on the iPhone&body=" + body, "_self");  
}

function orientationChanged() {
  if (window.innerWidth < window.innerHeight) {
    var swidth = screen.availWidth;
    $("WebCamSection").style.width = swidth + "px";
    width = swidth;
    height = window.innerHeight;
  }
  else {
    var swidth = window.innerWidth;
    $("WebCamSection").style.width = swidth + "px";
    width = swidth;
    height = window.innerHeight;
  }
  if (current) {
    setOptSize(document.images["WebCamImage" + current.id]);
  }  
  setTimeout(function() {window.scrollTo(0,1)}, 1);
  if ($("AllWebCamsSection").style.display == "block") {
    showAllWebCamsView();
  }
}

