//Ted Lawless July 2008, March 2009, June 2009, March 2010
//Lisa Genoese July 2011
(function($) {
  $('document').ready(function() {
	//recap section
	//grab date and time for setTimeout function
	var start=new Date().getTime();
	var title = title_find();
	offsite_rows.each(function (){
		var code_spot = $(this)[0];
		var barcode = trim_barcode($(code_spot).text());
		//check status, proceed if not due
		if (due_re.exec(($(this).next().text()))) {
			return
		} else {
		//slow down if loading takes longer than 2 seconds. setTimeout requires function wrapper
		var form_w_code = setTimeout(function(){form_html(code_spot, barcode, title);},0)
		};
	}); //ends function
	
	//begin microform paging section /lmg
	
	//check if has microform onsite location that is paged by Continuing Resources
	
	if (bib_location != null)
	{
		if (bib_location.search("2nd Fl M'fiche") > -1 || bib_location.search("2nd Fl Microfilm") > -1)
		{
			//alert("yes microform LOCATION");  //uncomment for testing
			add_onsite_microform_row();
		} else {	 //check sublocation for Cabinet, since main location may be Offsite in case of a split record with both on- and off-site items)
					if(bib_sublocation != null && bib_sublocation.search('Cabinet') > -1) 
					{
							//alert("yes microform SUBLOCATION");  //uncomment for testing
							add_onsite_microform_row();
					}
					/* else			//uncomment for testing
				alert("Not Microform!");  */ 
		}	 // END MICROFORM
			
	}
	
//IN PROCESS SECTION
	
	all_item_rows.each(function (){
		var status_spot = $(this).next()[0];
		//check if in process
		if (in_process_re.exec(($(this).next().text()))) {
			//console.debug(title, status_spot);
			page_in_process(bibnum, title, status_spot);
		}
	}); //ends function
	//Special Collections paging
	//console.debug(bib_location);
	//if (bib_location.match(/Treasure|SIPA1/)) {
        //if (
        //        ($(bib_location):contains('Treasure').length == 1) ||
        //        ($("span.fixed_bib_location:contains('SIPA1')").length ==1)) 
        //{
	//	 special_collections_page();
		 //alert();
	// }
	
	//microform paging request link -- add fake item record to display
	function add_onsite_microform_row() //add to item table
	{

			var microform_request_link ='<a class="request_form_link" href="javascript:window.open( \'\', \'formresult\', \'toolbar=no,location=no,directories=no,resizable=yes,scrollbars=yes,menubar=yes,width=600,height=600\'); document.getElementById(\'microform_form_form\').submit(); " >Request</a>';
	
			var microform_form_pt1 = '<form id="microform_form_form" target="formresult" style="padding:0px; margin:0px;" action="http://libdocs.law.columbia.edu/micropager/microform_request_form.php" method="post"> <input type="hidden" name="title" value="' + $.trim(title_find()) +'" /><input type="hidden" name="callnumber" value="' + $.trim(call_number) +'" /><input type="hidden" name="location" value="' + $.trim(bib_location) +'" /><input type="hidden" name="sublocation" value="' + $.trim(bib_sublocation) +'" /><input type="hidden" name="publisher" value="' + $.trim(bib_publisher_info) +'" /><input id="bibnumber" type="hidden" name="bibnumber" value="' + bibnum +'" />' ;
	
			var microform_form_pt2 = '</form>' + microform_request_link;
	
			if (item_table.length == 1) //just add row to existing item table
			{

					var appendText = '<tr  class="bibItemsEntry"><td width="25%" >&nbsp;Onsite microform</td><td width="33%" >&nbsp;'+call_number.replace(/^\s+|\s+$/g, '')+'<br/><span style="font-size:smaller;">(Select for any library item not listed above as offsite.)</span></td><td width="25%" >' + microform_form_pt1 + microform_form_pt2 + '</td><td width="17%" >&nbsp; </td></tr>';
		
					item_table.append(appendText);
			
			} else if (item_table.length == 0) {  //no item table, so add one

					//alert(call_number); //uncomment for testing
	
					$("div.bibContent").append('<table width="100%" border="3" cellspacing="1" class="bibItems"><tr  class="bibItemsHeader"><th width="25%"  class="bibItemsHeader">Location</th><th width="33%"  class="bibItemsHeader">Volume/Copy</th><th width="25%"  class="bibItemsHeader">Barcode</th><th width="17%"  class="bibItemsHeader">Status</th></tr><tr  class="bibItemsEntry"><td width="25%" >&nbsp;Onsite microform</td><td width="33%" >&nbsp;'+call_number.replace(/^\s+|\s+$/g, '')+'</td><td width="25%" >' + microform_form_pt1 + microform_form_pt2 + '</td><td width="17%" >&nbsp; </td></tr>');
			}
	}	 //END FUNCTION add_onsite_microform_row() 
	
	
	//bookplates
	if ($("tr.bibOrderEntry").length == 0) {
	    var gift = $("tr td.bibInfoLabel:contains('Gift')").text();
	    	    //don't add gift note if title is still 'ordered
	    	    if ($("tr.bibOrderEntry").length == 0) {
		    if (gift){
			    var donor_contents = $("tr td.bibInfoLabel:contains('Gift')").next().text()
			    //if (!(donor_contents)) {var donor_contents = $("table.bibDetail tbody tr.bibInfoEntry td table tbody tr td.bibInfoData:contains('Gift of')").text();}
			    if (donor_contents) {plate_maker(donor_contents)};
	    };
	    };
	 //toshiba bookplate
	   var gift = $("tr td.bibInfoLabel:contains('Donation')")
	    	    //don't add gift note if title is still 'ordered
		    if (gift){
			    var donor_contents = $("tr td.bibInfoLabel:contains('Donation')").next().text()
			    if (donor_contents) {
			    	toshiba_plate_maker(donor_contents);
				//hack to change label from donation to gift
				var label = '<td valign="top" width="20%" class="bibInfoLabel">Gift note</td>'
				$(gift).replaceWith(label);
			    };
	    };
	    };
	//ebooks
	var oclc = $("tr td.bibInfoLabel:contains('OCLC')").next().text().replace('\n', '');
	//call number starts with p don't find free stuff
	var serial = callnum_find().match(/P/);
	//see if there's e holdings already. or a checkin record which is in bibHoldings
	//if not look for free stuff.
	if (($("table.bibResourceBrief").length<1) && (!(serial)) && ($("table.bibHoldings").length<1) ){
		if (oclc) {
			oclc = oclc.match(/[0-9]+/)[0];
			var ebook_box = "<div id=\"ebook_box\"><h1>Available online:</h1><ul id='ebooks'></ul></div>";
			$(ebook_box).insertAfter("div.bibRecordLink")
			hathi(oclc);
			openlibrary(oclc);
			//gbooks(oclc);
		};
	};
	if ((bibnum) && (call_number)){
		textthis(bibnum)
	}
	//Tom - start here to disable Gateway app.  Javascript comments are //
	$('td.bibResourceEntry a').click(function() {
		re = /b[0-9]{6}/;	
		var recnum = re.exec($('a#recordnum').attr('href'));	
		var param = '?recnum=' + recnum + '&' + 'link=' + encodeURIComponent(this.href);
		resolve(param);
		return false;
	});
	//Tom - stop comments here
	//record bib number in GA
	track_bib(bibnum);
 });
})(jQuery);
//recap section  
//constants
var title = title_find();
var call_number = $("tr td.bibInfoLabel:contains('Call No.')").next().text();
var bib_location_spot = $("tr td.bibInfoLabel:contains('LOCATION')");
var bib_location = $(bib_location_spot).next().text();
var left_link_html = "<a class='request_form_link' href=\"http\:\/\/recap\.law\.columbia\.edu\/\?barcode\="
var right_link_html = "\" onclick=\"window.open(this.href, '_blank', 'toolbar=no,location=no,directories=no,resizable=yes,scrollbars=yes,menubar=yes,width=550,height=500'); return false;\">Request</a>"
var barcode_pattern = /35005{1}[0-9]{8}.*/;
var offsite_rows = $("tbody tr.bibItemsEntry:contains(Offsite storage) td:contains(35005)");
var all_item_rows = $("table.bibItems tbody tr.bibItemsEntry td");
var due_re = /due|lost/i; //for checking item status
var in_process_re = /in\sprocess/i; //for checking in process items
var bib_sublocation = $("tr td.bibInfoLabel:contains('Sub-Location')").next().text(); //for microform paging /lmg
var item_table = $("table.bibItems tbody:first"); //for microform paging /lmg
var bib_publisher_info = $("tr td.bibInfoLabel:contains('Published')").next().text();
var bib_reproduction = $("tr td.bibInfoLabel:contains('Reproduction')").next().text();
//capture bibnum
try {
	var bibnum =(($("a#recordnum").attr('href')).replace(/.*(b[0-9]{6})/, "$1")).substring(0,7);
}
catch(err) {var bibnum = "unknown";}
//function to trim leading white space and to encode URI
	function trim_barcode(code){
		code = code.replace(/^\s+|\s+$/g, '')
                //would like to only take first 14 characters of the barcode but it causes 
                //problems with IE 6, resulting in too short barcodes being sent to ReCap.
		code = code.toUpperCase()//.slice(0,14);
		code = barcode_pattern.exec(code);
		return encodeURIComponent(code);
	}
//function to create form html	
	function form_html(code_spot, barcode, title){
		if (barcode.match(barcode_pattern)) {
		var form_html = $(code_spot).append([
			  left_link_html,
			  barcode,
			  "&title=",
			  title,
			  right_link_html
			  ].join(""));
		var add_row_highlight = $('table.bibItems').addClass('highlight_row');
		}
		return;
	}	
//grabs the title if it appears on the page	
	function title_find (){
		var title = $("td.bibInfoData strong")[0];
		if (!title) var title=""
		else{
		$(title).addClass('bib-title');
		var title = encodeURIComponent($(title).text().substring(0,300));
		}
		return title;
	}
//finds call number
	 function callnum_find (){
	   var callnum = $("td.bibInfoLabel:contains('Call')");
	   callnum = $.trim($(callnum).next().text());
	   if (!callnum) callnum="";   
	   return callnum;
	  }
//bookplate inserter
function plate_maker (donor_contents){
		header = "The Arthur W. Diamond Law Library";
		 var html_message = "<div id='book_plate'><h1 class='book_plate_header'>" + header + "</h1>" + "<img id='book_plate_graphic' src='/screens/plate_crown.gif'></img><h2 class='donor_message'>" + donor_contents + "</h2>"
		 $(html_message).prependTo('body');
	}
//toshiba plate maker
function toshiba_plate_maker (donor_contents){
		header = "The Toshiba Library for Japanese Legal Research";
		 var html_message = "<div id='book_plate'><h1 class='book_plate_header'>" + header + "</h1>" + "<img id='book_plate_graphic' src='/screens/plate_crown.gif'></img><h2 class='donor_message'>" + donor_contents + "</h2>"
		 $(html_message).prependTo('body');
	}
//ebooks
function hathi(oclc) {

	$.getJSON('http://catalog.hathitrust.org/api/volumes/brief/oclc/' + oclc + '.json?callback=?', function (ht) {

			$.each(ht.items, function(i,item){
					var inserted_book = 0;
					if (item.rightsCode == 'pd') {
						var hathi_html = "<li><a id=\"hathi\" href=\"" + item.itemURL + "\" target=\"_blank;\" onclick=\"track_ebooks('Hathi Trust',bibnum)\">Hathi Trust</a></li>"
						$(hathi_html).appendTo("#ebooks");
						$('#ebook_box').css("display","block");
						var inserted_book = 1; //only insert one link per book
					};
					if (inserted_book == 1) {
						return;
					};
			});

			});

};

function openlibrary(oclc) {
	$.getJSON('http://openlibrary.org/api/books?bibkeys=OCLC:' + oclc + '&callback=?', 
		function (ol) {
			if (ol['OCLC:' + oclc]) {
				if ((ol['OCLC:' + oclc]['preview']).match(/full/i)){
					var ol_html = "<li><a href=\"" + ol['OCLC:' + oclc]['preview_url'] + "\" target=\"_blank;\" onclick=\"track_ebooks('Open Library',bibnum)\">Open Library</a></li>";
					$(ol_html).appendTo("#ebooks");
					$('#ebook_box').css("display","block");
				}
			}
			else {
				return;
			}
			});
	
};

//resolver
function resolve(param){
    window.location = 'http://libdocs.law.columbia.edu/gateway/' + param
    return false;
};
//sms
function textthis(bibnum) {
	$('<span id="textthis"><img src="/screens/phone.png"/><a href="http://libdocs.law.columbia.edu/peg/sendtext/' + bibnum + '?keepThis=true&TB_iframe=true&height=350&width=500" title="Diamond Law Library - send title to mobile device." class="thickbox">Text this</a></span><br/>').appendTo($("tr td.bibInfoLabel:contains('Call No.')").next())  

}
//track ebooks
function track_ebooks(platform, bibnum) {
	pageTracker._trackPageview('/ebooks/' + platform + '/' + bibnum);
	//console.debug('/ebooks/' + platform + '/' + bibnum);
	return;
}
//track bib record
function track_bib(bibnum) {
	pageTracker._trackPageview('/bibrecords/' + bibnum);
	return;
}

//for requesting in process titles
function page_in_process(bibnum, title, in_process_spot) {
	//$('<span class="page_in_process"><a href="http://libdocs.law.columbia.edu/staff/tools/inprocess/new/?bibnumber=' + bibnum + '&title=' + title + '&keepThis=true&TB_iframe=true&height=500&width=500" title="Diamond Law Library - request title." class="thickbox">Request</a></span><br/>').appendTo(in_process_spot)  
        $('<span class="page_in_process"><a href="http://libdocs.law.columbia.edu:5530/inprocess/new/?bibnumber=' + bibnum + '&title=' + title.substring(0,150) + '&keepThis=true&TB_iframe=true&height=500&width=500" title="Diamond Law Library - request title." class="thickbox">Request</a></span><br/>').appendTo(in_process_spot)  

}

//for Special Collections paging
function special_collections_page(){
	$('<span class="page_in_process"><a href="http://libdocs.law.columbia.edu/staff/tools/special/request/?bibnumber=' + bibnum + '&title=' + title + '&callnumber=' + call_number + '&location=' + bib_location + '&keepThis=true&TB_iframe=true&height=500&width=500" title="Diamond Law Library - request title.." class="thickbox">Request</a></span><br/>').appendTo($(bib_location_spot).next());
	return;  	
};


