var expireDate = new Date(2050, 10, 23);
var g_prototypeAvailable = false;

//IE6 background image caching
try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}

if ( (typeof Prototype !='undefined') && (typeof Element != 'undefined') && (typeof Element.Methods !='undefined') )
{
	g_prototypeAvailable = true;
	// global Hash to store current page's usercontrol objects. They are added to the has when they are registered.
	var g_userControls = new Hash();
	
	//Event.observe(window, 'load', function() {
	//  updateUserConnections();
	//});
}

function cookieVal(cookieName)
{
thisCookie = document.cookie.split("; ")
for (i=0; i<thisCookie.length; i++)
	{
	if (cookieName == thisCookie[i].split("=")[0])
		{
		return thisCookie[i].split("=")[1]
		}
	}
return 0;
}

function setCookie(cookieName,cookieContent,transientBoolean)
{
if (transientBoolean)
	{
	document.cookie = cookieName+"="+cookieContent;
	}
else
	{
	document.cookie = cookieName+"="+cookieContent+";expires="+expireDate.toGMTString();
	}
}

function setDisplayforID(id, display) // showhide is used in response.php
{
document.getElementById(id).style.display = display;
}

function toggleShowHide(id, state)
{
if (document.getElementById(id).style.display == 'none')
	{
	setDisplayforID(id, state);
	}
else
	{
	setDisplayforID(id, 'none');
	}
}

function gotoaURL(url)
{
window.top.location = url;
}

function checkSpans(page) {
	var x=document.getElementById('*');
	var postArray='';
	if(x){ x.parentNode.removeChild(x); }
	for(var x=0,y=document.getElementsByTagName('*'),oStr='';y[x];x++) {
		if(y[x].id&&y[x].tagName.match("span","i")) {
			var saneStr=y[x].id.replace(/&/,'&amp;').replace(/</,'&lt;').replace(/>/,'&gt;').replace(/\"/,'&quot;'); //nice string fixer
			if (saneStr.match("tr[0-9]{6}")&&saneStr) {
				void(postArray+=saneStr+',');
			}
		}
	}

	postArray=postArray.replace(/,$/g,'');
	var tForm=document.createElement('form');
	void(tForm.name='translateForm');
	void(tForm.action='/translate.php?page='+page);
	void(tForm.method='POST');
	void(tForm.innerHTML='<input type="hidden" name="stuff" value="'+postArray+'">');
	void(document.body.appendChild(tForm));
	tForm.submit();
}

function lightSpan()
{
//document.getElementById("translatethis").style.backgroundColor = "yellow";
}

function scaleTextBox(id, size)
{
document.getElementById("ms_"+id).style.display = "none";
new Effect.Scale(id, size, {scaleX: false, scaleContent: false });
}

// send an ajax request and update elt_to_update with the response text
function basic_ajax_updater( url, params, elt_to_update )
{
basic_ajax( url, params, function(r)
	{ 
	$( elt_to_update ).innerHTML = r.responseText;
	}
	);
}

// send a simple ajax request.  
// callback is an optional *function*, e.g. 
//function(r){ alert(r.responseText);}
function basic_ajax( url, params, callback ) {
	//console.log(Prototype);
	var request = new Ajax.Request(
		url,
		{
		method: "post",
		asynchronous: true,
		parameters: params,
		onSuccess: callback
		});
	return request;
}

function basic_ajax_sync (url, params, callback ) {
	var request = new Ajax.Request(
		url,
		{
		method: "post",
		asynchronous: false,
		parameters: params,
		onSuccess: callback
		});
}


function basic_ajax_eval( url, params, callback ) {
	var request = new Ajax.Request(
		url,
		{
		method: "post",
		asynchronous: true,
		parameters: params,
		onSuccess: callback,
		evalJS: 'force'
		});
	
}

/**
 * Ajax.Request.abort
 * extend the prototype.js Ajax.Request object so that it supports an abort method
 */

if (g_prototypeAvailable)
{
	Ajax.Request.prototype.abort = function()
	{
		// prevent and state change callbacks from being issued
		this.transport.onreadystatechange = Prototype.emptyFunction;
		// abort the XHR
		this.transport.abort();
		// update the request counter
		//if (Ajax.activeRequestCount > 0)
		{
			Ajax.activeRequestCount--;
		}
	};
}

// disable a submit button onclick, so the user only clicks once
// add it to a submit button like this: <input onclick='disable_button(this)'...
// optional second argument is the new text for the button after it's clicked
function disable_button(button, button_text) {
	button_text = button_text || "loading...";
	button.setAttribute('disabled', true);
	button.value = button_text;
	button.form.submit();
	return false;
}


function updateUserConnections() {
	var handleReturn = function(t) {
		if (t.responseText)
		{
			setTimeout( 'updateUserControls()', 100 );
		}
		// I put a delay on it because safari multithreads enough that it was sending the ajax request
		// before it had finished rendering the page so the usercontrols were not instantiated yet.
	};
	basic_ajax('/ajax_updateUserConnections.php', null, handleReturn);
}

function updateUserControls() {
	var gsize = g_userControls.size();
	
	
	if ( g_prototypeAvailable  && gsize)
	{
		var i = 0;
		var outString = 'objects=';
		var paramHash = new Hash();
		var len = g_userControls.size();
		g_userControls.each(function(uc) {
			paramHash[uc.key] = uc.value.number;
			outString += uc.key+':'+uc.value.number;
			if (i < (len - 1))
				outString += ',';
			i++;
		});
		var par =$H({
			objects: paramHash
		});
		
		var handleReturn1 = function(t) {
			var infoHash = $H(t.responseText.evalJSON(true));
			infoHash.each(function(pair) {
				
				theUC = g_userControls[pair.key];
				affInfo = $H(pair.value);
				theUC.updateAffinityDisplay(affInfo.uc_percentile, affInfo.uc_overlap); 
			});
		}

		basic_ajax('/ajax_updateUserControls.php', outString, handleReturn1);
	}
}

if ( g_prototypeAvailable )
{
	// User control object
	//function LTUserControl(element, name,number, affinity, affinityOverlap, isSelf) {
	var LTUserControl = Class.create();
	LTUserControl.prototype = {
		initialize: function(el, paramList) {
			var params = paramList.evalJSON(true);
			this.inputParams = params;
			this.element = $(el);
			this.controlid = params.controlid;
			this.controlcode = params.controlcode;
			this.name = params.name;
			this.number = params.number;
			this.isSelf = params.isSelf;
			this.element.className = 'userControlObject';
			this.originalHTML = this.element.innerHTML;
			this.affinity = new Object ({ 
				percentile: parseInt(params.affinityPercentile), 
				overlap: parseInt(params.affinityOverlap), 
				control: $('ucaf_'+this.controlcode), 
				textbox: $('ucafp_'+this.controlcode)}
			);
			
			var afp = $('ucafp_'+this.controlcode);
			if ((this.affinity.overlap > 0) && (!this.isSelf))
				afp.innerHTML = this.affinity.percentile + '%';
			else
				afp.innerHTML = '';
				
			this.arrow = $('ucar_'+this.controlcode);
			this.rightside = $('ucrs_'+this.controlcode);
				
			// Create mainMenu document object...but don't add it yet.
			this.mainMenu = document.createElement('div');
			this.mainMenu.className = 'ucoMenu ucoMainMenu';
			this.mainMenu.id = 'ucmm_'+this.controlcode;
			document.body.appendChild(this.mainMenu);
			this.mainMenu.style.position = 'absolute';
			this.mainMenu.style.zIndex = '10';
			Position.absolutize(this.mainMenu);
			
			// links
			this.links = new Object();
			this.links.profile = '/profile/'+this.name;
			this.links.catalog = '/catalog/'+this.name;
			this.links.reviews = '/profile_reviews.php?view='+this.name;
			this.links.tagcloud = '/tagcloud.php?view='+this.name;
			this.links.authorcloud = '/authorcloud.php?view='+this.name;
			
			// Handle events
			this.registerEvents();
		},
		
		destroy: function() {
		},
		
		registerEvents: function() {
			Event.observe(this.arrow, "click", this.dropdown.bindAsEventListener(this));
			//Event.observe(this.arrow, "mouseup", this.dropdown.bindAsEventListener(this));
			//Event.observe(this.element, "mouseout", this.onmouseout.bindAsEventListener(this));
			//Event.observe(this.mainMenu, "mouseout", this.onmouseout.bindAsEventListener(this));
			Event.observe($('ucrs_'+this.controlcode), "click", this.onclick.bindAsEventListener(this));
			//Event.observe(this.arrow, "click", this.dropdown.bindAsEventListener(this));
			Event.observe(document, "click", this.onmouseout.bindAsEventListener(this));
		 },
		
		// Customized presentation layer. Maybe we should just use Tooltip to do that?
		addMenuItem: function (parent,imgfile,text,link, disabled,hasSubmenu, afterElement)
		{
			var menuItem = document.createElement('div');
			menuItem.className = 'ucoMenuItem';
			var base = '<span class="ucoMenuIcon">';
			if (imgfile)
			{
				base += '<img src="/pics/'+imgfile+'">';
			}
			base += '</span><span class="ucoMenuItemText">'+text+'</span>';
			if (hasSubmenu)
			{
				base = '<div class="ucoMenuItemArrow">&#x25B6;</div>' + base;
			}
			if (link)
			{
				menuItem.onclick = function() { gotoaURL(link) };
			}
			menuItem.update(base);
			
			if (disabled)
			{
				menuItem.addClassName('ucoDisabled');
			}
			
			if (parent)
			{
				if (afterElement)
				{
					var pels = parent.descendants();
					var pcount = pels.length;
					if (pels[pcount-1] == $(afterElement))
					{
						parent.appendChild(menuItem);
					}
					else
					{
						var ae = $(afterElement);
						var ne = ae.next();
						var newel = this.mainMenu.insertBefore(menuItem, ne);
					}
				}
				else
				{
					parent.appendChild(menuItem);
				}
			}
			return menuItem;
		},
		
		updateAffinityDisplay: function (percentile, overlap)
		{
			if (!this.isSelf)
			{
				this.affinity.percentile = percentile;
				this.affinity.overlap = overlap;
				
				if (this.menuItemsExist)
				{
					var am1 = $('ucafpm_'+this.controlcode);
					var am2 = $('ucafom_'+this.controlcode);
					if (this.affinity.overlap)
					{
						var s1 = $('ucafsi_'+this.controlcode);
						if (!am1)
						{
							afftext1 = this.affinity.percentile+'% similar library';
							afftext2 = this.affinity.overlap+' shared book'+plural;
							var am1 = this.addMenuItem(this.mainMenu,'',afftext1, '',true,false,s1);
							am1.id = 'ucafpm_'+this.controlcode;
							var am2 = this.addMenuItem(this.mainMenu,'',afftext2, '',true,false,s1);
							am2.id = 'ucafom_'+this.controlcode;
							this.addSeparatorItem(this.mainMenu);
						}
						else
						{
							// need to update the text here.
							var am1 = $('ucafpm_'+this.controlcode);
							var am2 = $('ucafom_'+this.controlcode);
							afftext1 = this.affinity.percentile+'% similar library';
							afftext2 = this.affinity.overlap+' shared book'+plural;
							am1.down('.ucoMenuItemText').innerHTML = afftext1;
							am2.down('.ucoMenuItemText').innerHTML = afftext2;
						}
					}
				}
				
				// Need to update the main affinity number
				if (this.affinity.overlap)
				{
					var mainaff = $('ucafp_'+this.controlcode);
					mainaff.innerHTML = percentile+'%';
					var tt = overlap+' shared book';
					if (overlap != 1)
						tt += 's';
					mainaff.title = tt;
				}
			}
		},
		
		addSeparatorItem: function (parent)
		{
			var menuItem = document.createElement('div');
			menuItem.className = 'ucoMenuDivider';
			parent.appendChild(menuItem);
			return menuItem;
		},
	
		doNothing: function (event)
		{
		},
		
		//LTUserControl functions
		onclick: function (event)
		{
			Event.stop(event);
			gotoaURL(this.profileURL);
		},
		
		onmouseout: function (event)
		{
			//this.mainMenu.style.display = 'none';
			this.mainMenu.hide();
			this.mainMenu.style.display = 'none';
			this.arrow.removeClassName('ucoArrowOn');
			this.element.removeClassName('userControlHover');
		},
		
		dropdown: function (event)
		{
			Event.stop(event);
			g_userControls.each(function(o){ o.value.onmouseout(); });
			if (!this.menuItemsExist)
			{
				var plural = '';
				if (this.affinity.overlap > 1)
					plural = 's';
				
				// Make the menu items...	
				this.addMenuItem(this.mainMenu,'status_offline_tiny.png', 'Profile',this.links.profile,false, false,null);
				this.addMenuItem(this.mainMenu,'book_tiny.png', 'Catalog',this.links.catalog,false, false,null);
				var s1 = this.addSeparatorItem(this.mainMenu);
				s1.id = 'ucafsi_'+this.controlcode;
				if (this.affinity.overlap)
				{
					afftext1 = this.affinity.percentile+'% similar library';
					afftext2 = this.affinity.overlap+' shared book'+plural;
					var am1 = this.addMenuItem(this.mainMenu,'',afftext1, '',true,false,null);
					am1.id = 'ucafpm_'+this.controlcode;
					var am2 = this.addMenuItem(this.mainMenu,'',afftext2, '',true,false,null);
					am2.id = 'ucafom_'+this.controlcode;
					this.addSeparatorItem(this.mainMenu);
				}
				this.addMenuItem(this.mainMenu,'reviews_tiny.png', 'Reviews',this.links.reviews,false, false,null);
				this.addMenuItem(this.mainMenu,'tag_yellow_tiny.png', 'Tag Cloud',this.links.tagcloud,false, false,null);
				this.addMenuItem(this.mainMenu,'author_cloud_tiny.png', 'Author Cloud',this.links.authorcloud,false, false,null);
				//this.addSeparatorItem(this.mainMenu);
				//var conMenu = this.addMenuItem(this.mainMenu,'connections_tiny.png', 'Connections','',false, true);
				this.menuItemsExist = true;
			}
			
			//this.mainMenu.style.display = 'block';
			var elof = Position.positionedOffset(this.element);
			this.mainMenu.style.top = elof[1]+17+'px';
			this.mainMenu.style.left = elof[0]+1+'px';
			this.mainMenu.style.borderWidth = '1px';
			this.mainMenu.show();
			this.mainMenu.style.display = 'block';
			
			this.arrow.addClassName('ucoArrowOn');
			this.element.addClassName('userControlHover');
				
		}
		
		
	};

}

function registerUserControlObject(ucname, params) { // (username, userid, ucname, affinity, affinityOverlap, isSelf) {
	if (g_prototypeAvailable)
	{
		var controlElement = $(ucname);
		// Create a new LTUserControl object with the given params
		var uc = new LTUserControl(controlElement, params); //username, userid, affinity, affinityOverlap, isSelf);
		// Push the new LTUserControl object onto the userControls array so that 
		/// we can later communicate with all user controls on the page
		//g_userControls.ucname = uc;
		//g_userControls.push(uc);
		g_userControls[ucname] = uc;
		// Attach the LTUserControl to the DOM object in case we want to get to it that way some time.
		controlElement.userControlObject = uc;
	}
}

function releaseMenu(menu)
{
	menu.style.display = 'none';
}



// Collections calls here...
function toggleCollectionMembership(checkbox,bookid,fullcode)
{
	//cList_4
	//Need to do an ajax update of the collections table.
		
	//checkbox.value = checkbox.checked;	
	checkbox.disabled = true;
	var url = '/ajax_collectionsToggleMembership.php';
	var params = {
		c_id: checkbox.value,
		newvalue: checkbox.checked,
		bookid: bookid,
		fullcode: fullcode
	};
	var responseFunction = function(t) 
	{
		if (t.responseText == '1')
		{
			checkbox.disabled = false;
		}
		else
		{
			checkbox.checked = !checkbox.checked;
			checkbox.disabled = false;
		}
	};
	
	basic_ajax(url,params,responseFunction);
}


function addCollection(name, omit, listcontainerID, bookid, fullcode)
{
	var url = '/ajax_collectionsAddCollection.php';
	var params = {
		name: name.value,
		omit: omit.checked,
		book: bookid
	};
	var responseFunction = function(t) {
		var rArray = t.responseText.evalJSON();
		
		if (rArray.success)
		{
			var container = $(listcontainerID);
			var newel = document.createElement('div');
			newel.className = 'collectionModItem';
			newel.id = 'collectionItem_'+rArray.c_id;
			
			var newlines = '<input name="cList_'+rArray.c_id+'" id="cList_'+rArray.c_id+'" type="checkbox" value="'+rArray.c_id+'" ';
			if (rArray.inCollection)
				newlines += ' checked ';
			newlines += 'onChange="javascript:toggleCollectionMembership(this,'+bookid+','+fullcode+'); return false;">';
			newlines += name.value;
			if (omit.checked)
				newlines += ' * ';
			newlines += ' (<a href="#" onclick="javascript:deleteCollection('+rArray.c_id+'); return false;">delete</a>)';

			newel.innerHTML = newlines;
			container.appendChild(newel);
		}
		else
		{

		}
		
	};
	
	basic_ajax(url,params,responseFunction);
}


function deleteCollection(c_id)
{
	//cList_4
	//Need to do an ajax update of the collections table.
		
	var url = '/ajax_collectionsDeleteCollection.php';
	var params = {
		c_id: c_id
	};
	var responseFunction = function(t) 
	{
		if (t.responseText == '1')
		{
			//checkbox.disabled = false;
			var clist = $('collectionModList');
			var item = $('collectionItem_'+c_id);
			item.style.display = 'none';
			clist.removeChild(item);
		}
		else
		{
			//checkbox.checked = !checkbox.checked;
			//checkbox.disabled = false;
			alert('failure');
		}
	};
	
	basic_ajax(url,params,responseFunction);
}


function setRating(container, bookid, rating, editable, style)
{
	co = LT_findObj(container);
	var uid = LT_GetRandomID(8);
	var url = '/ajax_setBookRating.php';
	var params = {
		uid: uid,
		book: bookid,
		editable: editable,
		container: container,
		style: style,
		rating: rating
	};
	
	var rateSuccessF = function(t) {
		if (co)
		{
			if (t.responseText != '0')
			{
				co.innerHTML = t.responseText;
			}
			co.style.opacity = 1;
			co.style.filter = 'alpha(opacity=100)';
		}
	};
	
	if (co)
	{
		co.style.opacity = 0.3;
		co.style.filter = 'alpha(opacity=' + 30 + ')';
	}
	basic_ajax(url,params,rateSuccessF);
}

function showuwyb()
{
$('showmoreuwyb').style.display='none';
$('uwybhide').style.display='inline';
}

function showMore(element)
{
var el = $(element);
var className = el.className;
className = className.replace("showmore", "showmore_show");
el.className = className;
}
   
// define a console object and associated methods if it doesn't already exist (i.e. we're using IE) to prevent JS errors on trying to use console.log
// intended to wrap the firebug console methods described here: http://getfirebug.com/console.html
if( typeof window.console == "undefined" )
	{
		window.console = {};
		console.log = function(o) 
			{
				// do nothing, for now
			};
		console.debug = function(o) 
			{
				// do nothing, for now
			};
		console.info = function(o) 
			{
				// do nothing, for now
			};
		console.warn = function(o) 
			{
				// do nothing, for now
			};
		console.assert = function(expr) 
			{
				// do nothing, for now
			};
		console.error = function(o) 
			{
				// do nothing, for now
			};
		console.dir = function(o) 
			{
				// do nothing, for now
			};
		console.dirxml = function(node) 
			{
				// do nothing, for now
			};
		console.trace = function() 
			{
				// do nothing, for now
			};
		console.group = function(o) 
			{
				// do nothing, for now
			};
		console.groupEnd = function() 
			{
				// do nothing, for now
			};
		console.time = function(name) 
			{
				// do nothing, for now
			};
		console.timeEnd = function(name) 
			{
				// do nothing, for now
			};
		console.profile= function(title) 
			{
				// do nothing, for now
			};
		console.profileEnd = function() 
			{
				// do nothing, for now
			};
		console.profileEnd = function() 
			{
				// do nothing, for now
			};
		console.count = function(title) 
			{
				// do nothing, for now
			};
	}

function dovote(type, id, vote)
{
var theid = 'vote_' + type + '_' + id;
var url = "/ajax_voter.php?type=" + encodeURIComponent(type) + "&id=" + encodeURIComponent(id) + "&vote=" + encodeURIComponent(vote);
$(theid).innerHTML = "<span class='main'>Saving...</span>";
basic_ajax_updater( url , null, $(theid));
}