/*
# Copyright (c) 2007 New York University 
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or 
# without modification, are permitted for nonprofit educational 
# purposes provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above 
#    copyright notice, this list of conditions and the following 
#    disclaimer. 
# 2. Redistributions in binary form must reproduce the above 
#    copyright notice, this list of conditions and the following 
#    disclaimer in the documentation and/or other materials 
#    provided with the distribution. 
# 3. All advertising materials mentioning features or use of 
#    this software must display the following acknowledgement: 
#    This product includes software developed by New York 
#    University and its contributors. 
# 4. Neither the name of the University nor the names of its 
#    contributors may be used to endorse or promote products 
#    derived from this software without specific prior written 
#    permission.
# 5. This software is not used nor made available for use as 
#    part of a for-profit service without specific prior written 
#    permission.
#
# THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS 
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
# BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
# AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO 
# EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE
#
###############################################################################
# $Id$
###############################################################################
*/

/*
Function used by the static Finding Aid index page to
pre-select a collection based on a parameter in the URI
For example, dlib.nyu.edu/findingaids?collectionId:fales
*/
function checkSelects(divID){
var div = document.getElementById(divID);
var opt, opts = div.getElementsByTagName('option');
for (var i=0, len=opts.length; i<len; i++){
	opt = opts[i];

	if (opt.value == gup('collectionId')) {
		opt.selected = true;
	}
	

}
}

//Collection Names
var cArray = new Array();
		cArray['fales'] = "The Fales Library";
		cArray['archives'] = "New York University Archives";
		cArray['tamwag'] = "The Tamiment Library";
		cArray['nyhs'] = "New-York Historical Society";
		cArray['all'] = "all";





//whitespace stripper
String.prototype.normalise = function() {
return this.replace(/^\s+|\s+$/g, '').replace(/\s{2,}/g, ' ');
};

//Function for grabbing params from the URL
//http://www.netlobo.com/url_query_string_javascript.html

function gup( name )
{
 name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
 var regexS = "[\\?&]"+name+"=([^&#]*)";
 var regex = new RegExp( regexS );
 var results = regex.exec( window.location.href );
 if( results == null )
   return "";
 else
   return results[1];
}


function validateSearchStr(obj,divName){
	var validStr = /^[\w\s\"]+\*?$/i;
	var valid = true;
	var qValue = document.getElementById(divName).q.value;
    var match = validStr.test(qValue);
    if (qValue.length == 0){
		alert("Please enter a search term");
		valid = false;
	}
    else if (!validStr.test(qValue)){
        alert("Invalid search string. Please enter an alphanumeric search string");
        valid = false;
    }
	else if (qValue.match(/^\"/)){
		var quoteMatch = /^\"[\w\s]+\*?\"$/;
		if (!quoteMatch.test(qValue)){
			alert("Please enter phrase between quotes");
			valid = false;
		}
   }
	if (valid == true && obj == 'submitBtn'){
   		document.getElementById(divName).submit();
	}
	return valid;
}



function showCollId(htmlId,coll){
   for(var i in cArray){
if (i == coll){
	htmlId.innerHTML += cArray[i];
}
   }
}

//whitespace stripper
String.prototype.normalise = function() {
	return this.replace(/^\s+|\s+$/g, '').replace(/\s{2,}/g, ' ');
};


//escaped quotes stripper
String.prototype.stripEscapedQuotes = function() {
	return this.replace(/%22/g, '');
}

//array data type checker
function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function expandQuery(paramAndValue) {
		var nixedInputTag = document.getElementById(paramAndValue);
		try {
			nixedInputTag.parentNode.removeChild(nixedInputTag); // strange but this is how it seems to be done
		} catch (e) {
			nixedInputTag.value = ""; //an alterantive in case that doesn't work, try everything else		    
			document.getElementById('simpleSearchForm').removeChild(nixedInputTag);
		}

		reQuery('0');
}


//event: user clicks a facet link; param and value are pushed to 


function refineQuery(param, value) {
		var paramAndValue = param + ":" + '\"' + value + '\"';
		var newInputTag;
		try {
			newInputTag = document.createElement("<input type='hidden' name='accesspt' />");
		} catch (e) {
			newInputTag = document.createElement("input");			
		    newInputTag.setAttribute("name", "accesspt");
		    
		}
		newInputTag.setAttribute("value", paramAndValue);
		newInputTag.setAttribute("type", "hidden");
		document.getElementById('simpleSearchForm').appendChild(newInputTag);
		reQuery('0');
}


function reQuery(start){
	document.getElementById('startID').value=start;
	document.getElementById('simpleSearchForm').submit();
}

// AJAX Functions (Searching inside a findind aid)

function showResults(docId){
         var resultID = docId + 'getEadResults';
         var resultHeader = document.getElementById(resultID).innerHTML;
	  var result = docId + "IntraSearchResults";
	  if (resultHeader.match("Show")) {
	     document.getElementById(result).style.display = 'block';
	  document.getElementById(resultID).innerHTML = "Hide Occurrences";  
	 }
         else if(resultHeader.match("Hide")){
	  document.getElementById(resultID).innerHTML = "Show Occurrences";  
	  document.getElementById(result).style.display = 'none';
	}
} 


function load(divID,searchTerm,docID){
	//docID is comma separated list of ids
    var coll = "";
    var htmlID = "";
    checkSelects(divID);

    if (gup('collectionId').length > 0){
       coll = gup('collectionId');
       htmlID = document.getElementById("searchHeading");
       htmlID.innerHTML += ": ";
       showCollId(htmlID,coll);
    }

    var getEachDocId = docID.split(",");
    srchURL="?";
    for(i=0; i < getEachDocId.length; i++){
       var singleDocId = getEachDocId[i];
		if (singleDocId.length < 1) return; //this is a fix - it was going one iteration even when there are no results
       if (!(gup('collectionId').length > 0)){
          var regex = /(.*?)\_.*/;
          var match = singleDocId.match(regex);
		  coll = RegExp.$1;
          htmlID = document.getElementById("showColl"+singleDocId);
      showCollId(htmlID,coll);
       } 

    	query(srchURL,singleDocId,searchTerm);
    }

}

function query(strURL, docId,query) {

		if (query == 'id:[* TO *]') return; //Don't do an inner EAD search if the key 'id:[* TO *]' is used 
		//dynamically naming object to have one for each docId
		window['xquery_' + docId] = false;
	    if (window.XMLHttpRequest) { // Mozilla/Safari
	        window['xquery_' + docId] = new XMLHttpRequest(); 
	    }
	    else if (window.ActiveXObject) { // IE
	        window['xquery_' + docId] = new ActiveXObject("Microsoft.XMLHTTP");
	    }

	    window['xquery_' + docId].open('POST', strURL, true);
	    window['xquery_' + docId].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    window['xquery_' + docId].onreadystatechange = function() {

	        if (window['xquery_' + docId].readyState == 4) {

	            updatepage(window['xquery_' + docId].responseText, docId);
	        }
	    }

	    var params = getquerystring(docId,query);
	    var strData = params;
	    window['xquery_' + docId].send(strData);
	}

	function getquerystring(docId,query) {
	  qstr = 'q=' + escape(query);
	  qstr += '&fq=collectionId:' + docId;
	  qstr += '&mode=intra';
	  return qstr;
	}

	function updatepage(str, docId){
	  var result = docId + "IntraSearchResults";
      var resultID = docId + 'getEadResults';
	  var bio = document.getElementById(docId+"_bioghist");
	  var scope = document.getElementById(docId+"_description.scopecontent");
	  var bioVal = "";
	  var scopeVal = "";
	  var bioURI = "";
	  var scopeURI = "";
	  var htmlBio = "";
	  var htmlScope = "";
	  var html="";
	  if (bio){
	  bioURI = document.getElementById(docId+"_bioghistURI").innerHTML;
	  bioVal = bio.innerHTML;
	  bioVal = highlightStr(bioVal);
	  htmlBio= "<div class=\"solr1\"><span class=\"heading\"><a href=\""+bioURI+"\">Biographical Information</a></span>" + bioVal +"...</div><p/>";
	  }
	  if (scope){
	  scopeURI = document.getElementById(docId+"_scopecontentURI").innerHTML;
	  scopeVal = scope.innerHTML;
	  scopeVal = highlightStr(scopeVal);
	  htmlScope  = "<div class=\"solr1\"><span class=\"heading\"><a href=\""+scopeURI+"\">Scope information</a></span>" + scopeVal + "...</div><p/>"; 
	 }
	

	var containerBlock = false;
	
	  try {
	  	var rsp = eval("("+str+")"); // use eval to parse Solr's JSON response
		if (rsp.response.numFound > 0) {
		var containerBlock = true;
		} 
	  } catch(e) {
	  }
	
	if ((containerBlock == true) || (scope) || (bio)){
		document.getElementById(resultID).innerHTML='Show Occurrences';
	 	document.getElementById(resultID).style.display='block';
	}
		
	if (containerBlock == true) {
	  	var results = rsp.response.docs;
	  	var highlight = rsp.highlighting;
  		var containerURI = document.getElementById(docId+"_containerURI").innerHTML;
  		html = "<span class=\"heading\"><a href=\""+containerURI+"\">Container Information</a></span>";
      	for(var i=0; i < results.length; i++){
          	var id = results[i].id;
          	var title = highlight[id].title;
	  		if (results[i].container){
				//using regular expressions, don't know what the name of container is
				var container = results[i].container.toString();
				//could have just one container
				var matchContStr = /(.*?)\:(.*)/;
				var match = container.match(matchContStr);
				//label, i.e. box
				var cont1Lbl = RegExp.$1;
				//rest of the string, 3,folder:2 or just 3
				var restStr = RegExp.$2;
				var cont1Num = "";
				//check to see if there is a sub container
				var chkCont2Str = /(.*?)\,(.*?)\:(.*)/;
				var chkCont2 = chkCont2Str.test(restStr);
				//if there is
				if (chkCont2){
				   //grab cont1 num and the rest of the string
				   cont1Num = RegExp.$1;
				   var cont2Lbl = RegExp.$2;
				   var cont2Num = RegExp.$3;
				}
				else{
				    cont1Num = restStr;
				}
				var firstLetter = cont1Lbl.substring(0,1);
				firstLetter = firstLetter.toUpperCase();
				var restLbl = cont1Lbl.substring(1,cont1Lbl.length);
				cont1Lbl = firstLetter+restLbl;
				html += "<p id=\"containerInfo\"><a target=\"_blank\" href=\""+ results[i].uri +"\">"+ cont1Lbl + " " + cont1Num;
				if (cont2Lbl && cont2Num != " "){
					html +=  ", " + cont2Lbl + " " +cont2Num +  "</a>";
				}
				else if (cont1Num && (!(cont2Num) || (cont2Num = " "))){
					html +=  "</a>";
				}
				else if (cont2Num && !(cont1Num)){
					html += cont2Lbl + " " + cont2Num  + "</a>";
				}
		        html += "<br/><span id=\"containerTitle\" class=\"highlights\">"+ title + "</span></p>";
		    }
          }
	  	document.getElementById(result).innerHTML = htmlBio + htmlScope + html;
  		} else {
			document.getElementById(result).innerHTML = htmlBio + htmlScope;
		return;
	}
}


        function highlightStr(string){
	       	var chkStr = /&lt;em&gt;(.*?)&lt;\/em&gt;/;
		//splitting up string so that search terms can be formatted
		var str = string.split(" ");
		var html = "";
		//iterating through string array. If string array value matches
		//search term, format search term
		for(i=0; i < str.length; i++){
		  var testStr = str[i].toString();
		  if (chkStr.exec(testStr)) {
			//strip out tags
		        var getStr = testStr.replace(chkStr,"$1");	
			matchStr = "<span id=\"lineInfo\" class=\"highlights\">" + getStr +"</span>";
			html += matchStr+" ";
		  }
		  else{
			html += str[i]+" ";
		  }
		}
	return html;
	}



