//#$Id: functions.js,v 1.1.1.1 2006/05/05 21:35:24 john 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';
  return 'Characters left: ' +(maxLength-dataString.length);
}
/* 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 + "');");
}

/* clever edit widget stuff */
//global:
styles = {ids: new Array(), styles: new Array()};
// ea: "edit area"
// ca: "content area"
// ta: "text area"
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);
  if (ca && ea) {
  	ea.className = 'visible';
	storeStyle(id, ca.className);
	ca.className = 'hidden';
  }
  /*
  // debugging:
  else {
	if (ea)
	  alert("Can't find ca_"+id);
	else if (ca)
	  alert("Can't find ea_"+id);
	else
	  alert("Can't find either ea_"+id+" or ca_"+id);
  }
  */
}
function uneditContentArea(id) {
// so far just swapping visibility, not trying to save
  var ca = fd('ca_'+id);
  var ea = fd('ea_'+id);
  if (ca && ea) {
  	ea.className = 'hidden';
	ca.className = retrieveStyle(id);
  }
  /*
  // debugging:
  else {
	if (ea)
	  alert("Can't find ca_"+id);
	else if (ca)
	  alert("Can't find ea_"+id);
	else
	  alert("Can't find either ea_"+id+" or ca_"+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 req = new DataRequestor;
  req.setObjToReplace(ca);

  req.addArg(_GET, 'id',      id);
  req.addArg(_GET, 'content', content);
  req.getURL('/admin/saveContentArea.php');

  uneditContentArea(id);
}
/* 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 */

function accountTypeChanged(e) {
  var widget = fd('accountType');
  var rightPaneDiv = fd('rightPane');
  if (getSelectedText(widget) == 'Vendor') {
  	rightPaneDiv.className = 'visible';
  } else {
  	rightPaneDiv.className = 'hidden';
  }
}

function categoryChanged(e) {
  var catWidget    = fd('selectCategory');
  var subcat_div = fd('selectSubcategory_div');
  var subcatWidget = fd('selectSubcategory');
  if (catWidget.selectedIndex > 0) {
	var req = new DataRequestor;
	req.setObjToReplace(subcat_div);

	req.addArg(_GET, 'catId', getSelectedValue(catWidget));
	req.addArg(_GET, 'id', getSelectedValue(subcatWidget));
	req.getURL('/accounts/adjustSubcategoryWidget.php');
  } else {
  	subcatWidget.disabled = 'true';
  }
}
