/****************************************************
// Author: Woon Khang Tang (woonkhang@gmail.com)
// University Libraries, Bowling Green State University.
//
// Introduction: This is a javascript code which scrapes locations, call numbers from the bib_display table,
//                         and then display the 'mapit' button right beside each call number. A new window will open
//                         when 'mapit' is clicked, showing the location of the item based on the location and call number.
//
// Note: 1) The locations and call numbers can be either hyperlinked or not.
//           2) Please enter information below noted as "SETUP" before first use.
// 
****************************************************/


/********************************************************
 * Trim leading and trailing white spaces. Required because sometimes location and coll nos have trailing white spaces,
 * and the stack map will fail to search.
*/
function trim(str) {
    var whitespace = ' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000';
    for (var i = 0; i < str.length; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    for (i = str.length - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

/********************************************************
 * extract the text that contains the fieldCode.
 * eg, <TD width="28%"><!-- field 1 -->&nbsp;<A href="http://www.bgsu.edu/colleges/library/loc_abbrev.html#list">Music Listening Center </A></TD>
 * This will extract the text "Music Listening Center" where the fieldCode is "field 1"
 */
function extractText(fieldCode, itemCells)
{
    var extractedText = "";
    
    for (var j = 0; j <itemCells.length; j++)
    {
        // Check for field code, which contains the targeted text information
        if (itemCells[j].innerHTML.indexOf(fieldCode) != -1) 
        {
            var childs = itemCells[j].childNodes;
            
            // First check for all hyperlinked nodes for targeted text
            for (var k = 0; k < childs.length; k++)
            {
                // Check if it's hyperlinked
                if (childs[k].nodeName == 'A' && 
                    childs[k].nodeType == document.ELEMENT_NODE)
                {
                    extractedText = trim(childs[k].firstChild.nodeValue);
                    //alert("Link exist: Extracted text = " + extractedText); // for debug 
                    
                    // targeted text found. Text is embedded in a hyperlink <a>extractedText</a>
                    return extractedText;
                }
            }   // end for

            // Now, the only possibility is the target text is not hyperlinked.
            for (var k = 0; k < childs.length; k++)
            {
                // Make sure the targeted text is type of text node (it can be a comment node)
                if (childs[k].nodeType == document.TEXT_NODE)
                {
                    extractedText = trim(childs[k].nodeValue);
                    //alert("Link doesnt exist: Extracted Text = " + extractedText);  // for debug
                    
                    // targeted text found. Text is without hyperlink.
                    return extractedText;
                }

            }   // end for
        }   // end if
    }   // end outer for
    
    // targeted text not found! This will probably cause error, so comment out the alert statement for debugging purpose.
    //alert("Targeted text not found!");  // for debug
    return "";
}

/********************************************************
 * Main entry point. Function is automatically called when this javascript file is referenced in the HTML file.
 * Please note the section "Setup this first!" and change any necessary values.
 */
function stackMapParse() {
/****************************************************
 SETUP THIS FIRST!!!
***************************************************/
    // What is the class name of your item table row?
    var itemEntryClassName = 'bibItemsEntry';

    // What is the fixed-length field code your library uses for item Location? (You can find this in webpub.def)
    var locCode = "1";
/****************************************************
 SETUP END
***************************************************/

    var itemRows = getElementsByClassName(itemEntryClassName, "tr");

    // Add the field in front so that it becomes field <locCode>
    locCode = "field " + locCode;
    
    // This code is necessary for browsers that don't reflect the DOM constants (like IE).
    if (document.ELEMENT_NODE == null) {
        document.ELEMENT_NODE = 1;
        document.TEXT_NODE = 3;
    }   // end if

    // You may have mutiple item rows entry
    for (var i = 0; i < itemRows.length; i++)
    {
        var itemCells = itemRows[i].cells;
        var loc = extractText(locCode, itemCells);
        var call = extractText('field C', itemCells);

        // Insert html code that displays the 'mapit' button just next to the call no, which search for the location from the stackmap DB.
        var bookInfoHtml = itemRows[i].getElementsByTagName('td')[1];
        bookInfoHtml.innerHTML += "<span style='padding-left:20px'><a href='#' onclick='window.open(\"http://ul.bgsu.edu/stackmap/search.php?loc_arr="+escape(loc)+"&call_arr="+escape(call)+"\", name=\"_blank\", \"menubar=1,resizable=1,location=1,scrollbars=1,width=800,height=600\"); return false;'><img border='0' title='Map the location! (Opens in new window)' src='http://ul.bgsu.edu/stackmap/mapit.gif' /></a></span>";
        //alert("<span style='padding-left:20px'><a href='#' onclick='window.open(\"http://ul.bgsu.edu/stackmap/search.php?loc_arr="+escape(loc)+"&call_arr="+escape(call)+"\", name=\"_blank\", \"menubar=1,resizable=1,location=1,scrollbars=1,width=800,height=600\"); return false;'><img border='0' title='Map the location! (Opens in new window)' src='http://ul.bgsu.edu/stackmap/mapit.gif' /></a></span>");
    }   // end for
    

}   // end stackMapParse()

// Note that this will overwrite any onloads that's been asigned!
// If you have multiple onload events, see this solution: http://dean.edwards.name/weblog/2005/09/busted/

addDOMLoadEvent(stackMapParse);

//window.onload = stackMapParse;