
/*
 *library.js
 *Contains all the javascript for the library
 */


/*
 *GLOBAL VARIABLES
 */

var selectedTab = 0;




/*
 *This script changes the button appearance for the selected tab when the button is clicked
 */
function tabHighlight(tabOn){
    //turn off all buttons then turn on the one that was clicked
    var i=0;
    var tabs=new Array();
    tabs[0]="tab0";
    tabs[1]="tab1";
    tabs[2]="tab2";
    tabs[3]="tab3";
    tabs[4]="tab4";
    tabs[5]="tab5";
    for (i=0; i< 5; i++){        
        document.getElementById(tabs[i]).style.backgroundImage="url(/images/button.png)";
    }
    document.getElementById("tab"+tabOn).style.backgroundImage="url(/images/buttonOn.png)";
    
}


/**
 *This script responds to the navigation tabs being clicked and using ajax
 *goes and fetches the appropriate page for the tab from tabGetter.php
 *it also calls tabHighlight passing it the tab that was clicked.
 *It writes to the div with the id frame_container which is the main
 *content area.
 */
function tabSelect(tab){
    selectedTab = tab;
    tabHighlight(tab);
    var query = "tab="+tab;
    var http=getHTTPObject();
    var url = "tabGetter.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){       
        if(http.readyState ==4 ){// 4 = "loaded"
            document.getElementById('frame_container').innerHTML=http.responseText;
        }
    };
    
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");   
    http.send(query);
}

/*
 *This function is called when a user clicks the login button.
 *It callse the getFormValues function to retrieve the values in the
 *login form and using ajax, posts these values to login.php
 *which validates the user and returns a logout button and "logged in as" message
 *or returns an error message and the login prompt if the login fails. *
 */
function loginUser(form){
    var formData = getFormValues(form);
    var http = getHTTPObject();
    var url = 'login.php';
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState == 4 ){// 4 = "loaded"
            document.getElementById('loginDiv').innerHTML=http.responseText;
            tabSelect(selectedTab);//refresh the page after login
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(formData);   
}

function logoutUser(){
    var str = "logout=true";
    var http = getHTTPObject();
    var url = "login.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState == 4 ){// 4 = "loaded"
            document.getElementById('loginDiv').innerHTML=http.responseText;
            tabSelect(selectedTab);//refresh the page after logout
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(str);    
}

/*
 *These functions mangage the button under the tabs and login bar that allows a user to look at and choose the libraries they are currently using *
 */
function hideLibraries(){
    //just show the button to expand and show libraries
    var button = "<span id=\"libChooser\" style=\"\" onclick=\"showLibraries();\" onmouseover=\"buttonHover('plus');\"  onmouseout=\"buttonNoHover('plus');\">show libraries <span id=\"plus\">[+]</span></span>";
    document.getElementById("showLibrariesButton").innerHTML= button;
    document.getElementById("showLibrariesContent").innerHTML="";
    document.getElementById("showLibrariesChangeButton").innerHTML="";
}

function showLibraries(){
    //show the button to collapse the libraries
    var button = "<span id=\"libChooser\" style=\"\" onclick=\"hideLibraries();\" onmouseover=\"buttonHover('minus');\"  onmouseout=\"buttonNoHover('minus');\">hide libraries <span id=\"minus\">[-]</span></span>";
    document.getElementById("showLibrariesButton").innerHTML= button;
    
    //get the currently selected libraries to display them in the field
    getLibraries();
    
    //display the change libraries button
    var libraries = "<p><form id=\"libraryChangeForm\" ><input type=\"button\" id=\"libraryChangeButton\" value=\"Change Libraries\" onclick=\"changeLibraries();\" /></form></p>";
    document.getElementById("showLibrariesChangeButton").innerHTML= libraries;
}

function buttonHover(id){
    document.getElementById(id).style.color = "red";
}

function buttonNoHover(id){
    document.getElementById(id).style.color = "white";
}

/*
 *This function is called when the change libraries form Go button is clicked
 *it calls library.php to set the Session variable for the libraries *
 */
function setLibraries(form){
    var strs = getFormValues(form);
    if(strs == ""){
        alert('You must choose a library.');
        return;
    }
    
    var http=getHTTPObject();
    var url = "library.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState ==4 ){// 4 = "loaded"
            document.getElementById('frame_container').innerHTML=tabSelect(selectedTab);
            showLibraries();
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(strs);
    
}

function getLibraries(){
    var http=getHTTPObject();
    var strs="library_get=get";
    var url = "library.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState ==4 ){// 4 = "loaded"
            if (http.status==200){// 200 = "OK"
                document.getElementById("showLibrariesContent").innerHTML=http.responseText;
            }
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(strs);
}

/*
 *This function is called when a user hits the change libraries button
 */
function changeLibraries(){
    var strs ="refresh=true";
    var http=getHTTPObject();
    var url = "library_select.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState ==4 ){// 4 = "loaded"
            document.getElementById('frame_container').innerHTML=http.responseText;
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(strs);
}



//======================================================SEARCH=============================================================
var progress = true;
/*
 *
 */
function searchLibrary(form){
    document.getElementById('searchTarget').style.display="block";
    document.getElementById('searchTarget').innerHTML="Searching Library...";   
    var fields ="";
    var sub = "";
    if(form.elements == null){
        //this is being called from viewAllByMedia
        sub = form.substr(0,2);
    }   
    
    if(sub == "m_"){
        fields = "viewByMedia="+document.getElementById(form).name;        
    }else{
        fields = getFormValues(form);
    }
    
    var http=getHTTPObject();    
    var url = "library.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState ==4 ){// 4 = "loaded"
            if (http.status==200){// 200 = "OK"
                progress = false;
                document.getElementById('frame_container').innerHTML=http.responseText;
            }
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(fields);
}









//======================================================KEEP=============================================================

function getFormValues(fobj,valFunc){
    
    var str = "";
    var valueArr = null;
    var val = "";
    var cmd = "";
    
    for(var i = 0;i < fobj.elements.length;i++){
        switch(fobj.elements[i].type){
            
            case "text":
                if(valFunc){
                    //use single quotes for argument so that the value of
                    //fobj.elements[i].value is treated as a string not a literal
                    cmd = valFunc + "(" + 'fobj.elements[i].value' + ")";
                    val = eval(cmd);
                }
                
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
            case "select-one":
                str += fobj.elements[i].name +
                "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
                break;
            case "checkbox":
                if(fobj.elements[i].checked){
                    str += fobj.elements[i].name +
                    "=" + escape(fobj.elements[i].value) + "&";
                }                
                break;
            case "textarea":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
            case "password":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
            case "hidden":
                str += fobj.elements[i].name +
                "=" + escape(fobj.elements[i].value) + "&";
                break;
        }
    }
    str = str.substr(0,(str.length - 1));
    return str;
}

function getHTTPObject(){
    var xmlhttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlhttp=new XMLHttpRequest();

    }
    catch (e) {
        //Internet Explorer
        try {
            xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlhttp;
}

//======================================================OLD=============================================================



function tagIt(formIn,ref){	
    //alert(ref +\" \"+tag_church);
    var subs = prompt('Please help our library by telling us what subjects this books contains separated by spaces or hit cancel to skip:');
    //if person entered string and it is not null
    if(subs){
        var flag = confirm('You said '+subs+ ' Is this correct?' );
        //if person confirms their entry
        if(flag){
            //social tagging may need moderator intercession
            addTags(formIn,subs ,ref);
        }
    }else{
        //if the user does not add any tags submit the return        
        formIn.submit(); 
    }            
}    

function addTags(formIn, tagsIn, book){
    var socialForm = formIn;
    var str = "number="+book+"&tags="+tagsIn+"&social=true&save=true";	
    var xmlhttpX=getHTTPObject();
    if (xmlhttpX==null){
        alert("Browser does not support HTTP Request");
        return;
    }
    var url="bookedit.php";
    xmlhttpX.onreadystatechange=function(){
        if (xmlhttpX.readyState==4){// 4 = "loaded"
            if (xmlhttpX.status==200){// 200 = "OK"
                //alert('status OK '+xmlhttpX.responseText);
                socialForm.submit();
            }
        }
    };
    xmlhttpX.open("POST",url,true);
    xmlhttpX.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    xmlhttpX.send(str);
}

/**
 *This method is used both for adding new books to the db and for
 *updating the db the difference is whether the k,v pair save=true is set
 *which puts it in update mode using the editBook() method in bookFunctions.php
 */
function addBookData(f){
    var str = getFormValues(f);
    var xmlhttp=getHTTPObject();
    if (xmlhttp==null){
        alert("Browser does not support HTTP Request");
        return;
    }
    var url="bookFunctions.php";

  xmlhttp.onreadystatechange= function(){
        if(xmlhttp.readyState ==4 ){// 4 = "loaded"
            document.getElementById('message_area').innerHTML=xmlhttp.responseText;
        }
    };

    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    //alert(str);
    xmlhttp.send(str);
}

/**
 *
 */
function getEditBookForm(num ,ISBN){
    var strs ="";
    
    if(num ==null){        
        num = 1;
    }
    if(ISBN != null){
        strs ="edit=true&ISBNseek="+ISBN;        
    }else{
        strs ="edit=true&number="+num;
    }
   
    
   
    var http=getHTTPObject();
    var url = "bookFunctions.php";
    if (http == null ){
        alert("Browser does not support HTTP Request");
        return;
    }
    http.onreadystatechange= function(){
        if(http.readyState ==4 ){// 4 = "loaded"
            document.getElementById('frame_container').innerHTML=http.responseText;
        }
    };
    http.open("POST",url,true);
    http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    http.send(strs);
}



function capture(x){
    document.getElementById(x).select();
}

function clearForm(x){
    x.reset();
}

function selectForm(x){
    document.getElementById(x).select();
}


//=================================================AUTOFILL FUNCTIONS=======================================
var xmlDoc;
function loadXMLString(txt){
    try //Internet Explorer
    {
        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(txt);
        return(xmlDoc); 
    }
    catch(e)//{alert(e.message)}
    {
        try //Firefox, Mozilla, Opera, etc.
        {
            parser=new DOMParser();
            xmlDoc=parser.parseFromString(txt,"text/xml");
            // alert(txt);
            return(xmlDoc);
        }
        catch(e) {
            alert(e.message);
        }
    }
    return(null);
}


var semaphore;
//USED FOR ONE ISBN
function autoFill(f){
    var  xmlDoc = null;
    var str = getFormValues(f);
    var xmlhttp=getHTTPObject();

    if (xmlhttp==null){
        alert("Browser does not support HTTP Request");
        return;
    }
    var url="../services/query_isbn.php";
    //USED FOR A SINGLE ISBN - FILLS FORM WHICH CAN THEN BE SUBMITTED
    xmlhttp.onreadystatechange=function(){
    
        if (xmlhttp.readyState==4){// 4 = "loaded"
            if (xmlhttp.status==200){// 200 = "OK"

                // alert(xmlhttp.responseText.replace("\&","and"));
                var xmlString = xmlhttp.responseText;
                xmlString = xmlString.replace("&","and");
                xmlDoc = loadXMLString(xmlString);

            
                if(xmlDoc.getElementsByTagName("BookList")[0].getAttribute("total_results") == 0){
                    alert('Sorry data for this book was not available');
                }else{
                
                    var x=xmlDoc.getElementsByTagName("BookData")[0].childNodes;
                
                    for (i=0;i<x.length;i++){
                        //alert(x[i].nodeName);
                        if(x[i].nodeName =="TitleLong" && x[i].nodeValue){
                            document.getElementById('Title').value=xmlDoc.getElementsByTagName("TitleLong")[0].childNodes[0].nodeValue;
                        }
                        else if(x[i].nodeName =="Westminster" && x[i].hasChildNodes()){
                            document.getElementById('Westminster').value=xmlDoc.getElementsByTagName("Westminster")[0].childNodes[0].nodeValue;
                        }
                        else if(x[i].nodeName =="book_id" && x[i].hasChildNodes()){
                            document.getElementById('book_id').value=xmlDoc.getElementsByTagName("book_id")[0].childNodes[0].nodeValue;
                        }
                        else if(x[i].nodeName =="PubYear" && x[i].hasChildNodes()){
                            document.getElementById('PubYear').value=xmlDoc.getElementsByTagName("PubYear")[0].childNodes[0].nodeValue;
                        }
                        else if(x[i].nodeName =="Format" && x[i].hasChildNodes()){
                            document.getElementById('Format').value=xmlDoc.getElementsByTagName("Format")[0].childNodes[0].nodeValue;
                        }
                        else if(x[i].nodeName =="Media" && x[i].hasChildNodes()){
                            document.getElementById('Media').value=xmlDoc.getElementsByTagName("Media")[0].childNodes[0].nodeValue;
                        }
                        else if(x[i].nodeName =="Volume" && x[i].hasChildNodes()){
                            document.getElementById('Volume').value=xmlDoc.getElementsByTagName("Volume")[0].childNodes[0].nodeValue;
                        }
                    
                        else if(x[i].nodeName =="Title" && x[i].hasChildNodes()){
                            document.getElementById('Title').value=xmlDoc.getElementsByTagName("Title")[0].childNodes[0].nodeValue;
                        }
                    
                        else if(x[i].nodeName =="AuthorsText" && x[i].hasChildNodes()){
                            document.getElementById('Author').value= xmlDoc.getElementsByTagName("AuthorsText")[0].childNodes[0].nodeValue;
                        }
                    
                        else if(x[i].nodeName =="PublisherText" && x[i].hasChildNodes()){
                            document.getElementById('Publisher').value=xmlDoc.getElementsByTagName("PublisherText")[0].childNodes[0].nodeValue;
                        }
                    
                        else if(x[i].nodeName =="Subjects"){
                            //get all the child subject nodes
                            var s=xmlDoc.getElementsByTagName("Subjects")[0].childNodes;
                            var subjects ="";
                            //concatenate all the content of the subject nodes and write to subject form field
                            for (j=0;j<s.length;j++){
                                //Display only element nodes
                                if (s.item(j).nodeType==1){
                                    subjects = subjects + s.item(j).childNodes[0].nodeValue;
                                }
                            }
                            document.getElementById('tags').value = subjects;
                        }
                    
                        else if(x[i].nodeName =="Details"){
                    //document.getElementById('Title').value=xmlDoc.getElementsByTagName("TitleLong")[0].childNodes[0].nodeValue;
                    }
                    }
                
                }
            
            
            }else{
                alert("Problem retrieving XML data:" + xmlhttp.statusText);
            }
        }
    };
    xmlhttp.open("POST",url,true);
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
    //alert(str);
    xmlhttp.send(str);
}



//USED FOR A LIST OF ISBN'S
function autoFillBatch(f){
    //str is a \n seperated string of isbn's
    var str = getFormValues(f);
    str = str.replace(/isbnArea=/g,"");
    var strArr = str.split("%0A");//split over new lines
    //alert("SPLIT "+strArr.length);
    semaphore = true;
    var i =0;
    while(i<strArr.length){
        if(semaphore){
            xmlhttp=getHTTPObject();
            if (xmlhttp==null){
                alert("Browser does not support HTTP Request");
                return;
            }
            var url="services/query_isbn.php";
            xmlhttp.onreadystatechange=batch_State_Change;
            
            xmlhttp.open("POST",url,true);
            xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
            
            //alert("isbnArea="+strArr[i]);
            xmlhttp.send("isbnArea="+strArr[i]);
            i++;
            semaphore = false;
        }
        
    }	
}

//USED FOR A BATCH OF ISBN'S
function batch_State_Change(){
    if (xmlhttp.readyState==4){// 4 = "loaded"
        if (xmlhttp.status==200){// 200 = "OK"
            alert(xmlhttp.responseText);
            
            
            xmlDoc=loadXMLString(xmlhttp.responseText);
            //IF THE DATABASE DOES NOT HAVE THIS BOOK IT RETURNS total_results = 0
            //CHECK IF THE DB HAS THE BOOK
            if(xmlDoc.getElementsByTagName("BookList")[0].getAttribute("total_results") == 0){
                //DO A POPUP TO NOTIFY USER THAT NO DATA IS AVAILABLE
                alert('Sorry data for this book was not available');
            }else{
                
                
                //ELEMENT HAS DATA - GET IT, AN ISBN WILL ALWAYS RETURN ONLY ONE BOOK
                var x=xmlDoc.getElementsByTagName("BookData")[0].childNodes;
                var queryString = "";
                for (i=0;i<x.length;i++){
                    
                    if(x[i].nodeName =="TitleLong" && x[i].nodeValue){
                        queryString += "Title="+ xmlDoc.getElementsByTagName("TitleLong")[0].childNodes[0].nodeValue.replace(/,/g," ");
                    }
                    
                    else if(x[i].nodeName =="Title" && x[i].childNodes[0].nodeValue){
                        queryString += "Title="+ xmlDoc.getElementsByTagName("Title")[0].childNodes[0].nodeValue.replace(/,/g," ");
                    }
                    
                    else if(x[i].nodeName =="AuthorsText" && x[i].childNodes[0].nodeValue){
                        queryString += "&Author="+ xmlDoc.getElementsByTagName("AuthorsText")[0].childNodes[0].nodeValue.replace(/,/g," ");
                    }
                    
                    else if(x[i].nodeName =="PublisherText" && x[i].childNodes[0].nodeValue){
                        queryString += "&Publisher="+ xmlDoc.getElementsByTagName("PublisherText")[0].childNodes[0].nodeValue.replace(/,/g," ");
                    }
                    
                    else if(x[i].nodeName =="Subjects"){
                        //get all the child subject nodes
                        var s=xmlDoc.getElementsByTagName("Subjects")[0].childNodes;
                        var subjects ="";
                        //concatenate all the content of the subject nodes
                        for (j=0;j<s.length;j++){
                            //Display only element nodes
                            if (s.item(j).nodeType==1){
                                subjects = subjects + s.item(j).childNodes[0].nodeValue.replace(/,/g," ");
                            }
                        }
                        queryString += "&Subject"+ subjects;
                    }
                    
                    else if(x[i].nodeName =="Details"){
                //document.getElementById('Title').value=xmlDoc.getElementsByTagName("TitleLong")[0].childNodes[0].nodeValue.replace(/,/g," ");
                }
                }
                
                /*
                 *
            IS RETURNING :
            Title,Author,Pulisher,Subject
                 */
                
                document.getElementById('isbnArea').value= queryString;
                semaphore = true;
            }
            
            
        }else{
            alert("Problem retrieving XML data:" + xmlhttp.statusText);
        }
    }
    
}


