﻿// JScript File


//Declare Global variable for max number of results to display
  var ShowMaxResults = 20;
 

function GetSearchType()
{
    var SearchType;
    
    switch(document.getElementById('lstLimit').options[document.getElementById('lstLimit').selectedIndex].value)
    {
        case ".gw":
            SearchType= " a keyword search of ";
            break;
    
        case ".tw":
            SearchType= " a title search of ";
            break;
        
        case ".aw":
            SearchType= " an author search for ";
            break;
       
        case ".sw":
            SearchType= " a subject search on ";
            break;
            
         case "isbne":
            SearchType= " an ISBN search of ";
            break;
    }
    
    return SearchType
}

function SearchBooks(zone, search, limit, PageNo)
{
    //PURPOSE : to search the union catalog for the results from the home library's search term, limit, and return it to the user
    //VARIABLES :   search = the search term entered by the user
    //              limit = the limit selected by the user (keyword, title, author, etc)
    //              page = the page number the user wants to view
    
    
    
    //Spell Check For Search String
    if(document.getElementById("SpellCheck").value == "false")
    {
        SpellCheck(search)
    
        //set the value to true so we don't recheck spelling for additional 
        //result loads
        document.getElementById("SpellCheck").value = "true";
    }
    
    
    
    //display the searching image
    
    var strLoading;
    
    if (zone == 1)
    {
        strLoading = "<span class='SearchingLabel'>Searching Cal State Fullerton For : " + search +"</span><br/>"
    }
    
    if (zone == 2)
    {
        strLoading = "<span class='SearchingLabel'>Searching All CSU Libraries For : " + search +"</span><br/>"
    }
    
    if(zone < 3) //You are searching Fullerton or All CSU libraries
    {
         
         if(PageNo == 1)
           { 
             document.getElementById('divStatusMessages').style.display = "block";
             document.getElementById('StatusMessage').innerHTML = "<div class='loading'>" + strLoading + "<img src='images/searching.gif' alt='Searching...' /></div>";
             document.getElementById('divWelcomeInfo').style.display="none";
            }else
            {
                //hide the search bar
                document.getElementById('divStatusMessages').style.display = "none";
                document.getElementById('divWelcomeInfo').style.display="none";
           
            }
    
    
            //create the URL for getting data from the union catalog
      //      var profile = 'cfi'; // your OCLC symbol -- default is Fullerton's
      //        var serverloc = 'processor.aspx?TheURL='; 
    
           var XMLURL = "processor.aspx?search=" + search + "&PageNo=" + PageNo + "&limit=" + limit + "&zone=" + zone
   
            //display the right results window
            document.getElementById('divResults').style.display = "block";
    
            //document.getElementById('WelcomeInfo').style.display = "none";
    
            //alert(XMLURL);
   
            //go fetch the data for the right page
            if(parseInt(PageNo) == 1)
            {
                getMultiSearchData(XMLURL, zone) 
            }
            else
            {
               getMultiSearchData_NPage(XMLURL, zone)
            }
        }
     
   else
   {
        // user wants to search world cat
        window.open("http://worldcatlibraries.org/search?qt=worldcat_org&q=" + document.getElementById('txtSearch').value +" &submit=Search&loc=92834");
                        
   }   
}


function SpellCheck(search)
{
    
    //Run the search string through the Yahoo! spell check API
    var XMLURL = "processor.aspx?spellcheck=" + search 
   
    getData(XMLURL, "SpellCheck", "SpellCheck")

}

function ShowSpelling(strData)
{
    //gets the results from the spell check data 
    //we need to display to the user
    document.getElementById("divSpelling").innerHTML = strData;
    
}

function getMultiSearchData(datasource, zone)
{
   //PURPOSE: Calls getData to do the search transaction and tells it that the user wants
   //         to perform a multi search request
   
   
   document.getElementById('StatusText').innerHTML = "Searching..."
  // alert("getMultiSearchData");
   getData(datasource, 'Multi', zone)
  
}

function getMultiSearchData_NPage(datasource, zone)
{
   //PURPOSE: Calls getData to do the search transaction and tells it that the user wants
   //         to perform a multi search request
   
   
   document.getElementById('StatusText').innerHTML = "Fetching next result set..."
   //alert("getMultiSearchData_NPage");
   getData(datasource, 'Multi_NPage', zone)
  
}

function ProcessMultiResults(strData, zone)
{
    //PURPOSE: display the multi search results and start to process the holdings data
    
    document.getElementById('StatusText').innerHTML = "Processing holdings information...";
   // break out the results from the data
   var ResultsArray = strData.split("||**");
   var ResultsPagesArray = ResultsArray[0].split("|");
   document.getElementById('txtResults').value = ResultsPagesArray[0]
   
   
   //check to see if this is the first time they used the search the max results will be 0
   //should be in this function but ProcessMultiResults_NPage won't necessarily be the case
    if(ResultsArray[0].charAt(1) == "h")
    {
        document.getElementById('divResults').innerHTML  = ResultsArray[0];
     } else
     {
        
     
    if(parseInt(ResultsPagesArray[0]) == 0)
    {
        var strNoResults = "";
        var strSpelling = document.getElementById('divSpelling').innerHTML;
        
        strNoResults = "<div id='divNoResults' style='position:absolute; top:20px; width:550px; left:40px;'><fieldset class='Part'><legend> No Results Found </legend><div style='padding:5px;'>";
        strNoResults = strNoResults + "<p>We were unable to locate any results based on your current search.<br/><br/><b><font size='4'> You tried " + GetSearchType() + ":</font> <font size='5' color='#098bc3'>" + document.getElementById('txtSearch').value + "</font></b>.</p>" ;
        if(strSpelling != '')
        {
            strNoResults = strNoResults + "<p><h2>" + strSpelling + "</h2></p>";
        }
        strNoResults = strNoResults + "<p>Below we have identified some ways you can improve your search:<br/>"  ;
        strNoResults = strNoResults + "<p><table><tr><th>Try Using</th><th>Example</th></tr>"  ;
        strNoResults = strNoResults + "<tr><td style='width:200px; padding-bottom:5px; border-bottom:dotted 1px #444444;' valign='top'><b>fewer search terms</td><td style='padding-bottom:5px; border-bottom:dotted 1px #444444;'><em>global warming and pollution</em>, <b>instead of</b><br/> <em>the effects of pollution on global warming</em></td></tr>"  ;
        strNoResults = strNoResults + "<tr><td style='width:200px; padding-bottom:5px; border-bottom:dotted 1px #444444;' valign='top'><b>the signular instead of plural</td><td style='padding-bottom:5px; border-bottom:dotted 1px #444444;'><em>garden</em>, <b>instead of</b> <em>gardens</em></td></tr>"  ;
        strNoResults = strNoResults + "<tr><td style='width:200px; padding-bottom:5px; border-bottom:dotted 1px #444444;' valign='top'><b>broader terms</td><td style='padding-bottom:5px; border-bottom:dotted 1px #444444;'><em>earthquakes</em>, <b>instead of</b> <em>techtonic earthquakes</em></td></tr>"  ;
        strNoResults = strNoResults + "</table></p><p> Or<p>"  ;
        if(getQueryVariable('zone') < 2)
        {
            //try to expand your search to all csu libraries
            strNoResults = strNoResults + "<p><img src='images/expandarrow.jpg' alt='Expand your search' /> Expand your search to <a href='javascript:ExpandSearch(2)'>books at all CSU libraries</a>.</p>";
        }
        
         if(getQueryVariable('zone') < 3)
        {
            //try to expand your search to all csu libraries
            strNoResults = strNoResults + "<p><img src='images/expandarrow.jpg' alt='Expand your search' /> Expand your search to <a href='javascript:ExpandSearch(3)'>libraries worldwide</a>.</p>";
        }
       
        strNoResults = strNoResults + "</p></div></fieldset></div>";
        
        document.getElementById('divResults').innerHTML = strNoResults;
        document.getElementById('StatusText').innerHTML = "No Results Found";
    }else
    {   
        //There are results
        
        document.getElementById('ResultsActivites').style.visibility = 'visible';
        if(ResultsPagesArray[0] == '')
        {
            //The result came back with a single result
            document.getElementById('txtResults').value = 1;
            
            //set the max results to found results
            document.getElementById('txtMaxResults').value = 1;
            
            // set the shown results to be the whole set
            document.getElementById('txtShowResults').value = 1;
        }
        else
        {
        
        if(parseInt(ResultsPagesArray[0]) <= 10)
        { //set the max results to found results
            document.getElementById('txtMaxResults').value = ResultsPagesArray[0];
            // set the shown results to be the whole set
            document.getElementById('txtShowResults').value = ResultsPagesArray[0];
        }else
        {
            // set the shown results to be the first 10
            document.getElementById('txtShowResults').value = 10;
            
            if(parseInt(ResultsPagesArray[0]) <= ShowMaxResults)
            {
                //set the max results to ShowMaxResults
                document.getElementById('txtMaxResults').value = ResultsPagesArray[0];
            }else
            {
             document.getElementById('txtMaxResults').value = ShowMaxResults;
            }      
        }
        
   }
   
        //put the page count to the first page
        document.getElementById('txtCurrentPage').value = 1;
   
   
        document.getElementById('ResultsText').innerHTML = "Found " + ResultsPagesArray[0] + " items<br/>Formatting Results For Page 1";
   
        //display the results for the search minus the results data
        document.getElementById('divResults').innerHTML = ResultsArray[1];


        //start to process the search data
        var ProcessArray = ResultsArray[1].split("|*||");
        document.getElementById('StatusText').innerHTML = "Fetching holdings information..."
   
        //alert(ProcessArray[1]);
        for( var i = 1; i<= ProcessArray.length-1; i = i + 2)
        {
        
                var ItemArray = ProcessArray[i].split("*-*");
                var elementID = ItemArray[3];
  
                var strHoldings;
                var XMLURL = "processor.aspx?GetHoldings=1&Bib=" + ItemArray[1] + "&Zone=" + zone;
   
                strHoldings = getData(XMLURL, 'Holdings', elementID)
                document.getElementById('StatusText').innerHTML = "Loading holdings information";
        }    
    
        document.getElementById('StatusText').innerHTML = "Pulling next result set";
        //load the next set of results for future use
        if(parseInt(document.getElementById('txtShowResults').value) < parseInt(document.getElementById('txtResults').value) )
        {var nextpage = 2;       
         ShowPage(nextpage)
        }
    } // Results = 0
  }
}


function ProcessMultiResults_NPage(strData, zone)
{
    //PURPOSE: display the multi search results and start to process the holdings data
    
    //Variables:    strData = has the multi search results data
    //              zone = tells you where you are searching, CSUF / UNION CATALOG 
    
    
    document.getElementById('StatusText').innerHTML = "Adding next result set...";
   
    // break out the results from the data
    var ResultsArray = strData.split("||**");
    var ResultsPagesArray = ResultsArray[0].split("|");
    //   document.getElementById('txtResults').value = ResultsPagesArray[0]
    //   document.getElementById('ResultsText').innerHTML = "Found " + ResultsPagesArray[0] + " items<br/>Now Showing Page " + ResultsPagesArray[1];
   
    //add another count to the shown results count
    if(parseInt(document.getElementById('txtResults').value) > (parseInt(document.getElementById('txtShowResults').value) + 10))
    {
        //adding another 10 records to the results list
        document.getElementById('txtShowResults').value = parseInt(document.getElementById('txtShowResults').value) + 10;
    }
    else
    {
        document.getElementById('txtShowResults').value = document.getElementById('txtResults').value;
        document.getElementById('divShowMore').innerHTML = "";
        
    }
    
   
    //put the page count to the first page
    document.getElementById('txtCurrentPage').value = parseInt(document.getElementById('txtCurrentPage').value) + 1;
   
   
    //display the results for the search minus the results data
    document.getElementById('divResults').innerHTML = document.getElementById('divResults').innerHTML + ResultsArray[1];

    //start to process the search data
    var ProcessArray = ResultsArray[1].split("|*||");
    document.getElementById('StatusText').innerHTML = "Parsing holdings information..."
   
    //alert(ProcessArray[1]);
    for( var i = 1; i<= ProcessArray.length-1; i = i + 2)
    {
        
        var ItemArray = ProcessArray[i].split("*-*");
        var elementID = ItemArray[3];
  
        var strHoldings;
        var XMLURL = "processor.aspx?GetHoldings=1&Bib=" + ItemArray[1] + "&Zone=" + zone;
   
        strHoldings = getData(XMLURL, 'Holdings', elementID)
        document.getElementById('StatusText').innerHTML = "Loading holdings information";
    }      
    
    //If you have more results to display and haven't reached the max number to display then go ahead and show the page
    if(parseInt(document.getElementById('txtShowResults').value) < parseInt(document.getElementById('txtResults').value))
    {
        if(parseInt(document.getElementById('txtCurrentPage').value) < (parseInt(document.getElementById('txtMaxResults').value) / 10)) 
        {
            //There are still more results that can be shown
            var nextpage = parseInt(document.getElementById('txtCurrentPage').value) + 1;
                 ShowPage(nextpage)
        }else
        {
            //The user has reached their max number of results and we wait for them to tell us more or not.
            document.getElementById('StatusText').innerHTML = "Ready to search.";
   
        }
    }
   
}

function ShowHoldings(strData, ElementID)
{
        //Purpose: After getting the holdings information this function replaces the div place holder with the graphic with the actual holdings text
        
        //Variables:    strData = the string data that is produced from the xml/xsl results for the holdings data
        //              ElementID = the div tag id to replace the data
        
       document.getElementById(ElementID).innerHTML = strData;
      
        //check to see if the current results set is the better
        if(document.getElementById('txtMaxResults').value == document.getElementById('txtShowResults').value)
        { //finished showing the current max set of results
            document.getElementById('StatusText').innerHTML = "Finished loading " + document.getElementById('txtShowResults').value + " of " + document.getElementById('txtResults').value 
                  document.getElementById('divShowMore').innerHTML = "<br/><font size='4'>" + document.getElementById('StatusText').innerHTML + "</font><br/><br/>";
          
            //determine if there should be another set available to show, if so display the link to activate the function
            if(parseInt(document.getElementById('txtResults').value) > parseInt(document.getElementById('txtMaxResults').value))
            {
                document.getElementById('StatusText').innerHTML = document.getElementById('StatusText').innerHTML + "<br/><a href='javascript:ShowMore()'>Want To View More >></a>";
                document.getElementById('divShowMore').innerHTML = "<br/><font size='4'>" + document.getElementById('StatusText').innerHTML + "</font><br/><br/>";
            }
        }
}


function ShowMore()
{
    //Purpose: to increase the max number or results the user sees displayed.  This function will increase it by 50 or to the total number of results

     document.getElementById('divShowMore').innerHTML = "<font size='4'>Fetching next set of results...</font><br/><br/>";
    

    if(parseInt(document.getElementById('txtResults').value) > parseInt(document.getElementById('txtMaxResults').value))
    {
        //there are more results to show
        if((parseInt(document.getElementById('txtResults').value) - parseInt(document.getElementById('txtMaxResults').value)) < ShowMaxResults)
        {
            //There are less than 50 more results to show, we are just going to show the rest
            document.getElementById('txtMaxResults').value = document.getElementById('txtResults').value;
        }else
        {
            //We are going to add another 50 to the max number of results
            document.getElementById('txtMaxResults').value = parseInt(document.getElementById('txtMaxResults').value) + ShowMaxResults;
        }
        
        //go ahead and load the next set of results
          var nextpage = parseInt(document.getElementById('txtCurrentPage').value) + 1;       
            ShowPage(nextpage)
    }
}

function getData(datasource, ProcessType, ElementID)
{
   //PURPOSE: Calls the back end server page which processes the request and then pushes it into the page
   //PARAMETERS: datasource = url that contains the means to get the data you want
   //            ProcessType = where you deliver the data after it completes the fetching
   
   // **** ElementID is used for 'zone' when Passing to ProcessMultiResults
   
   // alert(datasource);
  
    var objXML = initXMLHttpRequest();
    var strData= "";
    
    objXML.open("GET", datasource)
    objXML.onreadystatechange = function()
    {
        if(objXML.readyState == 4 )
        {
            //alert(objXML.responseText);
            
            strData = objXML.responseText;
            switch (ProcessType)
            {
                case "Multi": //show the multi results set
                    document.getElementById('divStatusMessages').style.display = "none";
                    ProcessMultiResults(strData, ElementID);
                    break;
                case "Multi_NPage": //show the next pages of results
                     ProcessMultiResults_NPage(strData, ElementID);
                    break;
               
               case "Holdings": //display holdings information for materials
                    ShowHoldings(strData, ElementID);
                    break;
                    
               case "Item": //shows the item level information
                   document.getElementById('divSingleBook').innerHTML = strData;
                   document.getElementById('StatusText').innerHTML = "Item record displayed";
                    break;
                  
               case "SpellCheck": //spell check the search string with Yahoo! 
                  ShowSpelling(strData);
                    break;
            }
        }
        else
        {
           // document.getElementById('StatusText').innerHTML = "Getting data...";
            //alert(objXML.readyState);
        }
    }
    
    objXML.send(null);

}


//function Transform(theData)
//{
//    //PURPOSE : Get the data back from the server and transform it into useful text for the user
//     
//   try
//    {
//        var xmlDOM = createDOM();
//        var xslDOM = createDOM();
//    }
//    catch (oError)
//    {
//        alert(oError);
//    }   
//      
//    var browser = navigator.userAgent;
//    browser = browser.toLowerCase();
////   
////    //verify the header data came across, if not add it
////   if( theData.indexOf('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>') == -1)
////   {
////        theData = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + theData;
////   }else
////   {    // do nothing
////   }
//    
//    //load the xmldocument
//     xmlDOM.async = false;
//     xslDOM.async = false;
//     
//     xmlDOM.load(theData);
//     xslDOM.load("xsl/unioncat_multirecords.xsl");
//    
//    //process the xsl style sheets
//     if(browser.indexOf("msie") > 1)
//     {
//         //IE  
//           try
//             { 
//                 alert(xmlDOM);
//                            
//               var xslTest = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.3.0");
//                xslTest.async = false;
//                xslTest.load("xsl/unioncat_multirecords.xsl");
//                alert(xslTest.transformNode(xslDOM));
//                
//               var results = xmlDOM.transformNode(xslDOM);
//                alert("try");
//                var xslTemp = new ActiveXObject("Msxml2.XSLTemplate.3.0");
//                xslTemp.stylesheet = xslTest;
//                 
//             
//                var xslProc = xslTemp.createProcessor();
//                xslProc.input = xmlDOM;
//                
//                xslProc.transform();
//                document.getElementById('divResults').innerHTML = xslProc.output;
//                
//             // var sResults =  xmlDOM.transformNode(xslDOM);
//                  alert("transfered worked");
//             }
//             catch (oError)
//             {      alert(oError);
//                    alert("this didn't work");
//                  document.getElementById('divResults').innerHTML = xmlDOM.transformNode(xslDOM);
//             }
//             
//         }
//         else
//         {
//             // Non IE
//           var oProcessor = new XSLTProcessor();
//           oProcessor.importStylesheet(xslDOM);
//           
//           var newDoc = oProcessor.transformToDocument(xmlDOM);
//           alert(newDoc.reponseXML);
//           document.getElementById('divResults').innerHTML = newDoc.responseXML;
//         //  document.getElementById('divResults').appendChild(oResults);
//           
//         
//      }
//   
//   //display results area
//    //   alert(oResults);
// }

function GetSetupInfo(Field)
{
    // PURPOSE: gets the xml data from the setup file to help create the Find Books page for the current library
    // RETURNS: Value of the requested field
    
    //create a variable to use as the xml request object
var XMLHttpRequestObject = false;

//if the request does not exist, then we need to create it
if (window.XMLHttpRequest)
{
    //should work for non IE browsers
    XMLHttpRequestObject = new XMLHttpRequest();
  //  alert("Non IE Request Object");
}
else if (window.ActiveXObject)
{
    //should work for IE browsers
    XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
  //  alert("IE Request Object");
}

  if(XMLHttpRequestObject)
    {   
        var obj = document.getElementById('divResults');
     
        obj.innerHTML= "Request Object Has Been Created <br/>";
     
        obj.innerHTML += "Results Area Defined<br/>";
        obj.innerHTML += "XML Request Object Status Code : " + getRequestStatus(XMLHttpRequestObject.readyState) + "<br/>";
        obj.innerHTML += "Going to : " + URL + "<br/>";
        
        
        try  {
        
         //open the request
             XMLHttpRequestObject.open("GET", URL, true);
      
          obj.innerHTML += "Request has been opened<br/>";
            obj.innerHTML += "XML Request Object Status Code : " + getRequestStatus(XMLHttpRequestObject.readyState) + "<br/>";
       
        }
        catch (oError)
        {
            obj.innerHTML += "There is a problem.<br/>";
            obj.innerHTML += oError + "<br/><br/>";
        }
        
        XMLHttpRequestObject.onreadystatechange = function()
        {
            if(XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
            {
                alert(XMLHttpRequestObject.responseText);
                obj.innerHTML += XMLHttpRequestObject.responseText;
            }else
            {
              obj.innerHTML += "XML Request Object Status Code : " + getRequestStatus(XMLHttpRequestObject.readyState) + "<br/>";
     
            }
        }
        XMLHttpRequestObject.send(null);
    }else
    {
        alert("No Object Created");
    }
}
