var globalLastPositionX;
var globalLastPositionY;
var globalUrlBase = "";
var globalName;


if (typeof urlbase != "undefined") 
{
  globalUrlBase = urlbase;
}

var target = ""
var updatepoints = false;
var inSpellCheckMode = false;

function setGlobalUrlBase(urlbase) 
{
  globalUrlBase = urlbase;
}

function setGlobalCookieName(name) 
{
  globalName = name;
}

function setGlobalLastPosition(x, y)
{
  globalLastPositionX = x;
  globalLastPositionY = y;

//setEditorText('content', "globallastpos " + globalLastPositionX + "  " + globalLastPositionY );
}

function xmlhttpPost(strURL, targetIn) 
{
  var xmlHttpReq = false;
  var self = this;
  target = targetIn;

  // Mozilla/Safari
  if (window.XMLHttpRequest)
  {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject)
  {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }

  self.xmlHttpReq.open('GET', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
  if (self.xmlHttpReq.readyState == 4) 
  {
    updatepage(self.xmlHttpReq.responseText);
  }
  }
  self.xmlHttpReq.send("");
}

function xmlhttpRealPost(strURL, formData) 
{
  var xmlHttpReq = false;
  var self = this;

  // Mozilla/Safari
  if (window.XMLHttpRequest)
  {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // IE
  else if (window.ActiveXObject)
  {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }

  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.send(formData);

}

function getquerystring() 
{
  var form     = document.forms['f1'];
  var word = form.word.value;
  qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
  return qstr;
}

function updatepage(str)
{
  if(target == 'resultset')
  {
    document.getElementById("phraseset").innerHTML = "&nbsp;";
  }
  if( document.getElementById(target) )
  {
    document.getElementById(target).scrollTop = 0;
    document.getElementById(target).innerHTML = str;
  }
  if(updatepoints == true)
  {
    UpdatePoints()
    updatepoints = false;
  }
}

function SaveDefinitionBottomDone()
{
  clearDiv('definitionAddOutputBottom');
  hideDiv('definitionAddOutputBottom');
  showDiv('definitionAddBottom');
}

function SaveDefinitionBottom(thisform, baseurl) 
{
  var newWord = document.getElementById("NewWordBottom").value;
  var newDef = document.getElementById("NewDefinitionBottom").value;
  if((newWord == "Type Word") || (newWord == ""))
  {
    alert("Enter the word that you would like to define.");
  }
  else
  {
    if((newDef == "Type Definition Here") || (newDef == ""))
    {
      alert("Enter the definition.");
    }
    else
    {
      xmlhttpPost(baseurl + '/ajax/submit_definition.php?word=' + newWord + '&definition=' + newDef, 'definitionAddOutputBottom');
      document.getElementById("NewWordBottom").value = 'Type Word';
      document.getElementById("NewDefinitionBottom").value = 'Type Definition Here';
      hideDiv('definitionAddBottom');
      showDiv('definitionAddOutputBottom');
      setTimeout('SaveDefinitionBottomDone()', 3000);
    }
  }
  return false;
}

function SavePhraseTop(thisform, catid) 
{
  var newText = document.getElementById("NewPhraseTop").value;
  xmlhttpPost('./ajax/submit_phrase.php?phrase=' + newText + '&categoryid=' + catid, 'phraseAddOutputTop');
  document.getElementById("NewPhraseTop").value = '';
  return false;
}

function SavePhraseBottom(thisform, catid) 
{
  var newText = document.getElementById("NewPhraseBottom").value;
  xmlhttpPost('./ajax/submit_phrase.php?phrase=' + newText + '&categoryid=' + catid, 'phraseAddOutputBottom');
  document.getElementById("NewPhraseBottom").value = '';
  return false;
}

function AddDefinition(thisform, catid) 
{
  xmlhttpPost('./ajax/subcategory.php?mode=add_definitions&id=' + catid, 'phraseset')
  return false;
}

function ShowAddDefinitionBlock(word) 
{
  document.getElementById("DefWord").value = word;
  document.getElementById('newPhraseWordSpan').innerHTML = word;
  

  var thistipobj = document.all? document.all["DefinitionAddOutput"] : document.getElementById? document.getElementById("DefinitionAddOutput") : "";
  var e = lastpos

var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<thistipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
thistipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-thistipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-thistipobj.offsetWidth+"px"
else if (curX<leftedge)
thistipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
thistipobj.style.left=curX+offsetxpoint+"px"

//same concept with the vertical position
if (bottomedge<thistipobj.offsetHeight)
thistipobj.style.top=ie? ietruebody().scrollTop+event.clientY-thistipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-thistipobj.offsetHeight-offsetypoint+"px"
else
thistipobj.style.top=curY+offsetypoint+"px"
thistipobj.style.visibility="visible"


thistipobj.style.left = 200;
thistipobj.style.top = 200;


  return false;
}

function CancelAddDefinition(thisform) 
{
  document.getElementById("NewDefinition").value = "";
  var thistipobj = document.all? document.all["DefinitionAddOutput"] : document.getElementById? document.getElementById("DefinitionAddOutput") : ""
  thistipobj.style.visibility="hidden"
  return false;
}

function SubmitAddDefinition(thisform) 
{
  var word = document.getElementById("DefWord").value;
  var definition = document.getElementById("NewDefinition").value;
  var thistipobj = document.all? document.all["DefinitionAddOutput"] : document.getElementById? document.getElementById("DefinitionAddOutput") : ""
  thistipobj.style.visibility="hidden"

  updatepoints = true;


  xmlhttpRealPost('./ajax/submit_definition.php', 'word=' + word + '&definition=' + definition);

  document.getElementById("NewDefinition").value = "";

  //setTimeout('UpdatePoints()', 2000);
  return false;
}


function clearDiv(divid) {
   if (document.layers) document.layers[divid].innerHTML = "";
   else document.getElementById(divid).innerHTML = "";
}

function setDivContents(divid, newhtml) 
{
 try {
   if (document.layers) document.layers[divid].innerHTML = newhtml;
   else document.getElementById(divid).innerHTML = newhtml;
 } catch (e) {
 }
}

function showDiv(divid) 
{
  if(isObjGood(divid))
  {
    if (document.layers) document.layers[divid].visibility="show";
    else document.getElementById(divid).style.visibility="visible";
  }
}

function isObjGood(divid)
{
  if(document.layers)
  {
  }
  else
  {
    if(!(document.getElementById(divid)))
    {
      return false;
    }
  }
  return true;
}
function hideDiv(divid) 
{
  if(isObjGood(divid))
  {
    if (document.layers) document.layers[divid].visibility="hide";
    else document.getElementById(divid).style.visibility="hidden";
  }
}

function showFullDefinition(divid, word)
{
  //clearDiv(divid);
  xmlhttpPost('./show_full_definition.php?word=' + word, divid)
}

function validate_required(field, alerttxt)
{
  with (field)
  {
    if (value==null||value=="")
    {
      alert(alerttxt);
      field.focus();
      return false;
    }
    else 
    {
      return true;
    }
  }
}


function CancelAddCategory(thisform) 
{
  clearDiv('phraseset');
}

function SubmitAddCategory(thisform) 
{
  var cat = document.getElementById("category").value;
  var newcat = document.getElementById("NewCategory").value;
  
  if(newcat == null || newcat =="")
  {
    alert("Category must be filled out before you hit the 'Add Category' button!");
    return false;
  }

  xmlhttpPost('./add_category.php?cat=' + cat + '&newcat=' + newcat, 'phraseset');
}


function AdClicked(url, pai)
{
  xmlhttpPost('./ajax/track_click.php?paid_ad_id=' + pai, 'hiddenNotShown');
  window.open(url,'_new','')
  return false; 
}

function trackClick(type, extra)
{
  xmlhttpPost('./ajax/track_click.php?type=' + type + '&extra=' + extra, 'hiddenNotShown');
  return false; 
}


function UpdatePoints()
{
  var currentTime = new Date();
  var ts = currentTime.getTime();
  xmlhttpPost('./ajax/points.php?ts=' + ts, 'points');
}

function ChangeCategory(cat)
{
  // start with saving our location for returning later
  var curPage = window.location + "";
  var qs = curPage.indexOf('?');
  if(qs > 0)
  {  
    var pos = curPage.indexOf('&subid=');
    if(pos > 0)
    {
      curPage = curPage.substr(0, pos);
    }
    pos = curPage.indexOf('?subid=');
    if(pos > 0)
    {
      curPage = curPage.substr(0, pos);
      curPage = curPage + '?subid=' + cat;
    }
    else
    {       
      curPage = curPage + '&subid=' + cat;
    }
  }
  else
  {
    curPage = curPage + '?subid=' + cat;
  }
  SaveLastPage('thesaurus', curPage);


  // now switch the page.
  var currentTime = new Date();
  var ts = currentTime.getTime();
  updatepoints = true;
  xmlhttpPost('./ajax/subcategory.php?id=' + cat + '&ts=' + ts, 'phraseset');

  //setTimeout('UpdatePoints()', 2000);
}
function ChangeCategoryAdmin(cat)
{
  var currentTime = new Date();
  var ts = currentTime.getTime();
  xmlhttpPost('../ajax/subcategory.php?adminMode=admin&id=' + cat + '&ts=' + ts, 'AdminEditPhrasesRight');
}

function AdminShowCategory(cat, name)
{
  setDivContents('AdminEditPhrasesRight', cat + '  ' + name);
  xmlhttpPost('../ajax/subcategory.php?adminMode=admin&id=' + cat, 'AdminEditPhrasesLeft');
}

function AdminPhraseSaveChangesDone() 
{
  hideDiv('AdminEditPhrasesSaving');
  showDiv('AdminEditPhrasesRight');
}

function AdminPhraseSaveChanges(phraseid) 
{
  var fieldname = 'field' + phraseid;
  var originalfieldname = 'originalField' + phraseid;
  var phrase = document.getElementById(fieldname).value;
  var originalphrase = document.getElementById(originalfieldname).value;

  if(phrase != originalphrase)
  {
    hideDiv('AdminEditPhrasesRight');
    showDiv('AdminEditPhrasesSaving');
    setTimeout('AdminPhraseSaveChangesDone()', 1000);
    xmlhttpPost('./edit_existing_phrases.php?action=editPhrase&id=' + phraseid + '&phrase=' + phrase, 'hiddenNotShown');
    document.getElementById(fieldname).value = phrase;
    document.getElementById(originalfieldname).value = phrase;
  }
  return false;
}

function AdminPhraseDelete(phraseid) 
{
  var divname = 'phraseDiv' + phraseid;
  hideDiv(divname);
  xmlhttpPost('./edit_existing_phrases.php?action=deletePhrase&id=' + phraseid, 'hiddenNotShown');
}

function AdminPhraseMerge(phraseid, prevphraseid) 
{
  var divname = 'phraseDiv' + phraseid;
  hideDiv(divname);

  var fieldname = 'field' + phraseid;
  var phrase = document.getElementById(fieldname).value;

  var prevfieldname = 'field' + prevphraseid;
  var prevphrase = document.getElementById(prevfieldname).value;

  var originalprevfieldname = 'originalField' + prevphraseid;
  var originalprevphrase = document.getElementById(originalprevfieldname).value;

  newphrase = prevphrase + ' ' + phrase;
  
  document.getElementById(prevfieldname).value = newphrase;
  document.getElementById(originalprevfieldname).value = newphrase;

  xmlhttpPost('./edit_existing_phrases.php?action=editPhrase&id=' + prevphraseid + '&phrase=' + newphrase, 'hiddenNotShown');
  xmlhttpPost('./edit_existing_phrases.php?action=deletePhrase&id=' + phraseid, 'hiddenNotShown');
}




function AdminSpellCheckSaveChanges(phraseid) 
{
  var outputname = 'output' + phraseid;
  var fieldname = 'field' + phraseid;
  var originalfieldname = 'originalField' + phraseid;
  var phrase = document.getElementById(fieldname).value;
  var originalphrase = document.getElementById(originalfieldname).value;

  if(phrase != originalphrase)
  {
    xmlhttpPost('./edit_existing_phrases.php?action=editPhrase&id=' + phraseid + '&phrase=' + phrase, outputname);
    document.getElementById(fieldname).value = phrase;
    document.getElementById(originalfieldname).value = phrase;
  }
  else
  {
    alert("nothing to save");
  }
  return false;
}


function whichBrs() {
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("opera") != -1) return 'Opera';
if (agt.indexOf("staroffice") != -1) return 'Star Office';
if (agt.indexOf("webtv") != -1) return 'WebTV';
if (agt.indexOf("beonex") != -1) return 'Beonex';
if (agt.indexOf("chimera") != -1) return 'Chimera';
if (agt.indexOf("netpositive") != -1) return 'NetPositive';
if (agt.indexOf("phoenix") != -1) return 'Phoenix';
if (agt.indexOf("firefox") != -1) return 'Firefox';
if (agt.indexOf("safari") != -1) return 'Safari';
if (agt.indexOf("skipstone") != -1) return 'SkipStone';
if (agt.indexOf("msie") != -1) return 'Internet Explorer';
if (agt.indexOf("netscape") != -1) return 'Netscape';
if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
if (agt.indexOf('\/') != -1) {
if (agt.substr(0,agt.indexOf('\/')) != 'mozilla') {
return navigator.userAgent.substr(0,agt.indexOf('\/'));}
else return 'Netscape';} else if (agt.indexOf(' ') != -1)
return navigator.userAgent.substr(0,agt.indexOf(' '));
else return navigator.userAgent;
}

function firefoxClearSelection()
{
  if(whichBrs() == 'Firefox')
  {
    var thistipobj = document.all? document.all["DefinitionAddOutput"] : document.getElementById? document.getElementById("DefinitionAddOutput") : "";
    
    if(thistipobj)
    {
      if(thistipobj.style.visibility != "hidden")
      {
	return;
      }
    }
    document.getElementById('NewPhrase').focus();
  }
}



var newwindow;
function poptastic(url)
{
	//newwindow=window.open(url,'name','height=400,width=200');
	//if (window.focus) {newwindow.focus()}
}

function popItUp(page,PWidth,PHeight,id) 
{
 eval("stevepopupwindow"+id+"=window.open('"+page+"','stevepopupwindow1','scrollbars=0,location=0,status=0,menubars=0,resizable=0,width="+PWidth+",height="+PHeight+"')")
 eval("stevepopupwindow"+id+".window.moveTo((screen.width/2)-(PWidth/2),(screen.height/2)-(PHeight/2))")
 eval("stevepopupwindow"+id+".focus()")
}


function IEClipBoard(cliptext)
{
  holdtext.innerText = cliptext;
  Copied = holdtext.createTextRange();
  Copied.execCommand("Copy");
}

function copyPhrase(phraseid, phrase, url)
{
  trackClick("Copy", phraseid);
  if(whichBrs() == 'Internet Explorer')
  {
    IEClipBoard(phrase);
  }
  else
  {
    popItUp(url, 400, 200, 1);
  }

}


function copyPhraseToEditor(phraseid, phrase)
{
  trackClick("CopyToEditor", phraseid);

  if(whichBrs() == 'Internet Explorer')
  {
    var edit = document.getElementById("content").contentWindow.document;
    var mainField = document.getElementById("content").contentWindow;
    mainField.focus();
    edit.selection.createRange().pasteHTML(" " + phrase + " ");
    mainField.focus();
  }
  else
  {
    editorCommand("content", "inserthtml", " " + phrase + " ");
  }
}


function addToFavoriteDone(divid)
{
  clearDiv(divid);
}


function addToFavorites(phraseid, divid)
{
  xmlhttpPost('./ajax/addToFavorites.php?phrase=' + phraseid, divid);
  setTimeout('addToFavoriteDone(\'' + divid + '\')', 3000);
}


function deleteFavorites(phraseid, divid)
{
  var answer = confirm("Do you want to remove this favorite")
  if (answer)
  {
    xmlhttpPost('./ajax/deleteFavorites.php?phrase=' + phraseid, divid);
    hideDiv(divid);
  }
}


function ratePhrase(phraseid)
{
  ShowRatePhraseBlock(phraseid);
  //trackClick("Rate", phraseid);
}


function ShowRatePhraseBlock(phrase) 
{
  document.getElementById("phraseid").value = phrase;
  var tipobj = document.all? document.all["RatePhraseDiv"] : document.getElementById? document.getElementById("RatePhraseDiv") : ""

  tipobj.style.left = lastposx;
  tipobj.style.top = lastposy;
  showDiv('RatePhraseStars');
  hideDiv('RatePhraseResults');
  showDiv('RatePhraseDiv');
  hideDiv('RatePhraseDiv');
  return false;
}
var closingPhrases = 0;
function CancelRatePhrase() 
{
  if(closingPhrases == 0)
  {
    submitRatePhraseDone();
  }
  CancelSpellFix();
  return false;
}

function submitRatePhraseDone()
{
  hideDiv("RatePhraseDiv");
  hideDiv('RatePhraseStars');
  hideDiv('RatePhraseResults');
  closingPhrases = 0;
}

function SubmitRatePhrase(thisform, star) 
{
  closingPhrases = 1;
  var phrase = document.getElementById("phraseid").value;
  hideDiv('RatePhraseStars');
  showDiv('RatePhraseResults');
  setTimeout('submitRatePhraseDone()', 1000);
  xmlhttpPost('./ajax/rate_phrase.php?phrase=' + phrase + '&stars=' + star, 'RatePhraseHideOutput');

  return false;
}


function showStars(starNum, base)
{
  if(starNum == 1)
  {
    movepic('Star1', base + '/images/blue_star.jpg')
    movepic('Star2', base + '/images/white_star.jpg')
    movepic('Star3', base + '/images/white_star.jpg')
    movepic('Star4', base + '/images/white_star.jpg')
    movepic('Star5', base + '/images/white_star.jpg')
  }
  else if(starNum == 2)
  {
    movepic('Star1', base + '/images/blue_star.jpg')
    movepic('Star2', base + '/images/blue_star.jpg')
    movepic('Star3', base + '/images/white_star.jpg')
    movepic('Star4', base + '/images/white_star.jpg')
    movepic('Star5', base + '/images/white_star.jpg')
  }
  else if(starNum == 3)
  {
    movepic('Star1', base + '/images/blue_star.jpg')
    movepic('Star2', base + '/images/blue_star.jpg')
    movepic('Star3', base + '/images/blue_star.jpg')
    movepic('Star4', base + '/images/white_star.jpg')
    movepic('Star5', base + '/images/white_star.jpg')
  }
  else if(starNum == 4)
  {
    movepic('Star1', base + '/images/blue_star.jpg')
    movepic('Star2', base + '/images/blue_star.jpg')
    movepic('Star3', base + '/images/blue_star.jpg')
    movepic('Star4', base + '/images/blue_star.jpg')
    movepic('Star5', base + '/images/white_star.jpg')
  }
  else if(starNum == 5)
  {
    movepic('Star1', base + '/images/blue_star.jpg')
    movepic('Star2', base + '/images/blue_star.jpg')
    movepic('Star3', base + '/images/blue_star.jpg')
    movepic('Star4', base + '/images/blue_star.jpg')
    movepic('Star5', base + '/images/blue_star.jpg')
  }

}
function movepic(img_name,img_src) 
{
  document[img_name].src=img_src;
}



function DeleteDescription(editor, id, name, urlbase)
{
  globalUrlBase = urlbase;

  var answer = confirm("Are you sure that you want to delete the description:\n" + name)
  if (answer)
  {
    var xmlhttp = GetXMLSender();
    xmlhttp.open("GET", urlbase + "/ajax/delete_description.php?id=" + id, true);
    xmlhttp.onreadystatechange=function() 
    {
      window.location.reload();
    }
    xmlhttp.send(null)
  }
  else
  {
    alert(name + " was not deleted.");
  }



}

function LoadEditorDescription(editor, id, name, urlbase)
{
  globalUrlBase = urlbase;

  inSpellCheckMode = false;
  hideDiv("SpellChecking");
  showDiv("top_buttons");

  saveSpellCheckCookie(name);

  var hiddenField = document.getElementById('hiddenDescriptionId');
  hiddenField.value = id;

  var nameField = document.getElementById('savedName');
  nameField.value = name;

  var xmlhttp = GetXMLSender();
  xmlhttp.open("GET", urlbase + "/ajax/get_description.php?id=" + id, true);
  xmlhttp.onreadystatechange=function() 
  {
    if (xmlhttp.readyState==4) 
    {
      setEditorText('content', xmlhttp.responseText);
      LockUnlockEditor('content', inSpellCheckMode, xmlhttp.responseText);
    }
  }
  xmlhttp.send(null)
}



function DebugEditor(thisform, editor, urlbase, name) 
{
  var textChanged = "";

  updateEditor(editor);

  if (document.all) textChanged = document.all['hidden' + editor].value;
  else textChanged = document.getElementById('hidden' + editor).value;

  alert(textChanged);
}

function ReloadSavedDescriptionsList()
{
  xmlhttpPost( './ajax/saved_description_list.php', "SavedDescriptionList");
}

function SaveEditorDescription(thisform, editor, urlbase, name) 
{
  globalUrlBase = urlbase;

  var textChanged = "";
  var existingId = "";

  if(inSpellCheckMode)
  {
    SpellCheckEditor(thisform, editor, urlbase, name);
  }


  updateEditor(editor);
  if (document.all) textChanged = document.all['hidden' + editor].value;
  else textChanged = document.getElementById('hidden' + editor).value;

  if (document.all) existingId = document.all['hiddenDescriptionId'].value;
  else existingId = document.getElementById('hiddenDescriptionId').value;

  var descName = "";

  if(existingId > 0)
  {
    //alert(existingId);
  }
  else
  {
    descName = prompt('Name to save as?', '');
  }
  if(descName != null)
  {
    xmlhttpRealPost(urlbase + '/ajax/save_description.php', 'desc=' + textChanged + '&name=' + descName + '&id=' + existingId);
  }
  setDivContents("SavedDescriptionList", "<center>Updating List</center>");
  setTimeout('ReloadSavedDescriptionsList()', 1000);
  return false;
}


function GetXMLSender()
{
var xmlhttp=false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
 try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

  return xmlhttp;
}


function ClearEditor(thisform, editor, urlbase, name) 
{
  globalUrlBase = urlbase;

  var answer = confirm("Do you want to save your current work before you clear your present work?\n\nClick OK to save or \nCANCEL to not save your current work.");
  if (answer)
  {
    SaveEditorDescription(thisform, editor, urlbase, name) 
  }
  answer = confirm("Do you still want to clear the editor?");
  if (answer)
  {
    setEditorText('content', "");

    if (document.all) document.all['hiddenDescriptionId'].value = "";
    else document.getElementById('hiddenDescriptionId').value = "";

    inSpellCheckMode = false;
    hideDiv("SpellChecking");
    showDiv("top_buttons");

    saveSpellCheckCookie(name);
  }
}

function initSpellCheckVar(name)
{
  inSpellCheckMode = Get_Cookie(name + 'editor_spell_check');
  if((inSpellCheckMode == null) || (inSpellCheckMode == "") || 
     (inSpellCheckMode == 'undefined') ||  (inSpellCheckMode == 'false'))
  {
    inSpellCheckMode = false;
  }
  else if (inSpellCheckMode == 'true')
  {
    inSpellCheckMode = true;
  }
  
  if(inSpellCheckMode == false)
  {
    hideDiv("SpellChecking");
    hideDiv("SpellFix");
    showDiv("top_buttons");
  }
  else
  {
    showDiv("SpellChecking");
    hideDiv("SpellFix");
    hideDiv("top_buttons");
  }

}

function saveSpellCheckCookie(name)
{
  if(name.length > 0)
  {
    globalName = name;
  }
  else
  {
    name = globalName;
  }
  Set_Cookie(name + 'editor_spell_check', inSpellCheckMode, 30, '/', '', '' );
}

function CancelSpellFix() 
{
  hideDiv("SpellFix");
  showDiv("top_buttons");
  return false;
}

function getStyleObject(objectId) 
{
    // cross-browser function to get an object's style object given its
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
}

function GetIgnoreList(name)
{
  if(name.length > 0)
  {
    globalName = name;
  }
  else
  {
    name = globalName;
  }
  ignoreList = Get_Cookie(name + 'editor_spell_check_ignore');
  if (typeof ignoreList == "undefined") 
  {
    ignoreList = "";
  }

  return ignoreList;
}

function SetIgnoreList(list, name)
{
  if(name.length > 0)
  {
    globalName = name;
  }
  else
  {
    name = globalName;
  }
  Set_Cookie(name + 'editor_spell_check_ignore', list, 0, '/', '', '' );
}

function AddToIgnoreList(addWord, name)
{
  var ignoreList = GetIgnoreList(name);
  if((ignoreList) && (ignoreList.length > 0))
  {
    if(ignoreList != addWord)
    {
      var bInList = 0;
      var SplitResults = ignoreList.split(",");
      for(i = 0; i < SplitResults.length; i++)
      {
	if(SplitResults[i] == addWord)
        {
          bInList = 1;
        }
      }
      if(bInList == 0)
      {
        ignoreList = ignoreList + "," + addWord;
      }
    }
  }
  else
  {
    ignoreList = addWord;
  }
  SetIgnoreList(ignoreList, name);
  return ignoreList;
}

function ShowSpellFixBlock(word, count_offset) 
{
  var spfix = getStyleObject("SpellFix");
  var ed = getStyleObject("editor_block");
  spfix.visibility = "visible";

  var hword = document.getElementById ('hidden_word');
  if(hword)
  {
    hword.value = word;
  }
  var hoffset = document.getElementById ('hidden_offset');
  if(hoffset)
  {
    hoffset.value = count_offset;
  }

  setDivContents("SpellFixWord", "<strong>" + word + "</strong>");
  setDivContents("SpellFixList", "<p><center>Loading suggestions...</center><p>");

  var formData = "type=single&offset=" + count_offset + "&check=" + escape(word);




  var xmlhttp = GetXMLSender();
  xmlhttp.open("POST", globalUrlBase + "/ajax/spelling.php", true);
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4)
    {
      if(xmlhttp.responseText.length > 0)
      {
        setDivContents("SpellFixList", xmlhttp.responseText);
      }
      else
      {
        setDivContents("SpellFixList", "<p><center>No suggestions found</center><p>");
      }
    }
  }
  xmlhttp.send(formData);


  return false;
}


function SpellFixWord(word, count_offset)
{
  ShowSpellFixBlock(word, count_offset);
}

function SpellFixWordSelected(originalWord, newWord, count_offset, AddCustomDictionaryWord)
{
  if (typeof AddCustomDictionaryWord == "undefined") 
  {
    AddCustomDictionaryWord = "";
  }

  var formData = "type=correct&offset=" + count_offset + "&originalWord=" + escape(originalWord) + "&newWord=" + escape(newWord);
  var textChanged = "";
  updateEditor('content');
  if (document.all) textChanged = document.all['hiddencontent'].value;
  else textChanged = document.getElementById('hiddencontent').value;

  var ignoreList = GetIgnoreList("");

  formData = formData + "&check=" + escape(textChanged) + "&ignore=" + escape(ignoreList) + "&addDictionary=" + escape(AddCustomDictionaryWord);

  var xmlhttp = GetXMLSender();
  xmlhttp.open("POST", globalUrlBase + "/ajax/spelling.php", true);
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

  xmlhttp.onreadystatechange=function()
  {
    if (xmlhttp.readyState==4)
    {
      if(xmlhttp.responseText.length > 0)
      {
        var textCheck = xmlhttp.responseText;
        var lookingFor = "<h2>Spell Checking</h2>";
        var chk = textCheck.substring(0, lookingFor.length);
	if(chk.toUpperCase() !== lookingFor.toUpperCase())
	{
	  inSpellCheckMode = false;
          CancelSpellFix();
          saveSpellCheckCookie("");
	  hideDiv("SpellChecking");
	  SetIgnoreList("", "");

	  alert("Spell checking is complete");
 	}
        LockUnlockEditor('content', inSpellCheckMode, textCheck);
      }
      else
      {
        LockUnlockEditor('content', inSpellCheckMode, "");
      }
    }
  }
  xmlhttp.send(formData);
}

function IgnoreWord(thisform, editor, urlbase, name) 
{
  var word = "";
  var offset = "";

  var hword = document.getElementById ('hidden_word');
  if(hword)
  {
    word = hword.value;
  }
  var hoffset = document.getElementById ('hidden_offset');
  if(hoffset)
  {
    offset = hoffset.value;
  }
  var ignoreList = AddToIgnoreList(word, name);
  SpellFixWordSelected(word, word, offset);
}

function IgnoreAll(thisform, editor, urlbase, name) 
{
  alert("ignore all - not yet implemented");
}


function AddToDictionary(thisform, editor, urlbase, name) 
{
  var word = "";
  var offset = "";

  var hword = document.getElementById ('hidden_word');
  if(hword)
  {
    word = hword.value;
  }
  var hoffset = document.getElementById ('hidden_offset');
  if(hoffset)
  {
    offset = hoffset.value;
  }
  SpellFixWordSelected(word, word, offset, word);
}

function SpellCheckEditor(thisform, editor, urlbase, name) 
{
  globalUrlBase = urlbase;

  var textChanged = "";
  updateEditor(editor);
  if (document.all) textChanged = document.all['hidden' + editor].value;
  else textChanged = document.getElementById('hidden' + editor).value;


  var ignoreList = GetIgnoreList("");

  var formData = "check=" + escape(textChanged) + "&ignore=" + escape(ignoreList);

  if(inSpellCheckMode)
  {
    inSpellCheckMode = false;
    SetIgnoreList("", "");
    hideDiv("SpellChecking");
    formData = "done=true&" + formData;
  }
  else
  {
    inSpellCheckMode = true;
    showDiv("SpellChecking");
    hideDiv("top_buttons");
  }
  saveSpellCheckCookie(name);
  

  var xmlhttp = GetXMLSender();
  xmlhttp.open("POST", urlbase + "/ajax/spelling.php", true);
  xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

 xmlhttp.onreadystatechange=function()
 {
  if (xmlhttp.readyState==4)
  {
    if(xmlhttp.responseText.length > 0)
    {
      LockUnlockEditor(editor, inSpellCheckMode, xmlhttp.responseText);
    }
    else
    {
      alert("No Spelling Errors");
      inSpellCheckMode = false;
      saveSpellCheckCookie(name);
      SetIgnoreList("", name);
      hideDiv("SpellChecking");
    }
  }
 }
  xmlhttp.send(formData);
  return false;
}


function Set_Cookie( name, value, expires, path, domain, secure ) 
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct 
expires time, the current script below will set 
it for x number of days, to make it for hours, 
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
( ( path ) ? ";path=" + path : "" ) + 
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}


// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) 
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');


		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
                        if(a_temp_cookie[1]) 
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
				return cookie_value;
				break;
			}
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}				
	

function getBrowserWidth() 
{
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //window.alert( 'Width = ' + myWidth );
  //window.alert( 'Height = ' + myHeight );
  return myWidth;
}

function URLEncode( plaintext )
{
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" +// Numeric
	"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +// Alphabetic
	"abcdefghijklmnopqrstuvwxyz" +
	"-_.!~*'()";// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var encoded = "";
    for (var i = 0; i < plaintext.length; i++ ) {
	var ch = plaintext.charAt(i);
	if (ch == " ") {
	    encoded += "+";// x-www-urlencoded, rather than %20
	} else if (SAFECHARS.indexOf(ch) != -1) {
	    encoded += ch;
	} else {
	    var charCode = ch.charCodeAt(0);
	    if (charCode > 255) {
		alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
		                 "(URL encoding only supports 8-bit characters.)\n" +
		       "A space (+) will be substituted." );
		encoded += "+";
	    } else {
		encoded += "%";
		encoded += HEX.charAt((charCode >> 4) & 0xF);
		encoded += HEX.charAt(charCode & 0xF);
	    }
	}
    } // for

    return encoded;
};

function URLDecode( encoded )
{
    // Replace + with ' '
    // Replace %xx with equivalent character
    // Put [ERROR] in output if %xx is invalid.
    var HEXCHARS = "0123456789ABCDEFabcdef"; 
    var plaintext = "";
    var i = 0;
    while (i < encoded.length) {
	var ch = encoded.charAt(i);
	if (ch == "+") {
	    plaintext += " ";
	    i++;
	} else if (ch == "%") {
	    if (i < (encoded.length-2) 
		&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
		&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
		plaintext += unescape( encoded.substr(i,3) );
		i += 3;
	    } else {
		alert( 'Bad escape combination near ...' + encoded.substr(i) );
		plaintext += "%[ERROR]";
		i++;
	    }
	} else {
	    plaintext += ch;
	    i++;
	}
    } // while
    return plaintext;
};

function FullSearchQuery(q, outputDivId, urlbase, type)
{
  globalUrlBase = urlbase;
  SaveLastPage('thesaurus', globalUrlBase + '/index.php?search=1&q=' + q);  
  q = URLEncode(q);
  xmlhttpPost(globalUrlBase + '/ajax/search.php?type=' + type + '&q=' + q, outputDivId);
}

function FullSearch(thisform, outputDivId, urlbase) 
{
  var q = document.getElementById("q").value;
  if ((typeof q == "undefined") || (q.length < 1))
  {
    setDivContents(outputDivId, "<font color=red>Search term is empty.  Please enter your search term above.</font>");
  }
  else
  {
    FullSearchQuery(q, outputDivId, urlbase, '');
  }
  return false;
}

function FullSearchShowResults(q, outputDivId, urlbase, type) 
{
  if ((typeof q == "undefined") || (q.length < 1))
  {
    setDivContents(outputDivId, "<font color=red>Search term is empty.  Please enter your search term above.</font>");
  }
  else
  {
    FullSearchQuery(q, outputDivId, urlbase, type);
  }
  return false;
}

function ShowSearchHints(urlbase)
{
    setDivContents("SearchHints", "Searching..");
    showDiv("SearchHints");
    xmlhttpPost(urlbase + '/content/boolean.html', "SearchHints");
}

function HideSearchHints()
{
    hideDiv("SearchHints");
    setDivContents("SearchHints", "");
}

function RemoveSpellcheckUserDict(theDiv, id, word, urlbase)
{
  globalUrlBase = urlbase;
  answer = confirm("Do you really want to remove '" + word + "'\nfrom your custom spell check dictionary?");
  if (answer)
  {
    clearDiv(theDiv);
    hideDiv(theDiv);

    var xmlhttp = GetXMLSender();
    xmlhttp.open("GET", urlbase + "/ajax/RemoveSpellcheckUserDict.php?id=" + id, true);
    xmlhttp.onreadystatechange=function() 
    {
      clearDiv(theDiv);
      hideDiv(theDiv);
    }
    xmlhttp.send(null)

  }
 
}

// type is either thesaurus or glossary
function SaveLastPage(type, page)
{
  Set_Cookie(type + '_last_page', page, 0, '/', '', '' );
}

function NavigateBackToLastPage(type)
{
  var going_to = Get_Cookie(type + '_last_page');

  var pos = going_to.indexOf('http://');
  if(pos == -1)
  {
    going_to = 'http://' + going_to;
  }

  window.location = going_to;
}