var usingApplet = false;

var ptzFine         = 0;
var cView           = 0;
var viewIcons       = ['view1','view4','view9','view16','viewfocused','viewcentral'];
var maxFeeds        = 1;
var feedsSelected   = 1;
var lastSelect      = 1;
var lastSlot        = 1;
var lastFeed        = 1;
var lastWasUnselect = false;
var expired         = false;
var appletRunning   = false;
var setUpJS         = true;
var expireTime      = 0;
var modeSetLockout  = true;
var appletSafe      = false;

var cQual = 2;
var cZoom = 3;

//if (forcequality != -1)
//  cQual = forcequality;

var feedSelected = new Array();
var feedSlots    = new Array();

var ptzImage = new Image();

var imageTimerID     = 0;

for (n=0; n<totalFeeds; n++) {
  feedSelected[n] = 0;
  feedSlots[n] = -1;
  if (feedIDs[n] == defaultFeed) {
    feedSelected[n] = 1;
    feedSlots[n] = 1;
  }
}

var qualitySetting = 0;

var cookieQuality;
var useQuality = cQual;

cookieQuality = getCookie("quality");

if (cookieQuality != null)
  useQuality = cookieQuality;

if (forcequality != -1)
  useQuality = forcequality;

if (useQuality == 1)
  qualitySetting = 15;
if (useQuality == 1)
  qualitySetting = 25;
if (useQuality == 1)
  qualitySetting = 50;
if (useQuality == 1)
  qualitySetting = 75;
if (useQuality == 1)
  qualitySetting = 0;

var viewmode = 0;
var cookieViewmode;

cookieViewmode = getCookie("viewmode");

if (cookieViewmode != null) {
  if (cookieViewmode == 1)
    viewmode = 1;
  else
    viewmode = 0;
}

if (forceviewmode != -1) {
  if (forceviewmode == 1) {
    userPref = confirm("You have forced the i-Catcher web view to use JavaScript mode. This is usually only\nnecessary if you are experiencing problems with the Java applet.\n\nClick OK to make this change permanent (affects this machine only).");
    if (userPref)
      setCookie("viewmode",1);
  } else {
    userPref = confirm("You have forced the i-Catcher web view to use Java mode.\n\nClick OK to make this change permanent (affects this machine only).");
    if (userPref)
      setCookie("viewmode",2);
  }

  viewmode = forceviewmode;
}

if (viewmode > 1)
  viewmode = 0;

if (viewmode < 1)
  usingApplet = true;

// vars below here are used only for the javascript emulation of the feeds
var tempSlot = ['','','','','','','','','','','','','','','',''];
var realSlot = ['','','','','','','','','','','','','','','',''];
var throttleCount = 0;
var throttling = true;

var lastUpdate = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
var feedStatus = [0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];

var slotImages = new Array();
for (n=1; n<=16; n++) {
  slotImages[n] = new Image();
  slotImages[n].name = 'cache'+n;
  slotImages[n].onload = imageLoaded;
  slotImages[n].onerror = imageLoaded;
}

var slotIDs = ['','','','','','','','','','','','','','','',''];

slotIDs[0] = defaultFeed;

var currentLayout = 1;
var zoomMultiplier = 1.0;

var cWidth1 = 1;
var cHeight1 = 1;

// functions below here relate to the javascript emulation

function feedMark(n) {
  feedStatus[n-1] = 0;
}

function getMillis() {
  var d = new Date();
  return d.getTime();
}

function imageLoaded() {
  feedID = parseInt(this.name.substring(5));

  now = getMillis();
  
  i = document.getElementById('image'+feedID);
  if (i != null) {
    i.src = this.src;

    if (currentLayout > 1) {
      for (n=0; n<totalFeeds; n++) {
        if (feedIDs[n] == slotIDs[feedID-1]) {
          i.alt = 'Click to view just the "'+feedNames[n]+'" feed.';
          i.title = 'Click to view just the "'+feedNames[n]+'" feed.';
        }
      }
    } else {
      i.alt='';
      i.title='';
    }

    if (currentLayout == 1) {
      if ((this.width != cWidth1) || (this.height != cHeight1)) {
        requestNewResolution(this.width * zoomMultiplier, this.height * zoomMultiplier);
        cWidth1 = this.width; cHeight1 = this.height;
      }
    }
  }
     
  lastUpdate[feedID-1] = now;
  feedStatus[feedID-1] = 0;
}

function killImageTimer() {
  if (imageTimerID != 0)
    window.clearTimeout(imageTimerID);

  imageTimerID = 0;
}

function imageTimer() {
  imageTimerID = 0;

  if ((usingApplet) || (expired))
    return;

  now = getMillis();

  for (n=1; n<=maxFeeds; n++) {
    diff = now - lastUpdate[n-1];

    if ((realSlot[n-1] != '') && (feedStatus[n-1]==0) && (diff>50)) {
      feedStatus[n-1] = 1;

      qs = '';
      if (qualitySetting > 0)
        qs = '&quality='+qualitySetting;

      slotImages[n].src = '/image.jpg?feed='+realSlot[n-1]+qs+'&uniq='+now;
    } 
  }

  if (throttling) {
    throttleCount += 500;
 
    if (throttleCount >= 30000)
      throttling = false;
  }

  if (throttling) 
    imageTimerID = window.setTimeout("imageTimer()", 500);
  else 
    imageTimerID = window.setTimeout("imageTimer()", 30);

}

var preload_i = new Array();
var preload_n = 0;

function preload(preload_image) {
  preload_i[preload_n] = new Image();
  preload_i[preload_n].src = '/images/'+preload_image;

  preload_n++;
}

// Preloaders:
  
// standard parts
preload('panel-h.gif'); preload('panel-v.gif'); preload('panel-h2.gif');
preload('panel-tl.gif'); preload('panel-tr.gif'); preload('panel-bl.gif'); preload('panel-br.gif');
preload('button.gif');
preload('buttonhover.gif');
preload('scale1.gif'); preload('scale2.gif');

// Live feeds
if (allowMultiview) {
  preload('layout.gif');
} else {
  preload('layoutdis.gif');
}

// functions proper start here

function appletInited() {
  appletSafe = true;
  requestNewResolution(320, 240);

  // Set the applet PTZ caps
  if (currentLayout == 1) {
    f = 0;
    for (n=0; n<totalFeeds; n++) {
      if (feedSelected[n]) {
        document.MJPGApplet.setSlot(1, feedIDs[n], ptzCaps[n]);
      }
    }
  }
}

function selectMode(mode) {
  if (modeSetLockout)
    return;

  if (mode != viewmode) {
    location.href='/index.htm?feed='+playFeed+'&mode='+mode;
  }
}

function expireTimer() {
  expired = true;

  if (usingApplet) {
    document.MJPGApplet.notifyInvalidSession();
  } else {
    viewSelect(0);

    if (!allowMultiview)
      writeLayout();

    // Update the view image
    i = document.getElementById('image1');
    i.src = '/status/expired.gif';
    i.width = 352; i.height = 288;
  }

  // Hide the gradient control
  pi = document.getElementById('panimage');
  if (pi != null) { pi.style.display="none"; }
  ti = document.getElementById('tiltimage');
  if (ti != null) { ti.style.display="none"; }

  // And the PTZ controls
  document.getElementById('ptzpanel').style.display='none';
}

function expireInc() {
  expireTime++;

  if (expireTime > duration)
    expireTimer();
  else
    window.setTimeout("expireInc()",1000);  
}

function viewHover(view) {
  if (!allowMultiview)
    return;

  img = document.getElementById(viewIcons[view]);
  img.className = 'displayIconSel';
}

function unViewHover(view) {
  if (!allowMultiview)
    return;

  img = document.getElementById(viewIcons[view]);
  if (cView != view) {
    img.className='displayIcon';
  }
}

function getNextSlot() {
  if (lastSlot > 16)
    return;

  if (lastSlot == -1)
    lastSlot = 0;

  for (n=lastSlot+1; n<=16; n++) {
    if (slotIDs[n-1] == '') {
      lastSlot = n;
      return;
    }
  }
}

function viewSelect(view) {
  if (!allowMultiview)
    return;

  img = document.getElementById(viewIcons[cView]);
  img.className = 'displayIcon';
  img = document.getElementById(viewIcons[view]);
  img.className = 'displayIconSel';

  cView = view;

  oMaxFeeds = maxFeeds;

  if (cView == 0) maxFeeds = 1;
  if (cView == 1) maxFeeds = 4;
  if (cView == 2) maxFeeds = 9;
  if (cView == 3) maxFeeds = 16;
  if (cView == 4) maxFeeds = 6;
  if (cView == 5) maxFeeds = 13;

  setLayout(cView+1);

  if (cView == 0) {
    enterFeed(lastFeed,1);

    lastWasUnselect = false;
    lastSelect = -1;
    lastSlot = -1;

    return;
  }

  lastSlot = 0;

  if (maxFeeds > oMaxFeeds) {
    f = feedsSelected;

    for (c = 1; c <= totalFeeds; c++) {
      if ((feedSelected[c-1] == 0) && (f < maxFeeds)) {
        getNextSlot();
        enterFeed(c,0);
        f++;
      }
    }
  } else {
    for (n = 1; n <= totalFeeds; n++) {
      if ((feedSelected[n-1] == 1) && (feedSlots[n-1] > maxFeeds)) {
        enterFeed(n,0);
      }
    }

    for (n = maxFeeds + 1; n <= oMaxFeeds; n++) {
      killSlot(n);
    }
  }

  lastWasUnselect = false;
  lastSelect = -1;
  lastSlot = -1;

  commitSlots();

  if (currentLayout == 1) {
    for (f=0; f<totalFeeds; f++) {
      if (feedSelected[f]) enablePTZControls(f);
    }
  } else {
    enablePTZControls(0);
  }
}

function feedHover(feed) {
  td = document.getElementById('tdfeed'+feed);
  td.className = 'feedHover';
}

function feedUnHover(feed) {
  td = document.getElementById('tdfeed'+feed);
  if (feedSelected[feed-1] == 0) {
    td.className = 'feedUnSelect';
  } else {
    td.className = 'feedSelect';
  }
}

function enterFeed(feed,commit) {

  expireTime = 0;

  if (cView == 0) { // Single view
    for (n = 1; n <= totalFeeds; n++) {
      if (feedSelected[n-1]) {
        td = document.getElementById('tdfeed'+n);
        td.className = 'feedUnSelect';
 
        feedSelected[n-1] = 0;
        feedSlots[n-1] = -1;
      }
    }

    for (n=2; n<=16; n++)
      killSlot(n);

    feedsSelected = 0;
    lastSlot = 1;
  }

  if ((commit == 1) && (lastWasUnselect) && (feedSelected[feed-1])) {
    feedSelected[lastSelect-1] = 1;
    td = document.getElementById('tdfeed'+lastSelect);
    td.className = 'feedSelect';
    feedsSelected++;
    feedSlots[lastSelect-1] = lastSlot;
  }

  if ((feedsSelected <= maxFeeds) && (feedSelected[feed-1] == 1)) {
    feedSelected[feed-1] = 1 - feedSelected[feed-1];
    feedsSelected--;
    lastSlot = feedSlots[feed-1];
    feedSlots[feed-1] = -1;
  } else if ((feedsSelected < maxFeeds) && (feedSelected[feed-1] == 0)) {
     feedSelected[feed-1] = 1;
     feedsSelected++;
  } else if (feedsSelected > maxFeeds) {
     feedSelected[feed-1] = 0;
     feedsSelected--;
  } else if ((feedsSelected == maxFeeds) && (feedSelected[feed-1] == 0)) {
     return;
  }

  td = document.getElementById('tdfeed'+feed);

  if (feedSelected[feed-1]) {
    td.className = 'feedSelect';
    setSlot(lastSlot,feedIDs[feed-1]);

    if (currentLayout == 1)
      enablePTZControls(feed-1);

    feedSlots[feed-1] = lastSlot;

    lastWasUnselect = false;

    playFeed = feedIDs[feed-1];

    document.getElementById('playLink').href = '/playback/?feed='+playFeed;

    lastFeed = feed;

  } else {

    td.className = 'feedUnSelect';

    feedSlots[feed-1] = -1;

    lastWasUnselect = true;
    lastSelect = feed;

  }

  if (commit)
    commitSlots();
}

function setSlot(slot, feedID) {
  if (usingApplet) {
    ptz = 0;
    for (n=0; n<totalFeeds; n++) {
      if (feedIDs[n] == feedID)
        ptz = ptzCaps[n];
    }

    if (checkApplet())
      document.MJPGApplet.setSlot(slot,feedID,ptz);

    slotIDs[slot-1] = feedID;
  } else {
    tempSlot[slot-1] = feedID;
    slotIDs[slot-1] = feedID;
  }
}

function killSlot(slot) {
  if (usingApplet) {
    if (checkApplet())
      document.MJPGApplet.killSlot(slot);
  } else
    tempSlot[slot-1] = '';
    slotIDs[slot-1] = '';
}

function commitSlots() {
  if (usingApplet) {
    if (checkApplet())
      document.MJPGApplet.commitSlots();
  } else {
    for (n=0; n<16; n++) {
      realSlot[n] = tempSlot[n];
    }
  }
}

function setLayout(newView) {
  if (usingApplet) {
    if (checkApplet())
      document.MJPGApplet.setLayout(newView);
    currentLayout = newView;
  } else {
    killImageTimer();
    currentLayout = newView;
    writeLayout();

    for (n=1; n<=16; n++) {
      feedStatus[n-1] = 0;
      lastUpdate[n-1] = 0;
      slotImages[n].onload = imageLoaded;
      slotImages[n].onerror = imageLoaded;
    }

    imageTimerID = window.setTimeout("imageTimer()",50);
  }
}

function notifyZoom(zoomLevel) {
  if (usingApplet) {
    if (checkApplet())
      document.MJPGApplet.setZoom(zoomLevel);
  } else {
    if (zoomLevel == 1)
      zoomMultiplier = 0.25;
    if (zoomLevel == 2)
      zoomMultiplier = 0.5;
    if (zoomLevel == 3)
      zoomMultiplier = 1.0;
    if (zoomLevel == 4)
      zoomMultiplier = 2.0;
    if (zoomLevel == 5)
      zoomMultiplier = 4.0;

    if (currentLayout == 1)
      requestNewResolution(slotImages[1].width * zoomMultiplier, slotImages[1].height * zoomMultiplier);

    if ((currentLayout >= 2) && (currentLayout <= 4)) {
      var w = [0,192,170,160]; var h = [0,144,128,120];

      for (n=1; n<=maxFeeds; n++) {
        i = document.getElementById('image'+n);
        if (i != null) {
          i.width = w[currentLayout] * zoomMultiplier;
          i.height = h[currentLayout] * zoomMultiplier;
        }
      }
    }

    if (currentLayout == 5) {

      for (n=2; n<=maxFeeds; n++) {
        i = document.getElementById('image'+n);
        if (i != null) {
          i.width = 170 * zoomMultiplier;
          i.height = 128 * zoomMultiplier;
        }
      }

      i = document.getElementById('image1');
      if (i != null) {
        i.width = 340 * zoomMultiplier;
        i.height = 256 * zoomMultiplier;
      }
    }

    if (currentLayout == 6) {

      for (n=1; n<=maxFeeds; n++) {
        i = document.getElementById('image'+n);
        if ((i != null) && (n != 6)) {
          i.width = 160 * zoomMultiplier;
          i.height = 120 * zoomMultiplier;
        }
      }

      i = document.getElementById('image6');
      if (i != null) {
        i.width = 320 * zoomMultiplier;
        i.height = 240 * zoomMultiplier;
      }
    }

  }
}

function setZoomL(p) {
  if (!allowZooming)
    return;

  cZoom = p;
  notifyZoom(p);
}

function adjustZoom(p) {
  t = eval(cZoom + '+'+ p);
  if (t < 1) t = 1;
  if (t > 5) t = 5;
  setSlider(1,t);
  setZoomL(t);
}

function sliderChangeCallback(val, slider) {
  if (slider == 1)
    setZoomL(Math.floor(val + 0.5));
  if (slider == 2)
    setQual(Math.floor(val + 0.5));
}

function setQualSlider(p, commit) {
  cQual = p;
  setCookie("quality", p);
  if (commit == 1)
    notifyQual(p);
}

function notifyQual(qualLevel) {
  if (usingApplet) {
    if (checkApplet())
      document.MJPGApplet.setQuality(qualLevel);
  } else {
    if (qualLevel == 1)
      qualitySetting = 15;
    if (qualLevel == 2)
      qualitySetting = 25;
    if (qualLevel == 3)
      qualitySetting = 50;
    if (qualLevel == 4)
      qualitySetting = 75;
    if (qualLevel == 5)
      qualitySetting = 0;
  }
}

function setQual(p) {
  setQualSlider(p,1);
}

function adjustQual(p) {
  t = eval(cQual + '+' + p);
  if (t < 1) t = 1;
  if (t > 5) t = 5;
  setSlider(2,t);
  setQual(t);
}

function requestNewResolution(newWidth, newHeight) {
  if (usingApplet) {
    if (checkApplet()) {
      document.MJPGApplet.width = newWidth;
      document.MJPGApplet.height = newHeight;
    }
  } else {
    i = document.getElementById('image1');
    if (currentLayout == 1) {
      if (i != null) {
        i.width = newWidth;
        i.height = newHeight;
      }
    }
  }

  if (currentLayout == 1) {
    for (n=0; n<totalFeeds; n++) {
      if (feedSelected[n])
        enablePTZControls(n);
    }
  }

  //Resize the Gadget text (limited to 300px wide)
  document.getElementById('gadgetblock').style["width"] = (newWidth < 300 ? 300 : newWidth);
}

function slotSource(slot) {
  if (realSlot[slot-1] != '')
    return '/image.jpg?feed='+realSlot[slot-1]+'&quality='+qualitySetting+'&uniq='+lastUpdate[slot-1];
  else
    return '/status/pleasewait.gif';
}

function writeLayout() {
  lhtml = '';

  for (n=1; n<=16; n++) {
    feedStatus[n-1] = 1;
  }

  if (!usingApplet) {
    cl = currentLayout; z = zoomMultiplier;

    if (currentLayout == 1) {
      lhtml = lhtml + '<table cellpadding="0" cellspacing="0" border="0"><tr><td>';
      lhtml = lhtml + '<img src="'+slotSource(1)+'" id="image1" name="image1" onLoad="feedMark(1);">';
      lhtml = lhtml + '</td><td>';
      lhtml = lhtml + '<img src="" id="tiltimage" name="tiltimage" onclick="tiltscrollclick(event);" style="display: none;" height="0" width="0" alt="">';
      lhtml = lhtml + '</td></tr><tr><td valign="top">';
      lhtml = lhtml + '<img src="" id="panimage" name="panimage" onclick="panscrollclick(event);" style="display: none;" height="0" width="0" alt="">';
      lhtml = lhtml + '</td><td></td></tr></table>';
    }

    if ((currentLayout >=2) && (currentLayout <= 4)) { // grid view
      var w = [0,0,192,170,160]; var h = [0,0,144,128,120];
      f = 1;

      lhtml = lhtml + '<table cellpadding="0" cellspacing="0" border="0">';

      for (r=0; r<currentLayout; r++) {
        lhtml = lhtml + '<tr>';

        for (c=0; c<currentLayout; c++) {
          lhtml = lhtml + '<td>';
          lhtml = lhtml + '<img src="'+slotSource(f)+'" width="'+(w[cl] * z)+'" height="'+(h[cl] * z)+'" id="image'+f+'" name="image'+f+'" onLoad="feedMark('+f+');" onClick="jumpSlot('+f+');">';
          lhtml = lhtml + '</td>';
          f++;
        }

        lhtml = lhtml + '</tr>';
      }
        
      lhtml = lhtml + '</table>';
    }

    if (currentLayout == 5) { // focused view
      lhtml = lhtml + '<table cellpadding="0" cellspacing="0" border="0"><tr>';
      lhtml = lhtml + '<td rowspan="2" colspan="2"><img src="'+slotSource(1)+'" id="image1" name="image1" width="'+(340*z)+'" height="'+(256*z)+'" onLoad="feedMark(1);" onClick="jumpSlot(1);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(2)+'" id="image2" name="image2" width="'+(170*z)+'" height="'+(128*z)+'" onLoad="feedMark(2);" onClick="jumpSlot(2);"></td></tr>';
      lhtml = lhtml + '<tr><td><img src="'+slotSource(3)+'" id="image3" name="image3" width="'+(170*z)+'" height="'+(128*z)+'" onLoad="feedMark(3);" onClick="jumpSlot(3);"></td></tr>';
      lhtml = lhtml + '<tr><td><img src="'+slotSource(4)+'" id="image4" name="image4" width="'+(170*z)+'" height="'+(128*z)+'" onLoad="feedMark(4); onClick="jumpSlot(4);""></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(5)+'" id="image5" name="image5" width="'+(170*z)+'" height="'+(128*z)+'" onLoad="feedMark(5); onClick="jumpSlot(5);""></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(6)+'" id="image6" name="image6" width="'+(170*z)+'" height="'+(128*z)+'" onLoad="feedMark(6); onClick="jumpSlot(6);""></td></tr>';
      lhtml = lhtml + '</table>';
    }

    if (currentLayout == 6) { // central view
      lhtml = lhtml + '<table cellpadding="0" cellspacing="0" border="0"><tr>';
      // Top line
      lhtml = lhtml + '<td><img src="'+slotSource(1)+'" id="image1" name="image1" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(1);" onClick="jumpSlot(1);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(2)+'" id="image2" name="image2" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(2);" onClick="jumpSlot(2);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(3)+'" id="image3" name="image3" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(3);" onClick="jumpSlot(3);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(4)+'" id="image4" name="image4" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(4);" onClick="jumpSlot(4);"></td></tr>';

      // Middle set
      lhtml = lhtml + '<td><img src="'+slotSource(5)+'" id="image5" name="image5" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(5);" onClick="jumpSlot(5);"></td>';
      lhtml = lhtml + '<td colspan="2" rowspan="2"><img src="'+slotSource(6)+'" id="image6" name="image6" width="'+(384*z)+'" height="'+(288*z)+'" onLoad="feedMark(6);" onClick="jumpSlot(6);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(7)+'" id="image7" name="image7" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(7);" onClick="jumpSlot(7);"></td></tr>';

      // Middle set follower
      lhtml = lhtml + '<td><img src="'+slotSource(8)+'" id="image8" name="image8" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(8);" onClick="jumpSlot(1);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(9)+'" id="image9" name="image9" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(9);" onClick="jumpSlot(1);"></td></tr>';

      // Bottom row
      lhtml = lhtml + '<td><img src="'+slotSource(10)+'" id="iamge10" name="image10" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(10);" onClick="jumpSlot(1);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(11)+'" id="image11" name="image11" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(11);" onClick="jumpSlot(1);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(12)+'" id="image12" name="image12" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(12);" onClick="jumpSlot(1);"></td>';
      lhtml = lhtml + '<td><img src="'+slotSource(13)+'" id="image13" name="image13" width="'+(192*z)+'" height="'+(144*z)+'" onLoad="feedMark(13);" onClick="jumpSlot(1);"></td></tr>';

      lhtml = lhtml + '</table>';
    }

    writeLayoutHTML(lhtml);
  }
}

function writeLayoutHTML(sText) {
  if (document.getElementById) {
    document.getElementById('feedPanel').innerHTML = sText;
  } else {
    var oLayer;

    oLayer = document.layers['feedPanel'].document;
   
    oLayer.open();
    oLayer.write(sText);
    oLayer.close();
  }
}

function hoverPTZ(which) {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  s = '';

  if (ptzCaps[f] & 2) {
    if (which == 1) {
      i = document.getElementById('ptzup');
      s = '/images/ptzup-h.gif';
    }
    if (which == 4) {
      i = document.getElementById('ptzdown');
      s = '/images/ptzdown-h.gif';
    }
  }

  if (ptzCaps[f] & 1) {
    if (which == 2) {
      i = document.getElementById('ptzleft');
      s = '/images/ptzleft-h.gif';
    }
    if (which == 3) {
      i = document.getElementById('ptzright');
      s = '/images/ptzright-h.gif';
    }
  }

  if (ptzCaps[f] & 4) {
    if (which == 5) {
      i = document.getElementById('ptzzin');
      s = '/images/zi-h.gif';
    }
    if (which == 6) {
      i = document.getElementById('ptzzout');
      s = '/images/zo-h.gif';
    }
  }

  if (s != '')
    i.src = s;
}

function unHoverPTZ(which) {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  s = '';

  if (ptzCaps[f] & 2) {
    if (which == 1) {
      i = document.getElementById('ptzup');
      s = '/images/ptzup.gif';
    }
    if (which == 4) {
      i = document.getElementById('ptzdown');
      s = '/images/ptzdown.gif';
    }
  }

  if (ptzCaps[f] & 1) {
    if (which == 2) {
      i = document.getElementById('ptzleft');
      s = '/images/ptzleft.gif';
    }
    if (which == 3) {
      i = document.getElementById('ptzright');
      s = '/images/ptzright.gif';
    }
  }

  if (ptzCaps[f] & 4) {
    if (which == 5) {
      i = document.getElementById('ptzzin');
      s = '/images/zi.gif';
    }
    if (which == 6) {
      i = document.getElementById('ptzzout');
      s = '/images/zo.gif';
    }
  }

  if (s != '')
    i.src = s;
}

function doPTZ(which) {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  angle = 5;
  if (ptzFine)
    angle = 1;

  url = '/ptz/control.htm?feed='+feedIDs[f]+'&angle='+angle;

  if ((which >= 1) && (which <= 4))
    url = url + '&move=';

  if ((which >= 5) && (which <= 6))
    url = url + '&zoom=';

  if (which == 1)
    url = url + 'up';
  if (which == 2)
    url = url + 'left';
  if (which == 3)
    url = url + 'right';
  if (which == 4)
    url = url + 'down';
  if (which == 5)
    url = url + 'in';
  if (which == 6)
    url = url + 'out';

  url = url + '&uniq='+getMillis();

  ptzImage.src = url;     
}

function enablePTZControls(feed) {
  if (expired)
    return;
    
  var fw = 0;
  var fh = 0;
  panEn = 0;
  tiltEn = 0;
  zoomEn = 0;

  // If it is a single feed, enable as needed
  if (currentLayout == 1) {
    panEn = ptzCaps[feed] & 1;
    tiltEn = ptzCaps[feed] & 2;
    zoomEn = ptzCaps[feed] & 4;
  }

  // Get a reference to the PTZ gradient bars
  pi = document.getElementById('panimage');
  ti = document.getElementById('tiltimage');

  // If any of them are enabled..
  if ((zoomEn) || (panEn) || (tiltEn)) {

    // Enable the pan, tilt, and zoom buttons if that feature is available
    // There is no need to set them outside this block as the PTZ controsl will be hidden
    if (panEn) {
      document.getElementById('ptzleft').src = '/images/ptzleft.gif';
      document.getElementById('ptzright').src = '/images/ptzright.gif';
    } else {
      document.getElementById('ptzleft').src = '/images/ptzleft-d.gif';
      document.getElementById('ptzright').src = '/images/ptzright-d.gif';
    }

    if (tiltEn) {
      document.getElementById('ptzup').src = '/images/ptzup.gif';
      document.getElementById('ptzdown').src = '/images/ptzdown.gif';
    } else {
      document.getElementById('ptzup').src = '/images/ptzup-d.gif';
      document.getElementById('ptzdown').src = '/images/ptzdown-d.gif';
    }

    if (zoomEn) {
      document.getElementById('ptzzin').src = '/images/zi.gif';
      document.getElementById('ptzzout').src = '/images/zo.gif';
    } else {
      document.getElementById('ptzzin').src = '/images/zi-d.gif';
      document.getElementById('ptzzout').src = '/images/zo-d.gif';
    }

    if (!usingApplet) {
      // Get the image tag size
      fi = document.getElementById('image1');
      fw = fi.width; fh = fi.height;
    } else {
      if (checkApplet()) {
        // Get the image tag size
        fw = document.MJPGApplet.width; fh = document.MJPGApplet.height;
      }
      // If the applet hasn't loaded yet, it will be the default of 0 from above
    }

    m = getMillis();
    document.getElementById('homeText').className = 'small';
    document.getElementById('fineText').className = 'small';

    // Load the pan gradient image
    if ((pi != null) && (fw != 0) && (panEn)) {
      pi.width = fw; pi.height = 12;
      pi.src = '/ptz/gradient.gif?orientation=0&size='+fw;
      pi.style.display = "inline";
    }
 
    // Load the tilt gradient image
    if ((ti != null) && (fh != 0) && (tiltEn)) {
      ti.width = 17; ti.height = fh;
      ti.src = '/ptz/gradient.gif?orientation=1&size='+fh;
      ti.style.display = "inline";
    }

    document.getElementById('ptzpanel').style.display='inline';
    updatePresetList(feedIDs[feed]);

  } else {
    //Disable the PTZ buttons
    document.getElementById('ptzpanel').style.display='none';
    document.getElementById('homeText').className = 'smalldis';
    document.getElementById('fineText').className = 'smalldis';
    clearPresetList();
  }

  // If the PTZ gradients exist but they aren't available, hide them
  if ((!panEn) && (pi !=null)) { pi.style.display = "none"; } 
  if ((!tiltEn) && (ti !=null)) { ti.style.display = "none"; }
}

function panscrollclick(click) {
  if (navigator.appName=='Netscape') {
    rx = click.clientX - document.getElementById('panimage').x;
  } else {
    rx = click.offsetX;
  }

  mins = parseInt(rx * (360/(document.getElementById('panimage').width-1)));
  mins = (mins - 180);
  
  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  url = '/ptz/control.htm?feed='+feedIDs[f]+'&move=to&pan='+mins+'&uniq='+getMillis();
  ptzImage.src = url;
}

function tiltscrollclick(click) {
  if (navigator.appName=='Netscape') {
    rx = click.clientY - document.getElementById('tiltimage').y;
  } else {
    rx = click.offsetY;
  }

  mins = parseInt(rx * (360/document.getElementById('tiltimage').height));
  mins = -(mins - 180);
  
  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  url = '/ptz/control.htm?feed='+feedIDs[f]+'&move=to&tilt='+mins+'&uniq='+getMillis();
  ptzImage.src = url;
}
  
function setFine() {
  ptzFine = 1 - ptzFine;

  td = document.getElementById('fineButton');
  if (ptzFine)
    td.className = 'feedSelect';
  else
    td.className = 'feedUnSelect';
}

function hoverFine(h) {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  if ((ptzCaps[f] & 3) == 0)
    return;

  td = document.getElementById('fineButton');
  if (h) {
    td.className = 'feedHover';
  } else {
    if (ptzFine) 
      td.className = 'feedSelect';
    else
      td.className = 'feedUnSelect';
  }
} 

function goHome() {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  url = '/ptz/control.htm?feed='+feedIDs[f]+'&move=home&uniq='+getMillis();
  ptzImage.src = url;
}

function hoverHome(h) {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  if ((ptzCaps[f] & 3) == 0)
    return;

  td = document.getElementById('homeButton');
  if (h) {
    td.className = 'feedHover';
  } else {
    td.className = 'feedUnSelect';
  }
}  

function directPTZMovement(mX, mY) {
  if (currentLayout != 1)
    return;

  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  url = '/ptz/control.htm?feed=' + feedIDs[f] + '&move=inimage&x=' + mX + "&y=" + mY + "&width=" + document.MJPGApplet.width + "&height=" + document.MJPGApplet.height;
  ptzImage.src = url;
}

var http = getHTTPObject();

function clearPresetList() {
  //Clear the preset list
  var dropdown = document.getElementById('ptzpresetlist');
  while (dropdown.length > 1)
    dropdown.remove(1);
}

function updatePresetList(feedid) {
  clearPresetList();

  if (feedid != "") {
    http.open("GET", "/ptz/presets.xml?feed=" + feedid, true);
    http.onreadystatechange = HandlePresetReply;
    http.send(null);
  }
}   

function HandlePresetReply() {
  if (http.readyState == 4) {

    if (http.responseText != "") {
      var presetlist = http.responseXML.documentElement;
      var dropdown = document.getElementById('ptzpresetlist');

      var presets = presetlist.getElementsByTagName("preset");
      if (presets.length == 0) {
        dropdown.style.display='none';
      } else {
        dropdown.style.display='inline';

        var index;
        for (index = 0; index < presets.length; index++) {
          var preset = presets[index];
          var newoption=document.createElement('option');
          newoption.text=preset.attributes.getNamedItem('name').value

          try {
            dropdown.add(newoption,null); //The standard method
          } catch(ex){
            dropdown.add(newoption); //Damn IE....
          }
        }
      }

    } else {
      //request failed
    }
  }
}

function selectedPreset() {
  var dropdown = document.getElementById('ptzpresetlist');
  if (dropdown.selectedIndex > 0) {
    gotoPreset(dropdown.selectedIndex);
    dropdown.selectedIndex = 0;
  }
}

function gotoPreset(presetindex) {
  //1 based list of presets
  //0 is the home positions
  f = 0;
  for (n=0; n<totalFeeds; n++) {
    if (feedSelected[n])
      f = n;
  }

  url = '/ptz/control.htm?feed='+feedIDs[f]+'&move=preset&preset='+presetindex+'&uniq='+getMillis();
  ptzImage.src = url;
}

function disableViewControls() {
  document.getElementById('displayGrid').className='displayGridDis';
}

function disableZoomControls() {
  document.getElementById('izo').className = 'adjTextDis';
  document.getElementById('izi').className = 'adjTextDis';
  document.getElementById('slider01').className = 'sliderd';
  document.getElementById('zslider').src = '/images/scale2d.gif';
  document.getElementById('zoomtext').className = 'icontrolsd';
}

function jumpSlot(slot) {
  slotID = slotIDs[slot-1];

  viewSelect(0);

  feed = 1;

  for (n=0; n<totalFeeds; n++) {
    if (feedIDs[n] == slotID)
      feed = n+1;
  }

  enterFeed(feed,1);
}

function checkApplet() {
  return appletSafe;
}

function printFeedList() {
  t = totalFeeds;
  if (t>10) t = 10;
  divHeight = 19 * t;

  document.write('<div class="feed" style="height: '+divHeight+'px; width: 120px; overflow: auto;">');

  document.write('<table width="100" cellpadding="1" cellspacing="1" border="0">');

  for (f=1; f<=totalFeeds; f++) {
    tc = 'feedUnSelect';
    if (feedIDs[f-1] == defaultFeed)
      tc = 'feedSelect';

    document.write('<tr><td id="tdfeed'+f+'" onMouseOver="feedHover('+f+');" onMouseOut="feedUnHover('+f+');" onClick="enterFeed('+f+',1);" class="'+tc+'">');
    document.write('<p class="feed">'+feedNames[f-1]+'</p></td></tr>');
  }

  document.write('</table></div>');
}

function postLoad() {
  if (!allowMultiview)
    disableViewControls();

  if (!allowZooming)
    disableZoomControls();

  if (duration > 0)
    window.setTimeout("expireInc()",1000);

  document.getElementById('playLink').href='/playback/?feed='+defaultFeed;

  if (advancedFeatures) {
    document.getElementById('button2').style.display = 'block';
  }

  writeLayout();

  if (viewmode != 1) {
    setUpJS = false;
  }

  if ((!usingApplet) && (setUpJS)) {
    realSlot[0] = defaultFeed;
    tempSlot[0] = defaultFeed;

    imageTimerID = window.setTimeout("imageTimer()",50);
  }

  for (f=0; f<totalFeeds; f++) {
    if (feedIDs[f] == defaultFeed) {
      enablePTZControls(f);
    }
  }

  setQual(useQuality);

  if (viewmode >= 0)
    document.viewselect.viewer[1-viewmode].checked=true;
  else 
    document.viewselect.viewer[1].checked=true;

  modeSetLockout = false;

  //Show the Gadget block unless a cookie says otherwise
  var hideGadgetVal = getCookie("hidegadget");
  if (hideGadgetVal == null) { hideGadgetVal = 0; }

  if ((navigator.userAgent.indexOf("Windows NT 6.0") > -1) && hideGadgetVal == 0) { 
    //Windows vista 
    document.getElementById('gadgetblock').style.display = 'block';
  } 
}

//Gadget block code
function hideGadget() {
  document.getElementById('gadgetblock').style.display = 'none';
  setCookie('hidegadget',1);
  return false;
}

function sliderPostLoad() {
  setSlider(2, useQuality);
}

function buttonHover(button) {
  bt = document.getElementById('button'+button);
  bt.className = 'buttonHover';
}
 
function buttonUnHover(button) {
  bt = document.getElementById('button'+button);
  bt.className = 'button';
}

  // Original JavaScript code by Duncan Crombie: dcrombie at chirp.com.au
  // Please acknowledge use of this code by including this header.
  // http://members.ozemail.com.au/~dcrombie/cookie.html

function getCookie(name) { // use: getCookie("name");
  var cookie = document.cookie;
  var index = cookie.indexOf(name + "=");
  if (index == -1) return null; //Not found
  index = cookie.indexOf("=", index) + 1;
  var endstr = cookie.indexOf(";", index);
  if (endstr == -1) endstr = cookie.length;
  return unescape(cookie.substring(index, endstr));
}

function setCookie(name, value) { // use: setCookie("name", value);
  var today = new Date();
  var expiry = new Date(today.getTime() + 28 * 24 * 60 * 60 * 1000); // plus 28 days

  if (value != null && value != "")
    document.cookie = name + "=" + escape(value) + "; expires=" + expiry.toGMTString() + "; path=/";
}

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Originally from:
  http://www.arantius.com/article/lightweight+javascript+slider+control

Copyright (c) 2006 Anthony Lieuallen, http://www.arantius.com/

The following licensing information applies solely to slider.js, the
DHTML/JavaScript slider control. Please see the i-Catcher EULA for information
pertaining to the i-Catcher license.

Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal in 
the Software without restriction, including without limitation the rights to 
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
the Software, and to permit persons to whom the Software is furnished to do so, 
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all 
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//add event function from http://www.dynarch.com/projects/calendar/
function addAnEvent(el, evname, func) {
    if (el.attachEvent) { // IE
        el.attachEvent("on" + evname, func);
    } else if (el.addEventListener) { // Gecko / W3C
        el.addEventListener(evname, func, true);
    } else {
        el["on" + evname] = func;
    }
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function drawSliderByVal(slider) {
	slider.val = Math.floor(slider.val);
	var knob=slider.getElementsByTagName('img')[0];
	var p=(slider.val-slider.min)/(slider.max-slider.min);
	var x=(slider.scrollWidth-12)*p;
	knob.style.left=x+"px";
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function setSlider(num, val) {
  slider[num].val = val;

  s = document.getElementById('slider0'+num);

  if (s != null) {
    s.val = val;
    drawSliderByVal(s);
  }
}

function findPosX(obj)
{
var curleft = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
}
else if (obj.x)
curleft += obj.x;
return curleft;
} 
function setSliderByClientX(slider, clientX) {
//	var p=(clientX-findPosX(slider))/(slider.scrollWidth+10);
        var p=(clientX-slider.offsetLeft-6)/(slider.scrollWidth-12);
	slider.val=(slider.max-slider.min)*p + slider.min;
	if (slider.val>slider.max) slider.val=slider.max;
	if (slider.val<slider.min) slider.val=slider.min;

	drawSliderByVal(slider);
	slider.onchange(slider.val, slider.num);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderClick(e) {
	var el=sliderFromEvent(e);
	if (!el) return;

	setSliderByClientX(el, e.clientX);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderMouseMove(e) {
	var el=sliderFromEvent(e);
//	if (!el) return;
//	if (activeSlider<0) return;

	if ((!el) || (activeSlider<0)) {
	  activeSlider = -1;

	  return;
	}

	if ((el.num == 1) && (!allowZooming))
	  return;

	setSliderByClientX(el, e.clientX);
	stopEvent(e);
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function sliderFromEvent(e) {
	if (!e && window.event) e=window.event;
	if (!e) return false;

	var el;
	if (e.target) el=e.target;
	if (e.srcElement) el=e.srcElement;

	if (!el.id || !el.id.match(/slider\d+/)) el=el.parentNode;
	if (!el) return false;
	if (!el.id || !el.id.match(/slider\d+/)) return false;

	return el;
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
function attachSliderEvents() {
	var divs=document.getElementsByTagName('div');
	var divNum;
	for(var i=0; i<divs.length; i++) {
		if (divNum=divs[i].id.match(/\bslider(\d+)\b/)) {
			divNum=parseInt(divNum[1]);
			divs[i].min=slider[divNum].min;
			divs[i].max=slider[divNum].max;
			divs[i].val=slider[divNum].val;
			divs[i].onchange=slider[divNum].onchange;
			divs[i].num=divNum;

			addAnEvent(divs[i], 'mousedown', function(e){
				sliderClick(e);
				var el=sliderFromEvent(e);
				if (!el) return;
				activeSlider=el.num;
				stopEvent(e);
			});
			addAnEvent(divs[i], 'mouseup', function(e){
				activeSlider=-1;
				stopEvent(e);
			});
		}
	}

        sliderPostLoad();
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
//borrowed from prototype: http://prototype.conio.net/
function stopEvent(event) {
	if (event.preventDefault) {
		event.preventDefault();
		event.stopPropagation();
	} else {
		event.returnValue=false;
		event.cancelBubble=true;
	}
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
addAnEvent(window, 'load', attachSliderEvents);
addAnEvent(document, 'mousemove', sliderMouseMove);
var activeSlider=-1;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
var slider=new Array();
slider[1]=new Object();
slider[1].min=1;
slider[1].max=5;
slider[1].val=3;
slider[1].onchange=sliderChangeCallback;
slider[2]=new Object();
slider[2].min=1;
slider[2].max=5;
slider[2].val=3;
slider[2].onchange=sliderChangeCallback;
