/**
* Bob Hanson hansonr@stolaf.edu 
*
*/
BoxPlus = new Image()
BoxMinus = new Image()
BoxPlus.src = "img/plus2.gif";
BoxMinus.src = "img/minus2.gif";
boxFormat = '<li class="linobullet" id="li-ITEMID" class="CLASS" ><input id="cb-ITEMID" value="THISID" name="new_cat_vals[]" type="checkbox" CHECKED onclick="ToggleCheckBox(IdToNode[\'THISID\'])">'
  +'THISTEXTCOUNT</a></li>'
function getBox(itemID, thisClass, thisid, thistext, isChecked, count) {
  return boxFormat
    .replace(/ITEMID/g, itemID)
    .replace(/CLASS/g, thisClass)
    .replace(/THISID/g, thisid)
    .replace(/CHECKED/, (isChecked ? "Checked" : "Blank"))
    .replace(/THISTEXT/g, thistext)//.split("(")[0])
    .replace(/COUNT/g, count >=0 ? " ("+count+")":"")
}

/**
* UpdatePage() generates node.id, node.level, and the id-->node map
* and populates the category and preview pane with items 
* that were previously selected during the last search.
* 
* The previously selected categories are then retrieved from get variables. 
* They are all leaf nodes of form "1-2-3" (for categories) or "a-1" (for authors).
* If no nodes are passed in _GET variable then we have entered the page 
* for the first time or the "New Search" button was pressed on the results page.
*/

function addCategories() {
  sortNodes();
  var s = '<div id="SubCategoriesContainer" class="Container">\n';
  s += '<ul class="ulnobullet">\n'
  for (var i=0; i< TopConcepts.length; i++) {
    var node = TopConcepts[i];
    node.n = i;
    s += '<li class="linobullet" id="MainCategoryMenuItem '+ i +'">'
    s += '<a href="javascript:void(0);" class="" onclick="TopConcepts['+i+'].displayCheck(true)"><img border="0" id="CategoryImage'+i+'" src="img/plus2.gif">&nbsp;</a>'
    s += '<a href="javascript:void(0);" class="maincat2" value="'+node.id+'" onClick="SwitchParent(\''+node.id+'\',\'IdToNode\')"><span id="Category '+ node.id +'" style="color:black;font-weight:bold;font-size:12px" title="'+node.count+' items">' + node.name 
	+ (node.parent ? " " + '(' + node.count + ')' : "") + '</span></a>'
    s += '</li>\n'
    s += '<div id="SubCategory'+ i +'" class=SubCategoryDiv>\n'
    s += '<ul class="ulnobullet">\n' + node.getCategoryTree(node) + '</ul>\n'
    s += '</div>'
  }
  s += '</ul>';
  s += '</div>';
  document.getElementById("filterContainer").innerHTML = s;
  return;
}

function addPrinciples(){
  var s = '<div id="PrinciplesContainer" class="Container">\n<ul class="ulnobullet">\n';
  for (var i in Principles){
    var node = Principles[i];
    s+= '<li  class="linobullet" style="text-indent:-53px;margin:0 0 0 38px" id='+node.id+'>';
    s+= '<a href="javascript:void(0);" style="border:none" title="'+node.explanation+'" onclick="showQuestions('+i+')" title="Click here for more info"><img border="0" id="PrincipleImage'+i+'" src="img/i.gif" alt="info"></a>&nbsp;';
    s+= (node.id < 10 ? '&nbsp;&nbsp;':'')+node.id+'.&nbsp;<a href="javascript:void(0);" name="principles" class="maincat2" style="color:black;font-weight:bold;font-size:12px" onClick="SwitchParent('+i+',\'Principles\')" '+(node.checked?'checked':'')+' value='+node.id+'><span id="Principle '+ i +'" style="color:black;font-weight:bold;font-size:12px" title="'+node.count+' items">' +node.title + /*" (" + node.count + ")"+*/ '</span></a></li>\n';
  }
  s +='</ul></div>';
  document.getElementById("filterContainer").innerHTML += s;
  return;
}


function initDisplay(){
  addCategories();
  addPrinciples();
  setDisplay();
}

function setDisplay(filter){
  if (document.getElementById('radioCategories').checked && filter != "principles") { //cat options
    $('#catAndOr').show("slow");
    /*$('#SubCategoriesContainer').css('display','block');
    $('#PrinciplesContainer').css('display','none');*/
    document.getElementById('catAndOr').style.display='block';
    document.getElementById('SubCategoriesContainer').style.display = 'block';
    document.getElementById('PrinciplesContainer').style.display = 'none';
  }
  else { //principle options
    $('#catAndOr').hide("slow");
    /*$('#SubCategoriesContainer').css('display','none');
    $('#PrinciplesContainer').css('display','block');*/
    document.getElementById('catAndOr').style.display = 'none';
    document.getElementById('SubCategoriesContainer').style.display = 'none';
    document.getElementById('PrinciplesContainer').style.display = 'block';
  }
}

function SwitchParent(num, obj) {
 //alert("switchparent" + num + " " + obj)
  var divId='';
  num = '' + num;
  var object;
  switch(obj){
    case "Principles":
	divId='Principle ' + num; 
	object = Principles[num];
      //to deal with Principles as radio buttons
	clearAllOtherPrinciples(object); 
	break;
    case "IdToNode":
	var object = IdToNode[num];
	divId = 'Category '+object.id;
	break;
  } 
  CheckAllNodesBelow(object, !object.checked);
  SetParentColor(object,obj == "Principles");
  setCategoryAjaxInfo();
}

function SetParentColor(node, isPrinciple) {
  if (!node)return
  if (isPrinciple) {
    var divId="Principle " + node.id
    var color = (Principles[node.id].checked ? "darkgreen" : "black"); //"#E19410";  
    document.getElementById(divId).style.color = color;
    return;
  }

  var nchecked = 0;
  for (i = 0; i < node.nNodes; i++) {
  //If by checking this node all siblings become checked,
  //we must check the parent node
    if (node.nodes[i].checked)nchecked++
  }
  var divId = "Category " + node.id;
  var color = (nchecked > 0 ? "darkgreen" : "black"); //"#E19410";  
  document.getElementById(divId).style.color = color;  

}

function clearCatNodes(){
  for (var i = 0; i < Concepts.length; i++){
    if(Concepts[i]) {
     Concepts[i].checked = false;
     CheckNode(Concepts[i], false, true);
     if(Concepts[i].parent)
	     SetParentColor(Concepts[i].parent, false)
    }
  }
}

function clearAllOtherPrinciples(object){
  for (var i in Principles){
    if (!object || i != object.id){
      //clear checked value
      Principles[i].checked = false;
      //clear font color
      document.getElementById("Principle "+i).style.color = "black";
    }
  }
}

/**
* Creates a subcategory tree given a category node.  The results are displayed 
* in the subcategory pane. For all nodes except authors.
* @param node the category node
*/



function getCategoryTree(node){
  //get this node's li element and then print any underneath
  var n =  node.nodes ? -1 : node.count;
  //if (node.id == "66-1") alert("Is " + node.name + "checked?  " + node.checked)
  var s = (node.level == 1 ? "" : getBox(node.id, "Level"+node.level, node.id, fixName(node), node.checked, n))
  if (node.nodes) {
    for (var i = 0; i < node.nNodes; i++) 
      s += getCategoryTree(node.nodes[i])
  }
  return s;
}



/*
* Hides all subcategory divs in the category pane(in the center of the
* search page) except the one for the selected category. 
* The category being displayed has a green background.
* @param    n  the category number associated with the above div
*/
function DisplayCategory(n) {
  //Display just this one    
  //All category menu backgrounds are set to white except this one
  isOpen = (document.getElementById("SubCategory"+n).style.display == "block")
  document.getElementById("SubCategory"+n).innerHTML = getCategoryTree(TopConcepts[i])
  document.getElementById("SubCategory"+n).style.display = (isOpen ? "none" : "block")
  document.getElementById("CategoryImage"+n).src =  (isOpen ? BoxPlus.src : BoxMinus.src)
}

/**
* Given a subcategory node, toggles the check box at the beginning of the
* subcategory. Called from an onclick handler for a subcat item
*
* @param node subcategory node associated with the checkbox
*/

var isActive = true
function ToggleCheckBox(node) {
 //alert("search.js.ToggleCHeckbox:" + node.id)
  if (!isActive) return

  var checked = node.checked
  CheckAllNodesBelow(node, !checked)
  if (checked)UncheckAllParents(node)
  SetParentColor(node.parent)
  setCategoryAjaxInfo()
}

/**
* Checks this node's checkbox and checks to see if we need to check its parent
* @param SubCatID the DOM id of a subcategory node
*/

function CheckNode(node, TF, docheckbox){
  node.checked = TF
  if (docheckbox) {
	isActive = false
  	var d = document.getElementById("cb-" + node.id);
  	if(d)d.checked = TF
  	isActive = true
  }

/* doesn't work
  if (!TF)return
  //If no parent then we are done
  var parent = node.parent
  if (!parent) return

  for (i = 0; i < parent.nNodes; i++) {
  //If by checking this node all siblings become checked,
  //we must check the parent node
    if (!parent.nodes[i].checked) return;
  }
  //If we get here then all the siblings are checked 
  SwitchParent(parent.id,"IdToNode");
*/
       
}

/**
  * Checks all nodes below this one
  * @param SubCatID    the DOM id of a subcategory node
*/

function CheckAllNodesBelow(node, TF) {
  //Check this node and all nodes below it
  CheckNode(node, TF, true);    
  if (node.nodes)
    for (var i = 0; i < node.nNodes; i++) {
      CheckAllNodesBelow(node.nodes[i], TF)
      //alert(i+ ", " + node.nodes[i].checked)
    }
  else
    node.preview = TF
}

/**
* Unchecks a node's checkbox and all its parents up to the top
* @param node the subcategory node
*/
function UncheckAllParents(node) {
  CheckNode(node, false)
  if(node.parent)UncheckAllParents(node.parent)
}

/**
* Clear the Preview pane
*/
function ClearCats() {
  for (var i = 0; i < nTop; i++) CheckAllNodesBelow(TopConcepts[i], false)
  getAjaxInfo(1, -1)
}

/**
* Clear the Preview pane
*/
function ClearText() {
  document.SearchForm.FullTextSearchKeywords.focus()
  document.SearchForm.FullTextSearchKeywords.value = ""
  getAjaxInfo(2, -1)
}

function anyallClick() {
  setCategoryAjaxInfo()
}

function debug(s) {
  document.getElementById("TestDiv").innerHTML += "<pre>"+s+"</pre>"
}

function searchExists() {
		if (document.search_form.search_name.value =='') {
			alert('Please enter a name to save the search with.')
			return false
		} else {
			return true
		}
}

var resultInfo
var haveInfo = false

function showTips(TF) {
  if (TF && !haveInfo) {
    if (!haveInfo)resultInfo = document.getElementById("searchResults").innerHTML
    document.getElementById("searchResults").innerHTML = document.getElementById("instruction_div").innerHTML
    haveInfo = true
  } else {
    document.getElementById("searchResults").innerHTML = resultInfo
    haveInfo = false
  }
}


