// JavaScript Document


CategoryText ="";
CategoryIDs ="";
FullTextSearch ="";
nCatItems = -1 
nTextItems = -1

/*
* This function automates a search if presets are detected (without php help)
* (i.e. activating a saved search)
*/

function runSavedSearchCallback(responseText){
//  alert(responseText);
  try{
  
  innerHTML = eval(responseText);
  //alert("runsaved"+responseText)  
  eval(responseText);
//  alert(returnSearch.filter)
//  alert(returnSearch.search_text)
//  alert(returnSearch.and_or)
//  alert(returnSearch.new_cat_vals)
//  alert(returnSearch.principles)

  
  }
  catch(e){  alert(e+'; '+e.description)  }
  
  //adjust search text
  document.getElementById("search_text").value = returnSearch.search_text;
  //adjust and_or
  document.getElementById(returnSearch.and_or).checked = true;
  //deal with categories and principles
  recoverSearch(returnSearch.filter, returnSearch.new_cat_vals, returnSearch.principles); 
}

function recoverSearch(filter, catVals, prinVals){

  var isPrinciples = (filter != "categories")
  document.search_form.filter[0].checked = isPrinciples;
  document.search_form.filter[1].checked = !isPrinciples;
  clearCatNodes();
  clearAllOtherPrinciples(); 
    for (catID = 0; catID < catVals.length; catID++){
      //clear any previous check settings
	try{
		var node = IdToNode[catVals[catID]];
		if (node) {
			CheckNode(node, true, true);
			SetParentColor(node.parent, false)
		}
	} catch(e){
		alert(e.description)
	}
    }
    for (prinID = 0; prinID < prinVals.length; prinID++)
	if (prinVals[prinID]) {
      try{
		var n = eval(prinVals[prinID]);		
		var node = Principles[n];
		SwitchParent(n,"Principles")

	} catch(e){alert("error processing pinciple search " + prinVals + " " + e.description)}
	}
  setDisplay(filter);
  lastCall=""
  if (filter != "principles") 
    setCategoryAjaxInfo()

}

/*
* This function is called by the forms "onsubmit" event.
* It takes the current search categories that the user has selected, which are
* stored in Categories[], and copies them to form variables so that
* they can be passed out to the results page.
*/


function GetResults(ajaxMode, useO){
  if (!ajaxMode){
    ajaxMode = 0
    clearAjaxTimer()
  }
    var search = "";
    for (var i in Principles) {
      if (Principles[i].checked) {
        search += "&principle[]=" + Principles[i].id
      }
    }
    for (var i in Concepts) {
      var node = Concepts[i];
      var x = node.id.split("-",2);
      var childId = "" + x[1];
      node.parentId = "0-" + x[0];
      if ((Concepts[childId].nNodes == 0) && node.checked) {
        //we want [x]'ed children here only
        search += "&new_cat_vals[]="+node.id;
      }
    }
    return search
      + "&search_query=" + escape(document.search_form.search_query.value)
      + "&and_or=" + (document.getElementById("and").checked ? "and" : "or")
      + (useO? "&o=" + document.getElementById("o").value : "")
      + "&filter=" + (document.getElementById('radioCategories').checked ? "categories" : "principles");
}

lastCall = "";

function viewResults(useO) {
	//console.log("viewResults");
  var s = GetResults(1, useO)
  new hollerBack('GET','main.do?1=1','&module=ajax.ajax_get_results' + s         
         ,'searchResults','Loading...')
}

function saveSearchAjax(doOverwrite) {
  var searchName = document.search_form.search_name.value;
  var s = GetResults(1);
  new holler('GET','main.do?1=1','&module=ajax.ajax_search&search_name='+searchName+s+(doOverwrite ? "&overwrite=1":""),'saveSearchAjaxCallback(xmlhttp.responseText)');
}

function saveSearchAjaxCallback(responseText){
  var save_div = document.getElementById("save_div");
  if (responseText.indexOf("true") >= 0)
      str = "<span style='font-weight:bold'>Search saved!</span>"
  else if (responseText.indexOf("false") >= 0)
      str = "Your search could not be saved.  Please contact the administrator to report this problem.";
  else if (responseText.indexOf("non-unique") >= 0) {
      checkSaveOverwrite()
      return;
  }
  save_div.innerHTML = str;
  save_div.style.display = "block";
  setTimeout(function(){save_div.style.display = 'none';},3000);
  
}

function saveResourceCategoryCallback() {
  var responseText = xmlhttp.responseText;
  var S = responseText.split("|");
  if (S[0])
    document.getElementById("current_categories").innerHTML = S[0];
  document.getElementById("principlediv").innerHTML = S[1];

}

function checkSaveOverwrite() {
  var ok = prompt("Do you want to overwrite the search you have already saved under that name?", "yes");
  if (ok == "yes")saveSearchAjax(1)
  }
    
function setCategoryAjaxInfo() {
  var s = GetResults(1)
  if (s == lastCall) return;
  lastCall = s
  new holler('GET','main.do?1=1','&module=ajax.ajax_search' + s         
         ,"visDebug(xmlhttp.responseText)")
}

function setTextAjaxInfo(isDelayed) {
  if (isDelayed != 1) {
    setAjaxTimer("setTextAjaxInfo(1)", 500)
    return;
  }  
  //if (document.search_form.search_query.value.length > 2) {
    setCategoryAjaxInfo()
  //}
}

ajaxTimerID = 0
function clearAjaxTimer() {
  if (ajaxTimerID)clearTimeout(ajaxTimerID)
}

function setAjaxTimer(callback, ms) {
  clearAjaxTimer()
  ajaxTimerID = setTimeout(callback, ms)
}

function updatePrinciples() {
  var str = '';
  var form = document.upload_form.principles;  
  for (var i=0; i < form.length; i++) {
    if (form[i].checked){
      str += "&principles[]="+form[i].value;
    }
  }
  return str;
}

visDebugCategoryString = '';
visDebugPrincipleString = '';
CancelVisDebug = false;


function visDebug() {
/********************check if changes to string are necessary********************/
  if (arguments.length == 0) {
    if (document.getElementById('radioCategories').checked){
      document.getElementById('searchResults').innerHTML = visDebugCategoryString;
      return;
    }
    else {
      document.getElementById('searchResults').innerHTML = visDebugPrincipleString;
      return;
    }
  }
  if (CancelVisDebug) {
    CancelVisDebug = false; 
    return;
  }
 //alert("here in visDebug" + arguments[0])
  if(arguments[0].indexOf("alert(")==0){
	alert("visDebug message:" + arguments[0])
	eval(arguments[0]);
  }

  var args = arguments[0].split("| ");
  var names = new Array();
  names.parents = new Array();
  str = '<div class="SearchReqDiv">\n';
/**********************text suggestions*********************
  if (args.length > 1){
    str += '<ul class="ulnobullet"><p>Similar Searches<p>\n';
    for (var j=1; j<args.length; j++){
      str += '<li class="linobullet">' + parseQ(args[j]) + '</li>\n';
    }
    str += '\n</ul>'
  }
  else {
    //str += "<li class='linobullet'>No suggestions for search text found.</li>\n</ul>"; 
  }
/********************number of results displayed*******************/
  var n = parseInt("" + args[0])
  str = "<div style='text-align:center'><span style='color:#0066CC; text-align:center; font-size:16px; font-weight:bold'>";
  if (isNaN(n)) {
    str += "result: " + args[0]
  } else {
   switch(n) {
    case 0:  str += "No match" + (document.getElementById('radioCategories').checked ? " -- Are you using 'and' instead of 'or'?" : "")
      break
    case 1:  str += "There is 1 match for your search.  <p><a href='javascript:viewResults()'>view</a></p>" 
      break
    case 100:  str += "There are at least 100 matches for your search." 
      break
    default:  str += "There are " + n + " matches for your search.  <p><a href='javascript:viewResults()'>view</a></p>" 
      break
   }
  }
  str += '</span></div>\n<br>';
/**************************search text***************************/
  str += (document.search_form.search_query.value? "Searching for the text: \n<p><span id='SearchText'>" + parseQ(document.search_form.search_query.value) + "</span></p>\n" : "")
  if (document.getElementById('radioCategories').checked) {
/**************************loop through concepts*******************************/
    for (var i in Concepts) {
      var node = Concepts[i]    
      var x = node.id.split("-",2);
      var childId = "" + x[1];
      node.parentId = "0-" + x[0];
      if ((Concepts[childId].nNodes == 0) && node.checked) {
        //we want [x]'ed children here only
        //now organize into parents
        if (!names.parents[node.parentId]) {
          names.values = true;
          var parent = names.parents[node.parentId] = IdToNode[node.parentId];
          parent.numNodes = 0
          parent.children = new Array();
        }
        parent.children[parent.numNodes++] = node.name;
      }
    }
/*********************evaluate concepts***********************/
    if (names.values) {
      str += "Searching for articles concerning:  <br>\n";
      for (var i in names.parents) {
        str += '<table width="100%" style="text-align:center"><tr><th>' + names.parents[i].name + '</th></tr>\n';
        if (names.parents[i].children.length == Concepts[names.parents[i].id.slice(2)].nNodes) {
          str += '<tr><td style="font-size:xx-small">\nAll subcategories selected. <br> Click <img src="img/plus2.gif"> to select from a list of subcategories.\n</td></tr></table>';
        }
        else {
          str += '<tr><td style="font-size:xx-small">For the specific categories of:</td></tr>\n';
          str += "<div class='CatList'>\n<tr><td>" + names.parents[i].children.join("</tr></td>\n<tr><td>") + '</td></tr>\n</div>';
          str += '</table>\n';
        }
        str += '<div class="Conjunction" style=' + (document.getElementById('and').checked ? 'color:red">AND':'color:blue">OR') + '</div>';
      }
      //take out the last and/or:
      str = str.replace(/(AND|OR)<\/div>$/,'</div>\n');
    }
    else str += "With no filters... <br> Filter your search by selecting groups from the left.";
    str += '</div>';
    document.getElementById('searchResults').innerHTML = visDebugCategoryString = str;
  }
  else {  //principles
/*******************loop through principles**********************/
    for (var i=1; i<Principles.length; i++) {
      if (Principles[i].checked){
        names = Principles[i]
        //names.push(Principles[i].title);
      }
    }
    //conjunction = '</td></tr><td><tr><span class="Conjunction" style="'+(document.getElementById('and').checked ? 'color:red">AND</span>':'color:blue">OR</span>');  
    if (names.id != undefined) {
      str += 'Searching for resources that deal with:  <br>\n';
      str += '<table width="100%" style="text-align:center;"><tr><td>';
      str += '<span style="color:darkgreen;font-weight:bold">Green Chemistry Principle '+names.id+":  "+names.title;
      //str += names.join('</td></tr><td><tr>');
      str += '</span></td></tr></table>';
    }
    else {
      str += 'With no filters... <br> Filter your search by selecting groups from the left.'
    }
    document.getElementById('searchResults').innerHTML = visDebugPrincipleString = str;
  }
  //alert(str)
}


function parseQ(str) {
  str = str.replace(/</g, '&lt;span style="color:red"&gt;\<&lt;/span&gt;');
  str = str.replace(/>/g, '&lt;span style=&quot;color:red&quot;&gt;\>&lt;/span&gt;');
  str = replaceQuotes(str);
  str = str.replace(/&lt;/g, '\<');
  str = str.replace(/&gt;/g, '\>');
  str = str.replace(/&quot;/g,'"');
//  alert('||'+str+'||');
  str = str.replace(/\*/g, '<span style="color:red">*</span>');
  str = str.replace(/\+/g, '<span style="color:red">+</span>');
  str = str.replace(/-/g, '<span style="color:red">-</span>');
  str = str.replace(/~/g, '<span style="color:red">~</span>');
  str = str.replace(/\(/g, '<span style="color:red">(</span>');
  str = str.replace(/\)/g, '<span style="color:red">)</span>');
  str = str.replace(/\'/g, '<span style="color:red">\'</span>');
  return str;
}

function replaceQuotes(str){
  if (str) {
    var a = str.match(/"([^"]*)"/g);
    if (a != null) {
      for (var i=0; i < a.length; i++){
        if (a[i] = '"color:red"') continue;
        str = str.replace(a[i], '<span style="color:green">'+a[i]+'</span>');
      }
    }
  }
  return str;
}

    var mouse_x_pos;
	  var mouse_y_pos;
	  var mouse_clientx;
	  var mouse_clienty;
		var window_height;
		var window_width;
		var div_y_pos;
		var div_x_pos;
		var div_height;
		var div_width;

function displayChemical(casno, chemName, evt) {
  getCoordinates(evt);
  new hollerBack('GET','ajax.do?1=1','&module=ajax.ajax_display_chemical&casno=' + casno+'&chemName='+chemName
         ,null,'',displayCallback);         		
}

function showQuestions(num) {
  new hollerBack('GET','ajax.do?1=1','&module=ajax.ajax_display_principle&pid='+num,'search_results','',showQuestionsCallback);
}

function displayQuestions(num, evt){
  getCoordinates(evt);
  new hollerBack('GET','ajax.do?1=1','&module=ajax.ajax_display_principle&pid='+num,'search_results','',displayCallback);
}

function getCoordinates(evt) {

  var scrollTop = window.pageYOffset || document.documentElement.scrollTop || 0

  mouse_x_pos = (evt.pageX ? evt.pageX : document.body.scrollLeft+evt.clientX);
  mouse_y_pos = (evt.pageY ? evt.pageY : scrollTop+evt.clientY);


	mouse_clientx =(document.body.scrollLeft? mouse_x_pos - document.body.scrollLeft : evt.clientX);
	mouse_clienty =(scrollTop? mouse_y_pos - scrollTop : evt.clientY);  
//  Safari: clientY is not dependable.

}

/********************chemical popup stuff*********************/

function fixDivPosition(d) {

	// see http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

	div_height = d.offsetHeight;
	div_width = d.offsetWidth;

	window_width = (window.innerWidth ? window.innerWidth : document.body.clientWidth);

	if (window.innerHeight) {
		window_height = window.innerHeight
	} else if (document.documentElement && document.documentElement.clientHeight) {
		// IE 6 strict
		window_height = document.documentElement.clientHeight
	} else {
		window_height = document.body.clientHeight
	}

	div_x_pos = (window_width < mouse_clientx+div_width ?
		mouse_x_pos - mouse_clientx - div_width + window_width-20 : mouse_x_pos+10);
	div_y_pos = (window_height < mouse_clienty+div_height ?
		mouse_y_pos - mouse_clienty - div_height + window_height-20 :	mouse_y_pos+10);
	d.style.left = div_x_pos+"px";
	d.style.top = div_y_pos+"px";
	d.style.opacity = 0;
	d.style.visibility = 'visible';

	var i = 0;
	var oChange = setInterval(
		function(){
			if (d.style.opacity >= 1) {
        			d.style.opacity = 1;
			}else{
				d.style.opacity = i;
				i = i + .1;
			}
		}, 25)
	var timer = setTimeout(function(){clearInterval(oChange);}, 400)
}

function killOpacity(d){
  var num = 1;
  var oKill = setInterval(
    function(){
      if (d.style.opacity <= 0) {
        d.style.opacity = 0;
      }
      else{
        d.style.opacity = num;
        num = num - .1;
      }
    }
  ,25);
  var timer = setTimeout(
    function(){
      d.style.visibility = 'hidden';
      clearInterval(oKill);;    
    }
  ,400);
}

function displayCallback(message) {
  //incoming div should have id 'div0'
  var d = document.getElementById('div0');
  d.innerHTML = message;
  fixDivPosition(d);
}

function showQuestionsCallback(message){
  var d = document.getElementById('searchResults');
  d.style.display = "block";
  d.innerHTML = message;
}



