window.addEvent('domready', function() {

var loginState;
if ($('login_state')) {
	loginState = $('login_state').value;
	if (loginState == "1") { loginState = true; } else { loginState = false; }
}

// Pass in Necessary Variables
var topSpanner = $('spanner');
var ownerId = topSpanner.getElement('h1').getProperty('id');
var personId = ownerId;

var shelfWrapper = $('shelf_wrap');
var productType;
if (shelfWrapper.getElement('div.page_tabs_flat ul.product_tabs li')) {
	productType = shelfWrapper.getElement('div.page_tabs_flat ul.product_tabs li.selected').getProperty('id');
}
var productId = productType;

var shelfView = shelfWrapper.getProperty('class');
var targetView = shelfView;
var shelfViewArea = shelfWrapper.getElement('div.shelf');
var publicView = shelfViewArea.getProperty('id');

var currentSortingValue;
if ($('shelf_sort')) {
	currentSortingValue = $('shelf_sort').getProperty('rel');
}
var paginationWrap, currentPage, lastPage;
currentPage = $('default_page_number').value.toInt();
if ((shelfView == 'shelf_view') && (paginationWrap = shelfViewArea.getElement('p.pagination_wrap'))) {
	lastPage = paginationWrap.getElement('a.end').getProperty('title').toInt();
} else {
	lastPage = 9999;
}

var targetPage;
var shelfCurrentFilter;
if ($('selected_filter')){
	shelfCurrentFilter = $('selected_filter').value;
}

var flashShelfItem = null;

var shelfActiveFilter = "";

if ($('shelf_active_filter')) {
	shelfActiveFilter = $('shelf_active_filter').value;
} 

if (shelfActiveFilter == "") {
	shelfActiveFilter = "filter_progress";
}

var shelfRowsPerPage = 3;

var disableViewSelectors = false;

var shelfPageAlt = false;
if ($('spanner_links')) {
	if ($('spanner_links').getElement('strong')) {
		shelfPageAlt = $('spanner_links').getElement('strong').getProperty('class');
	}
}




///////////////////////////////////////////////////////////////////////////////////////
// AJAX Functions

var refreshFilter = function(filter) {
	
	var	area = filter.getElement('.listing_wrapper');
	shelfActiveFilter = filter.getProperty('id');
	
	var ajaxurl = '/InternalAPI/html/live/book-shelf/shelf-filter-ajax';
	// var ajaxurl = 'ajax/page_person_shelf_filter.php';
	
	new Request({
		url: ajaxurl,
		method: 'get',
		data:	{
			'personId': personId,
			'public': publicView,
			'filter': shelfActiveFilter,
			'selected': shelfCurrentFilter
		},
		onSuccess: function(responseText, responseXML){
			if ($('selected_filter')) {
				$('sidebar').getElements('ul.listing li').each(function(sel, i) {
					sel.removeProperty('id');
				});
				$('sidebar').getElements('ul.listing li.tagcloud a').each(function(sel, i) {
					sel.removeProperty('id');
				});
			}
			
			area.set('html', responseText);
			var newSelectedFilterItem
			if (newSelectedFilterItem = $('selected_filter')) {
				if (shelfActiveFilter == "filter_tags") {
					if ($('filter_tags').getElement('.tagcloud')) {
						shelfCurrentFilter = newSelectedFilterItem.getProperty('title');
					} else {
						shelfCurrentFilter = newSelectedFilterItem.value;						
					}
				} else {
					shelfCurrentFilter = newSelectedFilterItem.value;
				}
				shelfWrapper.getElement('.stack_title h4').set('text', newSelectedFilterItem.getProperty('name'));
				if (newSelectedFilterItem.value == 0 || newSelectedFilterItem.value == '0') {
					$$('#shelf_filter .listing_wrapper .listing .all').each(function(item, i) {
						item.setProperty('id', 'selected_filter');
					})
				}
			}
			filter.getElement('.options_wrap').getParent().setStyles({
				overflow: 'auto',
				height: 'auto'
			});
			setupFilterItems(filter);	
			setupFilterPagination(filter);
		}
	}).send();


};


var updateFilter = function(filter, area, sortBy, page) {
	
	var loading;
	
	// Please update the path to point to the actual Ajax Handler
	// var ajaxurl = 'ajax/page_person_shelf.php';
	
	var filterName = filter.getProperty('id');
	if (filterName == "filter_tags") {
		var ajaxurl = '/InternalAPI/html/live/book-shelf/tag-sort-ajax';
	} else {
		var ajaxurl = '/InternalAPI/html/live/book-shelf/author-sort-ajax';
	}
	
	var hasSelected = null;
	if (filter.getElement('#selected_filter')) {
		if (filterName == "filter_tags") {
			var hasSelected = filter.getElement('#selected_filter').getProperty('title');
		} else {
			var hasSelected = filter.getElement('#selected_filter').value;
		}
	}
		
	new Request({
		url: ajaxurl,
		method: 'get',
		data:	{
			'personId': personId,
			'public': publicView,
			'sort': sortBy,
			'selected': hasSelected,
			'page': page
		},
		onRequest: function() {
			// Launch Loading Effect
			
			loading = new LoadingEffect({loadArea: area});
			loading.startLoadingLite();
		},
		onSuccess: function(responseText, responseXML){
			area.set('html', responseText);
			filter.getElement('.options_wrap').getParent().setStyles({
				overflow: 'auto',
				height: 'auto'
			});
			shelfCurrentFilter = hasSelected;
			setupFilterItems(filter);
			setupFilterPagination(filter);
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}
	}).send();

};









// Submit Shoutbox 
var submitShoutbox = function(injectTop, indicator, content) {
	var loading;
	
	var ajaxurl = '/InternalAPI/html/live/shoutbox-ajax/send-comment';

	new Request({
		url: ajaxurl,
		method: 'post',
		data:	{
			'postShoutbox': true,
			'content': content,
			'personId': personId
		},
		onRequest: function(){
			loading = new LoadingEffect({loadArea: indicator});
			loading.startLoadingLite();
		},
		onSuccess: function(responseText, responseXML){
			var shoutBlock = new Element('dl').inject(injectTop, 'top').set('html', responseText).setOpacity(0).setStyle('backgroundColor', '#FFC');
			var fx = new Fx.Morph(shoutBlock, {
				duration: 1400, wait: false, transition: Fx.Transitions.Quad.easeOut
			}).start({'opacity': [0, 1]}).chain(function() {
				this.start.delay(1000, this, {'backgroundColor': ['#FFC', '#FFF']})
			});
			
			indicator.removeClass('on_focus').addClass('default_content');
			indicator.value = "Leave a comment";
			
			var removeButton;
			
			if (removeButton = shoutBlock.getElement('span.options a.remove')) {
				removeButton.addEvents({
					'mouseover':	function(e) { shoutBlock.addClass('hover'); },
					'mouseout':		function(e) { shoutBlock.removeClass('hover'); },
					'click':		function(e) {
										e = new Event(e).stop();
										removeShout(removeButton, shoutBlock);
									}	
				});
			}
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}
	}).send();
};



// Remove Shoutbox Message
var removeShout = function(indicator, shout) {
	var loading;
	
	var ajaxurl = '/InternalAPI/html/live/shoutbox-ajax/remove-comment';
	// var ajaxurl = 'page_owner_summary.html';

	new Request({
		url: ajaxurl,
		method: 'get',
		data:	{
			'shoutId':	shout.getElement('dd').getProperty('id')
		},
		onRequest: function(){
			loading = new LoadingEffect({loadArea: indicator});
			loading.startLoadingLite();
		},
		onSuccess: function(){
			var fx = new Fx.Morph(shout, {
				duration: 1000, wait: false, transition: Fx.Transitions.Cubic.easeOut
			}).start({'opacity': [1, 0]}).chain(function() {
				shout.dispose();
			});
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}
	}).send();
};











var updateListContent = function(list, area, page) {
		
	var loading;
	
	// var ajaxurl = 'ajax/page_person_shelf.php';
	var ajaxurl = '/InternalAPI/html/live/group-ajax/group-list';
	
	new Request({
		url: ajaxurl,
		method: 'get',
		data:	{
			'personId': personId,
			'sideList': list,
			'page': page
		},
		onRequest: function() {
			// Launch Loading Effect
			loading = new LoadingEffect({loadArea: area});
			loading.startLoadingLite();
		},
		onSuccess: function(responseText, responseXML){
			area.set('html', responseText);
			setupSideListPagination(area);
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}
	}).send();

};







/*
var histM = new HistoryManager();
var reqHistory = histM.register(
	'shelf-page',
	[currentPage],
	function(values) {
		updateShelf(values[0]);
	},
	function(values) {
		return 'page=(' + values[0] +')';
	},
	/page\=\((\d+)\)/
);
*/
// AJAX to Update Shelf Content
var updateShelf = function(page) {
	
	if (page < 1) 				{ page = 1; }
//	else if (page > lastPage) 	{ page = lastPage; }	
	page = page.toInt();
	
	var area = shelfViewArea;
	
	// Launch Loading Effect
	var loading;
	var lite = true;

	var ajaxurl;
	//ajaxurl = 'ajax/page_person_shelf.php';	
	if (shelfPageAlt == "wishlist") {
		ajaxurl = '/InternalAPI/html/live/wishlist/wishlist-ajax';
	} else {
		ajaxurl = '/InternalAPI/html/live/book-shelf/public-view-shelf-ajax';
	}
	
//	histM.setValues('shelf-page',[page]);
	
	if (shelfCurrentFilter == undefined) {
		var newSelectedFilterItem;
		if (newSelectedFilterItem = $('selected_filter')) {		
			if (shelfActiveFilter == "filter_tags") {
				if ($('filter_tags').getElement('.tagcloud')) {
					shelfCurrentFilter = newSelectedFilterItem.getProperty('title');
				} else {
					shelfCurrentFilter = newSelectedFilterItem.value;						
				}
			} else {
				shelfCurrentFilter = newSelectedFilterItem.value;
			}
		}
	}
	
	var updateShelfAJAX = new Request({
		url: ajaxurl,
		method: 'get',
		data:	{
			'personId': personId,
			'shelfView': targetView,
			'sort': currentSortingValue,
			'filter': shelfActiveFilter,
			'selected': shelfCurrentFilter,
			'page': page,
			'rows': shelfRowsPerPage,
			'public': publicView,
			'product': productId,
			'gotoItem': flashShelfItem
		},
		onRequest: function() {
			disableViewSelectors = true;
			if (shelfView == "shelf_view" && area.getElement('.shelf_view_container')) {
				if ((topSpanner.getCoordinates().top - window.getScrollTop()) < 0) {
					var viewAdjust = window.getScrollTop() - ((window.getHeight() + window.getScrollTop()) - shelfViewArea.getCoordinates().bottom - 15);
					if (viewAdjust < 0) viewAdjust = 0;					
					loading = new LoadingEffect({loadArea: area.getElement('.shelf_view_container'), scroll: true, toCoordinates: {x: 0, y: viewAdjust}});
				} else {
					loading = new LoadingEffect({loadArea: area.getElement('.shelf_view_container')});
				}
				loading.startLoading();
				lite = false;
			} else {
				if ((topSpanner.getCoordinates().top - window.getScrollTop()) < 0) {
					loading = new LoadingEffect({loadArea: area, wheelSize: 'large', wheelPos: 200, scroll: true, scrollTo: topSpanner});
				} else {
					loading = new LoadingEffect({loadArea: area, wheelSize: 'large', wheelPos: 200});
				}
				loading.startLoadingLite();
			}
		},
		onSuccess: function(responseText, responseXML){
			// Update ShelfView;
			shelfView = targetView;
			shelfWrapper.setProperty('class', shelfView);
			
			currentPage = page;
			
			area.set('html', responseText);			
			switch(shelfView) {
				case 'shelf_view':
					if (paginationWrap = shelfViewArea.getElement('p.pagination_wrap')) {
						currentPage = paginationWrap.getElement('span.on_page').getProperty('rel').toInt();
						lastPage = paginationWrap.getElement('a.end').getProperty('title').toInt();
					}
					initializeShelfDataManager(currentPage);
					break;
				case 'gallery_view':
					setupGalleryView();
					flashShelfItem = null;
					break;
				case 'list_view':
					setupMixedView();
					flashShelfItem = null;
					break;
				case 'simple_list_view':
					setupSimpleListView();
					flashShelfItem = null;
					break;
			}
			runFlashMe();
		},
		onFailure: function(){
			targetView = shelfView;
		},
		onCancel: function(){
			flashShelfItem = null;
			if (lite) {
				loading.loadingCompletedLite();
			} else {
				loading.loadingCompleted();
			}
			disableViewSelectors = false;	
		},
		onComplete: function(){			
			if (lite) {
				loading.loadingCompletedLite();
			} else {
				loading.loadingCompleted();
			}

			disableViewSelectors = false;
		}			
	}).send();
/*
	if (window.location.href.contains('#')) {
		area.removeClass('firstHistMLoad');
		updateShelfAJAX.send();
	} else if (area.hasClass('firstHistMLoad')) {
		area.removeClass('firstHistMLoad');
	} else {
		updateShelfAJAX.send();
	}
*/
};



// Initial Data Manager for Shelf Pagination

var shelfDataManager;
var histM = new HistoryManager();

var initializeShelfDataManager = function(initialPage) {
		
	var generateData = function(which_page, how_many) {
		return {
			'personId': personId,
			'shelfView': shelfView,
			'sort': currentSortingValue,
			'filter': shelfActiveFilter,
			'selected': shelfCurrentFilter,
			'page': (which_page + 1) + '-' + (which_page + how_many),
			'rows': shelfRowsPerPage,
			'public': publicView,
			'product': productId
		};
	};	
	var onSuccess = function(content) { // content = array
		currentPage = initialPage;
		shelfViewArea.set('html', content);
		if ($(flashShelfItem)) $(flashShelfItem).addClass('flashme');
		setupShelfView();
		var reqHistory = histM.register(
			'shelf-page',
			[initialPage],
			function(values) {
				smartGetShelfCluster(values[0]);
			},
			function(values) {
				return 'page=(' + values[0] +')';
			},
			/page\=\((\d+)\)/
		);
		histM.start();
		flashShelfItem = null;
	};
	var bufferReady = function() {
		shelfDataManager.loading.loadingCompleted();
		if (shelfDataManager.ignore_buffer_out){
			smartGetShelfCluster(shelfDataManager.ignore_buffer_out);
			shelfDataManager.ignore_buffer_out = false;
			return;
		}
		smartGetShelfCluster(targetPage, true);
		setupShelfView();
	};
	shelfDataManager = new DataManager({
		window_size: 4, // must be even
		ajaxURL: '/InternalAPI/html/live/book-shelf/public-view-shelf-ajax', // ajax url
		makeAjaxDataFunc: generateData, // Data set
		initial_cluster: initialPage - 1,
		total_clusters: lastPage,
		cluster_size: 1,
		initSuccessCallback: onSuccess,
		bufferReadyCallback: bufferReady
		
	});

	shelfDataManager.loading = new LoadingEffect({loadArea: shelfViewArea});

};

var smartGetShelfCluster = function(page, ignoreHistM) {
	if (!shelfDataManager.loading.running) {
		page = page.toInt();
		targetPage = page;
		
		if (!ignoreHistM) histM.setValues('shelf-page',[page]);

		if ((topSpanner.getCoordinates().top - window.getScrollTop()) < 0) {
			var viewAdjust = window.getScrollTop() - ((window.getHeight() + window.getScrollTop()) - shelfViewArea.getCoordinates().bottom - 15);
			if (viewAdjust < 0) viewAdjust = 0;
			new Fx.Scroll(window, {	wait: false, duration: 1000	}).start(0, viewAdjust);
		}

		(function() {
			var checkContent;
			if (currentPage - page == 1)
				checkContent = shelfDataManager.getPreviousCluster();
			else if (page - currentPage == 1)
				checkContent = shelfDataManager.getNextCluster();
			else 
				checkContent = shelfDataManager.getClusters(page - 1);

			if (checkContent == -1)
				shelfDataManager.loading.startLoading();
			else if (checkContent) {
				
			
				shelfViewArea.set('html', checkContent);
				setupShelfView();
				currentPage = page;

				var crossFadePages = new Chain();
				crossFadePages.chain(
				    function() {
						shelfViewArea.getElements('li.item').each(function(shelfItem, i) {
							shelfItem.setStyle('opacity', 0);
						});
					 },
				    function() {
						shelfViewArea.getElements('li.item').each(function(shelfItem, i) {
							shelfItem.tween('opacity', 1);
						});
					 }
				);
				
				if (window.location.href.contains('#')) {
					shelfViewArea.removeClass('firstHistMLoad');
					crossFadePages.callChain();
					crossFadePages.callChain();
				} else if (shelfViewArea.hasClass('firstHistMLoad')) {
					shelfViewArea.removeClass('firstHistMLoad');
				} else {
					crossFadePages.callChain();
					crossFadePages.callChain();
				}
				
			}
		}).delay(200);
	}
	else 
		shelfDataManager.ignore_buffer_out = page;
};




// AJAX to set the default Sorting value
var setDefaultSortingAJAX = function(popupObject, setValue, setText, setDefaultSortingLink) {

	var loading;
	var area = popupObject.element.getElement('form');
	
	var ajaxurl = '/InternalAPI/html/live/shelf-ajax/set-sorting';	
	// var ajaxurl = 'ajax/results.php';
	
	new Request({
		url: ajaxurl,
		method: 'get',
		data:	{
			sortValue: setValue
		},
		onRequest: function(){
			loading = new LoadingEffect({loadArea: area});
			loading.startLoadingLite();
		},
		onSuccess: function(responseText, responseXML){
			popupObject.closeOverlay();
			setDefaultSortingLink.set('text', setText);
			
			var currentSorting = $('shelf_sort');
			$$('#shelf_sort_dropdown ul li').each(function(sItem, j) {
				sItem.removeClass('selected');
			});
			var newSorting = $('shelf_sort_dropdown').getElement('li[value='+setValue+']');
			newSorting.addClass('selected');
			currentSortingValue = setValue;
			updateShelf(1);
			currentSorting.setProperty('rel', currentSortingValue);
			currentSorting.getElement('a').set('text', newSorting.getElement('a').get('text'));
			
			
		},
		onFailure: function(){
			new Element('p').set('text','Please try again!').inject(popupObject.element);
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}			
	}).send();

};






// AJAX to Handle Add To Actions
var addToActions = function(area, productId, addTo, personId, amount) {

	var loading;
	var addToWhere = addTo.getProperty('class').replace("add_to_","");
	var addToText = addTo.getProperty('title');

	// Please update the path to point to the actual Ajax Handler
	//var ajaxurl = 'ajax/results.php';
	if (addToWhere == 'shelf') {
		var ajaxurl = '/InternalAPI/html/live/shelf-ajax/add-shelf';
	} else {
		var ajaxurl = '/InternalAPI/html/live/wishlist-ajax/add-wishlist';
	}

	new Request({
		url: ajaxurl,
		method: 'get',
		data: {
			'id': '1:'+productId+':0'
		},
		onRequest: function(){
			loading = new LoadingEffect({loadArea: area});
			loading.startLoadingLite();
		},
		onSuccess: function(responseText, responseXML){
			// Put all codes to be executed on completion here:
			
			addToActionsCompleted(area, addTo, addToWhere, addToText, responseText);
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}	
	}).send();
};








///////////////////////////////////////////////////////////////////////////////////////
// Simple List View

var setupSimpleListView = function() {

	var listView = $$('#content div.simple_list_view div.shelf table tr.item');
	var listViewExtraButton = $$('#content div.simple_list_view div.shelf table tr.item td.progress div.progress_container_inner');
	var listViewExtra = $$('#content div.simple_list_view div.shelf table tr.item_extra td div.extra_wrapper');	
	
	var accordion = new Accordion(
		listViewExtraButton,
		listViewExtra,
		{ 	alwaysHide: true,
			start: 'first-close'	},
		$('content').getElement('div.simple_list_view div.shelf table')
	);
	
	listView.each(function(item, i) {
		i%2 ? item.addClass('even') : '';
		var extraTrigger;
		if (extraTrigger = item.getElement('div.progress_container_inner')) {
			extraTrigger.setStyle('height', item.getElement('td.progress').offsetHeight).addEvents({
				'mouseover':	function(e) { extraTrigger.addClass('hover'); },
				'mouseout':		function(e) { extraTrigger.removeClass('hover'); }
			});
		}
		
		item.addEvents({
			'mouseover': 	function(e) { item.addClass('hover') },
			'mouseout': 	function(e) { item.removeClass('hover') }
		});

		item.getElement('td.title').addEvent('click', function(e) {
			window.location.href = item.getElement('td.title a').getProperty('href');
		});
		
		// Show "AddTo Options"
		var addTo;
		if (addTo = item.getElement('div.options')) {
			setupAddTo(addTo, item.getElement('td.progress'), item.getProperty('id'));
		}
	});
	
	// Setup Each Item's Extra Info 
	applyEventsToExtra(listViewExtra);
	
	setupShelfPagination();

};



///////////////////////////////////////////////////////////////////////////////////////
// Mixed / List View

var setupMixedView = function() {


	var mixedView = $$('#content div.list_view div.shelf table tr.item');
	mixedView.each(function(item, i) {
		// Show "AddTo Options"
		var addTo;	
		if (addTo = item.getElement('li.options')) {
			setupAddTo(addTo, item.getElement('li.progress'), item.getProperty('id'));
		}

		item.getElement('li.title').addEvents('click',
			function(e) { window.location.href = item.getElement('li.title a').getProperty('href');
		});
		
	});
	
	// Setup Each Item's Extra Info 
	var mixedViewExtra;
	if (mixedViewExtra = $$('#content div.list_view div.shelf table tr.item_extra td div.extra_wrapper')) {
		applyEventsToExtra(mixedViewExtra);
	
		mixedViewExtra.each(function(extra, i) {
			var mixedViewComments;
			if (mixedViewComments = extra.getElements('div.comment_entry')) {
				mixedViewComments.each(function(comment, j) {
					var commentContinue;
					if (commentContinue = comment.getElement('a.continue')) {
						commentContinue.addEvent('click', function(e) {
							e = new Event(e).stop();
							
							if (comment.getTop() > window.getScrollTop()) {
								var scroll = new Fx.Scroll(window, {
									wait: false, duration: 1200, transition: Fx.Transitions.Quad.easeInOut
								});
								scroll.toElement(comment);
							}
							comment.getElement('div.comment_shorten').addClass('hide');
							comment.getElement('div.comment_full').removeClass('hide');
							extra.getParent().setStyle('height','auto');
						});
					}
				});		
			}
		});
	}


	var listViewContainer;
	if (listViewContainer = $('content').getElement('table.list_view_container')) {
		if (listViewContainer.hasClass('owner')) {
			mixedView.each(function(item, i) {
				var reviewIcon;
				if (item.getElement('a.icon_review')) {
					var extraSlider = new Fx.Slide(item.getNext().getElement('div.extra_wrapper'), {
						wait: false, duration: 800, transition: Fx.Transitions.Cubic.easeOut
					}).hide();
					item.getElement('a.icon_review').addEvent('click', function(e) {
						e = new Event(e).stop();
						extraSlider.toggle();					
					});
				}
			});
	
		}
	}
	setupShelfPagination();
};




///////////////////////////////////////////////////////////////////////////////////////
// Gallery View

var setupGalleryView = function() {
	var galleryViewItems = $$('#content div.gallery_view div.shelf ul.gallery_view_container li.item');
	
	galleryViewItems.each(function(item, i) {
		
		// Show "AddTo Options"
		var addTo;	
		if (addTo = item.getElement('li.options')) {
			setupAddTo(addTo, item.getElement('li.progress'), item.getProperty('id'));
		}
		
		var reviewLink;
		if (reviewLink = item.getElement('a.icon_review')) {
			reviewLink.addEvent('click', function(e) {
				e = new Event(e); e.stop();
				item.getElement('div.extra_wrapper').removeEvents().addClass('active_extra_wrapper');
				var itemExtra = new OverlayContent(item.getElement('div.extra_wrapper'));
				applyEventsToExtra(document.body.getElements('div.active_extra_wrapper'));
			});
		}
	});
	
	setupShelfPagination();
};




///////////////////////////////////////////////////////////////////////////////////////
// Shelf View

var autoLoadShelfView = function() {
	
	shelfRowsPerPage = Math.floor((window.getHeight() - 260) / 150); //Please floor this in PHP
	if (shelfRowsPerPage < 3) shelfRowsPerPage = 3;
	
	if (shelfViewArea.getElement('.shelf_view_container')) 
		shelfViewArea.getElement('.shelf_view_container').setStyle('min-height', shelfRowsPerPage * 150 + 'px')
		
	if (!Cookie.read('shelfviewrows')) {
		Cookie.write('shelfviewrows', shelfRowsPerPage, {duration: 365});

/*		if (shelfRowsPerPage > 3) updateShelf(currentPage);
		else setupShelfView();
*/
	} else {
		var rowsFromCookie = Cookie.read('shelfviewrows');
		if (shelfRowsPerPage != rowsFromCookie) {
			Cookie.write('shelfviewrows', shelfRowsPerPage, {duration: 365});
//			updateShelf(currentPage);
//		} else {
//			setupShelfView();
		}
	}
	if (shelfViewArea.getElement('.pagination_wrap')) {
		shelfViewArea.getElement('.pagination_wrap').setStyle('opacity', 0.5);
	}
	initializeShelfDataManager(currentPage);

};

var setupShelfView = function() {

	var shelfViewContainer = $('content').getElement('div.shelf_view div.shelf ul.shelf_view_container');
	var shelfViewItems = shelfViewContainer.getElements('li.item');
	
	shelfViewItems.each(function(item, i) {
		var delayTimer;
		var itemInfoVisible = false;
		var edgeDelay = false;
		var itemDD = item.getElement('dd');
		var itemInfo = item.getElement('div.item_info').addClass('hover');
		var itemInfoPos = {
			'right': itemInfo.offsetWidth + itemInfo.getLeft(),
			'bottom': itemInfo.offsetHeight + itemInfo.getTop()
		};
		itemInfo.removeClass('hover');

		var itemLink = itemInfo.getElement('li.title a');
		var shelfPagination, paginationPos;
		var paginationExist = false;
		if ($('shelf_bottom').getElement('p.pagination_wrap')) {
			shelfPagination = $('shelf_bottom').getElement('p.pagination_wrap');
			paginationExist = true;
			paginationPos = shelfPagination.getPosition().y;
		};
		var itemProgress = item.getElement('dl dd div.progress');
		var itemProgressExtra, itemProgressExtraHeight, itemProgressInsert;
		if (itemProgressExtra = itemProgress.getElement('p.extra_indicator')) {
			itemProgressExtraHeight = '28px';
			itemProgressInsert = true;
		} else if (itemProgressExtra = itemProgress.getElement('div.stars')) {
			itemProgressExtraHeight = '10px';
			itemProgressInsert = true;
		} else {
			itemProgressInsert = false;
		}
		
		if (itemProgressInsert) {
			var progressOverlay = new Element('div').addClass('progress_overlay').setStyles({
				'opacity':	0.3,
				'height':	itemProgressExtraHeight
			});
			progressOverlay.inject(itemProgress, 'before');
		}

				
		var reviewLink;
		if (reviewLink = itemInfo.getElement('a.icon_review')) {
			reviewLink.addEvent('click', function(e) {
				e = new Event(e); e.stop();
				item.getElement('div.extra_wrapper').removeEvents().addClass('active_extra_wrapper');
				var itemExtra = new OverlayContent(item.getElement('div.extra_wrapper'));
				applyEventsToExtra(document.body.getElements('div.active_extra_wrapper'));
			});
		}

		// Show "AddTo Options"
		var addTo;	
		if (addTo = itemInfo.getElement('li.options')) {
			setupAddTo(addTo, itemInfo.getElement('fieldset'), item.getProperty('id'));
			addTo.addEvents({
				'mouseover': 	function(e) { addTo.addClass('hover');	  },
				'mouseout': 	function(e) { addTo.removeClass('hover'); }
			});
		}



		item.getElement('div.item_info li.title').addEvents({
			'click':		function(e) { window.location.href = item.getElement('div.item_info li.title a').getProperty('href'); }
		});
		
		if (Browser.Engine.trident) {
			var tempInfo = false;
			var ieOnBook = false;
			var ieOnBubble = false;
		}
		
		var itemDT = item.getElement('dt');
		// Positioning Item Info Bubble
		var showItemInfo = function(element) {
			itemDT.addClass('hover');
			var delayFn = function() {
				element.removeClass('top').removeClass('left');
	 			var windowPos = {
	 				'right': window.getWidth() + window.getScrollLeft(),
	 				'bottom': window.getHeight() + window.getScrollTop()
	 			};
				if ((paginationExist) && (itemInfoPos.bottom > paginationPos))
					element.addClass('top');
				if (itemInfoPos.bottom > windowPos.bottom)
					element.addClass('top');
				if (itemInfoPos.right > (windowPos.right - 15))
					element.addClass('left');
				
				if (Browser.Engine.trident) {
					var elCol = element.addClass('hover').getCoordinates();
					element.removeClass('hover');
				
					if (tempInfo == false) {
						tempInfo = element.clone(true, true);
						tempInfo.setProperty('id', 'IEItemInfoOverlay').setStyles({top: elCol.top, left: elCol.left, zIndex: '99999', display: 'block'}).inject(document.body, 'inside');
						tempInfo.addEvents({
							'mouseover':	function(e) { ieOnBubble = true; showItemInfo(itemInfo); },
							'mouseout':		function(e) { ieOnBubble = false; hideItemInfo(itemInfo); }
						});
						var addTo;	
						if (addTo = tempInfo.getElement('li.options')) {
							setupAddTo(addTo, tempInfo.getElement('fieldset'), item.getProperty('id'));
							addTo.addEvents({
								'mouseover': 	function(e) { addTo.addClass('hover');	  },
								'mouseout': 	function(e) { addTo.removeClass('hover'); }
							});
						}
					} else {
						tempInfo.setStyle('display', 'block');
						itemDT.addClass('hover');
					}
				} else {
					element.addClass('hover');
					element.addEvents({
						'mouseover': 	function(e) { itemDT.addClass('hover'); },
						'mouseout': 	function(e) { itemDT.removeClass('hover'); }
					})
				}
				(function() { edgeDelay = true; }).delay(50);
			};

			if (edgeDelay) {
				delayFn();
			} else {
				delayTimer = delayFn.delay(1000);
			}
		};
		
		var hideItemInfo = function(element) {
			itemDT.removeClass('hover');
			delayTimer = $clear(delayTimer);
			if (Browser.Engine.trident) {
				(function() {
					if ((!ieOnBubble) && (!ieOnBubble)) tempInfo.setStyle('display', 'none');
				}).delay(500);
			} else {
				element.removeClass('hover');
			}
			(function() { edgeDelay = false; }).delay(20);
		};
		if (item.getElement('dt span img')) {
			item.getElement('dt span img').addEvents({
				'mouseover':	function(e) { ieOnBook = true; showItemInfo(itemInfo); },
				'mouseout':		function(e) { ieOnBook = false; hideItemInfo(itemInfo); }
			});
		} else if (item.getElement('dt a.no_cover')) {
			item.getElement('dt a.no_cover').addEvents({
				'mouseover':	function(e) { ieOnBook = true; showItemInfo(itemInfo); },
				'mouseout':		function(e) { ieOnBook = false; hideItemInfo(itemInfo); }
			});
		}
		
		if (itemProgressInsert) {
			progressOverlay.addEvents({
				'mouseover':	function(e) { ieOnBook = true; showItemInfo(itemInfo); },
				'mouseout':		function(e) { ieOnBook = false; hideItemInfo(itemInfo); }
			});
		}
		itemProgress.addEvents({
			'mouseover':	function(e) { ieOnBook = true; showItemInfo(itemInfo); },
			'mouseout':		function(e) { ieOnBook = false; hideItemInfo(itemInfo); }
		});
		itemInfo.addEvents({
			'mouseover':	function(e) { ieOnBook = true; showItemInfo(itemInfo); },
			'mouseout':		function(e) { ieOnBook = false; hideItemInfo(itemInfo); }			
		});
		
		if (item.hasClass('flashme')) {
			var flashmeOverlay = new Element('div').addClass('flashme_overlay').inject(item.getElement('dt'), 'after');
			flashmeOverlay.addEvents({
				'mouseover':	function(e) { ieOnBook = true; showItemInfo(itemInfo); },
				'mouseout':		function(e) { ieOnBook = false; hideItemInfo(itemInfo); }
			});
			(function() {
				new Fx.Morph(flashmeOverlay, {
					duration: 800, wait: false, transition: Fx.Transitions.Quad.easeOut
				}).start({'opacity': 0}).chain(function() {
					flashmeOverlay.dispose();
				});
			}).delay(4000);
		}
		
	});
	

	shelfViewContainer.addEvents({
		'mouseover':	function(e) { shelfViewContainer.addClass('hover'); },
		'mouseout':		function(e) { shelfViewContainer.removeClass('hover'); }
	});
	setupShelfPagination();

	
};






///////////////////////////////////////////////////////////////////////////////////////
// Shared Components for All Views

var setupViewSelector = function() {
	var viewSelectors = $('view_selector').getElements('li a');
	viewSelectors.each(function(item, i) {
		item.addEvent('click', function(e) {
			e = new Event(e); e.stop();
			
			if (!disableViewSelectors) {	
				// Set the target View
				targetView = item.getProperty('rel');
				
				// Update the Selected View treatment
				viewSelectors.each(function(sel, i) {
					sel.removeClass('selected');
					if (Browser.Engine.trident4) sel.removeProperty('id');
				});
				item.addClass('selected');
				if (Browser.Engine.trident4) item.setProperty('id', 'view_selected');
				
				if (targetView == 'shelf_view') {
					shelfRowsPerPage = Math.floor((window.getHeight() - 260) / 150);
					if (shelfRowsPerPage < 3) shelfRowsPerPage = 3;
				}
				
				updateShelf(1);
			}
		});
	});
};


var setupShelfSorting = function(currentSorting, sortingDropdown) {

	if (Browser.Engine.trident) {
	
		var ulContainer = sortingDropdown.getParent();
		var elCol = ulContainer.getCoordinates();
		elCol.top = elCol.top + 180 + 'px';
		if (Browser.Engine.trident4) {
			elCol.left = elCol.left + 520 + 'px';
		} else {
			elCol.left = elCol.left + 280 + 'px';
		}
		
		var ulContainerClone = new Element('div').setProperty('id', 'shelf_sort_dropdown').set('html', ulContainer.get('html'));
		ulContainerClone.setStyles({visibility: 'visible', position: 'absolute', top: elCol.top, left: elCol.left, zIndex: '99999'}).inject(document.body);
		ulContainer.dispose();
		
		sortingDropdown = ulContainerClone.getElement('ul');
	}

      var sortingSlider = new Fx.Slide(sortingDropdown, {transition: Fx.Transitions.Cubic.easeOut});
	sortingSlider.hide();
	
	//adjust sortingDropdown's position in IE6, by kayue
	if (Browser.Engine.trident && Browser.Engine.version === 4) {
		sortingDropdown.getParent().getParent().setStyles({'margin-left':-550,'margin-top':-180})
	} else if (Browser.Engine.trident && Browser.Engine.version === 5) {
		sortingDropdown.getParent().getParent().setStyles({'margin-left':-300,'margin-top':-180})
	}
	
	// var sortingSlider = new Fx.Slide(sortingDropdown, {transition: Fx.Transitions.Cubic.easeOut}).hide();
	
	currentSorting.removeEvents();
	currentSorting.addEvent('click', function(e) {
		e = new Event(e); e.stop();
		sortingSlider.slideIn().chain(function() {
			if (Browser.Engine.trident) {
				document.body.onmouseup = function() {
					sortingSlider.slideOut();
					document.body.onmouseup = null;
				}
			} else {
				document.body.addEvent('mouseup', function(event) {
					sortingSlider.slideOut();
					document.body.removeEvents('mouseup');
				});
			}
		});
	});
	var sortingDropdownItems = sortingDropdown.getElements('li');
	sortingDropdownItems.each(function(item, i) {
		item.removeEvents();
		item.addEvent('click', function(e) {
			e = new Event(e).stop();

			sortingDropdownItems.each(function(sItem, j) {
				sItem.removeClass('selected');
			});
			item.addClass('selected');
			currentSortingValue = item.getProperty('value');
			updateShelf(1);
			currentSorting.setProperty('rel', currentSortingValue);
			currentSorting.getElement('a').set('text', item.getElement('a').get('text'));

		});
	});
	var createCustomLink;
	if (createCustomLink = sortingDropdown.getElement('li.create_custom')) {
		createCustomLink.removeEvents();
	}
	var setDefaultSortingLink;
	if (setDefaultSortingLink = $('change_visitor_sorting')) {
		setDefaultSortingLink.addEvent('click', function(e) {
			e = new Event(e).stop();
			
			var selectedValue = $('default_sorting_options').getElement('option[name=selected]').getProperty('value');
			var setDefaultSortingPopup = new OverlayContent($('default_sorting_options'));
			setDefaultSortingPopup.setupCancel();
			setDefaultSortingPopup.element.getElement('option[value='+selectedValue+']').setProperty('selected','selected');
			
			var setDefaultSortingSelect = setDefaultSortingPopup.element.getElement('select');
			var setDefaultSortingSubmit = setDefaultSortingPopup.element.getElement('button');
			setDefaultSortingSubmit.addEvent('click', function(e) {
				e = new Event(e).stop();
				setDefaultSortingAJAX(
					setDefaultSortingPopup,
					setDefaultSortingSelect.value,
					setDefaultSortingSelect.getSelected().get('text'),
					setDefaultSortingLink);
			});
			
		});
	}
 
};

var setupAddTo = function(addTo, progress, itemId) {
	addTo.addEvents({
		'mouseover':	function(e) { addTo.addClass('hover'); },
		'mouseout':		function(e) { addTo.removeClass('hover'); }
	});
	if (addTo.getElement('a.edit')) {
		addTo.getElement('a.edit').addEvents({
			'mouseover':	function(e) { progress.addClass('hover'); },
			'mouseout':		function(e) { progress.removeClass('hover'); }
		});
	}
	
	// Add Actions to Each "AddTo Option"
	if (loginState) {
		var addToFurtherOptions;
		if (addToFurtherOptions = addTo.getElements('ul.options_further li a')) {
			addToFurtherOptions.each(function(fOpt, i) {
				fOpt.addEvent('click', function(e) {	e = new Event(e); e.stop();
					addToActions(addTo, itemId, fOpt, personId, '1'); 
				});
			});
		}
	}
};

// AddTo Actions Completed after the AJAX call

var addToActionsCompleted = function(area, addTo, addToWhere, addToText, responseText) {
	var originalAddTo;
	if (originalAddTo = area.getElement('a.add_to')) {
		originalAddTo.setProperty('class', 'on_'+addToWhere).set('text', 'Added to '+addToText).setProperty('href', responseText).addClass('hover');
	} else if (originalAddTo = area.getElement('a.on_wishlist')) {
		originalAddTo.setProperty('class', 'on_'+addToWhere).set('text', 'Added to '+addToText).setProperty('href', responseText).addClass('hover');
	} else if (originalAddTo = area.getElement('a.on_shelf')) {
		originalAddTo.setProperty('class', 'on_'+addToWhere).set('text', 'Added to '+addToText).setProperty('href', responseText).addClass('hover');
	}
	addTo.getParent().dispose();
};


var setupShelfPagination = function() {
	
	if (paginationWrap = shelfViewArea.getElement('p.pagination_wrap')) {
		paginationWrap.getElements('a').each(function(item, i) {
			item.removeEvents();
			item.addEvent('click', function(e) {
				e = new Event(e); e.stop();	
				if (item.get('text').toInt() != "NaN") {
					updateShelf(item.get('text').toInt());
				}
			});
		});
		var paginationPrev;
		if (paginationPrev = paginationWrap.getElement('a.prev')) {
			paginationPrev.removeEvents().addEvent('click', function(e) {
				e = new Event(e); e.stop();
				if (shelfView == 'shelf_view')
					smartGetShelfCluster(currentPage - 1);
				else
					updateShelf(currentPage - 1);
			});
		}
		var paginationNext;
		if (paginationNext = paginationWrap.getElement('a.next')) {
			paginationNext.removeEvents().addEvent('click', function(e) {
				e = new Event(e); e.stop();
				if (shelfView == 'shelf_view')
					smartGetShelfCluster(currentPage + 1);
				else
					updateShelf(currentPage + 1);
			});
		}
		var paginationStart;
		if (paginationStart = paginationWrap.getElement('a.start')) {
			paginationStart.removeEvents().addEvent('click', function(e) {
				e = new Event(e); e.stop();
				if (shelfView == 'shelf_view')
					smartGetShelfCluster(1);
				else
					updateShelf(1);
			});
		}
		var paginationEnd;
		if (paginationEnd = paginationWrap.getElement('a.end')) {
			paginationEnd.removeEvents().addEvent('click', function(e) {
				e = new Event(e); e.stop();
				if (shelfView == 'shelf_view')
					smartGetShelfCluster(paginationEnd.getProperty('title').toInt());
				else
					updateShelf(paginationEnd.getProperty('title').toInt());
			});
		}
		
		paginationWrap.getElements('a.disabled').each(function(disabled, i) {
			disabled.removeEvents().setOpacity(0.5).addEvent('click', function(e) {
				e = new Event(e).stop(); });
		});

	}
};


// Apply Events to the Extra Area of each item
var applyEventsToExtra = function(extraList) {
	// Each Item's Extra Info 
	extraList.each(function(item, i) {
		// Each comment of each Item
		var comments;
		if (shelfView == "shelf_view" || shelfView == "gallery_view") {
			if (comments = item.getElements('div.comment_block dl')) {
				comments.each(function(comment, i) {
					var c = new CommentBlocks(comment, item.getProperty('id'), productType, comment, loginState);
					c.setupCommentsWithCover();
				});
			}	
		} else {
			if (comments = item.getElements('ul.comment_block li')) {
				var c = new CommentBlocks(item, item.getProperty('id'), productType, comments, loginState);
				c.setupComments();
			}
		}
	});
};












///////////////////////////////////////////////////////////////////////////////////////
// Initialize Components

// Setup PageHeading Profile Link
// Setup Product Tabs Sliding Effect
var productTabs = shelfWrapper.getElements('div.page_tabs_flat ul.product_tabs li');
var szNormal = new Array(), szFull = new Array(), szSpan = new Array();
var productTabsFx = new Fx.Elements(productTabs, {
		wait: false, duration: 300, transition: Fx.Transitions.Back.easeOut
	});
productTabs.each(function(item, i) {
	
	// Get the various widths for the variables
	szSpan[i] = item.getElement('span').offsetWidth;
	item.getElement('span').setStyle('display', 'none');
	szNormal[i] = item.offsetWidth;
	szFull[i] = szNormal[i] + szSpan[i] + 5;
	
	// Setup initial appearance
	item.getElement('span').setStyle('display', 'inline');
	if (item.hasClass('selected')) {
		item.setStyle('width', szFull[i]);
	} else {
		item.setStyle('width', szNormal[i]);
	}
	
	// Apply mouseover events
	item.addEvent('mouseenter', function(e) {
		var o = {};
		o[i] = { width: [item.getStyle('width').toInt(), szFull[i]] };
		productTabs.each(function(other, j) {
			if(i != j) {
				var w = other.getStyle('width').toInt();
				if (w != szNormal[j]) o[j] = {width: [w, szNormal[j]]};
			}
		});
		productTabsFx.start(o);
	});
});

shelfWrapper.getElement('div.page_tabs_flat').addEvent('mouseleave', function(e) {
	var o = {};
	productTabs.each(function(item, i) {
		if (item.hasClass('selected')) {
			o[i] = {width: [item.getStyle('width').toInt(), szFull[i]]}
		} else {
			o[i] = {width: [item.getStyle('width').toInt(), szNormal[i]]}
		}
	});
	productTabsFx.start(o);
});



// Setup Add-To-Shelf
if ($('add_to_shelf')) {
	
	$('add_book_isbn').focus();

	var addToShelfAllow = true;
	var addToShelfWithISBN = function() {		
		if (addToShelfAllow) {
			var loading;
			var indicator = $('add_book_button');

			var ajaxurl = '/InternalAPI/html/live/search-ajax/add-book-isbn';
			new Request.JSON({
				url: ajaxurl,
				method: 'get',
				data:	{
					'keyword':	$('add_book_isbn').value
				},
				onRequest: function(){
					loading = new LoadingEffect({loadArea: indicator});
					loading.startLoadingLite();
					addToShelfAllow = false;
				},
				onSuccess: function(response){
					if (response[0]) { // If Add Book Successfully
						flashShelfItem = response[1];
						shelfCurrentFilter = 0;
						shelfActiveFilter = "filter_progress";
						
						if (response[2]) { // If the Book is New
							var currentSorting = $('shelf_sort');
							$$('#shelf_sort_dropdown ul li').each(function(sItem, j) {
								sItem.removeClass('selected');
							});
							var newSorting = $('shelf_sort_dropdown').getElement('li[value=1]');
							newSorting.addClass('selected');
							currentSortingValue = 1;
							updateShelf(1);
							currentSorting.setProperty('rel', currentSortingValue);
							currentSorting.getElement('a').set('text', newSorting.getElement('a').get('text'));
						} else {
							updateShelf(1);							
						}
						
						$$('#shelf_filter .filter_container').each(function(filter, i) {
							refreshFilter(filter);
						});
						updateNewlyAdded();
					} else {
						$('notify').set('html', response[1]);
					}
				},
				onComplete: function(){
					loading.loadingCompletedLite();
					$('add_book_isbn').value = "";
					$('add_book_isbn').focus();
					$('add_to_shelf').removeClass('success');
					$('notify').set('text', '');
					addToShelfAllow = true;
				}
			}).send();
		}
	};
	new SearchValidation($('add_to_shelf'), $('add_form').getElement('form'), addToShelfWithISBN);
}

var updateNewlyAdded = function() {
	var loading;
	var ajaxurl = '/InternalAPI/html/live/book-shelf/get-new-add-book';
	new Request({
		url: ajaxurl,
		method: 'get',
		onSuccess: function(responseText, responseXML){
			if($('person_batch_edit_item')) {
				$('person_batch_edit_item').dispose();
			}
			new Element('div').set('html', responseText).inject($('add_to_shelf'), 'before');
		}
	}).send();
};


// Setup Sorting
if ($('shelf_sort_dropdown')) {
	$('shelf_sort_dropdown').setStyle('visibility', 'visible');
	setupShelfSorting(
		$('shelf_sort'),
		$('shelf_sort_dropdown').getElement('ul')
	);
}


// Setup View Selector
if ($('view_selector')) { setupViewSelector(); }



// Setup Other Languages
if ($('other_product_types')) {
	$('other_product_types').getElement('a').addEvent('click', function(e){
		e = new Event(e); e.stop();
		$('product_type_other').toggleClass('hide');
	});
	$('product_type_other').getElements('input.language').each(function(item, i) {
		item.addEvent(
			'click', function(e) {
				if (item.getProperty('checked')) {
					item.getParent().addClass('highlighter');
					$('submit_product').removeClass('hide');
				} else {
					item.getParent().removeClass('highlighter');
				}
			}
		);
	});
}


// Scroll to Shelf if Applicable
var scroll = new Fx.Scroll(window, {
	wait: false, duration: 1500, transition: Fx.Transitions.Quad.easeInOut
});
var doScroll = $('do_scroll').get('value');
if (doScroll == 'true') scroll.toElement($('content'));






///////////////////////////////////////////////////////////////////////////////////////
// Sidebar Components


// Set the Cookie for Hiding and Showing Filters with the default state
var showHideStates = new Hash.Cookie('showHideStates', {path: '/', duration: 3600}); 

if (!(Cookie.read('showHideStates'))) {
	showHideStates.extend({
		'filter_progress': true,
		'filter_authors': false,
		'filter_languages': false,
		'filter_tags': false,
		'filter_trade': false,
		'filter_privacy': false,
		
		'filter_authors_sort': 'name',
		'filter_tags_sort': 'list'
	});
	showHideStates.save();
}


// Setup Function for the Sorting in Filters
var applySortEvent = function(filter, active, option, area) {
	active.removeEvents();
	option.addEvent('click', function(e) {	
		e = new Event(e).stop();
		updateFilter(filter, area, option.getProperty('id'), 1);
		
		showHideStates.set(filter.getProperty('id') + '_sort', option.getProperty('id'));
		showHideStates.save();

		var optionText = option.getElement('a').get('text');
		option.removeClass('option').addClass('option_active').set('html', optionText);		
		var newAction = new Element('a').setProperty('href', '#').set('html', active.get('text'));
		active.removeClass('option_active').addClass('option').empty().adopt(newAction);

		applySortEvent(filter, option, active, area);
	});
};


var setupFilterItems = function(filter) {
	if (filter.getElement('ul.listing li.tagcloud')) {
		filter.getElements('ul.listing li.tagcloud a').each(function(item, i) {
			item.addEvent('click', function(e) {
				e = new Event(e).stop();
			
				shelfCurrentFilter = item.getProperty('title');
				refreshFilter(filter);
				updateShelf(1);
			});
		});
	} else {
		filter.getElements('ul.listing li').each(function(item, i) {
			item.addEvent('click', function(e) {
				e = new Event(e).stop();
			
				shelfCurrentFilter = item.value;
				refreshFilter(filter);
				updateShelf(1);
			});
		});
	}
};


	
var setupFilterPagination = function(filter) {
	var showNext;
	if (showNext = filter.getElement('p.show_all a.next')) {
		showNext.addEvent('click', function(e) {
			e = new Event(e).stop();
			var sortValue = "default";
			if (filter.getElement('div.sort_listing span.option')) {
				sortValue = filter.getElement('div.sort_listing span.option_active').getProperty('id');
			}
			updateFilter(
				filter, //filter
				filter.getElement('div.options_wrap .listing_wrapper'), //area
				sortValue, //option
				showNext.getProperty('id') //page
			);
		});
	}
	var showPrev;
	if (showPrev = filter.getElement('p.show_all a.prev')) {
		showPrev.addEvent('click', function(e) {
			e = new Event(e).stop();
			var sortValue = "default";
			if (filter.getElement('div.sort_listing span.option')) {
				sortValue = filter.getElement('div.sort_listing span.option_active').getProperty('id');
			}
			updateFilter(
				filter, //filter
				filter.getElement('div.options_wrap .listing_wrapper'), //area
				sortValue, //option
				showPrev.getProperty('id') //page
			);
		});
	}
};


// Setup Filters
var shelfFilters = $$('#shelf_filter div.filter_container');
shelfFilters.each(function(item, i) {

	var heading = item.getElement('h4');
	var expandable = item.getElement('div.options_wrap');
	
	var alsoDo = function() {
		item.toggleClass('expanded');	
		if (item.hasClass('expanded')) {
			showHideStates.set(item.getProperty('id'), true);
			showHideStates.save();
		} else {
			showHideStates.set(item.getProperty('id'), false);
			showHideStates.save();
		}
	};
	var expanding = new ToggleElement(heading, expandable, {
		alsoDo: alsoDo
	});
	
	if (showHideStates.get(item.getProperty('id'))) {
		item.addClass('expanded'); 
		expanding.slider.show();
	} else {
		item.removeClass('expanded'); 
		expanding.slider.hide();
	}
	
	heading.addEvents({
		// Assign onMouseOver and onMouseOut events to each item
		'mouseover':	function(e) { heading.addClass('mouseover'); },
		'mouseout':		function(e) { heading.removeClass('mouseover'); }
	});
	
	if (item.getElement('div.sort_listing')) {
		applySortEvent(
			item,	// filter
			item.getElement('div.sort_listing span.option_active'), //active
			item.getElement('div.sort_listing span.option'),	// option
			item.getElement('div.options_wrap .listing_wrapper') //area
		);
	}
	setupFilterItems(item);
	setupFilterPagination(item);
});











// Shoutbox Button
var shoutContent;
if (shoutContent = $('shout_content')) {
	if (loginState) {
		var shoutSubmit = $('shout_button');
	
		var toggleShoutSubmit = function() {
			if (trim(shoutContent.value)!='') {
				shoutSubmit.removeClass('hide');
			} else {
				shoutSubmit.addClass('hide');
			}
		};
	
		// Setup Shoutbox
		shoutContent.addEvents({
			'focus': function(e) {
				// Clear Form Value
				if (shoutContent.hasClass('default_content')) { shoutContent.value = ""; }
				shoutContent.removeClass('default_content').addClass('on_focus');
				toggleShoutSubmit();
			},
			'blur': function(e) {
				toggleShoutSubmit();
				if (shoutSubmit.hasClass('hide')) {
					shoutContent.addClass('default_content').removeClass('on_focus');
					shoutContent.value = "Leave a comment";
				}
			},
			'mousedown': function(e) {
				//word_count('shout_content', 'shout_content_count', '400', '300');
				toggleShoutSubmit();
			},
			'mouseup': function(e) { toggleShoutSubmit(); },
			'keydown': function(e) { toggleShoutSubmit(); },
			'keyup': function(e) { toggleShoutSubmit(); },
			'keypress': function(e) { toggleShoutSubmit(); }
		});
		shoutSubmit.addEvent('click', function(e) {
			shoutSubmit.addClass('hide');
			submitShoutbox($('shout_content_span'), shoutContent, shoutContent.value);
		});
	
		$$('#shout_content_span dl').each(function(shout, i) {
			var userLink = shout.getElement('div.shout_details a');
			shout.getElement('a.buddy_icon_wrap').addEvents({
				'mouseover':	function(e) { userLink.addClass('hover'); },
				'mouseout':		function(e) { userLink.removeClass('hover'); }
			});
			var removeButton;
			if (removeButton = shout.getElement('.remove')) {
				removeButton.addEvents({
					'mouseover':	function(e) { shout.addClass('hover'); },
					'mouseout':		function(e) { shout.removeClass('hover'); },
					'click':		function(e) {
										e = new Event(e).stop();
										removeShout(removeButton, shout);
									}	
				});
			}
		});
	} else {
		if ($('shoutbox_login')) {
			shoutContent.addEvent('focus', function(e) {
				shoutContent.addClass('hide');
				$('shoutbox_login').removeClass('hide');
			});
		}
	}
}







// Setup Group Pagination if Applicable
var shelfGroups;
if (shelfGroups = $('shelf_groups')) {

	var setupSideListPagination = function(area) {
		var showNext;
		if (showNext = shelfGroups.getElement('p.show_all a.next')) {
			showNext.addEvent('click', function(e) {
				e = new Event(e).stop();
				updateListContent(
					area.getProperty('id'), //part ID
					area, //area
					showNext.getProperty('id') //page
				);
			});
		}
		var showPrev;
		if (showPrev = shelfGroups.getElement('p.show_all a.prev')) {
			showPrev.addEvent('click', function(e) {
				e = new Event(e).stop();
				updateListContent(
					area.getProperty('id'), //part ID
					area, //area
					showPrev.getProperty('id') //page
				);
			});
		}
	};
	
	var listContent = shelfGroups.getElement('.listing_wrapper');
	setupSideListPagination(listContent);
}




// Setup Shelf search
var shelfSearch;
if (shelfSearch = $('shelf_search')) {
	var shelfSearchInput = shelfSearch.getElement('input');
/*	var shelfSearchDefaultText = shelfSearchInput.value; */
	shelfSearchInput.addEvents({
		'mouseover': function(e) {
			e = new Event(e).stop();
			shelfSearchInput.addClass('hover');
		},
		'mouseout': function(e) {
			e = new Event(e).stop();
			shelfSearchInput.removeClass('hover');
		},
		'focus': function(e) {
			// Clear Form Value
			if (shelfSearchInput.hasClass('default')) { shelfSearchInput.value = ""; }
			shelfSearchInput.removeClass('default').addClass('on_focus');
		}
/*
		'blur': function(e) {
			if (shelfSearchInput.value == "") {
				shelfSearchInput.addClass('default').removeClass('on_focus');
				shelfSearchInput.value = shelfSearchDefaultText;
			}
		}
*/
	});
	/*
	if ($('shelf_search_field')) {
		var autoCompleteAJAX = '/InternalAPI/html/live/search-ajax/shelf?personId='+personId+'&public='+publicView;
		//var autoCompleteAJAX = '/autoCompleteZend/html/search-ajax/shelf3?personId='+personId+'&public='+publicView;
		//var autoCompleteAJAX = 'ajax/autocomplete.php';
			
		var autoSearch = function(field, selected, value, input) {
			if (selected.hasClass('authors')) {
				shelfCurrentFilter = selected.getProperty('id');
				refreshFilter($('filter_authors'));
				updateShelf(1);
			} else if (selected.hasClass('book_title')) {
				shelfCurrentFilter = 0;
				flashShelfItem = selected.getProperty('id');
				refreshFilter($('filter_progress'));
				updateShelf(currentPage);
			} else if (selected.hasClass('tags')) {
				shelfCurrentFilter = selected.getProperty('id');
				refreshFilter($('filter_tags'));
				updateShelf(1);
			}
		};

		new Autocompleter.Ajax.Xhtml('shelf_search_field', autoCompleteAJAX, {
		    'postVar': 'search',
			onSelection: autoSearch
		});
	}
	*/
}





// Setup Each View
if (!shelfViewArea.getElement('.empty_sign')) {
	switch(shelfView) {
		case 'shelf_view':
			autoLoadShelfView();
			break;

		case 'gallery_view':
			setupGalleryView();
			break;

		case 'list_view':
			setupMixedView();		
			break;

		case 'simple_list_view':
			setupSimpleListView();
		  	break;
	}
}



// Load Similar Shelves
var similarShelves;
if (similarShelves = $('similar_shelves')) {
	var loading;
	
	var urlajax = '/InternalAPI/html/live/user-to-user/bookshelf-similar';
	// var urlajax = 'ajax/similar_shelves.php';
	
	new Request({
		url: urlajax,
		method: 'get',
		data:	{
			'personId': personId
		},
		onRequest: function() {
			// Launch Loading Effect
			loading = new LoadingEffect({loadArea: similarShelves});
			loading.startLoadingLite();
		},
		onSuccess: function(responseText, responseXML){
			similarShelves.set('html', responseText);
		},
		onComplete: function(){
			loading.loadingCompletedLite();
		}
	}).send();

}


// Do Flash and Scroll
var runFlashMe = function() {
	var flashEl = false;
	if (shelfViewArea.getElements('.flashme') != "") {
		flashEl = shelfViewArea.getElements('.flashme');
		flashEl.each(function(el, i) {
			if (shelfView != "shelf_view") {
				el.setStyle('backgroundColor', '#FF9');
				(function() {
					new Fx.Morph(el, {
						duration: 1400, wait: false, transition: Fx.Transitions.Quad.easeOut
					}).start({'backgroundColor': '#FFF'}).chain(function() {
						el.removeClass('flashme');
					});
				}).delay(4000);
			}
		});
	
		// Scroll to Item
		var contentPos = {
			'top':		flashEl[0].getTop(),
			'left':		flashEl[0].getLeft(),
			'bottom':	flashEl[0].getTop() + flashEl[0].offsetHeight,
			'right':	flashEl[0].getLeft() + flashEl[0].offsetWidth
		};
		var windowPos = {
			'top':		window.getScrollTop(),
			'left':		window.getScrollLeft(),
			'bottom':	window.getHeight() + window.getScrollTop(),
			'right':	window.getWidth() + window.getScrollLeft()
		};
		if (contentPos.bottom > windowPos.bottom || contentPos.top < windowPos.top) {
			new Fx.Scroll(window, {
				wait: false, duration: 1000, transition: Fx.Transitions.Quad.easeInOut
			}).start(contentPos.left, contentPos.top - 100);
		}
	}
}
runFlashMe();


// Do Alert Box if Applicable 
var actionAlert;
if (actionAlert = $('action_alert')) {	
	var alertPopup = new OverlayAlert(actionAlert, {autoClose: true});
}




// Handle Bulk Edit link
if ($$('#layout .bulkedit') != '') {
	$$('#layout .bulkedit').each(function(bulkedit, i) {
		bulkedit.addEvent('click', function(e) {
			e = new Event(e).stop();
			var url = "/anobi/person_edit_all.php?id=";
			$$('#layout .shelf .item').each(function(item, j) {
				url += item.getProperty('id') + ',';
			});
			window.location = url;
		});
	});
}


if ($('bubble_shelfView') && $('view_selector')) {
	var newShelfViewSelector = $('view_selector').getElement('.shelf_selector');
	newShelfViewSelector.addClass('shelf_new');
	newShelfViewSelector.addEvent('click', function(e) {
		$('bubble_shelfView').addClass('hide');
		newShelfViewSelector.removeClass('shelf_new');
	});
	$('bubble_shelfView').getElement('.close').addEvent('click', function(e) {
		newShelfViewSelector.removeClass('shelf_new');
	});
}


if ($('bubble_customize_url')) {
	var setCustomURLButton = $('custom_url').getElement('button');
	
	setCustomURLButton.addEvent('click', function(e) {
		var loading;
		var ajaxurl = '/InternalAPI/html/live/person-ajax/custom-person-url?set=1';
		// var ajaxurl = 'ajax/set_custom_url.php?set=set';
		
		new Request.JSON({
			url: ajaxurl,
			method: 'get',
			data: {
				customUrl: $('custom_url').getElement('input').value
			},
			onRequest: function(){
				loading = new LoadingEffect({loadArea: setCustomURLButton});
				loading.startLoadingLite();
			},
			onSuccess: function(response){
				if (response[0]) {
					$('send_custom_url').addClass('hide');
					$('confirm_custom_url').removeClass('hide');
					
					$('confirm_url').getElement('strong').set('text', response[1]);
				} else {
					$('bubble_customize_url').getElement('.error_message').set('text', response[1]);
				}
			},
			onComplete: function(){
				loading.loadingCompletedLite();
			}	
		}).send();
	});
	
	var confirmCustomURLButton = $('confirm_custom_url').getElement('button');
	confirmCustomURLButton.addEvent('click', function(e) {
	
		var loading;
		var ajaxurl = '/InternalAPI/html/live/person-ajax/custom-person-url?confirm=1';
		// var ajaxurl = 'ajax/set_custom_url.php?set=confirm';

		new Request.JSON({
			url: ajaxurl,
			method: 'get',
			data: {
				customUrl: $('confirm_url').getElement('strong').get('text')
			},
			onRequest: function(){
				loading = new LoadingEffect({loadArea: confirmCustomURLButton});
				loading.startLoadingLite();
			},
			onSuccess: function(response){
				if (response[0]) {
					$('bubble_customize_url').addClass('hide');
					$('shelf_customized_url').dispose();
					var shelfLinks = $('content').getElement('.shelf_links');
					var newUrl = new Element('span').set('html', response[1]).inject(shelfLinks);
					new Fx.Tween(newUrl, {
						duration: 1200, wait: false, transition: Fx.Transitions.Quad.easeOut
					}).start('background-color', '#FF0', '#FFF');
				} else {
					$('bubble_customize_url').getElement('.error_message').set('text', response[1]);
					$('send_custom_url').removeClass('hide');
					$('confirm_custom_url').addClass('hide');
					$('custom_url').getElement('input').setProperty('value', '').focus();
				}
			},
			onComplete: function(){
				loading.loadingCompletedLite();
			}
		}).send();
	});
	$('confirm_custom_url').getElement('.cancel').addEvent('click', function(e) {
		e = new Event(e).stop();
		$('send_custom_url').removeClass('hide');
		$('confirm_custom_url').addClass('hide');
		$('custom_url').getElement('input').setProperty('value', '').focus();
	});
	
}



});
