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

var webcamCookie;
var settingsCookie;
var settings = {update:0, size:1};
var cycle = false;
var cycleTimer = null;
var updateTimer = null;

var width = 320;
var height = 400;

var predefined = null;

function setup() {
    try {
      var request = false;
      try {
        request = new ActiveXObject("Msxml2.request");
      } catch (e) {
        try {
          request = new ActiveXObject("Microsoft.request");
        } catch (e2) {
          request = false;
        }
      }    
      if (!request && typeof XMLHttpRequest != 'undefined') {
        request = new XMLHttpRequest();
      }
      request.open("GET", "predefined.js", false);
      request.send(null);
      var result = request.responseText;
      predefined = eval(result);      
    }
    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;
      /*
      if (!url) {
        loginUrlCookie.store("auto");        
      }
      else {
        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 && $("Login").url != "auto") {
    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.visibility = "visible";
}

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() {    
    settingsCookie = "WebCam-Settings";
    try {
      var value = storage.get(settingsCookie);
      if (value) {
        settings = eval("new Object(" + value + ")");
      }  
    }
    catch (e) {
    }
    $("ThumbSize").selectedIndex = settings.size;
    thumbSizeChanged();
    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();
    }
    
    $("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 = "";
      }
    }
    $("AutoUpdate").selectedIndex = settings.update;
    startAutoUpdate(); 
}

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 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 || title.length == 0) {
    title = readUrl();
  }
  createNewWebCam(readUrl(), title); 
  $("CamUrl").value = "";
  $("CamTitle").value = "";
}

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) {
  $("CloseButton" + webcamElement.webcam.id).style.display = "block";
  $("RefreshButton" + webcamElement.webcam.id).style.display = "block";
  $("LeftButton" + webcamElement.webcam.id).style.display = "block";
  $("RightButton" + webcamElement.webcam.id).style.display = "block";
}

function webcamMouseOut(webcamElement) {
  $("CloseButton" + webcamElement.webcam.id).style.display = "none";
  $("RefreshButton" + webcamElement.webcam.id).style.display = "none";
  $("LeftButton" + webcamElement.webcam.id).style.display = "none";
  $("RightButton" + webcamElement.webcam.id).style.display = "none";
}

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

function refreshWebCam(webcamElement) {
  var cam = webcamElement.webcam;
  loadImage(cam.id, cam.url);
}

function moveWebCamLeft(webcamElement) {
  var webcams = $("WebCams");
  var previous = webcamElement.previousSibling;
  if (previous != null) {
    webcams.removeChild(webcamElement);
    webcams.insertBefore(webcamElement, previous);
  }
  saveWebCamIds();
}

function moveWebCamRight(webcamElement) {
  var webcams = $("WebCams");
  var next = webcamElement.nextSibling;
  if (next != null) {
    webcams.removeChild(next);
    webcams.insertBefore(next, webcamElement);
  }
  saveWebCamIds();
}

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

function showControls() {
  $("WebCamControls").style.display = "block";
  $("WebCamTitleEdit").style.display= "inline";
}

function hideControls() {
  $("WebCamControls").style.display = "none";
  $("WebCamTitleEdit").style.display= "none";
}

function closeWebCamView(event) {
  $("WebCamSection").style.display = "none";
  stopCycling();
  stopAutoUpdate();
  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 loadId = id;
  var element1 = $("WebCam");
  var element2 = $("WebCamImage" + id);
  if (current && id == current.id) {
    element1.src = "loading.gif";
  }
  element2.src = "loading.gif";
  var img = new Image();  
  img.onload = function() {    
    element2.src = img.src;
    document.images[element2.id].orgWidth = img.width;
    document.images[element2.id].orgHeight = img.height;
    if (current && loadId == current.id) {
      element1.src = img.src;
      setOptSize(document.images[element2.id])
    }  
  }
  img.onerror = function() {
    element2.src = "error.png";
    document.images[element2.id].orgWidth = 320;
    document.images[element2.id].orgHeight = 240;
    if (current && loadId == current.id) {
      element1.src = "error.png";
      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() {
  if ($("WebCamTitleInput").style.display == "inline") {
    titleChanged();
  }    
  $("WebCamTitleEdit").style.display = "none";
  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;
      $("WebCamTitleText").innerHTML = current.title;
      $("WebCam").src = $("WebCamImage" + current.id).src;
      $("WebCam").title = current.title;
      setOptSize(document.images["WebCamImage" + current.id]);
      break;
  	}  
  }
}

function previousCam() {
  if ($("WebCamTitleInput").style.display == "inline") {
    titleChanged();  
  }  
  $("WebCamTitleEdit").style.display = "none";
  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;
      $("WebCamTitleText").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() {
  updateAllWebCams();
  startAutoUpdate();
}

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

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

function toggleAdd() {
  if ($("AddSection").style.display == "block") {
    hideAdd();
  }
  else {  
    $("AddSection").style.display = "block";
  }    
}

function hideAdd() {
  $("AddSection").style.display = "none";
  $("Preview").style.display = "none";
}

function openExternal() {
  if (current) {
    window.open(current.url, "_blank");
  }
}

function changeTitle() {
  stopCycling();
  $("WebCamTitleText").style.display = "none";
  $("WebCamTitleEdit").style.display = "none";
  $("WebCamTitleInput").style.display = "inline";
  $("WebCamTitleInput").value = $("WebCamTitleText").innerHTML;
}

function titleChanged() {
  $("WebCamTitleText").style.display = "inline";
  $("WebCamTitleEdit").style.display = "inline";
  $("WebCamTitleInput").style.display = "none";
  var title = $("WebCamTitleInput").value;
  $("WebCamTitleText").innerHTML = title;
  current.title = title;
  $("WebCamImage" + current.id).title = title;
  saveWebCam(current);
}

function thumbSizeChanged() {
  var value = $("ThumbSize").value;
  $("SizeCSS").href = value + "Cam" + ".css";
  settings.size = $("ThumbSize").selectedIndex;
  saveSettings();
}

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 openWidgetop() {
  if (current) {
    window.open("http://www.widgetop.com?addImage="
    + encodeURIComponent(current.url) + "&title=" + encodeURIComponent(current.title) + "&refresh=" + 1
    , "_blank");
  }
}

function saveSettings() {
  var text = "{update:" + settings.update + ",size:" + settings.size + ",empty:null}";
  storage.store(settingsCookie, text);
}

function hideNavBox() {
  $("NavBox").style.display = "none";
  $("WebCamSection").style.marginLeft = "0px";
  $("WebCams").style.marginLeft = "10px";
} 

function tellFriend() {
  var body = "Hi,<br><br>I just stumbled upon this webcam application:" +
      "<br><br>http://www.worldwatchr.com<br><br>" +
      "You can create your personal selection of webcams and watch them all together." +
      "<br><br>Best regards";
  window.open("mailto:?subject=WorldWatchr - Your collection of webcams&body=" + body, "_self");  
}
  
                   
