  var tmp_index = document.URL.substring(8).indexOf("/") + 8 + 1;
  var base = document.URL.substring(0, tmp_index);


  // If it is not IE, we assume that the browser is NS.
  var IE = document.all ? true : false;

  // Set-up to use getMouseXY function onMouseMove
  document.onmousemove = getMouseXY;

  // Temporary variables to hold mouse x-y pos.s
  var tempX = 0;
  var tempY = 0;

  function nop() {  }

  // Main function to retrieve mouse x-y pos.s
  function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
      tempX = event.clientX + document.body.scrollLeft;
      tempY = event.clientY + document.body.scrollTop;
    } else {  // grab the x-y pos.s if browser is NS
      tempX = e.pageX;
      tempY = e.pageY;
    }  

    // catch possible negative values in NS4
    if (tempX < 0) { tempX = 0; }
    if (tempY < 0) { tempY = 0; } 

    return true;
  }

    function ucword(word) {
      word = word.substring(0, 1).toUpperCase() + word.substring(1, word.length);
      return word;
    }

    var current_example = '';
    var current_counter = 0;
    var example_running = false;
    var current_timeout = 0;
    var current_pid = 0;
    var current_subject = 0;
    var max_subjects = 1;
    var pids = new Array();

    function isPictureUploaded() {
      return (pids.length > 0);
    }

    function add_photo(pid) {
      request = getRequestObject();
      msg = "add_pic|" + pid;
      url = base + "order_mgr.php?msg=" + escape(msg);
      request.open("GET", url, true);
      request.send("");

      if (pids.length == 1 && pids[0] == 0) {
        pids[0] = pid;
	current_pid = pid;
      } else {
        pids.length++;
	pids[pids.length-1] = pid;
	current_pid = pid;
      }

      current_subject = 0;
      renderPhotos();
    }

    // this function may be called more than once for the same pid
    // so it's important not to automatically assume something
    // will be deleted...
    function delete_photo(pid) {
      var x = 0;
      request = getRequestObject();
      msg = "delete_pic|" + pid;
      url = base + "order_mgr.php?msg=" + escape(msg);
      // make this async?
      request.onreadystatechange = nop;
      request.open("GET", url, true);
      request.send("");
      // HttpRequest(url);

      // reset the form...
      if (document.myform) {
        for (x=0; x<document.myform.length; x++) 
          if (document.myform[x].type == "checkbox")
	    document.myform[x].checked = false;
        // document.myform.comments.value = "";
        // char_counter(document.myform.comments, 'comment_counter', 250);
      }

      // remove pid from javascripts pids array
      tempArray = new Array();
      for (x=0; x<pids.length; x++) {
        if (pids[x] == pid) {
	  if (x == 0) {
	    pids = pids.slice(1);
	    break;
	  } else if (x + 1 < pids.length) {
	    pids = tempArray.concat(pids.slice(0, x), pids.slice(x + 1, pids.length));
	  } else {
	    pids = pids.slice(0, pids.length - 1);
	  }

	}
      }

      if (pid == current_pid)
        if (pids.length == 0) {
	  current_pid = 0;
	} else {
	  current_pid = pids[0];
	}

      current_subject = 0;
      initSubjects();
      renderSubjects();
      renderPhotos();
    }

    function load_pids() {
      msg = "load_pids|";
      url = base + "order_mgr.php?msg=" + escape(msg);
      temp_pids = HttpRequest(url);
      if (temp_pids == "") {
        pids = new Array(0);
      } else {
        pids = temp_pids.split(",");
      }

      if (pids.length > 0) 
        current_pid = pids[0]; 
    }

    function orderFormInit() {
      load_pids();
      renderPhotos();
      initSubjects();
      renderSubjects();
    }

    function saveState() {
      setSubjects();
      saveOther();      
    }

    // saves the comments/other/optional text for the current pid
    function saveOther() {
      // msg = "set_comments|" + current_pid + "==" + document.myform.comments.value;
      // url = base + "order_mgr.php?msg=" + escape(msg);
      // make synchronous... not sure if page transition is cancelling async calls
      // HttpRequest(url);

      counter = 0; 
      others = new Array();
      if (document.myform)
        for (x=0; x<document.myform.length; x++)
	  if (document.myform[x].name && document.myform[x].name.indexOf('other') != -1) 
	    others[counter++] = document.myform[x].name + "==" + escape(document.myform[x].value);

      data = others.join("::");
      msg = "set_other|" + current_pid + "==" + current_subject + "::" + data;
      url = base + "order_mgr.php?msg=" + escape(msg);
      HttpRequest(url);
    }

    // changes the picture we're currently working on in the order form...
    function touchup(pid) {
      if (pid == current_pid) return;
      saveState();
      current_pid = pid;
      current_subject = 0;
      initSubjects();
      renderPhotos();
    }

    function initSubjects() {
      msg = "get_subjects|" + current_pid;
      url = base + "order_mgr.php?msg=" + escape(msg);
      subjects = HttpRequest(url);
      subj = subjects.split(",");
      max_subjects = subj.length;
      renderSubjects();
      if (max_subjects > 1)
        document.myform.num_subjects.selectedIndex = (max_subjects - 1);
    }

    function modifySubjects(subjects) {
	setSubjects();

	num = subjects[subjects.selectedIndex].value;
	max_subjects = num;
	if (max_subjects <= current_subject) {
	  current_subject = 0;
	  changeSubject(current_subject);
	}

	deleteSubjects(max_subjects);
	renderSubjects();
    }

    function renderSubjects() {
      elem = document.getElementById("select_subject");
      newHTML = "";

      if (max_subjects == 1) {
	elem.innerHTML = newHTML;
	return;
      }

      msg = "get_subjects|" + current_pid;
      url = base + "order_mgr.php?msg=" + escape(msg);
      subjects = HttpRequest(url);
      subj = subjects.split(",");
      for (x=subj.length; x<max_subjects; x++)
        subj[x] = "";

      newHTML = '<TABLE CELLPADDING="4" CELLSPACING="2" BORDER="0">\n';
      for (x=0; x<max_subjects; x++) {
	newHTML += '  <TR>\n';
	if (x == current_subject) {
	  newHTML += "    <TD ALIGN=\"right\"><I>Editing Person " + (x + 1) + "</I></TD> ";
	} else {
	  newHTML += "    <TD ALIGN=\"right\"><A HREF=\"javascript: changeSubject(" + x + ")\">Edit Person " + (x + 1) + "</A></TD>";
	}
	newHTML += "    <TD>Person " + (x + 1) + " Location in Photo: ";
	newHTML += "<INPUT TYPE=\"text\" NAME=\"person" + x + "\" VALUE=\"" + subj[x] +  "\"><BR></TD>\n";
	newHTML += '  </TR>\n';
      }
      newHTML += '</TABLE>\n';

      elem.innerHTML = newHTML;
    }

    function setSubjects() {
      if (!document.myform) return;
      if (max_subjects <= 1) return;

      subj = new Array();      
      for (x=0; x<max_subjects; x++) 
        eval("subj[x] = document.myform.person" + x + ".value");

      for (x=0; x<max_subjects; x++)
        subj[x] = escape(subj[x]);

      subjects = subj.join(",");
      msg = "set_subjects|" + current_pid + "==" + subjects;
      url = base + "order_mgr.php?msg=" + escape(msg);
      result = HttpRequest(url);            
    }

    function changeSubject(which) {
      saveState();

      current_subject = which;
      renderSubjects();
      initItems();
    }

    function deleteSubjects(startingAt) {
      msg = "delete_subjects|" + current_pid + "==" + startingAt;
      url = base + "order_mgr.php?msg=" + escape(msg);
      HttpRequest(url);
    }

    function initItems() {
      var y = 0, x = 0;
      msg = "job_items|" + current_pid + "==" + current_subject;
      url = base + "order_mgr.php?msg=" + escape(msg);
      items = HttpRequest(url);
      items = items.split("|");

      msg = "get_other|" + current_pid + "==" + current_subject;
      url = base + "order_mgr.php?msg=" + escape(msg);	
      others = HttpRequest(url);
      other = others.split("::");

      // uncheck/erase everything
      for (x=0; x<document.myform.length; x++) {
        if (document.myform[x].type == "checkbox")
	  document.myform[x].checked = false;
	if (document.myform[x].name && document.myform[x].name.indexOf("other") != -1)
	  document.myform[x].value = "";
      }

      // check appropriately
      for (y=0; y<items.length; y++)
        for (x=0; x<document.myform.length; x++)
          if (document.myform[x].type == "checkbox" &&
	      document.myform[x].value == items[y]) 
	    document.myform[x].checked = true;

      for (y=1; y<other.length; y++) {
        data = other[y].split("==");
        for (x=0; x<document.myform.length; x++)
	  if (document.myform[x].name == data[0])
	    document.myform[x].value = data[1];
      }

      // ADJ 061206 Dead code... 
      // fetch the current comments
      // var result = "";
      // nmsg = "get_comments|" + current_pid;
      // url = base + "order_mgr.php?msg=" + escape(msg);
      // result = HttpRequest(url);
      // document.myform.comments.value = result;
    }

    function syncItem(formElement) {
      var item = "";
      item = formElement.value;
      shouldAdd = formElement.checked;
      act = (shouldAdd) ? "add_item" : "_item";

      msg = act + "|" + current_pid + "==" + current_subject + "==" + item ;
      url = base + "order_mgr.php?msg=" + escape(msg);
      request = getRequestObject();
      request.onreadystatechange = nop;
      request.open("GET", url, true);
      request.send("");
    }

    var extension_keys = new Array();
    var extension_vals = new Array();
    function upload_extension(pid) {
      request = getRequestObject();
      var found = -1, x = 0;      
      for (x=0; x<extension_keys.length; x++) 
        if (extension_keys[x] == pid)
	  found = x;

      if (found != -1) 
        return extension_vals[found];

      msg = "temp_extension|" + pid;
      url = base + "order_mgr.php?msg=" + escape(msg);
      extension = HttpRequest(url);
      extension_keys.length++;
      extension_vals.length++;
      extension_keys[extension_keys.length-1] = pid;
      extension_vals[extension_vals.length-1] = extension;

      return extension;
    }

    var geometry_cache = new Array();
    function fetchGeometry(image) {
      geometry = HttpRequest(base + "imagesize.php?image=" + escape(image));
      // geometry_cache[image] = geometry;
      return geometry;
    }

    function renderPhotos() {
      var x = 0, links = "";
      if (document.myform) {
        mydiv = document.getElementById("upload_text");
	if (pids.length == 0) {
	  mydiv.innerHTML = '<B><A HREF="javascript: uploadPhoto()">Upload a photo</A></B>';
	} else {
	  mydiv.innerHTML = '<B><A HREF="javascript: uploadPhoto()">Upload another photo</A></B>';
	}
      }

      table_head = '<TABLE CELLPADDING="8" CELLSPACING="2" BORDER="0" ALIGN="center"><TR>\n';
      table_foot = '</TR></TABLE>\n';

      doc = table_head;
      if (pids.length != 0 && pids[x] != 0) {
        links = "";
        for (x=0; x<pids.length; x++) 
	  if (pids.length > 1 && pids[x] != current_pid)
	    if (document.myform) {
	      links += '<A HREF="javascript: touchup(' + pids[x] + ');">Photo #' + (x + 1) + '</A><BR>\n';
	    } else {
	      links += '<A HREF="javascript: current_pid=' + pids[x] + '; renderPhotos();">Photo #' + (x + 1) + '</A><BR>\n';
	    }

	if (pids.length > 0 && !document.myform) 
	  links += '<A HREF="javascript: uploadPhoto()">Upload Another Photo</A><BR>\n';

        for (x=0; x<pids.length; x++) {
	  if (pids[x] == current_pid && document.myform) 
	    initItems();

	  //if (pids[x] == current_pid || !document.myform) {
            ext = upload_extension(pids[x]);
	    geometry = fetchGeometry("images/uploads/" + pids[x] + "." + ext);
  	    geometry = geometry.split(":");
            width = geometry[0];
	    height = geometry[1];
	    if (width > 200) { height *= 200 / width; width = 200; }
	    if (height > 300) { width *= 300 / height; height = 300; }
            doc += '<TD ALIGN="center" VALIGN="top"';
	    if (pids[x] == current_pid && document.myform && pids.length > 1) doc += ' BGCOLOR="#990000"';
            doc += '>';

	    if (document.myform)
	      doc += '<B>';
	    if (document.myform && current_pid == pids[x] && pids.length > 1)
	      doc += '<FONT COLOR="#ffffff">';
	    if (document.myform)
	      doc += 'Photo #' + (x + 1);
	    if (document.myform && current_pid == pids[x] && pids.length > 1)
	      doc += '</FONT>';
	    if (document.myform)
	      doc += '</B> ';

	    // remove delete if not on order form
	    if (document.myform) {
	      doc += '<A HREF="javascript: delete_photo(' + pids[x] + ');" ';
	      doc += 'onClick="return confirm(\'Are you sure you want to delete this photo?\');">';
	      if (current_pid == pids[x] && pids.length > 1)
	        doc += '<FONT COLOR="#ffffff">';
	      doc += 'Delete this Photo';
	      if (current_pid == pids[x] && pids.length > 1)
	        doc += '</FONT>';
	      doc += '</A><BR>\n';
	    }

            if (document.myform) {
	      //doc += '<A HREF="javascript: ajax_confirm(\'Delete this photo?\', \'delete_photo(' + pids[x] + ');\');">Delete</A> | ';
	      //doc += '<A HREF="javascript: touchup(' + pids[x] + ');">Edit Enhancements</A><BR>\n';
	      doc += '<A HREF="javascript: touchup(' + pids[x] + ');">\n';
            }

	    // the image itself
	    doc += '<IMG SRC="/images/uploads/' + pids[x] + '.' + ext + '" BORDER="0" WIDTH="' + width + '" HEIGHT="' + height + '">';

	    if (document.myform) {
	      doc += '</A>\n';
	      if (pids[x] == current_pid) {
	        doc += '<CENTER><FONT COLOR="#000000">Check ReTouch Options below for this photo</FONT></CENTER>';
	      } else {
	        doc += '<CENTER><A HREF="javascript: touchup(' + pids[x] + ')">Click here to edit order for this photo</A></CENTER>';
	      }
	    }

            doc += '</TD>\n';
	  //}
	}
      } else {
        doc += '<TD><A HREF="javascript: uploadPhoto();"><IMG SRC="/images/upload_gray2.gif" NAME="cimage" BORDER="0"></A></TD>\n';
	// we could be init'ing items for a form with no uploaded picture
	if (document.myform)
	  initItems();
      }

      //if (document.myform)
      //  doc += '<TD VALIGN="center">' + links + '</TD>';

      doc += table_foot;
      document.getElementById("photos").innerHTML = doc;
    }

    // this ain't atomic (race conditions exist), but close enough...
    function start_example(which) {
      if (example_running) clearTimeout(current_timeout);

      example_running = true;
      current_example = which;
      current_counter = 0;

      source = '/images/samples/' + current_example + '_' + current_counter + '.gif';
      myDiv = document.getElementById("mytext");
      myDiv.innerHTML = '<A HREF="javascript: closeHelper();">Close</A><BR><IMG SRC="' + source + '">';

      myDiv.style.top = tempY + 'px';
      myDiv.style.left = tempX + 'px';
      myDiv.style.visibility = 'visible';
      myDiv.style.background = 'white';
      current_timeout = self.setTimeout('rotatePic()', 1000);
    }

    function ajax_confirm(text, yes) {
      headerHTML  = '<TABLE CELLSPACING="2" CELLPADDING="4" BORDER="0"> ';
      headerHTML += '<TR> ';
      headerHTML += '  <TD NOWRAP BGCOLOR="#DDDDDD" COLSPAN="2"> ';
      headerHTML += text;
      footerHTML  = '  </TD>';
      footerHTML += '</TR><TR>';      
      footerHTML += '<TD NOWRAP ALIGN="middle" BGCOLOR="#DDDDDD" ';
      footerHTML += '   onMouseOver="style.backgroundColor=\'#DDFFDD\'" ';
      footerHTML += '   onMouseOut="style.backgroundColor=\'#DDDDDD\'" ';
      footerHTML += '   onClick="closeConfirm(); ' + yes + '">';
      footerHTML += '  <A HREF="javascript: closeConfirm(); ' + yes + '"><FONT SIZE="-1">Okay</FONT></A>';
      footerHTML += '</TD>';
      footerHTML += '<TD NOWRAP ALIGN="middle" BGCOLOR="#DDDDDD" ';
      footerHTML += '  onMouseOver="style.backgroundColor=\'#FFDDDD\'" ';
      footerHTML += '  onMouseOut="style.backgroundColor=\'#DDDDDD\'" ';
      footerHTML += '  onClick="closeConfirm();"> ';
      footerHTML += '  <A HREF="javascript: closeConfirm();"><FONT SIZE="-1">Cancel</FONT></A>';
      footerHTML += '</TD>';
      footerHTML += '</TR></TABLE>';
      document.getElementById("divconfirm").innerHTML = headerHTML + footerHTML;
      document.getElementById("divconfirm").style.top = tempY + 'px';
      document.getElementById("divconfirm").style.left = tempX + 'px';
      document.getElementById("divconfirm").style.visibility = 'visible';
    }

    function closeConfirm() {
      document.getElementById("divconfirm").style.visibility = 'hidden';
    }

    function rotatePic() {
      current_counter += 50;

      if (current_counter > 100) {
	example_running = false;
	return;
      } else {
        source = '/images/samples/' + current_example + '_' + current_counter + '.gif';
        myDiv = document.getElementById("mytext");
        myDiv.innerHTML = '<A HREF="javascript: closeHelper();">Close</A><BR><IMG SRC="' + source + '">';
	current_timeout = self.setTimeout('rotatePic()', 1000);
      }
    }

    function closeHelper() {
      myDiv = document.getElementById("mytext");
      myDiv.style.visibility = 'hidden';
    }

    function cancelChange() {
      closeHelper();
    }

    function radioSelectedIndex(elem) {
      var x = 0;
      var selIndex = -1;

      for (x=0; x<elem.length; x++)
        if (elem[x].checked) 
	  selIndex = x;

      return selIndex;
    }

    var upwin;

    function uploadPhoto() {
      if (upwin) { upwin.close(); upwin = false; }

      URL = "./upload1.php";
      options  = "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,";
      options += "width=400,height=220,top=" + tempY + ",left=" + tempX;
      upwin = open(URL, "Upload", options);
      upwin.focus();
    }

    function imageLoaded() { sample_render(); }
    function loadImage(name) {
      myImg = new Image();
      myImg.onload = imageLoaded;
      myImg.onerror = imageLoaded;
      myImg.onabort = imageLoaded;
      myImg.src = name;

      return myImg;
    }	

    var total_samples = 0;
    var current_sample = 0;
    var current_image = null;
    var current_which = "";
    var current_width = 0;
    var current_height = 0;
    function sample(which) {
      url = base + "sample.php?which=" + escape(which) + "&salt=" + escape(Math.random());
      total_samples = HttpRequest(url);

      current_which = which;
      current_sample = 1;
      image_name = "images/popups/" + current_which + "_" + current_sample + ".gif";
      current_image = new Image();
      current_image.src = image_name;
      geometry_info = fetchGeometry(image_name);
      geometry_info = geometry_info.split(":");
      current_width = geometry_info[0];
      current_height = geometry_info[1];
      // alert("height: " + current_height + " width: " + current_width);
      sample_render();

      //document.getElementById("mytext").style.top = tempY;
      //document.getElementById("mytext").style.left = tempX;
    }

    function sample_render() {
      doc  = "";
      doc += '<MAP NAME="sample_map">\n';
      // close button
      coords = (current_width - 30) + ",0," + current_width + ",30";
      doc += '  <AREA SHAPE="rect" COORDS="' + coords + '" HREF="javascript: sample_close()"> \n';
      // next button
      coords = (current_width - 160) + "," + (current_height - 30) + "," + 
        current_width + "," + current_height;
      doc += '  <AREA SHAPE="rect" COORDS="' + coords + '" HREF="javascript: sample_forward()"> \n';
      doc += '</MAP>\n';
      doc += '<TABLE CELLPADDING="1" CELLSPACING="0" BORDER="0">\n';
      doc += '  <TR><TD BGCOLOR="#000000">\n';
      doc += '    <IMG SRC="' + image_name + '" USEMAP="#sample_map" NAME="current_image">\n';
      doc += '  </TR></TD>\n';
      doc += '</TABLE>\n';

      document.getElementById("mytext").innerHTML = doc;
      document.getElementById("mytext").style.visibility = 'visible';
      temp = document.getElementById("mytext").style.left;
      temp = Number(temp.substring(0, temp.lastIndexOf('px')));
      right_side = Number(current_image.width) + temp;
    }

    function sample_close() { 
      document.getElementById("mytext").style.visibility = 'hidden';
      document.getElementById("mytext").innerHTML = "";
    }

    function sample_forward() {      
      current_sample++;
      if (current_sample > total_samples) current_sample = 1;
      image_name = "images/popups/" + current_which + "_" + current_sample + ".gif";
      current_image = new Image();
      current_image.src = image_name;
      geometry_info = HttpRequest(base + "imagesize.php?image=" + escape(image_name));
      geometry_info = geometry_info.split(":");
      current_width = geometry_info[0];
      current_height = geometry_info[1];

      sample_render();
    }

    // not implemented | used
    function sample_back() { }

    function getRequestObject() {
      http_request = null;

      if (window.XMLHttpRequest) {
        http_request = new XMLHttpRequest();
	http_request.overrideMimeType('text/xml');
      } else {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      }

      return http_request;
    }

    function HttpRequest(url) {
      request = getRequestObject();
      request.open("GET", url, false);
      request.send("");
      
      return request.responseText;    
    }

    
    function char_counter(elem, divname, maxchar) {
      txt = elem.value;

      if (txt.length > maxchar) {
	elem.value = elem.value.substring(0, maxchar);
	txt = elem.value;
      }

      left = maxchar - txt.length;
      doc = "(" + maxchar + " characters max. " + left + " remaining)";
      document.getElementById(divname).innerHTML = doc;
    }

    // forwards the user to the page given, but first
    // grabs all session variables we want to save, finds them	
    // in the page (if they exist) and adds them to the URL (as a GET request)
    function goTo(page) {
      mypid = "";
      for (x=0; x<document.forms.length; x++) 
        for (y=0; y<document.forms[x].length; y++) 
	  if (document.forms[x][y].name == "pid") 
	    mypid = document.forms[x][y].value;

      window.location = page + "?pid=" + escape(mypid);
      return false;
    }

    function popup(page, width, height) {
      opts  = "width=" + width + ",height=" + height + ",";
      opts += "left=200,top=100,scrollbars=1,location=0,statusbars=0,resizable=1,menubar=0";
      win1 = window.open(page, "window", opts);
      win1.focus();
    }

