var isbn;

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 showSaveForm()
{
    var http = createRequestObject();

    http.open("GET", path + "/Search/AJAX?method=IsLoggedIn&v=" + getTimestamp(), 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');
            } else {
                popupMenu('loginBox');
            }
        }
    }
    http.send(null);
}


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

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=AddFavourite&id=" + id +
              "&group=" + encodeURIComponent (group) +
              "&notes=" + encodeURIComponent (notes) +
              "&v=" + getTimestamp(), 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') {
                hideLightbox();
            } else {
                document.forms['loginForm'].elements['followup'].value='SaveRecord';
                popupMenu('loginBox');
            }
        }
    }
    http.send(null);
}


function getSaveStatus(id, elemId)
{
    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=GetSaveStatus&id=" + id  +
              "&v=" + getTimestamp(), 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';
                getElem(elemId).style.display = 'none';
            }
        }
    }
    http.send(null);
}

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

    var http = createRequestObject();
    var params = "to=" + to + "&ajax=true";
    http.open("POST", path + "/Record/" + id + "/Email", true);
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	http.send(params);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var result = http.responseXML.documentElement.getElementsByTagName('result').item(0).firstChild.data;
            if (result == "Done") {
                popupBox.innerHTML = "<h3>Message Sent</h3><p style='margin-left : 10px;'><a href=\" " + window.location.href + " \">Thanks!</a></p>";
            }
            else {
            	popupBox.innerHTML = "<h3>Message Error</h3><p style='margin-left : 10px;'>" + result + "</p><p style='margin-left : 10px;'><a href=\" " +  path + "/Record/" + id + " \">Return to record</a></p>";
           }
        }
    }
}


function SetCookie(cookieName,cookieValue,nDays)
{
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=1;
    expire.setTime(today.getTime() + 3600000*24*nDays);
    document.cookie = cookieName+"="+escape(cookieValue)
        + ";expires="+expire.toGMTString();
}


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

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=SaveComment&id=" + id +
              "&comment=" + encodeURIComponent (comment)  +
              "&v=" + getTimestamp(), 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 {
                SetCookie('vufind_comment',
                          encodeURIComponent(document.forms['commentForm'].elements['comment'].value));
                document.forms['loginForm'].elements['followup'].value='SaveComment';
                popupMenu('loginBox');
            }
        }
    }
    http.send(null);
}

function RemoveComment(id, cid)
{

    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=RemoveComment&id=" + id +
              "&cid=" + cid  +
              "&v=" + getTimestamp(), 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);
            } else {
            	alert(result);
                SetCookie('vufind_comment',
                          document.forms['commentForm'].elements['comment'].value);
                document.forms['loginForm'].elements['followup'].value='SaveComment';
                popupMenu('loginBox');
            }
        }
    }
    http.send(null);
}

function LoadComments(id)
{
    var output = '';
    var http = createRequestObject();
    http.open("GET", path + "/Record/AJAX?method=GetComments&id=" + id  +
              "&v=" + getTimestamp(), 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');
                        output += '<a href="" class="delete" onClick="RemoveComment(' + id + ', ' + commentList.item(i).getAttribute('id') + '); return false;">Remove this comment</a>';
                        output += '</div>';
                        output += '</li>';
                    }
                }
                getElem('commentList').innerHTML = output;
            } else {
                getElem('commentList').innerHTML = '<i>Error: Could Not Load Comments</i>';
            }
        }
    }
    http.send(null);
}


function showGoogleBooksPreview (bookinfo)
{
    for (var i in bookinfo['gbooks']) {
        if (bookinfo['gbooks'][i].preview &&
            bookinfo['gbooks'][i].preview != "noview") {
            document.getElementById('googlepreview').style.display = 'block';
            isbn = i;
        }
    }
}

function showOnlineShopLink (bookinfo)
{
    var span = $("onlineshop");

    for (var i in bookinfo['shop']) {
        var item = bookinfo['shop'][i];
        var desc = '<a style="margin-left : 20px;"  href="' + item.itemLink + '">Buy at our online shop</a>';
        if (item.price) {
            desc += ' <span style="font-size:75%">(AUD' + item.price.replace(/^\s+|\s+$/g, '') + ')</span>';
        }

        span.innerHTML = desc;
        span.style.display = 'block';
    }
}


function LTpop(booksInfo){
	for (i in booksInfo) {
 			var book = booksInfo[i];
 			if (book.link && book.copies != '0' ) {
				document.getElementById('externalservices').style.display = 'block';
				var desc = ''; var ratimg = '' ; if (book.copies) desc = book.copies + ' entries' ;
				if (book.reviews && (book.reviews != '0')) desc += ', ' + book.reviews + ' reviews' ;
				if (book.rating) ratimg = ' <img border="1" src="' + book.rating_img + '"/>' ;
				 document.getElementById('ltworkinfo').innerHTML = '<a style="margin-left : 20px;" href="' + book.link + '">' +
				 		desc + ' at LibraryThing ' + ratimg + '</a>';
				document.getElementById('ltworkinfo').style.display = 'block';
				break;
 			}
 	}
 }

function closePreview ()
{
    document.getElementById('viewerCanvas').style.display= 'none';
    document.getElementById('fade').style.display= 'none';

}

function openPreview ()
{
    document.getElementById('viewerCanvas').style.display= 'block';
    document.getElementById('fade').style.display= 'block';

    scroll(0,0);

    google.load("books", "0", {"callback" : function () {
                var viewer = new google.books.DefaultViewer(document.getElementById('viewerCanvas'));

                viewer.load(isbn);
            }});
}


var format_to_category = {
    'Audio' : 'OH',
    'Manuscript' : 'MAN',
    'Map' : 'MAPS',
    'Music' : 'MUS',
    'Picture' : 'PIC'
};


var default_category = 'COPY';

function getCopyrightStatus(bibid, formats)
{
    var service = '/fcgi-bin/copyright.fcgi?id=' + bibid + '&v=' + getTimestamp() ;
    formats = formats.split (",%20");

    var category = default_category;
    formats.each (function (fmt) {
            if (format_to_category[fmt]) {
                category = format_to_category[fmt];
            }
        });

    var http = createRequestObject();
    http.open("GET", service, true);
    http.onreadystatechange = function()
    {
        if ((http.readyState == 4) && (http.status == 200)) {
            var response = http.responseText;
            if (response) {
                var copyright = eval ('(' + response + ')');

                var div = document.getElementById ('copyrightStatus');

                var copyright_message = document.getElementById ("csmsg" + copyright.contextMsg);
                // copyright_message.style.display = "block";

                $$('.copyright_contact_link').each (function (copyright_link) {
                        copyright_link.href = copyright_link.href.replace ("COPYRIGHT_STATUS", escape (copyright.copyrightStatus));
                        copyright_link.href = copyright_link.href.replace ("RT_CATEGORY", escape (category));
                    });


                var html = ('<b>' + copyright.copyrightStatus + '</b>' + '.<br><br>' + copyright_message.innerHTML +
                            '<br><br><table>' +
                            (copyright.copyrightStatusReason ? '<tr><th>Reason for copyright status:</th><td>' + copyright.copyrightStatusReason + '</td></tr>' : '') +
                            '<tr style="border: none"><td>&nbsp;</td><td>&nbsp;</td></tr>' +
                            '<tr><th align="left" colspan="2">Copyright status was determined using the following information:</td></tr>' +
                            (copyright.materialType ? '<tr><th>Material type:</th><td>' + copyright.materialType + '</td></tr>' : '') +
                            (copyright.creatorDateOfDeath ? '<tr><th>Presumed date of death of creator (latest date):</th><td>' + copyright.creatorDateOfDeath + '</td></tr>' : '') +
                            (copyright.publishedStatus ? '<tr><th>Published status:</th><td>' + copyright.publishedStatus + '</td></tr>' : '') +
                            (copyright.creationDate ? '<tr><th>Creation date:</th><td>' + copyright.creationDate + '</td></tr>' : '') +
                            (copyright.publicationDate ? '<tr><th>Publication date:</th><td>' + copyright.publicationDate + '</td></tr>' : '') +
                            '<tr style="border: none"><td>&nbsp;</td><td>&nbsp;</td></tr>' +
                            '<tr style="border: none"><td colspan="2">Copyright status may not be correct if data in the record is incomplete or inaccurate.  For more information please see: <a href="http://wiki.nla.gov.au//x/A7U">how copyright status is determined</a>.</td></tr>' +
                            '</table>');

                div.innerHTML = html;
                div.style.display = "block";
            }
        }
    }

    http.send (null);
}


    function author_thumb_url (aid)
    {
        id = aid.split ("/")[2];

         return "http://covers.openlibrary.org/a/olid/" + id + "-S.jpg";
    }


    function showAuthorPic (bookInfo)
    {
        bookInfo = new Hash (bookInfo);

        var thumbs = [];

	info = bookInfo.get (bookInfo.keys().first ());

        info.details.authors.each (function (author) {
            $('authorthumbs').innerHTML += ('<img title="' +
					    author['name'] +
					    ' (Open Library)" src="' + author_thumb_url (author['key']) + '">');
        });
    }
