//#$Id: functions.js,v 1.17 2007/05/23 17:36:31 bfox Exp $
// JavaScript Document
var DH = 0;var an = 0;var al = 0;var ai = 0;if (document.getElementById) {ai = 1; DH = 1;}else {if (document.all) {al = 1; DH = 1;} else { browserVersion = parseInt(navigator.appVersion); if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {an = 1; DH = 1;}}} 
// var an = 0;var al = 0;var ai = 0;if (document.getElementById) {ai = 1;}else {if (document.all) {al = 1;} else { browserVersion = parseInt(navigator.appVersion); if ((navigator.appName.indexOf('Netscape') != -1) && (browserVersion == 4)) {an = 1;}}} 
function fd(oi, wS) {if (ai) return wS ? document.getElementById(oi).style:document.getElementById(oi); if (al) return wS ? document.all[oi].style: document.all[oi]; if (an) return document.layers[oi];}
function pw() {return window.innerWidth != null? window.innerWidth: document.body.clientWidth != null? document.body.clientWidth:null;}
function popUp(evt,oi) {
  if (DH) {
    var wp = pw(); ds = fd(oi,1); dm = fd(oi,0); st = ds.visibility; 
// alert('st: '+st);
    if (dm.offsetWidth) ew = dm.offsetWidth;
    else if (dm.clip.width) ew = dm.clip.width;
    if (st == "visible" || st == "show") { 
      ds.visibility = "hidden";
    } else  { 
      if (evt.clientY || evt.pageY) {
        if (evt.pageY) {
          tv = evt.pageY + 20;
          lv = evt.pageX - (ew/4);
        } else {
          tv = evt.clientY + 20 + document.body.scrollTop;
          lv = evt.clientX  - (ew/4) + document.body.scrollLeft;
        }
        if (lv < 2) lv = 2;
        else if (lv + ew > wp) lv -= ew/2;
        if (!an) {
          lv += 'px';tv += 'px'
        };
        ds.left = lv; ds.top = tv;
      }
      ds.visibility = "visible";
    }
  }
}
function insertTipDiv(id,tipText) {
  var tipDiv = document.createElement('div')
  tipDiv.setAttribute('id', 'tip_'+id);
  tipDiv.className = 'tip';
  tipDiv.innerHTML = tipText;
  document.body.insertBefore(tipDiv,document.body.firstChild);
}
function addTooltip(id, tipText) {
  // the id is that of the 'master' element
  // add the tooltip itself
  insertTipDiv(id, tipText);
  // add listeners to the master element
  var showTip = function(e) {popUp(e, 'tip_'+id);};
  var master = document.getElementById(id);
  // if (!master)
  //  alert("Can't find element " +id);
  master.addEventListener('mouseover', showTip, false);
  master.addEventListener('mouseout',  showTip, false);
}
function addManyTooltips(ttArray) {
  // ttArray is an object with keys:array and values:array
  // the keys are ids of document elements which get tooltips
  // and the values are the texts of the tips
  for (var i=0; i<ttArray.keys.length; i++) {
	// alert('adding tooltip: ' +ttArray.keys[i] +' ' +ttArray.values[i]);
	addTooltip(ttArray.keys[i], ttArray.values[i]);
  }
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function editPersonnel(id) {
  staffForm = document.getElementById('editStaff');
  hiddenField = document.getElementById('editItem');
  hiddenField.value = id;
  staffForm.submit();
}

/* Character count functionality */
//global
defaultMaxLength = 3000;

// note this is actually a substr match, not ==
document.getElementsByClassName = function (needle)
{
  var my_array = document.getElementsByTagName("*");
  var retvalue = new Array();
  var i;
  var j;

  for (i = 0, j = 0; i < my_array.length; i++)
  {
    // var c = " " + my_array[i].className + " ";
    // if (c.indexOf(" " + needle + " ") != -1)
    var c = my_array[i].className;
    if (c.indexOf(needle) != -1)

      retvalue[j++] = my_array[i];
  }
  return retvalue;
}

function addEvent(obj, evType, fn)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, true);
		return true;
	} 
	else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} 
	else 
	{
		return false;
	}
}

addEvent(window, 'load', function() {
  var dataWidgets = document.getElementsByClassName('characterCountData');
  var i;
  for (i=0; i<dataWidgets.length; i++) {
	dataWidget = dataWidgets[i];	
	dataWidget.countWidget = document.getElementById(dataWidget.id + '_characterCount');
	if (!dataWidget.countWidget) {
	  continue;
	}

	dWClassNameStr = new String(dataWidget.className);
	/(\d+)$/.test(dataWidget.className);
	dataWidget.maxLength = RegExp.$1;
	if (!dataWidget.maxLength) {
 	  dataWidget.maxLength = defaultMaxLength;
 	}

	dataWidget.onkeyup = function() {
	  var message = charCountMessage(this.value, this.maxLength);
	  this.countWidget.innerHTML = message;
	  if (this.value.length > this.maxLength)
		this.value = this.value.substr(0, this.maxLength);
	}
	dataWidget.onkeyup();
  }
});

function charCountMessage(dataString, maxLength) {
  // return dataString.length + ' of ' +maxLength+ ' character maximum';
  var count = maxLength-dataString.length +0;
  if (count < 0) count = 0;
  return 'Characters left: ' + count;
}
/* End Character count functionality */

/*
// ajaxically change the dropdowns in the Quick Search forms
function adjustQuickSearch(domain, changedWidgetId) {

  // alert('adjustQuickSearch('+domain+', '+changedWidgetId+')');

  // domain is 'shows' or 'users'
  searchFieldWidget    = fd('searchField');
  searchOperatorWidget = fd('searchOperator');
  searchValueWidget    = fd('searchValue');

  // searchValueWidget currently <input> or <select> ?
  if (searchValueWidget.length) { // array ie <select>
  	searchValueValue = getSelectedValue(searchValueWidget);
  } else { // scalar ie <input>
  	searchValueValue = searchValueWidget.value;
  }
  var req = new DataRequestor;
  if (changedWidgetId == 'searchField') {
  	nextWidget = fd('searchOperatorContainer');
  } else if (changedWidgetId == 'searchOperator') {
	nextWidget = fd('searchValueContainer');
  } else {
  	return false;
  }
  nextWidget.disabled = 1;
  req.setObjToReplace(nextWidget);

  req.addArg(_GET, 'domain',              domain);
  req.addArg(_GET, 'widgetId',            changedWidgetId);
  req.addArg(_GET, 'searchFieldValue',    getSelectedValue(searchFieldWidget));
  req.addArg(_GET, 'searchOperatorValue', getSelectedValue(searchOperatorWidget));
  req.addArg(_GET, 'searchValueValue',    searchValueValue);
  req.getURL('/admin/adjustQuickSearch.php');

  nextWidget.disabled = 0;
  nextWidget.focus(); // no ?
}
*/


function getSelectedValue(list){
  for(i=0; i<list.length; i++){
    if(list[i].selected){
      return list[i].value;
    }
  }
}
function getSelectedText(list){
  for(i=0; i<list.length; i++){
    if(list[i].selected){
      return list[i].text;
    }
  }
}

function newWin(URL, width, height) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=" + width + ",height=" + height + "');");
}
var largePicWindow;
function showLargePic(URL) {
  if (!largePicWindow || !(largePicWindow instanceof Window) || largePicWindow.closed) {
	largePicWindow = window.open('', 'largePicWindow', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=730,height=540');
  }
  largePicWindow.location = URL;
}
function newPictureWindow(URL, width, height) {
  day = new Date();
  id = day.getTime();
  if (!width) width = 730;
  if (!height) height = 540;
  eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=no,width=" + width + ",height=" + height + "');");
}

/* clever edit widget stuff */
//global:
styles = {ids: new Array(), styles: new Array()};
// ca: "content area" : the whole thing, outermost <div>
// ea: "edit area" : the half o the whole thing visible when editing (one inner <div>)
// ta: "text area"
// ua: "uneditable area" : the pretty rendered thing (other inner <div>)
function storeStyle(id, style) {
  if (style == null || style == '')
  	return;
  for (var i=0; i<styles.ids.length; i++) {
  	if (styles.ids[i] == id) {
	  styles.styles[i] = style;
	  return;
	}
  }
  styles.ids.push(id);
  styles.styles.push(style);
}
function retrieveStyle(id) {
  for (var i=0; i<styles.ids.length; i++) {
  	if (styles.ids[i] == id) {
	  return styles.styles[i];
	}
  }
  return '';
}
function editContentArea(id) {
  var ca = fd('ca_'+id);
  var ea = fd('ea_'+id);
  var ua = fd('ua_'+id);
  if (ua && ea) {
  	ea.className = 'visible';
	storeStyle(id, ca.className);
	ua.className = 'hidden';
  }
  /*
  // debugging:
  else {
	if (ea)
	  alert("Can't find ca_"+id);
	else if (ua)
	  alert("Can't find ea_"+id);
	else
	  alert("Can't find either ea_"+id+" or ua_"+id);
  }
  */
}
function uneditContentArea(id) {
  // just swap visibility
  var ua = fd('ua_'+id);
  var ea = fd('ea_'+id);
  if (ua && ea) {
  	ea.className = 'hidden';
	ua.className = retrieveStyle(id);
  }
  /*
  // debugging:
  else {
	if (ea)
	  alert("Can't find ua_"+id);
	else if (ua)
	  alert("Can't find ea_"+id);
	else
	  alert("Can't find either ea_"+id+" or ua_"+id);
  }
  */
}
function saveContentArea(id) {
  // ajaxically save the content area; then switch the hidden/visible

  var ca = fd('ca_'+id);
  var ta = fd('ta_'+id);
  var content = ta.value.replace(/'/g, "&rsquo;");
  var content = ta.value.replace(/"/g, "&#34;");

  var req = new DataRequestor;
  req.setObjToReplace(ca);

// alert(encodeURI(content));
  // var method = _GET;
  var method = _POST;
  req.addArg(method, 'id',      id);
  req.addArg(method, 'content', encodeURI(content));
  req.getURL('/admin/saveContentArea.php');

  uneditContentArea(id);
  // sizeEditableArea(id);
}
function sizeAllEditableAreas() {
  var editableAreas = document.getElementsByTagName('textarea');
  for(var i=0; i<editableAreas.length; i++) {
  	var id = editableAreas[i].id;
	if (/^ta_(\d+)$/.test(id)) {
	  sizeEditableArea(RegExp.$1);
	}
  }
}
function sizeEditableArea(id) {
  var ca = fd('ca_'+id);
  var ea = fd('ea_'+id);
  var ta = fd('ta_'+id);

  var divisor = 17;
  var rows = Math.floor(ca.offsetHeight/divisor);
  if (rows < 4) rows = 4;
// alert('setting rows to '+rows);
  ta.setAttribute('rows', rows);
  /* // this doesn't work:
  divisor = 2.5;
  ta.setAttribute('columns', Math.floor(ca.offsetWidth/divisor)); */
}
function helpEdit() {
  newWin("/helpEdit.html", 570, 400);
}
/* end clever edit widget stuff */

/* left nav */
// global:
currentSubcatId = null;
function leftnavSubcat(id) {
  id = 'vendors_'+id;
  var subcat = fd(id);
  if (!subcat)
  	return;
  if (currentSubcatId == id) {
  	// this one is open; close it
	subcat.className = 'hidden';
	currentSubcatId = null;
  } else if (currentSubcatId == null) {
  	// none is open; open this one
	subcat.className = 'leftnav_vendors';
	currentSubcatId = id;
  } else {
  	// another one is open; close it and open this one
	var opensubcat = fd(currentSubcatId);
	if (opensubcat) {
	  opensubcat.className = 'hidden';
	}
	subcat.className = 'leftnav_vendors';
	currentSubcatId = id;
	// not sure this is appropriate behavior; maybe we're supposed to 
	// leave opensubcat open; if so.. then i need an *array* of currentSubcatIds...
  }
}
/* end left nav */

/* begin stuff for /accounts/index.php */
function accountTypeChanged(e) {
  var widget = fd('accountType');
  var bn_tbody = fd('businessName_tbody');
  var sn_tbody = fd('sections_tbody');
  if (getSelectedText(widget) == 'Vendor') {
  	bn_tbody.className = 'visible';
  	sn_tbody.className   = 'visible';
  } else {
  	bn_tbody.className = 'hidden';
  	sn_tbody.className   = 'hidden';
  }
}
/* these categoryChanged functions are also used for /admin/moveVendors.php */
function allCategoriesChanged() {
  var selects = document.getElementsByTagName('select');
  for (var i=0; i<selects.length; i++) {
  	if (selects[i].id.match(/selectCategory/)) {
	  _categoryChanged(selects[i]);
	}
  }
}
function categoryChanged(e) {
  _categoryChanged(e.target);
}
function _categoryChanged(catWidget) {
  var subcat_div, subcatWidget, subcatId;
  if (catWidget.id == 'selectCategory') {
  	// the default widget ids
	subcat_div = fd('selectSubcategory_div');
	subcatWidgetName = 'selectSubcategory';
	subcatWidget = fd(subcatWidgetName);
	subcatId = fd('subcatId').value;
  } else if (/(\d+)$/.test(catWidget.id)) {
	idnum = RegExp.$1;
	// match up the widgets by the subcat id
	subcat_div = fd('selectSubcategory_' +idnum+ '_div');
	subcatWidgetName = 'selectSubcategory_' +idnum;
	subcatWidget = fd(subcatWidgetName);
	subcatId = fd('subcat_' +idnum+ '_id').value;
  } else {
  	return; // can't do anything useful
  }

  if (catWidget.selectedIndex > 0) {
	var req = new DataRequestor;
	req.setObjToReplace(subcat_div);
	req.addArg(_GET, 'catId', getSelectedValue(catWidget));
	req.addArg(_GET, 'subcatId', subcatId);
	req.addArg(_GET, 'widgetId', subcatWidgetName);
	req.addArg(_GET, 'widgetName', subcatWidgetName);
	req.getURL('/accounts/adjustSubcategoryWidget.php');
// alert(catWidget.id + ": " + getSelectedValue(catWidget) +' '+ subcatId +' '+ subcatWidgetName);
  	subcatWidget.removeAttribute('disabled');
  } else {
  	subcatWidget.disabled = 'disabled';
  }
}
/* end stuff for /accounts/index.php and /admin/moveVendors.php */


/* begin stuff for /admin/sections.php */
// here the strategy is to write a script! in the query-parameter "actions"
// which will be interpreted and executed in the php.
// global:
/*
newIds = {catIds: new Array(), subcatIds: new Array()};
function getSubcatNewId(catId) {
  for (var i=0; i<newIds.catIds.length; i++) {
	if (newIds.catIds[i] == catId) {
	  return newIds.subcatIds[i]++;
	}
  }
  // isn't there, so init it at 1 and return 0
  newIds.catIds[newIds.catIds.length] = catId;
  newIds.subcatIds[newIds.catIds.length] = 1;
  return 0;
} */
// global:
subcatNewId = 0;
function getSubcatNewId() {
  return subcatNewId++;
}
function addSectionsAction(action) {
  // appends a string to a string
  actionsElement = document.getElementById('actions');
  if (actionsElement) {
	actionsElement.value = actionsElement.value + ';' + action;
  }
}
function changeWarning(status) {
  _changeWarning(status, 'changeWarning');
  _changeWarning(status, 'changeWarning2');
}
function _changeWarning(status, tbodyId) {
  warning = document.getElementById(tbodyId);
  if (status && warning) {
  	warning.className = 'error';
  } else if (warning) {
  	warning.className = 'hidden';
  }
}
function descendantText(e) {
  // returns the first non-whitespace text found, searching depth-first
  // kindofa poor man's textContent
  if ((e.nodeType == 3) && (e.nodeValue.match(/\w/)))
  	return e.nodeValue;
  for (i=0; i<e.childNodes.length; i++) {
  	if (text = descendantText(e.childNodes[i]))
	  return text;
  }
}
function addSubcat(catId) {
  var tbody = document.getElementById('cat_'+catId);
  var subcatId = 'new' + getSubcatNewId();
  if (tbody) {
	// add a row to the form
  	row = document.createElement('tr');
	row.id = 'subcatRow_'+subcatId;

	// 1
	cell = document.createElement('td');
	cell.innerHTML = '&nbsp;'
	row.appendChild(cell);
	// 2 - 3
	cell = document.createElement('td');
	cell.setAttribute('colSpan', 2);
	input = document.createElement('input');
	input.setAttribute('type', 'text');
	input.setAttribute('name', subcatId+ '_name');
	input.className = 'textbox';
	cell.innerHTML = '';
	cell.appendChild(input);
	row.appendChild(cell);
	// 4
	cell = document.createElement('td');
	cell.id='up_' +subcatId;
	cell.setAttribute('align', 'right');
	cell.innerHTML = '<a href="javascript:upSubcat(\'' +subcatId+ '\');">Move up</a>&nbsp;&nbsp;</td>';
	row.appendChild(cell);
	// 5
	cell = document.createElement('td');
	cell.id='down_' +subcatId;
	cell.innerHTML = '<a href="javascript:downSubcat(\'' +subcatId+ '\');">Move down</a>';
	row.appendChild(cell);
	// 6
	cell = document.createElement('td');
	cell.innerHTML = '&nbsp;';
	row.appendChild(cell);
	// 7
	cell = document.createElement('td');
	cell.innerHTML = '<a href="javascript:deleteSubcat(\'' +subcatId+ '\');">Delete</a>';
	row.appendChild(cell);

	tbody.appendChild(row);
	input.focus();

	// add a new action to the actions script
	addSectionsAction('addSubcat(' +catId+ ',' +subcatId+ ')');
	
	// warning
	changeWarning(true);

	// may need to redo the "move up"s and "move down"s
	checkUpsAndDowns(tbody);
  }
}
function upSubcat(id) {
  // move it in the DOM
  thisRow = document.getElementById('subcatRow_' +id);
  tbody = thisRow.parentNode;
  rowAbove = thisRow.previousSibling;
  while (rowAbove && (rowAbove.tagName != 'TR')) {
  	// these are (empty) text nodes
  	rowAbove = rowAbove.previousSibling;
  }
  if (thisRow && tbody && rowAbove) {
  	removed = tbody.removeChild(thisRow);
	tbody.insertBefore(removed, rowAbove);
  }

  // add a new action to the actions script
  addSectionsAction('upSubcat(' +id+ ')');
	
  // warning
  changeWarning(true);

  // may need to redo the "move up"s and "move down"s
  checkUpsAndDowns(tbody);
}
function downSubcat(id) {
  // move it in the DOM
  thisRow = document.getElementById('subcatRow_' +id);
  tbody = thisRow.parentNode;
  // row below
  interveningRow = thisRow.nextSibling;
  while (interveningRow && (interveningRow.tagName != 'TR')) {
  	// these are (empty) text nodes
  	interveningRow = interveningRow.nextSibling;
  }
  // row *two* below
  rowBelow = interveningRow.nextSibling;
  while (rowBelow && (rowBelow.tagName != 'TR')) {
  	// these are (empty) text nodes
  	rowBelow = rowBelow.nextSibling;
  }
  // it's ok if rowBelow is null, cuz then it'll just appendChild anyway
  if (thisRow && tbody) {
  	removed = tbody.removeChild(thisRow);
	tbody.insertBefore(removed, rowBelow);
  }

  // add a new action to the actions script
  addSectionsAction('downSubcat(' +id+ ')');
	
  // warning
  changeWarning(true);

  // may need to redo the "move up"s and "move down"s
  checkUpsAndDowns(tbody);
}
function renameSubcat(id) {
  // swap in an <input> for the static name
  cell = document.getElementById('name_' +id);
  if (cell) {
	// moz, but not IE: name = cell.textContent;
	name = descendantText(cell);
	input = document.createElement('input');
	input.setAttribute('type', 'text');
	input.setAttribute('name', 'name_' +id);
	input.className = 'textbox';
	input.value=name;
	cell.innerHTML = '';
	cell.appendChild(input);
	input.focus();
  }

  // add a new action to the actions script
  addSectionsAction('renameSubcat(' +id+ ')');
	
  // warning
  changeWarning(true);
}
function deleteSubcat(id) {
  // remove it in the DOM
  thisRow = document.getElementById('subcatRow_' +id);
  tbody = thisRow.parentNode;
  if (thisRow && tbody) {
  	tbody.removeChild(thisRow);
  }

  // add a new action to the actions script
  addSectionsAction('deleteSubcat(' +id+ ')');
	
  // warning
  changeWarning(true);

  // may need to redo the "move up"s and "move down"s
  checkUpsAndDowns(tbody);
}
function checkUpsAndDowns(tbody) {
  // all but the first row should have move up; all but the last should have move down
  rows = tbody.rows;
  for (var i=1; i<rows.length; i++) {
  	id = rows[i].id.replace(/subcatRow_/, '');
	upCell   = document.getElementById('up_' +id)
	downCell = document.getElementById('down_' +id)
  	if ((i>1) && upCell) {
	  upCell.innerHTML = '<a href="javascript:upSubcat(\'' +id+ '\');">Move up</a>&nbsp;&nbsp;';
	} else if (upCell) {
	  upCell.innerHTML = '&nbsp;';
	}
	if ((i<rows.length-1) && downCell) {
	  downCell.innerHTML = '<a href="javascript:downSubcat(\'' +id+ '\');">Move down</a>&nbsp;&nbsp;';
	} else if (downCell) {
	  downCell.innerHTML = '&nbsp;';
	}
  }
}
/* end stuff for /admin/sections.php */

function moveStar(e) {
  var clickX, clickY;
  if (typeof(e.offsetX) == 'number') {
	// seems to be what IE wants
	clickX = e.offsetX;
	clickY = e.offsetY;
  } else if (typeof(e.layerX) == 'number') {
	// seems to be what moz wants
	clickX = e.layerX;
	clickY = e.layerY;
  }

  fudge = 13;
  mapxInput = fd('mapx');
  mapyInput = fd('mapy');
  mapxInput.value = clickX - fudge;
  mapyInput.value = clickY - fudge;

  starDivStyle = fd('starDiv', 1);
  starDivStyle.left = clickX - fudge;
  starDivStyle.top = clickY - fudge;

  theStarDiv = fd('starDiv');
  theStarDiv.className = 'visible';
}
function moveStar2(e) {
  // here, coords are relative to the star... 
}
var newNPIIndex = 0;
function addNewsPressItem() {
  var table = fd('newsPressItemsTable');
  if (!table) return false;
  /*
<tbody id="npi_{$item->id}_editableTbody" class="hidden">
<tr>
  <td colspan="3">Link text:<br>
  	<textarea rows="4">{$item->text}</textarea>
  </td>
</tr>
<tr>
  <td><input type="radio" name="npi_{$item->id}_type" value="file"{if $item->type eq 'file'} checked="checked"{/if}> File upload</td>
  <td colspan="2"><input type="file" name="npi_{$item->id}_fileUpload" /></td>
</tr>
<tr>
  <td><input type="radio" name="npi_{$item->id}_type" value="link"{if $item->type eq 'link'} checked="checked"{/if}> Web link</td>
  <td colspan="2"><input type="text" name="npi_{$item->id}_uri" /></td>
</tr>
<tr>
  <td colspan="3"><input type="radio" name="npi_{$item->id}_type" value="page"{if $item->type eq 'page'} checked="checked"{/if}> Page</td>
</tr>
<tr>
  <td colspan="3" align="right">
  	<input type="hidden" name="npi_{$item->id}_edited" value="0">
	<a href="#" onclick="uneditNewsPressItem({$item->id});return false">Cancel</a>
  </td>
</tr>
</tbody>
  */
  var tbody = document.createElement('tbody');
  var pseudoId = 'newNPI_'+newNPIIndex;
  var prefix = pseudoId+'_';
  tbody.id = prefix+'editableTbody';

  // first row: 'text' textarea
  var row = document.createElement('tr');
  var ta = document.createElement('textarea');
  ta.name = prefix+'text';
  var cell = document.createElement('td');
  cell.setAttribute('colSpan', 3);
  cell.className = 'content';
  cell.innerHTML = 'Link text:<br>';
  cell.appendChild(ta);
  row.appendChild(cell);
  tbody.appendChild(row);

  // second row: file upload
  row = document.createElement('tr');
  cell = document.createElement('td');
  cell.className = 'content';
  cell.innerHTML = '<img src="/images/spacer.gif" alt="" width="130" height="1" border="0"><input type="radio" name="'+prefix+'type" value="file" checked="checked"> File upload';
  row.appendChild(cell);
  cell = document.createElement('td');
  cell.className = 'content';
  cell.innerHTML = '<input type="file" name="'+prefix+'fileUpload" />';
  cell.setAttribute('colSpan', 2);
  row.appendChild(cell);
  tbody.appendChild(row);

  // second row: url-as-text-entry
  row = document.createElement('tr');
  cell = document.createElement('td');
  cell.className = 'content';
  cell.innerHTML = '<img src="/images/spacer.gif" alt="" width="130" height="1" border="0"><input type="radio" name="'+prefix+'type" value="link"> Web link';
  row.appendChild(cell);
  cell = document.createElement('td');
  cell.className = 'content';
  cell.innerHTML = '<input type="text" name="'+prefix+'uri" value="http://" />';
  cell.setAttribute('colSpan', 2);
  row.appendChild(cell);
  tbody.appendChild(row);
  
  // third row: new page
  row = document.createElement('tr');
  cell = document.createElement('td');
  cell.className = 'content';
  cell.setAttribute('colSpan', 3);
  cell.innerHTML = '<img src="/images/spacer.gif" alt="" width="130" height="1" border="0"><input type="radio" name="'+prefix+'type" value="page"> New page';
  row.appendChild(cell);
  tbody.appendChild(row);
  
  // fourth row: cancel button
  row = document.createElement('tr');
  cell = document.createElement('td');
  cell.className = 'content';
  cell.setAttribute('colSpan', 3);
  cell.setAttribute('align', 'right');
  /* var input = document.createElement('input');
  input.setAttribute('type','hidden');
  input.setAttribute('name',prefix+'edited');
  input.value = 1;
  input.id = prefix+'edited';
  cell.appendChild(input); */
  cell.innerHTML = '<input type="hidden" name="'+prefix+'edited" value="1" id="'+prefix+'edited">';

  cell.innerHTML += '<a href="#" onclick="uneditNewsPressItem(\''+prefix+'\');return false">Cancel</a>';
  row.appendChild(cell);
  tbody.appendChild(row);
  
  table.appendChild(tbody);
  
  newNPIIndex++;
}
function editNewsPressItem(key) {
  // arg is prefix, ie either newNPI_0_ or npi_33_
  var tbody = fd(key+'renderedTbody');
  if (tbody) tbody.className = 'hidden';
  tbody = fd(key+'editableTbody');
  if (tbody) tbody.className = 'visible';
  var widget = fd(key+'edited');
  if (widget) widget.value = 1;
}
function uneditNewsPressItem(key) {
  // arg is prefix, ie either newNPI_0_ or npi_33_
  var tbody = fd(key+'renderedTbody');
  if (tbody) tbody.className = 'visible';
  tbody = fd(key+'editableTbody');
  if (tbody) tbody.className = 'hidden';
  var widget = fd(key+'edited');
  if (widget) widget.value = 0;
}
function getAjaxResult() {
  var div = fd('postTheResultHere');
  var req = new DataRequestor;
  req.setObjToReplace(div);
  var method = _POST;
  req.addArg(method, 'argument', fd('widgetA').value);
  req.addArg(method, 'method', 'POST');
  req.getURL('/admin/bogusAjaxPage.php');

  var div = fd('getTheResultHere');
  var req = new DataRequestor;
  req.setObjToReplace(div);
  var method = _GET;
  req.addArg(method, 'argument', fd('widgetA').value);
  req.addArg(method, 'method', 'GET');
  req.getURL('/admin/bogusAjaxPage.php');
}
var editingPromo = 0;
function editPromo(key) {
  // arg is prefix, ie promo_0_
  var div = fd(key+'renderedDiv');
  if (div) div.className = 'hidden';
  div = fd(key+'editableDiv');
  if (div) div.className = 'visible';
  div = fd('savePromos_tbody');
  if (div) div.className = 'visible';
  var widget = fd(key+'edited');
  if (widget) widget.value = 1;
  editingPromo++;
}
function uneditPromo(key) {
  // arg is prefix, ie promo_0_
  var div = fd(key+'renderedDiv');
  if (div) div.className = 'visible';
  div = fd(key+'editableDiv');
  if (div) div.className = 'hidden';
  div = fd('savePromos_tbody');
  if (div && !--editingPromo) div.className = 'hidden';
  var widget = fd(key+'edited');
  if (widget) widget.value = 0;
}
