// GENERIC FUNCTIONS

function findPos(object) {
 var x = y = 0;
 if (object.offsetParent) {
  x = object.offsetLeft;
  y = object.offsetTop;
  while (object = object.offsetParent) {
   x += object.offsetLeft;
   y += object.offsetTop;
  }
 }
 return [x,y];
}

function findScroll() {
 var x,y;
 if (self.pageYOffset) { // all except Explorer
  x = self.pageXOffset;
  y = self.pageYOffset;
 } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
  x = document.documentElement.scrollLeft;
  y = document.documentElement.scrollTop;
 } else if (document.body) { // all other Explorers
  x = document.body.scrollLeft;
  y = document.body.scrollTop;
 }
 return [x,y]
}

function findClientSize() {
 var x,y;
 if (self.innerHeight) { // all except Explorer
  x = self.innerWidth;
  y = self.innerHeight;
 } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
  x = document.documentElement.clientWidth;
  y = document.documentElement.clientHeight;
 } else if (document.body) { // other Explorers
  x = document.body.clientWidth;
  y = document.body.clientHeight;
 }
 return [x,y]
}

function adjustFieldLength(object,min,max) {
 if (object.value.length <= min)
  object.style.width=(min+1)*0.70+'em';
 else if (object.value.length>=max)
  object.style.width=(max+1)*0.70+'em';
 else
  object.style.width=(object.value.length+1)*0.70+'em';
}

function previewLink(listName,previewSpace) {
 document.getElementById(previewSpace).innerHTML=strReplace(listName," ","");
}

function strReplace(str,from,to) {
 var idx = str.indexOf( from );
 while ( idx > -1 ) {
  str = str.replace( from, to );
  idx = str.indexOf( from );
 }
 return str;
}

function checkEmail(email) {
 if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email.toLowerCase())) {
  return true;
 } else {
  return false;
 }
}

function checkZip(zip) {
 if (/(^\d{5}$)/.test(zip)) {
  return true;
 } else {
  return false;
 }
}

function checkPC(pc) {
 if (/^\D{1}\d{1}\D{1} ?\d{1}\D{1}\d{1}$/.test(pc)) {
  return true;
 } else {
  return false;
 }
}

function sortArrayByValue(object) {
 var num = 0;
 var tmp = new Array();
 for (i in object) {
  tmp[num++] = object[i] + "|" + i;
  delete object[i];
 }
 tmp = tmp.sort();
 for (i = 0; i < tmp.length; i++) {
  x = tmp[i].split("|")
  object[x[1]]=x[0];
 }
}

function sortArrayByKey(object) {
 var num = 0;
 var tmp = new Array();
 for (i in object) {
  tmp[num++] = i + "|" + object[i];
  delete object[i];
 }
 tmp = tmp.sort();
 for (i = 0; i < tmp.length; i++) {
  x = tmp[i].split("|")
  object[x[0]]=x[1];
 }
}

function sortItems() {
 //first sort by category, by name
 var num = 0;
 var tmp = new Array();
 for (i in itemName) {
  tmp[num++] = itemCat[i] + "|" + itemName[i] + "|" + itemAvail[i] + "|" + i;
  delete itemName[i];
  delete itemCat[i];
  delete itemAvail[i];
 }
 tmp = tmp.sort();
 for (i = 0; i < tmp.length; i++) {
  x = tmp[i].split("|")
  itemName[x[3]]=x[1];
  itemCat[x[3]]=x[0];
  itemAvail[x[3]]=x[2];
 }
 cat="";
}

function handleKeyPress(e,action,var1,var2,var3,var4,var5) {
 var key=e.keyCode || e.which;
 if (key==13){
  eval(action+"('"+var1+"','"+var2+"','"+var3+"','"+var4+"','"+var5+"')");
  return false;
 }
}

function urlEncode(sStr) {
 sStr = escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
 return sStr;
}

var months = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var days = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

function smartDate(datetime) {
 var meridian = "am";
 if (datetime) {
  var dtArray = datetime.split(" ");
  var date = dtArray[0].split("-");
  var time = dtArray[1].split(":");
  var year = date[0];
  var month = date[1]-1;
  var day = date[2]*1;
  var hour = time[0];
  var min = time[1];
  var sec = time[2];
  if (hour==0) hour = 12;
  if (hour>12) { hour-=12;meridian="pm"; }

  var editedDate = new Date();
  editedDate.setFullYear(year,month,day);
  var currentDate = new Date();

  if (day==currentDate.getDate() && month==currentDate.getMonth() && year==currentDate.getFullYear()) { //today
   return hour+':'+min+meridian+', today';
  }

  currentDate.setDate(currentDate.getDate()-1);
  if (day==currentDate.getDate()) //yesterday
   return 'yesterday, '+hour+':'+min+meridian;

  currentDate.setDate(currentDate.getDate()-6);
  if (editedDate.getDate()>currentDate.getDate()) //within last 7 days
   return 'last '+days[editedDate.getDay()]+' '+hour+':'+min+meridian;

  currentDate.setDate(currentDate.getDate()+7);
  if (year!=currentDate.getFullYear()) //different year than current year
   return months[month]+'. '+day+', '+year;
  else
   return months[month]+'. '+day;

 } else {
  var currentDate = new Date();
  var hour = currentDate.getHours();
  var min = currentDate.getMinutes();
  if (min<10) min="0"+min;
  if (hour==0) hour = 12;
  if (hour>12) { hour-=12;meridian="pm"; }
  return hour+':'+min+meridian+', today';
 }
}

function smartDistance(country,prov,city,distance) {
 var smartDistance="";
 if (distance||country) {
  if (distance)
   smartDistance = distanceRound(distance)+"km from you";
  if (country) {
   smartDistance += " in ";
   if (city) smartDistance += city+", ";
   if (prov) smartDistance += prov+", ";
   smartDistance += country;
  }
  smartDistance += ".";
 }
 return smartDistance;
}

function distanceRound(distance) {
 if (distance>10000) distance=Math.round(distance/1000)*1000;
 else if (distance>1000) distance=Math.round(distance/100)*100;
 else if (distance>100) distance=Math.round(distance/10)*10;
 else if (distance<10) distance=Math.round(distance*10)/10;
 return distance;
}

function allValidChars(string) {
 var Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_";
 for (var i = 0; i < string.length; i++) {
  if (Chars.indexOf(string.charAt(i)) == -1)
   return false;
 }
 return true;
}

var reserved = new Array('import','img','pics','party','help','support','tour','alerts','share','about','blog','wiki','search','settings','login','logout','stats','privacy','terms','security','contact','press','media','lendlist','copyright','groups','friends','books','dvds','clothing','accessories','home','office','electronics','misc','miscellaneous','music','equipment','tools','sports','outdoors','toys','games');

function legalWords(string) {
 for (i=0;i<reserved.length;i++) {
  if (string.toLowerCase==reserved[i]) return false;
 }
 return true;
}

// REG & LOG

function processReg(object) {

 //check that all fields are filled in properly.
 if (object.list.value.length<3) { alert('Please enter a list name of at least 3 characters');object.list.focus();return false; } 
 else if (!legalWords(object.list.value)) { alert('That list name is reserved.');object.list.focus();return false; }
 else if (!allValidChars(object.list.value.replace(/ /g,''))) { alert('Please use only letters, numbers, spaces, hyphens(-), or underscores(_).');object.list.focus();return false; }
 else if (checkEmail(object.email.value)==false) { alert('Please enter a valid email address.');object.email.focus();return false; } 
 else if (object.password.value.length<6) { alert('Please enter a password of at least 6 characters');object.password.focus();return false; } 
 else if (object.password2.value != object.password.value) { alert('The passwords you entered do not match.');object.password2.select();return false; } 
 else if (object.country.options[object.country.selectedIndex].value=="CA" && checkPC(object.pc.value)==false) { alert('Please enter a valid Canadian postal code.');object.pc.focus();return false; }
 else if (object.country.options[object.country.selectedIndex].value=="US" && checkZip(object.pc.value)==false) { alert('Please enter a valid US zip code');object.pc.focus();return false; }
 else if (object.accept.checked==false) { alert('Please accept the terms of use to continue.');object.accept.focus();return false; }

 //submit reg
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/add-member.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     document.getElementById('regStatus').innerHTML = "";
     alert("List Created! We'll now take you to your list so you can add items, friends and join groups.");
     object.login.value=object.list.value;
     processLogin(document.regForm);
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('regStatus').innerHTML = "";
     alert("The list name you've chosen is already in use. Please choose a different one.");object.list.focus();
     object.submitButton.disabled=false;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==3) {
     document.getElementById('regStatus').innerHTML = "";
     alert("The email address you've used is already associated with a list. Please log in to your list instead, use a different email address, or delete your existing list.");object.email.focus();
     object.submitButton.disabled=false;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==4) {
     document.getElementById('regStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
     object.submitButton.disabled=false;
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('list='+urlEncode(object.list.value)+'&email='+urlEncode(object.email.value)+'&password='+urlEncode(object.password.value)+'&country='+object.country.options[object.country.selectedIndex].value+'&pc='+urlEncode(object.pc.value));
 document.getElementById('regStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
 object.submitButton.disabled=true;
}


function processLogin(object) {
 //check that all fields are filled in properly.
 if (object.login.value=="") { alert('Please enter your list name or email address.');object.login.focus();return false; } 
 else if (object.password.value=="") { alert('Please enter your password.');object.password.focus();return false; } 

 //submit login
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/login.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     document.getElementById('loginStatus').innerHTML = "";
     if (object.p.value!="")
      location.href=object.p.value;
     else
      location.href="/"+urlEncode(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('loginStatus').innerHTML = "";
     alert("The list name or email address you entered was not found.");object.login.focus();
     object.submitButton.disabled=false;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==3) {
     document.getElementById('loginStatus').innerHTML = "";
     alert("The password you entered does not match that email address or list name.");object.password.focus();
     object.submitButton.disabled=false;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==4) {
     document.getElementById('loginStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
     object.submitButton.disabled=false;
    }
   }
  }
 }
 var auto=''; if (object.auto) if (object.auto.checked==true) auto=1;
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('login='+urlEncode(object.login.value)+'&password='+urlEncode(object.password.value)+'&auto='+auto);
 document.getElementById('loginStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
 object.submitButton.disabled=true;
}

function pwdReminder() {
 var object=document.loginForm;
 if (checkEmail(object.login.value)) {
  var xmlhttp =  new XMLHttpRequest();
  xmlhttp.open('POST', '/forgot.php', true);
  xmlhttp.onreadystatechange = function() {
   if (xmlhttp.readyState == 4) {
    if (xmlhttp.status == 200) {
     alert(xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data);
     document.getElementById('loginStatus').innerHTML = "";
    }
   }
  }
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xmlhttp.send('login='+urlEncode(object.login.value));
  document.getElementById('loginStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
 } else {
  alert("Enter your email address in the 'LendList Name or Email Address' field. Then click this link again and we'll email you your password.");
  document.loginForm.login.focus();
 }
}


// DISPLAYS

function displayGroupList() {
 var darkRow = 1;
 var code = "";
 for (var group in groupList) {
  if (darkRow) {
   code += '<div class="sideDiv darkRow">';
   darkRow=0;
  } else {
   code += '<div class="sideDiv">';
   darkRow=1;
  }
  code += '<div style="float:right;margin-right:2px;">(<span title="# of members">'+ groupList[group] +'</span>) <a href="#" class="remove" title="Remove your list from this group" onclick="if (confirm(\'Are you sure you want to remove your list from this group?';
  if (groupList[group]==1) code += '\\n\\nSince you are the only member of this group, the group itself will also be removed.';
  code += '\')) removeGroup(\''+group+'\');">X</a></div><div class="singleLine"><a href="/'+urlEncode(group)+'" title="View the '+group+' group">'+group+'</a></div></div>';
 }
 
 if (code=="")
  document.getElementById('groups').innerHTML="You don't have any friends added yet. Add some below.";
 else 
  document.getElementById('groups').innerHTML=code;
 code="";
}

function displayFriendList() {
 var darkRow = 1;
 var code = "";
 for (var friend in friendList) {
  if (darkRow) {
   code += '<div class="sideDiv darkRow">';
   darkRow=0;
  } else {
   code += '<div class="sideDiv">';
   darkRow=1;
  }
  code += '<div style="float:right;margin-right:2px;">(<span title="# of items">'+ friendList[friend] +'</span>) <a href="#" class="remove" title="Remove this friend" onclick="if (confirm(\'Are you sure you want to remove this friend?\'))  removeFriend(\''+friend+'\'); return false;">X</a></div><div class="singleLine"><a href="/'+urlEncode(friend)+'" title="View '+friend+'\'s List">'+friend+'</a></div></div>';
 }
 if (code=="")
  document.getElementById('friends').innerHTML="You don't have any friends added yet. Add some below.";
 else 
  document.getElementById('friends').innerHTML=code;
 code="";
}

var cat = "";
var lastCat="";


function displayItemList() {
 var firstItem=1;
 var darkRow = 1;
 var code = '<table width="100%"><tr id="add_form" valign="top"><td><select name="cat" style="width:170px;">';
 for (i in cats) {
  code +='<option value="'+i+'"';
  if (i==lastCat) code+=' selected';
  code+='>'+cats[i]+'</option>';
 }
 code += '</select><br /><br /></td><td width="20"><img src="img/blank.gif" width="20" height="1"></td><td width="60%"><input type="text" name="item" maxlength="80" value="Item Name" style="width:100%;" onfocus="if (this.value ==\'Item Name\') this.value=\'\';" onblur="if (this.value ==\'\') this.value=\'Item Name\';" /></td><td width="20"><img src="img/blank.gif" width="20" height="1"></td><td width="30%"><input type="submit" name="itemButton" value="Add Item"></td><td width="20"><img src="img/blank.gif" width="20" height="1"></td></tr>';

 var numItems=0;
 var itemCode="";
 for (var itemID in itemName) {
  numItems++;
  if (darkRow) {
   itemCode += '<tr bgcolor="#EEEEEE">';
   darkRow=0;
  } else {
   itemCode += '<tr>';
   darkRow=1;
  }
  itemCode += '<td><div id="itemCat_'+itemID+'"';
  if (itemCat[itemID]==cat) {
   if (darkRow) itemCode+=' style="color:#FFFFFF"'; else itemCode+=' style="color:#EEEEEE"'; 
  }
  cat = itemCat[itemID];
  itemCode += ' class="catList" onmouseover="editableOver(\'itemCat_'+itemID+'\')">'+itemCat[itemID].replace(/ /g,'&nbsp;')+'</div></td><td></td>';
  itemCode += '<td><div style="height:2em;overflow:hidden"><div id="itemName_'+itemID+'" style="margin:0px 0px 0px 2px" onmouseover="editableOver(\'itemName_'+itemID+'\')" class="singleLine" title="'+itemName[itemID].replace(/"/g,'&quot;')+'">'+itemName[itemID]+'</div></div></td><td></td><td class="status"><div style="height:2em;overflow:hidden"><div id="itemAvail_'+itemID+'" style="margin:0px 0px 0px 2px;" onmouseover="editableOver(\'itemAvail_'+itemID+'\')" class="singleLine" title="'+itemAvail[itemID]+'">'+itemAvail[itemID]+'</div></div></td><td class="delete_spacer"></td><td class="delete_column" style="padding-right:4px;"><a href="#" class="remove" title="Remove this item" onclick="if (confirm(\'Are you sure you want to remove this item?\')) removeItem(\''+itemID+'\'); return false;">X</a></td></tr>';
 }

 if (numItems<1) {
  code+='<tr><td colspan="7">You aren\'t yet lending any items. Add an item above.</td></tr>';
 } else {
  code+= '<tr><th>Category</th><td></td><th>Item</th><td></td><th>Status / Info</th></tr>'+itemCode;
 }
 code +="</table>";
 if (numItems>0) code += " <div id='exportPrint' align='right' class='s' style='margin-top:10px;'><a href='/export.php'>Export to Excel</a> | <a href='#' onclick='javascript:window.print();return false;'>Print List</a></div>";
 document.getElementById('items').innerHTML=code;
 code="";
}

function displayGroupEdit() {
 if (!list)
  alert("You must be logged in to edit groups.");
 else if (!member)
  alert("You must be a member of this group to edit it.");
 else
  document.getElementById('gInfo').innerHTML = '<table class="padded"><tr><td>Description:</td><td width="10" rowspan="3"></td><td colspan="5"><input type="text" name="description" style="width:27em;" value="'+description+'" /></td></tr><tr><td>Keywords:</td><td colspan="5"><input type="text" name="keywords" style="width:27em;" value="'+keywords+'"></td></tr><tr><td>Country:</td><td>'+countryMenu+'</td><td width="20"></td><td>Zip / Postal Code:</td><td width="10"></td><td><input type="text" name="pc" style="width:4.8em;" value="'+pc+'" /></td></tr></table><p><input type="submit" name="submitButton" value="Edit Group" /> <input type="button" value="Cancel" onclick="displayGroupInfo();" /> <span id="groupStatus"></span></p>';
}

function displayGroupInfo() {
 document.getElementById('gInfo').innerHTML = description + '<div class="status" style="margin-top:3px;line-height:1.3em;">Located '+smartDistance(country,prov,city,distance)+'<br />Keywords: '+keywords+'</div><div class="s"><a href="#" onclick="displayGroupEdit();return false;">Edit group info</a> | Last edited by <a href="/'+editor+'/">'+editor+'</a>, '+smartDate(edited)+'</div>';
}

function showBubble(object,content,bubbleWidth) {
 var objectCoors = findPos(object);
 var screenSize = findClientSize();
 var scrollAmt = findScroll();
 if (!bubbleWidth) bubbleWidth=300;
 var bubbleBorderY=43;
 var bubbleBorderX=24;
 var bubblePointX=16;
 var bubblePointY=2;
 var bubbleMargin=0;
 var bubble = document.getElementById('bubble');
 var bubblePosX="left";
 var bubblePosY="top";

 //buildBubbleContent
 bubble.innerHTML='<div style="width:'+(bubbleWidth-bubbleBorderX)+'px;" class="xs">'+content+'</div>';

 //determine left or right display
 if ((screenSize[0]-objectCoors[0]-object.offsetWidth+scrollAmt[0]) > (bubbleWidth-bubblePointX-bubbleMargin)) {
  //display right
  bubble.style.left=objectCoors[0]+object.offsetWidth-bubblePointX;
 } else if (objectCoors[0]<bubbleWidth) {
  //display right
  bubble.style.left=objectCoors[0]+object.offsetWidth-bubbleWidth;
  var bubblePosX="right";
 } else {
  //display left
  bubble.style.left=objectCoors[0]-bubbleWidth+bubblePointX;
  var bubblePosX="right";
 }

 //determine top or bot display
 if ((objectCoors[1]-scrollAmt[1]) > (bubble.offsetHeight+bubbleBorderY+bubblePointY+bubbleMargin)) {
  //display top
  bubble.style.top=objectCoors[1]-bubble.offsetHeight-bubbleBorderY-bubblePointY;
 } else {
  //display bot
  bubble.style.top=objectCoors[1]+object.offsetHeight+bubblePointY;
  bubblePosY="bot";
 }

 //buildBubbleTop
 if (bubblePosY=="top") {
  bubble.innerHTML='<table><tr><td width="6" height="6"><img src="img/bubble-tl.gif" width="6" height="6"></td><td style="background-color:#FFFFE1;background-image:url(img/bubble-border.gif);background-repeat:repeat-x;background-position:top left;"></td><td width="6"><img src="img/bubble-tr.gif" width="6" height="6"></td></tr><tr><td style="background-color:#FFFFE1;background-image:url(img/bubble-border.gif);background-repeat:repeat-y;"></td><td bgcolor="#FFFFE1" style="padding:6px;color:#666600;">'
   + bubble.innerHTML
   + '</td><td style="background-color:#FFFFE1;background-image:url(img/bubble-border.gif);background-repeat:repeat-y;background-position:top right;"></td></tr><tr valign="top"><td><img src="img/bubble-bl.gif" width="6" height="6"></td><td valign="bottom" height="25" valign="top" background="img/bubble-b.gif" style="text-align:'+bubblePosX+';"><img src="img/bubble-point-down-'+bubblePosX+'.gif" width="19" height="20" style="margin:0px 10px 0px 10px;"></td><td><img src="img/bubble-br.gif" width="6" height="6"></td></tr></table>';
 } else {
  bubble.innerHTML='<table><tr valign="bottom"><td width="6"><img src="img/bubble-tl.gif" width="6" height="6"></td><td height="25" valign="top" background="img/bubble-t.gif" style="text-align:'+bubblePosX+';"><img src="img/bubble-point-'+bubblePosX+'.gif" width="19" height="20" style="margin:0px 10px 0px 10px;"></td><td width="6"><img src="img/bubble-tr.gif" width="6" height="6"></td></tr><tr><td style="background-color:#FFFFE1;background-image:url(img/bubble-border.gif);background-repeat:repeat-y;"></td><td bgcolor="#FFFFE1" style="padding:6px;color:#666600;">'
   + bubble.innerHTML
   + '</td><td style="background-color:#FFFFE1;background-image:url(img/bubble-border.gif);background-repeat:repeat-y;background-position:top right;"></td></tr><tr><td height="6"><img src="img/bubble-bl.gif" width="6" height="6"></td><td style="background-color:#FFFFE1;background-image:url(img/bubble-border.gif);background-repeat:repeat-x;background-position:bottom left;"></td><td><img src="img/bubble-br.gif" width="6" height="6"></td></tr></table>';
 }
 bubble.style.visibility="visible";
}

function hideBubble() {
 document.getElementById('bubble').style.visibility="hidden";
}

//EDITING
var editingOver="";
var editingValue="";
var editingOn="";
var setWidth="";

function editableOver(object) {
 if (editingOver!=object && editingOn=="") { 
  var x = object.split("_");
  var itemID=x[1];
  if (editingOver!="") editableOut(editingOver);
  editingOver=object;
  editingValue = document.getElementById(object).innerHTML;

  if (x[0]!="itemCat") { //regular field
   document.getElementById(object).style.margin="2px 0px 0px 0px";
   if (document.getElementById(object).style.width=="") document.getElementById(object).style.width = document.getElementById(object).offsetWidth-2;
   document.getElementById(object).innerHTML = '<input type="text" align="top" value="'+editingValue.replace(/&nbsp;/g,' ').replace(/"/g,'&quot;')+'" onfocus="editingOn=1;" onblur="if(this.value!=editingValue) updateEntry(\''+object+'\',this.value); else { editingOn=\'\';editableOut(\''+object+'\'); }" style="width:100%;" onmouseout="editableOut(\''+object+'\')" onkeypress="handleKeyPress(event,\'updateEntry\',\''+object+'\',this.value)"><br>';
  } else { // select menu
   var code = '<select style="font-weight:normal;width:170px;" onmouseout="editableOut(\''+object+'\');" onfocus="editingOn=1;" onblur="editingOn=0;editableOut(\''+object+'\');" onchange="updateEntry(\''+object+'\',this.options[this.selectedIndex].value)">';
   for (i in cats) {
    code +='<option value="'+i+'"';
    if (itemCat[itemID]==cats[i]) code +=' selected';
    code +='>'+cats[i]+'</option>';
   }
   code +='</select>';
   document.getElementById(object).style.paddingLeft="0px";
   document.getElementById(object).innerHTML = code;
  }
 }
} 

function editableOut(object) {
 if (editingOn=='') {
  var x = object.split("_");
  if (x[0]!="itemCat") { //regular field
   document.getElementById(object).style.margin="0px 0px 0px 2px";
  } else {
   document.getElementById(object).style.paddingLeft="5px";
  }
  editingOver="";
  document.getElementById(object).innerHTML=editingValue.replace(/ /g,'&nbsp;');
 }
}

function updateEntry(object,dbValue) {
 var x = object.split("_");
 var dbField=x[0];
 var itemID=x[1];
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/edit-item.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     editingOn='';
     editingOver='';
     editingValue='';
     editableOut(object);
     if (dbField=='itemName') { itemName[itemID]=dbValue; sortItems();displayItemList(); }
     else if (dbField=='itemCat') { itemCat[itemID]=cats[dbValue]; sortItems();displayItemList(); }
     else if (dbField=='itemAvail') { itemAvail[itemID]=dbValue; document.getElementById(object).innerHTML = dbValue; }
     document.getElementById('itemStatus').innerHTML = '';
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('itemStatus').innerHTML = "";
     editingOn='';
     editableOut(object);
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('itemID='+urlEncode(itemID)+'&dbField='+urlEncode(dbField)+'&dbValue='+urlEncode(dbValue));
 document.getElementById('itemStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

function updateGroup(object) {
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/edit-group.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     description = object.description.value;
     keywords = object.keywords.value;
     country = object.country.options[object.country.selectedIndex].text;
     pc = object.pc.value;
     object.oldpc.value=pc;
     edited="";
     if (xmlhttp.responseXML.getElementsByTagName('city')[0].firstChild) city=xmlhttp.responseXML.getElementsByTagName('city')[0].firstChild.data;
     if (xmlhttp.responseXML.getElementsByTagName('prov')[0].firstChild) prov=xmlhttp.responseXML.getElementsByTagName('prov')[0].firstChild.data;
     if (xmlhttp.responseXML.getElementsByTagName('distance')[0].firstChild) distance=xmlhttp.responseXML.getElementsByTagName('distance')[0].firstChild.data;
     displayGroupInfo(); 
     object.friend.value="List name or email";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('groupStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('gname='+urlEncode(object.gname.value)+'&description='+urlEncode(object.description.value)+'&keywords='+urlEncode(object.keywords.value)+'&country='+object.country.options[object.country.selectedIndex].value+'&pc='+urlEncode(object.pc.value)+'&oldpc='+urlEncode(object.oldpc.value));
 document.getElementById('groupStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}


//REMOVALS

function removeFriend(friend) {
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/remove-friend.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     delete friendList[friend]
     displayFriendList(); 
     document.getElementById('friendStatus').innerHTML = "";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('friendStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('friend='+urlEncode(friend));
 document.getElementById('friendStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

function removePic() {
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/remove-pic.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     document.getElementById('picStatus').innerHTML = "";
     document.getElementById('picDelete').innerHTML = "";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('picStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send("delete=1");
 document.getElementById('picStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}


function removeGroup(gname) {
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/remove-group.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     delete groupList[gname]
     displayGroupList();
     document.getElementById('groupStatus').innerHTML = "";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('groupStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('gname='+urlEncode(gname));
 document.getElementById('groupStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

function removeItem(itemID) {
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/remove-item.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     delete itemName[itemID];
     delete itemCat[itemID];
     delete itemAvail[itemID];
     sortItems();
     displayItemList();
     document.getElementById('itemStatus').innerHTML = "";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('itemStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('itemID='+urlEncode(itemID));
 document.getElementById('items').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

// ADDING

function addFriend(object) {
 var friend = object.friend.value;
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/add-friend.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     friendList[xmlhttp.responseXML.getElementsByTagName('list')[0].firstChild.data]=xmlhttp.responseXML.getElementsByTagName('items')[0].firstChild.data;
     sortArrayByKey(friendList);
     displayFriendList(); 
     document.getElementById('friendStatus').innerHTML = "";
     object.friend.value="List name or email";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('friendStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('friend='+urlEncode(friend));
 document.getElementById('friendStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

function addFriendLink(friend) {
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/add-friend.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    document.getElementById('friendStatus').innerHTML = "";
    alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('friend='+urlEncode(friend));
 document.getElementById('friendStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

function addItem(object) {
 if (object.item.value=="Item Name" || object.item.value.length<3) { alert("Please enter an item name that's at least 3 characters long.");object.item.focus();return false; }
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/add-item.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     itemName[xmlhttp.responseXML.getElementsByTagName('itemID')[0].firstChild.data]=xmlhttp.responseXML.getElementsByTagName('item')[0].firstChild.data;
     itemCat[xmlhttp.responseXML.getElementsByTagName('itemID')[0].firstChild.data]=xmlhttp.responseXML.getElementsByTagName('cat')[0].firstChild.data;
     if (xmlhttp.responseXML.getElementsByTagName('status')[0].firstChild) itemAvail[xmlhttp.responseXML.getElementsByTagName('itemID')[0].firstChild.data]=xmlhttp.responseXML.getElementsByTagName('status')[0].firstChild.data;
     sortItems();
     lastCat=object.cat.options[object.cat.selectedIndex].value;
     displayItemList(); 
     itemForm.item.focus();
     document.getElementById('itemStatus').innerHTML = "";
     object.item.value="";
     object.itemButton.disabled=false;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('itemStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
     object.itemButton.disabled=false;
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('cat_id='+object.cat.options[object.cat.selectedIndex].value+'&item='+urlEncode(object.item.value));
 document.getElementById('itemStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
 object.itemButton.disabled=true;
}

function addGroup(object) {
 //CHECK that the group name contains only the proper characters.

 //check that all fields are filled in properly.
 if (object.gname.value.length<3) { alert('Please enter a group name of at least 3 characters');object.gname.focus();return false; } 
 else if (!allValidChars(object.gname.value.replace(/ /g,''))) { alert('Please use only letters, numbers, spaces, hyphens(-), or underscores(_).');object.gname.focus();return false; }
 else if (object.description.value=="") { alert('Please enter a description of the group.');object.description.focus();return false; } 
 else if (object.description.value.length<8) { alert('Please enter a description that is at least 8 characters.');object.description.focus();return false; } 
 else if (object.country.options[object.country.selectedIndex].value=="CA" && checkPC(object.pc.value)==false) { alert('Please enter a valid Canadian postal code.');object.pc.focus();return false; }
 else if (object.country.options[object.country.selectedIndex].value=="US" && checkZip(object.pc.value)==false) { alert('Please enter a valid US zip code');object.pc.focus();return false; }

 //submit reg
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/add-group.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     location.href="/"+urlEncode(object.gname.value)+"/";
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==2) {
     document.getElementById('groupStatus').innerHTML = "";
     alert("The group name you've chosen is already in use. Please choose a different one.");object.gname.focus();
     object.submitButton.disabled=false;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==3) {
     document.getElementById('groupStatus').innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
     object.submitButton.disabled=false;
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('gname='+urlEncode(object.gname.value)+'&description='+urlEncode(object.description.value)+'&keywords='+urlEncode(object.keywords.value)+'&country='+object.country.options[object.country.selectedIndex].value+'&pc='+urlEncode(object.pc.value));
 document.getElementById('groupStatus').innerHTML = "<img src='img/working.gif' width='13' height='13'>";
 object.submitButton.disabled=true;
}

function joinGroup(gname,statusIcon) {
 if (!list) { if (confirm('You must be logged in to join a group. Click "ok" to go to the registration / login page.')) location.href='/?p='+location+'#create'; return false; }
 var xmlhttp =  new XMLHttpRequest();
 xmlhttp.open('POST', '/join-group.php', true);
 xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4) {
   if (xmlhttp.status == 200) {
    if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==1) {
     document.getElementById(statusIcon).innerHTML = "";
     alert("You have been added to this group.");
     location.href="./"+gname;
    } else if (xmlhttp.responseXML.getElementsByTagName('result')[0].firstChild.data==3) {
     document.getElementById(statusIcon).innerHTML = "";
     alert(xmlhttp.responseXML.getElementsByTagName('message')[0].firstChild.data);
    }
   }
  }
 }
 xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
 xmlhttp.send('gname='+urlEncode(gname));
 document.getElementById(statusIcon).innerHTML = "<img src='img/working.gif' width='13' height='13'>";
}

// NAVIGATING
function getList(list) {
 location.href="/"+urlEncode(list);
}

function expandAll() {
 for (i=1;i<=12;i++) {
  if (document.getElementById('c'+i)) {
   document.getElementById('c'+i).style.height='';
   document.getElementById('img'+i).src='/img/arrow-open.gif';
   catClosed[i]=0;
  }
 }
}

function collapseAll() {
 for (i=1;i<=12;i++) {
  if (document.getElementById('c'+i)) {
   document.getElementById('c'+i).style.height='1.8em';
   document.getElementById('img'+i).src='/img/arrow-closed.gif';
   catClosed[i]=1;
  }
 }
}

function toggleCat(object) {
 if (catClosed[object]==1) {
  document.getElementById('c'+object).style.height='';
  document.getElementById('img'+object).src='/img/arrow-open.gif';
  catClosed[object]=0;
 } else {
  document.getElementById('c'+object).style.height="1.8em";
  document.getElementById('img'+object).src='/img/arrow-closed.gif';
  catClosed[object]=1;
 }
}

function selectAll() {
 for (i=1;i<=max;i++) {
  if (document.getElementById('c'+i)) {
   document.getElementById('c'+i).checked=true;
  }
 }
}

function unSelectAll() {
 for (i=1;i<=max;i++) {
  if (document.getElementById('c'+i)) {
   document.getElementById('c'+i).checked=false;
  }
 }
}
