function createRequestObject() {  
    // find the correct xmlHTTP, works with IE, FF and Opera
    var xmlhttp;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            xmlhttp = null;
        }
    }
    
    if (!xmlhttp && typeof XMLHttpRequest!="undefined") {
        xmlhttp = new XMLHttpRequest();
    }
    
    return xmlhttp;
}

function getGooglePreview(ipAddress, theQuery, theLink, theImage)
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());
    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=GetGooglePreviewData&q="+theQuery+"&ip="+ipAddress+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var link = http.responseXML.documentElement.getElementsByTagName('link').item(0).firstChild.data;
            var type = http.responseXML.documentElement.getElementsByTagName('type').item(0).firstChild.data;
            var viewability = http.responseXML.documentElement.getElementsByTagName('viewability').item(0).firstChild.data;

            if (link) {
               var the_image = document.getElementById(theImage);

               if (viewability == 'all') {
                  the_image.src = path + '/images/google-full-text.jpg';
               } else if (viewability == 'partial') {
                  the_image.src = path + '/images/google-limited-preview.jpg';
               } else if (viewability == 'none') {
                  the_image.src = path + '/images/google-no-view.jpg';
               } else {
                  the_image.src = path + '/images/googlepreview.png';
               }

               var the_link = document.getElementById(theLink);
               the_link.href = link;
               the_link.style.display = '';
            }

        }
    }
    http.send(null);
}

function displaySFXOptions(issn)
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());
    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=GetSFXData&issn="+issn+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var response = http.responseXML.documentElement;
            if (response.getElementsByTagName('menu').item(0)) {
                var url = response.getElementsByTagName('menu').item(0).firstChild.data;
            }
        }
    }
    http.send(null);
}

function showSaveForm()
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());

    var http = createRequestObject();
    http.open("GET", path + "/Search/AJAX?method=IsLoggedIn"+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == "True") {
                popupMenu('saveRecord');
                document.listForm.tags.focus(); 
            } else {
                //popupMenu('loginBox');
                //document.loginForm.username.focus(); 
                window.location = path + "/MyResearch/Home?message=You+must+be+logged+in+for+this+action&followup=" + escape(fullpath + "?followupJS=popupMenu('saveRecord')");
            }
        }
    }
    http.send(null);
}

function showEmailForm()
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());

    var http = createRequestObject();
    http.open("GET", path + "/Search/AJAX?method=IsLoggedIn"+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == "True") {
                popupMenu('emailBox');
            } else {
                //popupMenu('loginBox');
                //document.loginForm.username.focus(); 
                window.location = path + "/MyResearch/Home?message=You+must+be+logged+in+for+this+action&followup=" + escape(fullpath + "?followupJS=popupMenu('emailBox')");
            }
        }
    }
    http.send(null);
}

function showTagsForm()
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());

    var http = createRequestObject();
    http.open("GET", path + "/Search/AJAX?method=IsLoggedIn"+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == "True") {
                showTagForm();
            } else {
                //popupMenu('loginBox');
                //document.loginForm.username.focus(); 
                window.location = path + "/MyResearch/Home?message=You+must+be+logged+in+for+this+action&followup=" + escape(fullpath + "?followupJS=showTagForm()");
            }
        }
    }
    http.send(null);
}

function saveRecord()
{
    var id = document.forms['listForm'].elements['recordId'].value;
    var tags = document.forms['listForm'].elements['tags'].value;
    var notes = document.forms['listForm'].elements['notes'].value;

    var http = createRequestObject();
    http.open("GET", path + "/Search/AJAX?method=SaveRecord&id=" + id + "&tags=" + tags + "&notes=" + notes, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result != 'Unauthorized') {
                elem = getElem('saveLink');
                elem.style.backgroundColor = '#FFFFCC';
                hideLightbox();
                GetTags(id, 'tagList'); // refresh the new list
            } else {
                document.forms['loginForm'].elements['followup'].value='SaveRecord';
                popupMenu('loginBox');
                document.loginForm.username.focus(); 
            }
        }
    }
    http.send(null);
}

function getSaveStatus(id, elemId)
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=GetSaveStatus&id=" + id + "&time=" + ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == 'Saved') {
                getElem(elemId).style.backgroundColor = '#FFFFCC';
            }
        }
    }
    http.send(null);
}

function SendEmail(id, elems, popupBoxId)
{
    //document.getElementById(popupBoxId).innerHTML = '<h3>Sending Message ...</h3>';

    var from    = elems['from'].value;
    var to      = elems['to'].value;
    var message = elems['message'].value;

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=SendEmail&id=" + id + "&from=" + from + "&to=" + to + "&message=" + message, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == "Done") {
                //document.getElementById(popupBoxId).innerHTML = '<h3>Message Sent</h3>';
                //setTimeout("hideLightbox(); document.getElementById('" + popupBoxId + "').style.display='none';", 3000);
                hideLightbox(); document.getElementById(popupBoxId).style.display='none';
                alert('Email sent!');
            } else {
                alert('Error: ' + result);
            }
        }
    }
    http.send(null);
}

function GetTags(id, elemId)
{
    // we want to sync the 'add to favorites' form
    document.forms['listForm'].elements['tags'].value = '';
    var new_tags_value = '';

    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());

    var tags;
    var output = "";
    var http = createRequestObject();
    http.open("GET", "AJAX?method=GetTags&id="+id+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var response = http.responseXML.documentElement;
            if (response.getElementsByTagName('result')) {
                tags = response.getElementsByTagName("Tag");
                if(tags.length > 0) {
                    j = 0;
                    for(i = 0; i < tags.length && i < 100; i++) {
                        if (j > 0) {
                            output = output + ", ";
                        }

                        if (tags.item(i) && tags.item(i).childNodes[0]) {
                           j++;
                           output = output + '<a href="' + path + '/Search/Home?tag=' +
                                 tags.item(i).childNodes[0].nodeValue + '">' + 
                                 tags.item(i).childNodes[0].nodeValue;

                           if (tags.item(i).getAttribute("cnt") && tags.item(i).getAttribute("cnt") > 1) {
                              output = output + ' (' + tags.item(i).getAttribute("cnt") + ')';
                           }

                           output = output + '</a>';

                           if (tags.item(i).getAttribute("owner")) {
                              output += ' <a class="delete tool" href="" onClick="confirm(\'Delete Tag: ' + escape(tags.item(i).childNodes[0].nodeValue) + '?\') && removeTag(\'' + id + '\',\'' + tags.item(i).getAttribute("id") + '\'); return false;"></a>';

                              // put double quotes around multiword tags
                              if (new_tags_value != '') new_tags_value += ' ';
                              if (tags.item(i).childNodes[0].nodeValue.indexOf(' ') != -1)
                                 new_tags_value += '"' + tags.item(i).childNodes[0].nodeValue + '"';
                              else
                                 new_tags_value += tags.item(i).childNodes[0].nodeValue;

                           }


                       }
                    }
                } else {
                    output = 'No Tags, Be the first to tag this record!';
                }
                getElem(elemId).innerHTML = output;
                // refresh this value
                document.forms['listForm'].elements['tags'].value = new_tags_value;
            } else {
                getElem(elemId).innerHTML = '<i>Error: Could Not Load Tags</i>';
            }
        }
    }
    http.send(null);
}

function removeTag(id, tagid)
{
    document.getElementById('tagForm').style.display='none';
   
    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=RemoveTag&id=" + id + "&tagid=" + tagid, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result != 'Unauthorized') {
                document.forms['tagForm'].elements['tag'].value = '';
                GetTags(id, 'tagList');
            } else {
                document.forms['loginForm'].elements['followup'].value='RemoveTag';
                popupMenu('loginBox');
                document.loginForm.username.focus();
            }

        }
    }
    http.send(null);
}


function SaveTag(id, userId)
{
    document.getElementById('tagForm').style.display='none';
    
    var tag = document.forms['tagForm'].elements['tag'].value;

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=SaveTag&id=" + id + "&tag=" + tag + "&user=" + userId, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result != 'Unauthorized') {
                document.forms['tagForm'].elements['tag'].value = '';
                GetTags(id, 'tagList');
            } else {
                document.forms['loginForm'].elements['followup'].value='SaveTag';
                popupMenu('loginBox');
                document.loginForm.username.focus(); 
            }

        }
    }
    http.send(null);
}

function SaveComment(id)
{
    comment = document.forms['commentForm'].elements['comment'].value;

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=SaveComment&id=" + id + "&comment=" + comment, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == 'Done') {
                LoadComments(id);
                document.forms['commentForm'].elements['comment'].value = '';
            } else {
                document.forms['loginForm'].elements['followup'].value='SaveComment';
                popupMenu('loginBox');
                document.loginForm.username.focus(); 

                //getElem("loginWarning_Log_In").onclick = new Function("window.location.href='" + path + "/MyResearch/Home?id=" + id + "&followup=" + escape(window.location.href) + "';");
                //getElem('loginWarning').style.display = 'block';
            }
        }
    }
    http.send(null);
}

function LoadComments(id)
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());
    var output = '';
    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=GetComments&id=" + id + "&time=" + ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var response = http.responseXML.documentElement;
            if (response.getElementsByTagName('result')) {
                var commentList = response.getElementsByTagName('result').item(0);
                commentList = commentList.getElementsByTagName("Comment");
                if(commentList.length > 0) {
                    for(i = 0; i < commentList.length; i++) {
                        output += '<li>';
                        output += commentList.item(i).childNodes[0].nodeValue;
                        output += '<div class="posted">Posted by <strong>';
                        output += commentList.item(i).getAttribute('by') + '</strong>';
                        output += ' on ' + commentList.item(i).getAttribute('on');
                        if (commentList.item(i).getAttribute("owner")) {
                           output += '<br><a class="delete tool" href="' + path + '/Record/' + id + '/UserComments?delete=' + commentList.item(i).getAttribute("id") + '">Delete</a>';
                        }
                        output += '</li>';
                    }
                }
                getElem('commentList').innerHTML = output;
            } else {
                getElem('commentList').innerHTML = '<i>Error: Could Not Load Comments</i>';
            }
        }
    }
    http.send(null);
}

function getHoldings(id, elemId)
{
    var now = new Date();
    // ts is used as a cache preventer for IE
    var ts = Date.UTC(now.getFullYear(),now.getMonth(),now.getDay(),now.getHours(),now.getMinutes());
    var tags;
    var output = "";
    var http = createRequestObject();
    http.open("GET", "AJAX?method=GetHoldings&id="+id+"&time="+ts, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
           var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
           getElem(elemId).innerHTML = result;
        }
    }
    http.send(null);
}

function showThese(elemId)
{
   var el = getElem(elemId);
   el.style.display='block';
}

function hideThese(elemId)
{
   var el = getElem(elemId);
   el.style.display='none';
}

function showSmsForm(txt_title, txt_callnumber, txt_location, txt_status, txt_university, cn_index, cell_number, cell_provider) {  
   var i;
   var smsDiv = document.getElementById("smsForm" + cn_index);
   var providers = ['Alltel','AT&amp;T','Boost Mobile','Cellular One','Cingular','Cricket','Nextel','Sprint','SunCom','T-Mobile','US Cellular','Verizon','Virgin Mobile'];

   txt_title = "'" + txt_title + "'";
   txt_callnumber = "'" + txt_callnumber + "'";
   txt_location = "'" + txt_location + "'";
   txt_status = "'" + txt_status + "'";
   txt_university = "'" + txt_university + "'";
   cell_number = "'" + cell_number + "'";

   var divHtml = '<form id="sms_cell" action="sms.cgi" method="post">';
   divHtml += '<label for="cell">Your Cell Number:</label><br>';
   divHtml += '<input type="text" id="cell" name="cell" class="required" value=' + cell_number + '/>';
   divHtml += '<br>';
   divHtml += '<label for="provider">Your Provider: </label>';
   divHtml += '<br>';
   divHtml += '<select id="provider" name="provider" class="required">';
   divHtml += '<option value="">- Select your provider -</option>';
   for (i = 0; i < providers.length; i++) {
      if (cell_provider != "" && i == cell_provider) {
         divHtml += '<option selected="selected" value="i">' + providers[i] + '</option>';
      } else {
         divHtml += '<option value="i">' + providers[i] + '</option>';
      }
   }
   divHtml += '</select>';
   divHtml += '<p><input type="button" onclick="sendSMS(provider.selectedIndex, cell.value, ';
   divHtml += txt_title + ',' + txt_callnumber + ',' + txt_location + ',' + txt_status + ',' + txt_university + ',' + cn_index;
   divHtml += ')" value="Send text message" />';
   divHtml += '</form>';
 
   if (typeof showSmsForm.display == 'undefined') { 
      showSmsForm.display = true;
      smsDiv.innerHTML = divHtml;
   }
   else {
      if (showSmsForm.display) {
         smsDiv.innerHTML = '';
         showSmsForm.display = false;
      }
      else {
         smsDiv.innerHTML = divHtml;
         showSmsForm.display = true;
      }
   }
}

function sendSMS(provider, cell, txt_title, txt_callnumber, txt_location, txt_status, txt_university, cn_index) {

   var smsDiv = document.getElementById("smsForm" + cn_index);
   var xhr = new XMLHttpRequest();
   var getParams = "&provider=" + provider + "&cell=" + cell + "&txt_title=" + txt_title + "&txt_callnumber=" + txt_callnumber + "&txt_location=" + txt_location + "&txt_status=" + txt_status + "&txt_university=" + txt_university;
 
   xhr.open("GET", "AJAX?method=sendSMS" + getParams,  true); 
   xhr.onreadystatechange  = function()
    { 
       if(xhr.readyState  == 4) {
          if(xhr.status  == 200) {
             smsDiv.innerHTML = xhr.responseText;
             showSmsForm.display = false;
          }
          else { 
             smsDiv.innerHTML = "Error code " + xhr.status;
             showSmsForm.display = false;
          }
       }
    }; 

   xhr.send(null); 
}

function getSFXLink(id, linkurl, imageurl, librarycode)
{
    var url = doc_src(document.location.href) + '/public/sfxFullText.pl?d=' + librarycode + 'db&u=' + linkurl;

    var http = createRequestObject();
    http.open("GET", url, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var response = http.responseXML.documentElement;
            var isFullText = 0;
            var item = response.getElementsByTagName('sfxFullText');
            if (item != null && item[0].firstChild.data == 'true') {
               isFullText = 1;
            }
            // If there's SFX full text, show the SFX link _instead of_ the 856 links
            if (isFullText) {
               // First, blank out availability info since it doesn't apply anymore
               //getElem('status' + id).innerHTML = '';

               getElem('the856s' + id).innerHTML = '<a href="' + unescape(linkurl) + '" class="fulltext" onClick="window.open(\'' + unescape(linkurl) + "', 'SFXmenu', 'toolbar=no,location=no,directories=no,buttons=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=550,height=600'); return false;\"><img src=\"" + unescape(imageurl) + '" border="0"></a><br>';
            }
        }
    }
    http.send(null);
}

function doc_src(doc)
{
   var inx = doc.indexOf("http://");
   var lenOfMatch = 7;
   if (inx == -1) {
      inx = doc.indexOf("https://");
      lenOfMatch = 8;
   }
   if (inx == -1) return '';
   var docsrc = doc.substring(0, lenOfMatch);

   inx = doc.indexOf('/', lenOfMatch);
   if (inx == -1) return doc;

   docsrc = doc.substring(0, inx);
   return docsrc;
}


