////
//// Utility Functions
////

function readJSON(str) {
  var obj;
  eval('obj = ' + str);
  return obj;
}

////
//// Page-specific Functions
////

// used in header.php
function clearIfOrig(t, str) {
  if (t.value == str) t.value = '';
}

// used in header.php
function setIfEmpty(t, str) {
  if (t.value.length == 0) t.value = str;
}

// used in home.php
function clearNews() {
  new Ajax.Request('clear-news.php', {
    method:    'get',
    onSuccess: function (req) {
      var nau = $('news_adds_updates');
      new Effect.Fade(nau, {
	duration:    1.0,
	afterFinish: function () {
	  nau.parentNode.removeChild(nau);
	}
      });
    }
  });

  return false;
}

// used in list.php
// called when delete completes successfully
// assumes var ordered_ids = [ ... ]; in the code
function deleteItemDone(req) {
  // get the id and status from the result
  var res = readJSON(req.responseText);
  var id  = res.id;

  // if deleteItem() (in PHP) returned false, we need to confirm
  if (!res.deleted) document.location = 'delete-confirm.php?id=' + id;

  // ooh!  perdy!
  Effect.SlideUp('row_' + id);

  // and now renumber
  var found = null;
  for (var i = 0; i < ordered_ids.length; i++) {
    var oid = ordered_ids[i];
    if (id == oid) {
      found = i;
    } else if (found != null) {
      var num = $('ord_' + oid);
      num.innerHTML = '' + i + '.';
    }
  }
  ordered_ids.splice(found, 1);

  // and update the item count
  $('item_count').innerHTML = ordered_ids.length;
}

// used in list.php
// call this if you have javascript and click on Delete
function deleteItem(id) {
  new Ajax.Request('ajax/delete/' + id, { 
    method:    'get', 
    onSuccess: deleteItemDone
  });

  return false;
}

// used in list.php
// call this when someone clicks on a priority change box
function changePriority(id, from, to) {
  if (from != to)
    new Ajax.Updater('priority_' + id, 'ajax/priority/' + id + '/' + to, 
      { method: 'get' });

  return false;
}

// used in list.php
// call this to toggle the substitution-ability
function changeSubstitute(id, currentVal) {
  var newVal = currentVal ? 0 : 1;
  new Ajax.Request('ajax/save/' + id + '/subs_ok', { 
    method:     'get',
    parameters: 'value='+newVal,
    onSuccess:  function (req) {
      var div = $('substitute_' + id);
      var divClass = 'help ';
      divClass += newVal ? 'ltGreenBg' : 'small';
      div.className = divClass;
      div.onclick = function onclick(event) {
	changeSubstitute(id, newVal);
      };

      $('subs_ok_' + id).innerHTML = newVal ? 'OK' : 'Not OK';
    }
  });

  return false;
}

// used in list.php
// assumes var ajaxList = []; in page
function listPageInit() {
  var fields = ['descr', 'maker', 'vendor', 'model', 'price', 'num',
		'comment'];

  for (var i = 0; i < ordered_ids.length; i++) {
    var id = ordered_ids[i];
    for (var j = 0; j < fields.length; j++) {
      var field = fields[j];
      var obj   = $(field + '_' + id);
      if (!ajaxList[field]) ajaxList[field] = Array();
      if (obj) 
	ajaxList[field][id] =
	new Ajax.InPlaceEditor(obj, 'ajax/save/' + id + '/' + field, {
	  okText:     'Save',
	  cancelText: 'Cancel',
	  size:	(field == 'price') ? 5 : 20
	});
	// Set up these event handlers for use by the 'Add Comments' button
	var elmt = ajaxList[field][id];
	if (elmt && field == 'comment') {
	  elmt.onEnterEditMode = function () {
	    var arr = this.element.id.split('_');
	    var field = arr[0];
	    var id = arr[1];
	    $(field+"_button_"+id).style.display = 'none';
	    $(field+"_header_"+id).style.display = 'block';
	    $(field+"_"+id).style.display = 'block';
	  }
	  elmt.onLeaveEditMode = function () {
	    var arr = this.element.id.split('_');
	    var field = arr[0];
	    var id = arr[1];
	    if (this.element.innerHTML == '') {
	      $(field+"_button_"+id).style.display = 'block';
	      $(field+"_header_"+id).style.display = 'none';
	      $(field+"_"+id).style.display = 'none';
	    }
	  }
	}
    }
  }
}

// used in list.php
// Manually cause the edit field to appear when a button is pressed
function showEdit(field, id) {
  ajaxList[field][id].enterEditMode();
  return false;
}

// used in view.php
// mark an item purchased
function markPurchase(id, lid, quantity) {
  var inc;

  if (quantity) {
    if (quantity > 1) {
      inc = parseInt(prompt(
	'How many would you like to get?  (up to ' + quantity + ')'));
      if (inc == null) return false;
      if (inc > quantity) inc = quantity;
    } else {
      inc = 1;
    }
  } else {
    inc  = -1;
  }

  new Ajax.Updater('purchasing_' + id, 'purchase.php', {
    method:     'get',
    parameters: 'id=' + id + '&lid=' + lid + '&inc=' + inc + '&ajax=1',
    onSuccess:  function (req) {
      var rec = $('received_' + id).firstChild;
      rec.nodeValue = parseInt(rec.nodeValue) + inc;
    },
    onFailure:  function (req) {
      alert('Oops!  This item is no longer available.  Please choose another.');
    }
  });
  return false;
}

// used in shopping.php
// toggles checked items
function toggleShopping(pid) {
  if (!moveShoppingItem(pid, unchecked, checked,   'u', 'c', true))
       moveShoppingItem(pid, checked,   unchecked, 'c', 'u', false);
}

function moveShoppingItem(pid, fromList, toList, fromPre, toPre, chkState) {
  for (var i = 0; i < fromList.length; i++) {
    if (pid == fromList[i]) {
      new Ajax.Request('update-shopping-item.php', {
	parameters: 'ajax=1&pid=' + pid + '&action=' + toPre,
	onSuccess:  function (req) {
	  fromList.splice(i, 1);

	  toList.push(pid);
	  if (toList.length == 1) $('empty_' + toPre).style.display = 'none';

	  Element.hide('p' + fromPre + pid);
	  $('p' + toPre + 'c' + pid).checked = chkState;
	  Element.show('p' + toPre + pid);

	  if (!fromList.length) 
	    Element.show('empty_' + fromPre);
	}
      });

      return true;
    }
  }
  return false;
}

function ignoreShopping(pid) {
  if (!confirm('Are you sure you want to permanently remove this item from your shopping list?\n(It will still be marked as purchased by you!)')) return false;

  new Ajax.Request('update-shopping-item.php', {
    parameters: 'ajax=1&pid=' + pid + '&action=i',
    onSuccess: function (req) {
      Effect.Fade('pc' + pid);
    }
  });

  return false;
}

// used in about.php

function toggleFAQ(node) {
  do { node = node.nextSibling; } while (node && node.tagName != 'DIV');

  var st = node.style;
  if (!st.display || st.display == 'none') {
    st.display = 'block';
  } else {
    st.display = 'none';
  }

  return false;
}

