/* need to be able to clear cookies in order to make logout less ugly.
 * all the cookies I need to clear should not contain weird characters. */
function clear_cookie(cookie_name, domain) {
	if(!cookie_name) {return;}
	var re = new RegExp(cookie_name);
	if(re.test(document.cookie)) {
		var expDate = new Date();
		expDate.setFullYear(expDate.getFullYear() - 1);
		document.cookie = cookie_name + "=; expires=" + expDate.toUTCString() + "; path=/";
	}
}

/* this version of generate_details_graph_rows is used by popups, where the whole book data structure is available */
/* superceded by below, delete at some point */
function generate_details_graph_rows(book, css_color_class,req_max_topics,max_label_width, bg_bar_class) {

	// defaults
	req_max_topics = typeof(req_max_topics) != 'undefined' ? req_max_topics : 5;
	max_label_width = typeof(max_label_width) != 'undefined' ? max_label_width : 25;
	bg_bar_class = typeof(bg_bar_class) != 'undefined' ? bg_bar_class : "bar";

	var max_topics = book.topic_labels.length;
	var retval = "";
	if(max_topics == 0) {
		retval='<tr><td class="topicTableText">Topic Data Unavailable :(</td></tr>';
		return retval;
	}
	if(max_topics > req_max_topics) {max_topics = req_max_topics;};
	for(var idx=0; idx < max_topics; idx++) {
		var topic_code = book.topic_codes[idx];
		var topic_label = book.topic_labels[idx];
		var topic_value = book.topic_values[idx];
		var topic_link = "search_list.php?term=tbrowse|" + topic_code;
		if(topic_label.length > max_label_width) {
			topic_label = topic_label.substr(0, max_label_width);
			topic_label += '...';
		}
		retval += '<tr> <td class="topicTableText"><a href="' + topic_link + '">' + topic_label + '</a></td>';
		retval += '<td><div class="' + css_color_class + ' ' + bg_bar_class + '"><div style="width: ' + topic_value + '%">';
		retval += '</div></div></td></tr>' + "\n";
	}
	return retval;
}

/* this version is for when we only have the topic_codes and topic_values, typically where we are loading lots of graphs 
   should convert the above into a wrapper for this, just need to parameterize class of td
   depends on topics.js */
function generate_details_graph_rows_2(topic_codes, topic_values, css_color_class,req_max_topics,max_label_width, bg_bar_class,td_class) {

	// defaults
	req_max_topics = typeof(req_max_topics) != 'undefined' ? req_max_topics : 5;
	max_label_width = typeof(max_label_width) != 'undefined' ? max_label_width : 25;
	bg_bar_class = typeof(bg_bar_class) != 'undefined' ? bg_bar_class : "bar";
	td_class = typeof(td_class) != 'undefined' ? td_class : "smalltext";

	var max_topics = topic_codes.length;
	var retval = "";
	if(max_topics == 0) {
		retval='<tr><td class="' + td_class + '">Topic Data Unavailable :(</td></tr>';
		return retval;
	}
	if(max_topics > req_max_topics) {max_topics = req_max_topics;};
	for(var idx=0; idx < max_topics; idx++) {
		var topic_code = topic_codes[idx];
		var topic_value = topic_values[idx];
		var topic_label = gl_topics[topic_code].label;
		var topic_link = "search_list.php?term=tbrowse|" + topic_code;
		if(topic_label.length > max_label_width) {
			topic_label = topic_label.substr(0, max_label_width);
			topic_label += '...';
		}
		retval += '<tr> <td class="' + td_class + '"><a href="' + topic_link + '">' + topic_label + '</a></td>';
		retval += '<td><div class="' + css_color_class + ' ' + bg_bar_class + '"><div style="width: ' + topic_value + '%">';
		retval += '</div></div></td></tr>' + "\n";
	}
	return retval;
}

function generate_style_graph_rows(book, css_color_class, bg_bar_class,do_all) {

	// defaults
	bg_bar_class = typeof(bg_bar_class) != 'undefined' ? bg_bar_class : "bar";
	do_all = typeof(do_all) != 'undefined' ? do_all : false;

	var retval = "";
	var style_labels = ["Motion", "Density", "Pacing", "Dialog", "Description"];
	var styles = ["action", "density", "pacing", "dialog", "description"];

	for(var style_idx in styles) {
		var style = styles[style_idx];
		var style_label = style_labels[style_idx];
		var style_value = book[style];
		retval += '<tr><td class="styleTableText">' + style_label + '</td>';
		retval += '<td><div class="' + css_color_class + ' ' + bg_bar_class + '"><div style="width: ' + style_value + '%">';
		retval += '</div></div></td></tr>' + "\n";
	}
	return retval;
}

// use this callback in get_book below to populate and open a dialog with full BookDNA
// just need a div with ID book_dna in the page somewhere
function show_bookdna(book_ary, textStatus, jqXHR) {
	var book = book_ary[0];
        var dialog_title = "<i>" + book.title + "</i>, " + book.author;
        var output = '<h2>Language</h2>';
        output += '<table id="styleTable"><col width="250px"/><col/>';
        output += generate_style_graph_rows(book, "greenbar");
        output += "</table>";
	output += '<a id="popup_def_link" href="http://storytime.booklamp.org/booklamps-faq/#qa2_3">(click here for language definitions)</a>';
	output += "<hr/>";

        output += '<h2>StoryDNA</h2>';
        output += '<div id="hugeTopicTableDiv">';
        output += '<table id="hugeTopicTable"><col width="250px"/><col/>';
        output += generate_details_graph_rows_2(book.topic_codes, book.topic_values, "bluebar", 100, 100, "bar", "topicTableText");
        output += "</table></div>";

        $("#book_dna").html(output);
        $("#book_dna").dialog({width: 450, 
			title: dialog_title, 
			buttons: {"Close": function() { $(this).dialog("close");}},
			open: function() {$('#popup_def_link').blur();}
			});
}

// this is sort of the entry point
// isbn: a single isbn, or a hyphen-separated list of isbns
// big_summary: 0 if you want full summary, 1 if truncated
// callback: a function expecting standard jQuery params, like show_bookdna above
function get_book(isbn, big_summary,callback) {
        var data = {term: isbn, sum: big_summary };
        $.getJSON("json_book.php", data, callback );
}

function get_book_dna(isbn) {
	get_book(isbn, '0', show_bookdna);
}

var summary_text="empty";
function show_summary(data, textStatus, jqXHR) {
        var dialog_title = data.title ;
	dialog_title += '<hr/><span class="summary_title_details">' + data.author + "</span><br/>"
        dialog_title += '<span class="summary_title_details">Listed by the publisher as ' + data.genre + "</span>" ;
        summary_text = '<span class="summary_body_heading">Publisher\'s Description</span>';
	summary_text += '<hr style="width: 550px; margin-top:0; margin-left: 0" /></span>';
	summary_text += '<p style="margin-left: 35px; font-size: 11pt">' + data.summary + '</p>';
        $("#summary_text").html(summary_text);
        $("#summary_text").dialog({width: 600, 
			title: dialog_title, 
			buttons: {"Close": function() { $(this).dialog("close");}}
			});
}

function get_summary(isbn) {
        var data = {term: isbn};
        //var topDim = $("#contentBox").scrollTop();
        //alert(topDim);
        $.getJSON("json_book_summary.php", data, show_summary );
}

function email_success(data, textStatus, jqXHR) {
	$('#getEmailStatus').html("email address submission success!");
	setTimeout("$('#getEmail').dialog('close')", 3000);
}

function email_error(jqXHR, textStatus, errorThrown) {
	$('#getEmailStatus').html("oops!  There was a problem, please try later!");
	setTimeout("$('#getEmail').dialog('close')", 3000);
}


function send_emailaddr() {
        var data = {email: $('#emailText').val(), name: $('#nameText').val()};
	if(data.email.length < 1) {
		$('#getEmailStatus').html("please enter an email address");
		return false;
	}
        $.ajax({url: "collect_email.php",  data: data, success: email_success, error: email_error });
	return false;
}


function show_email_req() {
	var dialog_title='Coming Soon!';
	$('#getEmail').dialog({modal: true, title: dialog_title, buttons: {"Submit": send_emailaddr, "Cancel": function() { $(this).dialog("close");} }     });
	$('#getEmailStatus').html("");
}

/*
 * book bin functionality section
 * */
bookbin_dirty = true;

function set_ebl_message(data, textStatus, jqXHR) {
	var $code = data.code;
	var $text = data.text;
	if($code == 0) {
		$('#bookBinEmailSuccess').html($text);
		$('#bookBinEmailError').html("");
		setTimeout("$('#bookBinDialog').dialog('close')", 3000);
	} else {
		$('#bookBinEmailSuccess').html("");
		$('#bookBinEmailError').html($text);
	}
}

function ebl_complete() {
	$('#emailBookListSpinner').hide();
}

function email_book_list() {
	var isbns = get_book_bin_isbns();
	$('#emailBookListSpinner').show();
	var ajax_call = $.ajax({ url: "ajax_book_bin.php",
                                 dataType: 'json',
                                 data: {'isbns': isbns, 'action': 'email'}, 
                                 success: set_ebl_message, complete: ebl_complete });
}

function push_book_list() {
	if(gl_logged_in) {
		var isbns = get_book_bin_isbns();
		var ajax_call = $.ajax({ url: "ajax_book_bin.php",
                                         dataType: 'json',
                                         data: {'isbns': isbns, 'action': 'update'} });
	}
}


function add_to_bin(isbn) {
	var bookBinTab = $('#bookBinTab').get(0);
	if(window.localStorage) {
		localStorage[isbn] = "1";
	}
	else if(bookBinTab.addBehavior) {
		bookBinTab.load("isbnList");
		var isbnsString=bookBinTab.getAttribute("isbns");
		if(isbnsString === null) {
			isbnsString = isbn;
		} else {
			if(isbnsString.length < 1) {
				isbnsString =  isbn;
			} else {
				if(isbnsString.indexOf(isbn) == -1) {
					isbnsString += "-" + isbn;
				}
			}
		}
		bookBinTab.setAttribute("isbns", isbnsString);
		bookBinTab.save("isbnList");
	}
	update_bin_tab();
	bookbin_dirty=true;
	push_book_list();
}

function sync_book_bin() {
	/* only exists in new sessions */
	if (typeof(gl_bookbin_sync) === "undefined") {
	       return;
	}
	var isbnPattern = /[0-9]{13}/;

	var bookBinTab = $('#bookBinTab').get(0);
	if(window.localStorage) {
		var delete_keys=[];
		/* "for .. in" iterator doesn't work on localStorage in Firefox 3.6 */
		/* clear out old isbns in two steps.  because deleting from localStorage while
		 * iterating through it tends to not go well */
		/* I need to use the approach I took with IE here as well hindsight etc */
		for(var idx=0; idx < localStorage.length; idx++) {
			var isbn = localStorage.key(idx);
			if(isbnPattern.test(isbn) && localStorage[isbn] == "1") {
				delete_keys.push(isbn);
			}
		}
		for(var idx in delete_keys) {
			delete localStorage[delete_keys[idx]]; 
		}
		if(gl_bookbin_sync == 'empty') {
			return;
		}
		var isbnAry = gl_bookbin_sync.split("-");
		for(var idx in isbnAry) {
			localStorage[isbnAry[idx]] = 1; 
		}
	} else if(bookBinTab.addBehavior) {
		bookBinTab.load("isbnList");
		if(gl_bookbin_sync == 'empty') {
			bookBinTab.setAttribute("isbns", "");
		} else {
			bookBinTab.setAttribute("isbns", gl_bookbin_sync);
		}
		bookBinTab.save("isbnList");
	}
}

function remove_from_bin(isbn) {
	var bookBinTab = $('#bookBinTab').get(0);
	if(window.localStorage) {
		delete localStorage[isbn] ;
	} 
	else if(bookBinTab.addBehavior) {
		bookBinTab.load("isbnList");
		var isbnsString=bookBinTab.getAttribute("isbns");
		var newIsbnsString="";

		if(isbnsString === null) {
			return;
		} else {
			var isbnAry = isbnsString.split("-");
			for(var idx in isbnAry) {
				if(isbnAry[idx] != isbn) {
					if(newIsbnsString.length < 1) {
						newIsbnsString = isbnAry[idx];
					} else {
						newIsbnsString += "-" + isbnAry[idx];
					}
				}
			}
		}
		bookBinTab.setAttribute("isbns", newIsbnsString);
		bookBinTab.save("isbnList");
	}

	$(".addToBinButton").attr('disabled', false);
	var count = update_bin_tab();
	if(count == 0) {
		$('#bookBinDialog').dialog('close');
	}
	var rowToHide = '#bookBinRow' + isbn;
	$(rowToHide).hide(500);
	bookbin_dirty=true; /* this forces a reload next time the book bin is opened */
	push_book_list();
}

function show_book_bin(book_ary, textStatus, jqXHR) {
	var dialog_text = '<a style="font-size: 1px" id="bookBinFocusBait" href="javascript:void(0)">&nbsp;</a>';
	dialog_text += '<table class="bookBinTable">';
	for(var book_idx in book_ary) {
		var book = book_ary[book_idx];
		dialog_text += '<tr id="bookBinRow' + book.isbn + '">'
		dialog_text += '<td><img class="bookBinThumb" src="' + book.thumb + '" /></td>';
		dialog_text += '<td><b>Title:</b> <a href="book_suggestions.php?refbook=' + book.isbn + '">' + book.title + '</a><br/>';
		var counter=0;
		var author_text="";
		for(var author in book.authors) {
			if(counter != 0) {
				author_text += ", ";
			}
			author_text += '<a href="search_list.php?term=author%7c' + author + '">' + book.authors[author] + '</a>';
			counter++;
		}
		if(counter > 1) {
			dialog_text += '<b>Authors:</b> ';
		} else {
			dialog_text += '<b>Author:</b> ';
		}
		dialog_text += author_text;
		dialog_text += '</td>';
		dialog_text += '<td><a href="javascript:remove_from_bin(' + book.isbn + ')">Remove</a></td>';

		dialog_text += '</tr>';
	}
	dialog_text += '</table>';
	dialog_text += '<br/>';
	dialog_text += '<img id="emailBookListSpinner" style="display: none" src="images/smallLoading.gif" alt="loading..." />';
	dialog_text += '<span id="bookBinEmailError" style="color: red"></span>';
	dialog_text += '<span id="bookBinEmailSuccess" style="color: green"></span>';
	$('#bookBinDialog').html(dialog_text);
	$('#bookBinDialog').dialog('open');
	bookbin_dirty = false;
}
	
function get_book_bin_isbns() {
	var count=0;
	var isbnPattern = /[0-9]{13}/;
	var isbns = "";

	var bookBinTab = $('#bookBinTab').get(0);
	if(window.localStorage) {
		/* "for .. in" iterator doesn't work in Firefox 3.6 */
		for(var idx=0; idx < localStorage.length; idx++) {
			var isbn = localStorage.key(idx);
			if(isbnPattern.test(isbn) && localStorage[isbn] == "1") {
				if(count != 0) {isbns += "-";}
				isbns += isbn;
				count++;
			}
		}
	}
	else if(bookBinTab.addBehavior) {
		bookBinTab.load("isbnList");
		isbns=bookBinTab.getAttribute("isbns");
		if(isbns.length > 0) {
			count=1;
		}
	}
	if(count == 0) {
		return null;
	}
	return isbns;
}

function get_book_bin() {
	$('#bookBinEmailSuccess').html("");
	$('#bookBinEmailError').html("");

	if(bookbin_dirty === false) {
		$('#bookBinDialog').dialog('open');
		return;
	}

	var isbns = get_book_bin_isbns();
	get_book(isbns, 0, show_book_bin); 
}

function update_bin_tab() {
	var count=0;
	var isbnPattern = /[0-9]{13}/;

	var bookBinTab = $('#bookBinTab').get(0);
	if(window.localStorage) {
		for(var idx=0; idx < localStorage.length; idx++) {
			var isbn = localStorage.key(idx);
			if(isbnPattern.test(isbn) && localStorage[isbn] == "1") {
				count++;
			}
		}
	} 
	else if(bookBinTab.addBehavior) {
		bookBinTab.load("isbnList");
		isbns=bookBinTab.getAttribute("isbns");
		if(isbns != null) {
			if(isbns.length > 0) {
				/* each isbn is 13 chars, plus a hyphen if more than 1 
				 * add a 1 to normalize length so we can compute number
				 * of isbns based on the string length */
				var temp = isbns.length+1;
				count = temp/14;
			}
		}
	}

	if(count > 0) {
		if(count > 9) {
			$("#bookBinCount").html(count + " (List is full!)");
			$("#bookBinTab").css("width",330);
			$(".addToBinButton").attr('disabled', true);
		} else {
			$("#bookBinCount").html(count);
			$("#bookBinTab").css("width",260);
		}
		$("#bookBinTab").show(500);
	}
	else {
		/* my theory: in IE8 and possibly earlier, DOM objects with display=none
		 * have removeAttribute method, but even testing for its existence throws an exception.
		 * this causes problems in the guts of jQuery.  workaround is, make sure it's not display: none
		 * before trying to hide it.  should work fine for other browsers too */
		if($("#bookBinTab").css('display') != "none") {
			$("#bookBinTab").hide(500);
		}
	}
	return count;
}

/*
 * search box functions
 * */
function stop_spinny() {
        $('#loadingGif').css('visibility','hidden');
}

function search_callback(req, resp_callback) {
	//var stype = $("select option:selected").attr("value");
	var stype = "multi";
	$('#loadingGif').css('visibility', 'visible');
	var data={term: req['term'], stype: stype};
	var ajax_call = $.ajax({ url: "json_search.php",
                                 dataType: 'json',
                                 data:  data, 
                                 success: resp_callback,
				 complete: stop_spinny });
}

function select_callback(event, ui) {
	if( /^No results/i.test(ui.item['value']) ) {
		var path="http://storytime.booklamp.org/booklamps-faq/#qa1_9";
	} else if( /^No title/i.test(ui.item['value']) ) {
		var query = encodeURIComponent(ui.item['value']);
		var path = "search_list.php?term=" + query;
	} else {
		var query = encodeURIComponent(ui.item['value']);
		var path = "search_list.php?term=" + query;
	}
	window.location = path;
	return false;
}

var last_search_item="";

function search_keyup(event) {
	if(event.which == 13) {
		if(last_search_item.length > 2) {
			var path = "search_list.php?term=" + encodeURIComponent(last_search_item);
			window.location = path;
		}
		var value = $("#searchText").val();
		if(value.length < 3) {
			return;
		}
		var query = encodeURIComponent("multi|" + value);
		var path = "search_list.php?term=" + query;
		window.location = path;
	} else {
		last_search_item="";
	}
}

function search_menufocus(event, ui) {
	last_search_item=ui.item.value;
	return false;
}

/* pages using search feature should call this */
function search_init() {
	$("#searchText").autocomplete( { source: search_callback, select: select_callback, focus: search_menufocus, minLength: 2 });
	$("#searchText").placeholder(); /* the placeholders in the login popup will get hosed if we add them now, so just do this one */
	$("#searchText").keyup(search_keyup);
}

function isDevMode() {
	var devMode=0;
	if(window.localStorage) {
		if(localStorage['dev'] == "1") {
			devMode=1;
		}
	}
	return devMode;
}

function create_placeholders(which) {
	$('#' + which + ' input[placeholder]').placeholder();
}

/* 
function create_recaptcha() {
	Recaptcha.create('6LckoMcSAAAAAL5IXv5Ig_bby72ISjdsOWtOjcl6', $('#recaptchaDiv').get(0), {});
}

function load_recaptcha() {
	if(typeof(Recaptcha)=="object") {return;}
	var scr = document.createElement('script'); scr.type = 'text/javascript'; scr.async = true;
	scr.src = ('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js');
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(scr, s);
} */

function login_complete(jqXHR, textStatus) {
	$('#loginSpinner').hide();
}
function login_error(jqXHR, textStatus, errorThrown) {
	var statusSpan = $('#loginStatusText');
	statusSpan.html(textStatus);
	statusSpan.css("color","red");
}

function login_callback(data, textStatus, jqXHR) {
	var mode = data.mode;
	var statusSpan = $('#loginStatusText');
	if('error' in data) {
		statusSpan.html(data.error);
		statusSpan.css("color","red");
	} else {
		statusSpan.html(data.status);
		statusSpan.css("color","green");
		if(mode == 'login') {
			location.reload();
		}
	}
}

function login_keyup(event, form) {
	if(event.keyCode == 13){
		login_action(form);
	}
}

function login_action(action) {
	/* action is login,reset,or register */
	var data={};
	data[action] = true;
	switch(action) {
		case 'login':
			data.user = $('#loginCellUser').val();
			data.pass = $('#loginCellPass').val();
			break;
		case 'reset':
			data.user = $('#resetCellUser').val();
			break;
		case 'register':
			data.user = $('#registerCellUser').val();
			data.pwd = $('#registerCellPass').val();
			data.pwd2 = $('#registerCellPass2').val();
			break;
		default:
			return;
	}
	$('#loginSpinner').show();
	$.ajax({type: 'POST', url: 'ajax_login.php', data: data, success: login_callback, dataType: 'json',complete: login_complete, error: login_error });
}

/* have to create placeholders only after the absolute div they are in is visible, so all the callback nonsense */
/* those responsible for coding this Javascript, have been sacked. */
function show_login() {
	// load_recaptcha();
	create_placeholders('loginCell');
	$('#loginStatusText').html('');
	$('#loginCell').show();
	$('#resetCell').hide();
	$('#registerCell').hide();
	$('#loginDialog').dialog({width: 600, height: 250, modal: true,  open: function() {$('#loginFocusBait').blur();} });
}

/* those responsible for sacking those who coded the above Javascript, have been sacked. */
function show_register() {
	create_placeholders('registerCell');
	$('#loginStatusText').html('');
	$('#loginCell').hide();
	$('#resetCell').hide();
	$('#registerCell').show();
	$('#loginDialog').dialog({width: 600, height: 250, modal: true, open: function() {$('#loginFocusBait').blur();} });
}

function switch_login_dlg(from, to) {
	$('#' + from).fadeOut(500);
	$('#' + to).fadeIn(500,create_placeholders(to));
	$('#loginStatusText').html('');
	/*
	if(to == "registerCell") {
		create_recaptcha();
	} */
}

/*
 * shared UI initialization
 * */
$(document).ready(function () {
	if(typeof gl_discount_sift != 'undefined') {
		return;
	}
	if(gl_logged_in) {
		var emailButton = {text: "E-mail Your List", disabled: false, click: email_book_list};
	} else {
		var emailButton = {text: "Sign In to E-mail Your List", disabled: false, click: function() { window.location="login.php";}};
	}
		
	$('#bookBinDialog').dialog({ autoOpen: false, modal: true, width: "480px",
		buttons: [ 
			   emailButton,
			   {text: "Close", click: function() { $(this).dialog("close");}}
		],
		open: function() {$('#bookBinFocusBait').blur();}
	});
	sync_book_bin();
	update_bin_tab();
	});

