// This file is intended to handle all the JS that is unique to EssentiaList pages and Favorite Product Pages
var WaitingOnceForListErrorsToClear = false;

$(function() {
		   
	$.global.SortList = new $.SortList();

	/*if ($('#ListOrFavProductFlag').exists() && $('#ListOrFavProductFlag').val() == 'EssentiaList') {
	   //getListFeedback();
       //getRelatedLists();
	}*/
	
	if ($('#scrollArea_Lists').height() > 400) {
		$('#scrollArea_Lists').height(400);
	}

	var editModeStatus = getUrlParam('editMode');

	if (editModeStatus == 'Y') {
		$(CallServiceSetListToEdit());
	}

	if($("#choosePennameOnList").exists()) {
		$.global.PenNameSelector  = new $.PenNameSelector({
			onComplete: function(penname) {
				//$("#choosePenname").html("Show My Pen Name (" + penname +")");			
				if ($('#choosePennameOnListFlag').exists() && $('#choosePennameOnListFlag').val() == 'true' && $('#editMode').val() == 'true') {
					CallServiceSaveListChanges('SaveListChangesAfterChoosingPennameCallBack');	
				} else {
					window.location.reload(true);
				}
			},
			type: "list"
		});
	}
	
	// left nav - other essentialists sorting
	$("#listNavSortSelect").change(function(e) {
		//hard-refresh - $("#listNavSort").submit();
		$("#scrollArea_Lists ul").hide();
		$("#listsort-" + $(this).val()).show();
	});
})

var DeleteListPrompt_Content_Holder = '';
var CancelListChangesPrompt_Content_Holder  = '';
var SaveListforPennamePrompt_Content_Holder = '';

function getUrlParam( name )
	{
	var stringField = "[\\?&]"+name+"=([^&#]*)";
	var qString = new RegExp(stringField);
	var results = qString.exec(window.location.href);
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");


		if (results == null)
			return "";
		  else
			return results[1];
};


var ListOrFavProductFlagValue = "";
var shortPageTypeFlagValue = "";
var original_ListId = "";


/* Related Lists...*/

    function getRelatedLists() {
        var page_parameter = "";
	    var action_parameter = "";
	    var list_id_parameter = "";

        page_parameter = "page=List";
	    action_parameter = '&uiAction=GetRelatedListsByListID&maxCount=5&threshold=3';
	    list_id_parameter = "&ListId=" + currentListId ;
		//alert("list_id_parameter: " + list_id_parameter );
        var myParameters = page_parameter + action_parameter + list_id_parameter;

        ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
		    parameters: myParameters,
		    callback: {name: "cbf", value: "RelatedListCallback" }
	    });
    }

    function RelatedListCallback(response) {
		// alert ("response.output: " + response.output);
		if(response.output != 'NoError') {
	        $("#scrollArea_relatedLists").html(response.output);

	        if( $("#relatedEssentiaListsNav").is(":hidden") ) {
    	        $("#relatedEssentiaListsNav").show();
        	}
		}
    }

/*...related lists */


/* Feedback...*/

    function getListFeedback() {
        var page_parameter = "";
        var action_parameter = "";
        var list_id_parameter = "";

        page_parameter = "page=List";
        action_parameter = '&uiAction=GetFeedback';
        list_id_parameter = "&ListId=" + currentListId ;

        var myParameters = page_parameter + action_parameter + list_id_parameter;

        ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
	        parameters: myParameters,
	        callback: {name: "cbf", value: "AdjustListFeedbackCallback" }
        });
    }

    function AdjustListFeedbackCallback(result) {

        //get total and positive numbers and put them into the div
        //fake data
        var total = result.output.total;
        var positive = result.output.positive;
        if(total == 0) total = '0';
        if(positive == 0) positive = '0';

        $("#feedbackPositive").html(positive);
        $("#feedbackTotal").html(total);

        if ($("#listFeedbackContent").is(":hidden")) {
            $("#listFeedbackContent").show();
        }

    }

	function submitYesFeedback(e) {
		e.preventDefault(e);
		
		if (ListOrFavProductFlagValue == "EssentiaList") {
			page_parameter = "page=List";
			action_parameter = '&uiAction=AddFeedBack';
			list_id_parameter = "&ListId=" + currentListId ;

			var myParameters = page_parameter + action_parameter + list_id_parameter ;

			myParameters += "&isFavorable=true";

			ui.request({ baseURL: $.hosts.commServices + '?',
				parameters: myParameters,
				callback: {name: "cbf", value: "submitYesFeedbackCallBack" }
			});
		}
		return false;
	}

	function submitNoFeedback (e) {
		e.preventDefault(e);
		if (ListOrFavProductFlagValue == "EssentiaList") {
			page_parameter = "page=List";
			action_parameter = '&uiAction=AddFeedBack';
			list_id_parameter = "&ListId=" + currentListId ;

			var myParameters = page_parameter + action_parameter + list_id_parameter ;

			myParameters += "&isFavorable=false";

			ui.request({ baseURL: $.hosts.commServices + '?',
				parameters: myParameters,
				callback: {name: "cbf", value: "submitNoFeedbackCallBack" }
			});
		}
		return false;
	}

    function submitYesFeedbackCallBack (result) {

		if (isGeneralErrorFound(result, "Providing List feedback did not succeed: ")) {
			return;
		}

        getListFeedback();
		$('#list_feedback_call_result').show();
    }

    function submitNoFeedbackCallBack (result) {

		if (isGeneralErrorFound(result, "Providing List feedback did not succeed: ")) {
			return;
		}

        getListFeedback();
		$('#list_feedback_call_result').show();
    }

/*...feedback */


$.SortList = function(options){
	var self = this;
	this.list = $("#list-items");

	var container = null;



	ListOrFavProductFlagValue = $('#ListOrFavProductFlag').val();
	shortPageTypeFlagValue = String($('#pageTypeFlag').val()).replace(/Owner/, '');
	shortPageTypeFlagValue = String(shortPageTypeFlagValue).replace(/Visitor/, '')

	//alert ('ListOrFavProductFlagValue: ' + ListOrFavProductFlagValue);

	function init() {

		CallServiceAddItem = function (e) {
			e.preventDefault(e);

			var values = $(e.target).get(0).id.split("_");
			var pt = values[0];
			var ean = values[1];

			var page_parameter = "";
			var action_parameter = "";
			var list_id_parameter = "";

			//alert('adding: ' + pt + ', ' + ean);

			if (ListOrFavProductFlagValue == "EssentiaList") {
				page_parameter = "page=List";
				action_parameter = '&uiAction=AddItemToList';
				list_id_parameter = "&ListId=" + currentListId ;
			}
			else {
				page_parameter = "page=FavoriteProducts";
				action_parameter = '&uiAction=AddItemToListFavoriteProducts';
				list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
				
				// pt is in fact not the productType but instead it is the product code. There was some confusion when it was written in 2008
			}



			ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
				parameters:  page_parameter + list_id_parameter + action_parameter + "&bnOutput=1&ean="+ ean +"&productCode=" + pt, 
				callback: {name: "cbf", value: "jQuery.global.SortList.ListAddItemCallback"},
				errorMsgHolder: $("#searchMaxLimitError")
			});
		}

		myProductTypes = $.SearchWidget.productTypesTemplate
		mySearchWidgetHeader = "Add to EssentiaList"

		if(ListOrFavProductFlagValue == 'FavoriteProducts') {
			switch (shortPageTypeFlagValue){

				case 'favBK':
					myProductTypes = ["Books",	"DigAudio",	"eBooks"];
					mySearchWidgetHeader = "Add to My Favorite Books";
					break;
				case 'favMU':
					myProductTypes = ["Music"];
					mySearchWidgetHeader = "Add to My Favorite Music";
					break;
				case 'favDV':
					myProductTypes = ["DVD"];
					mySearchWidgetHeader = "Add to My Favorite DVDs";
					break;
				case 'favRN':
					myProductTypes =  ["Books",	"DigAudio",	"eBooks"];
					mySearchWidgetHeader = "Add to My Reading Now List"
					break;
			}
		}

		self.searchWidget = new $.SearchWidget({
			heading: mySearchWidgetHeader,
			productTypes: myProductTypes,
			add: CallServiceAddItem,
			refresh: function() {

			},
			cbf: "jQuery.global.SortList.searchWidget.displayResults"
		});

		self.container = $("#ListMainContainer");

		self.container.delegate("click", {
		  "img.top": moveToTop,
		  "a.removeIcon": removeItem,
	  	  "textarea.unFocused": _focused,
		  "a#list_simple_sort_by_title_link": simpleSortListByTitle,
          "a#list_simple_sort_by_list_order_link": simpleSortListByListOrder,
          "a#list_simple_sort_by_date_link": simpleSortListByDate,
		  "input#radio_set_list_private": saveListAsPrivate,
		  "input#radio_set_list_public": saveListAsPublic

		});

		$("button.addItems").click(function(e) { startAddItemsToList(e) });
		$("button.btn_updateSmall").click(function(e) { moveToNewLocation(e) });
		$("button.btn_saveChanges").click(function(e) { 
			e.preventDefault(e);
			saveListChanges(e);
		});
		 
	
		var $inputTitle = $("#inputTitle");
		$inputTitle.change (function() {Call_Service_List_Change_Title()});
		$inputTitle.keydown(function(e) {
			if(e.keyCode == 13) {
				e.preventDefault(e);
			}
		});
		
		
		$("#Description").change (function() {Call_Service_List_Change_Description()});
		$(".list_comment").change (function() {CallServiceListChangeComment	(this)});
		
		$("#selectPenNameOnList").click(function(e) {
			e.preventDefault(e);
			if ($('#editMode').exists() && $('#editMode').val() == 'true') {
				$.global.ReadyServiceSaveListforPennamePrompt.prompt();
			}
			else {
				$.global.PenNameSelector.open();
			}

		});

		reorderList ($("#list-items"), true);


        var feedback = $("#wasThisHelpfulFeedback");
        feedback.delegate("click", {
            "button.btn_helpful_yes": submitYesFeedback,
            "button.btn_helpful_no": submitNoFeedback
        });

		MakePromptsContent ();

	}


	this.refreshListObject = function () {
		$(".overlay:has(#ovrly-addItem)").remove();
		$("#ListMainContainer").unbind();
		init();
		if ($('#ListOrFavProductFlag').exists() && $('#ListOrFavProductFlag').val() == 'EssentiaList') {
			getRelatedLists();
		}
		

		//Re-starts Ratings stars on page; duplicated from ui.js - 9-18-08
		var ratingWidgets = $("span.rating-widget").not("span.ignore");
		for(var i=0; i<ratingWidgets.length; i++) {
			var spanParent = ratingWidgets[i];
			if(spanParent.getElementsByTagName("img").length == 0) {
				spanParent.className += " noNA";
			}
			spanParent.innerHTML = "<a href='#' class='section_rateTitle rating-0'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-1'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-2'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-3'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-4'>&nbsp;&nbsp;&nbsp;&nbsp;</a><a href='#' class='section_rateTitle ratingVal rating-5'>&nbsp;&nbsp;&nbsp;&nbsp;</a>" + spanParent.innerHTML;
			if ($.browser.msie) {
				$('a.ratingVal').css('top', 'auto');
			}
		}
		
		initUpdateBoxes ();
	}


	this.ListAddItemCallback = function (response, errorMsgHolder) {
		if(response.status == "False" && errorMsgHolder) {
		   errorMsgHolder.html(response.output).show();
		} else if(response.output != "") {
			if ($('#ListOrFavProductFlag').val() == 'EssentiaList'){
				$('#list-items').prepend($(response.output));
				$(".list-item:first .list_comment").change (function() {CallServiceListChangeComment	(this)});
			}
			else {
				$('#list-items').append($(response.output));
				$(".list-item:last .list_comment").change (function() {CallServiceListChangeComment	(this)});					
			}
			
			self.list = $('#list-items');
			$("div.first", self.list).removeClass("first");
			$("div.last", self.list).removeClass("last");
			$("div.list-item:first", self.list).addClass("first").find('textarea.list_comment')
			var $textarea = $("div.list-item:first", self.list).find('textarea.list_comment');




		 	$("div.list-item:first img.top").click (function(e) {moveToTop()});
			$("div.list-item:first button.btn_updateSmall").click(function(e) { moveToNewLocation(e) });
	
			$textarea.maxLength(250, $textarea.prev('span.charLimit'), 'Character remaining');
			$("div.list-item:last", self.list).addClass("last");
			AdjustListCountDisplay (1);
			initUpdateBoxes ();

			var listItem = $("div.list-item").get(0);
			
			
			
			reorderList($("#list-items"));			
		}
	}


	function textAreaFocus(e) {
		var target = $(e.target);
		if(target.hasClass("unFocused")) {
			_focused(e);
		}
	}

	function moveToTop(e) {
		_removeClasses();

		var listItem = $(e.target).parents("div.list-item");

		listItem.addClass("first").prependTo($("#list-items"));

	  	$("div.list-item:last", self.list).addClass("last");

		reorderList($("#list-items"));
	}



	function moveToNewLocation(e) {

		//alert('testing re-0order');

		var listItem = $(e.target).parents("div.list-item");	
		
		var target_rank_val =  Number($(e.target).siblings().filter('.list_item_rank').val());

	
		if (target_rank_val < 1) {
			
			target_rank_val = 1;
		}

		if (target_rank_val >= $("div.list-item").length) {
			
			listItem.insertAfter($("div.list-item:last"));
		}
		else if (listItem.nextAll("div.list-item:nth-child(" + target_rank_val + ")").exists()) {  // if the target location is after the current item
		
			listItem.insertBefore($("div.list-item:eq(" + String(target_rank_val) + ")"));
		}
		else {
			listItem.insertBefore($("div.list-item:eq(" + String(target_rank_val - 1) + ")"));
		}

		// Note: in the above jquery :nth-child() is needed because it explicitly escapes the context of nextAll and test indices based on parents.  
		//		In the interBefore though, eq() can be used because there is no limiting context and the result is the same.

		_removeClasses();

	 	$("div.list-item:first").addClass("first");
	  	$("div.list-item:last").addClass("last");

		reorderList($("#list-items"));


		return false;
	}

	function removeItem(e) {  // ie: re-move it from the list
		_removeClasses();
		var listItem = $(e.target).parents("div.list-item");
		//alert ('item to remove: ' + listItem.attr('id'));

		var page_parameter = "";
		var action_parameter = "";
		var list_id_parameter = "";


		if (ListOrFavProductFlagValue == "EssentiaList") {
			page_parameter = "page=List";
			action_parameter = '&uiAction=RemoveListItem';
			list_id_parameter = "&ListId=" + currentListId ;
		}
		else {
			page_parameter = "page=FavoriteProducts";
			action_parameter = '&uiAction=RemoveListFavoriteProductsItem';
			list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
		}



		var myParameters = page_parameter + action_parameter + list_id_parameter ;


		myParameters += '&ListItemId=' + listItem.attr('id')+'';

		listItem.after ('<div id="' + listItem.attr('id') + '_errorHolder" class="removeErrorHolder"></div>');

		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: myParameters,
			errorMsgHolder: $(e.target).parents('div.list-item').siblings('.removeErrorHolder'),
			callback: {name: "cbf", value: "ListRemoveItemCallBack" }
		});

		listItem.remove();
		reorderList($("#list-items"));
		$("div.list-item:first").removeClass("first").addClass("first");
		$("div.list-item:last").addClass("last");
		return false;
	}


	function _removeClasses() {
		//alert('removing classes');
		$("div.updateState").removeClass("updateState");
		$("#list-items .first").removeClass("first");
		$("#list-items .last").removeClass("last");
	}

	function _focused(e) {
		var el = $(e.target).get(0);
		el.className = "list_comment";
		el.innerHTML = "";
		$(e.target).parent("label").find("span.shareThoughts").hide();
	}

	function reorderList(list, suppress_service_call) {

		setTimeout(
			function() {
				$("div.list-item", list).each(
					function(index, item) {
						$(item).find("div.ordering input").val(index + 1);
					}

				);
				if (! suppress_service_call) {
					Call_Service_List_ReOrder ();
				}

			}, 100);
	}

	this.reorder_Sortlist = function () {
		reorderList($("#list-items"), true);
	}


	function Call_Service_List_ReOrder () {


		var reorderItems = "&ListItemOrder=";

		$('#list_test_output').html ("");

		$("div.list-item").each(function (myIndex, myItem) {
				$(myItem).data('ListOrderIndex', myIndex);
				if (reorderItems != '&ListItemOrder=') {
					reorderItems += "|";
				}
				reorderItems += $(myItem).attr('id');

				if (false) {
					$('#list_test_output').html (
						 $('#list_test_output').html () + $(myItem).attr('id') + ', index:' + $(myItem).data('ListOrderIndex') + "<br/>"
						 )
					}
				}
		);

		$('#list_test_output').prepend(reorderItems + "<br/>");


		var page_parameter = "";
		var action_parameter = "";
		var list_id_parameter = "";


		if (ListOrFavProductFlagValue == "EssentiaList") {
			page_parameter = "page=List";
			action_parameter = '&uiAction=ChangeListOrder';
			list_id_parameter = "&ListId=" + currentListId ;
		}
		else {
			page_parameter = "page=FavoriteProducts";
			action_parameter = '&uiAction=ChangeFavoriteProductsOrder';
			list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
		}




		var myParameters = page_parameter + action_parameter + list_id_parameter ;

		myParameters += reorderItems;

		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: myParameters,

			callback: {name: "cbf", value: "ListReOrderCallBack" }
		});

		//////////////////////////////////////
	}



	function Call_Service_List_Change_Title () {
	

		// This is assumed to only be called from an EssentiaList page

		var myParameters = "uiAction=UpdateListAttributes&bnOutput=1&page=List&ListID=" + currentListId;

		myParameters += "&Title=" + encodeURIComponent($('#inputTitle').attr('value'));

		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: myParameters,
			callback: {name: "cbf", value: "updateTitleCallback" }
		});


		//alert ($("#ListID").attr('value') + " title has changed to: " + $("#inputTitle").attr('value'));
	}

	function Call_Service_List_Change_Description () {

		// This is assumed to only be called from an EssentiaList page

		var myParameters = "uiAction=UpdateListAttributes&bnOutput=1&page=List&ListID=" + currentListId;

		myParameters += "&desc=" + encodeURIComponent($('#Description').attr('value'));

		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: myParameters,
			callback: {name: "cbf", value: "updateDescCallback" }
		});


		//alert ($("#ListID").attr('value') + " title has changed to: " + $("#inputTitle").attr('value'));
	}

	function CallServiceListChangeComment (target) {

		//alert ('changing ' + this.id + "("+ String(this.id).substr(8) +")(" + this.value + ")");

		var index_to_use = $(target).attr('id').split("_")[1];
		var ean_to_use = $(target).attr('id').split("_")[2]

		var page_parameter = "";
		var action_parameter = "";

		if (ListOrFavProductFlagValue == "EssentiaList") {
			page_parameter = "page=List";
			action_parameter = '&uiAction=UpdateListItemComment';
		}
		else {
			page_parameter = "page=FavoriteProducts";
			action_parameter = '&uiAction=UpdateListFavoriteProductsItemComment';
			list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
			page_parameter += list_id_parameter;
		}


		var myParameters = page_parameter + action_parameter ;

		myParameters += "&ListItemID=" + index_to_use;
		myParameters += "&ean=" + ean_to_use;
		myParameters += "&comments=" + encodeURIComponent($(target).val());

		$.global.listCommentID = "comment_" + index_to_use + "_" + ean_to_use;
		//extraParameters: "#comment_" + index_to_use + "_" + ean_to_use
		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: myParameters,
			errorMsgHolder: $(target).parents('div.list-item'),
			callback: {name: "cbf", value: "updateListCommentCallback" }
		});
		
	}

	init();
}



function startAddItemsToList () {
	//alert( Number($('.ListCountDisplay:first').text()));
	
	$('.AddItemFailed').remove();
	
	if ( Number($('.ListCountDisplay:first').text()) >= 100) {
		if ($('#ListOrFavProductFlag').val() == 'EssentiaList') {
			errorMessage = "Your EssentiaList has reached its limit of 100 titles. If you wish to add this item, delete an existing title to make room.  ";
		}
		else if (String($('#pageTypeFlag').val()).indexOf ('favRN') != -1) {
			errorMessage = "Your Reading Now list has reached its limit of 100 titles. If you wish to add this item, delete an existing title to make room.  ";			
		}
		else {
			errorMessage = "Your Favorite Products list has reached its limit of 100 titles. If you wish to add this item, delete an existing title to make room.   ";			
		}
		showManualError (errorMessage, "AddItemFailed", $('.AddItemsMessage'));
		return false;
	}

	$.global.SortList.searchWidget.addItems();


}


function saveListAsPrivate() {
	
	saveListPrivacy('Private');
}
function saveListAsPublic() {

	
	if ($('#editMode').val() == 'false' && $('#choosePennameOnListFlag').exists() && $('#choosePennameOnListFlag').val() == 'true' ) {
		
		$.global.PenNameSelector.open();
	}
	else {
		saveListPrivacy('Public');
	}
}

function saveListPrivacy (newLevel) {
	
		var myParameters = "uiAction=UpdateListAttributes&page=List&pageType=List"

		var list_id_parameter = "&ListID=" + currentListId;
	

		myParameters += "&PrivacyLevel=" + newLevel;
		

		var myEditingParameter = '&bIsTemp=false';
		
		//alert("$('#editMode').val(): " + $('#editMode').val());

		ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters + list_id_parameter +  myEditingParameter ,
			callback: {name: "cbf", value: "saveListPrivacyCallBack" }
		});
		
		// Send second request in case in editMode, so temp table gets same setting (&bIsTemp=false is omited)
		
		if ((! $('#editMode').exists()) || $('#editMode').exists() && $('#editMode').val() == 'true') {
			ui.request({ baseURL: $.hosts.commServices + '?',
				parameters: myParameters + list_id_parameter,
				callback: {name: "cbf", value: "saveListPrivacyCallBack" }
			});
		
		}
		
		return false;
}

function saveListPrivacyCallBack(response) {

	if (isGeneralErrorFound(response, "Saving the new Wish List privacy did not succeed: ")) {
		return;
	}

	return;
}


function updateListCommentCallback (response, errorMdgHolder) {

	if(isLocalizedErrorFound (response, "", "SaveCommentFailed", errorMdgHolder)) {

		return;
	}



}



function CallServiceDeleteList() {

	// This is assumed to only be called from an EssentiaList page

	var myParameters = "uiAction=DeleteList&bnOutput=1&page=List&ListID=" + currentListId;

	if($('#listNavLink_'+ currentListId + ' ~ li').exists()) {
		var next_list = $('#listNavLink_'+ currentListId + ' ~ li').attr('id').split("_")[1];

		if (String(next_list).length > 0) {
			myParameters += '&ListIDtoBeSelected=' + next_list;
		}
	}
	//alert ("currentListId:" + currentListId + ", next list: " + $('#listNavLink_'+ currentListId + ' ~ li').attr('id') + ", " + myParameters);

	ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
		parameters: myParameters,
		callback: {name: "cbf", value: "DeleteListCallBack" }
	});

	return true;
}

function DeleteListCallBack  (result){
	//alert ("List Deleted");

	if (isGeneralErrorFound(result, "Deleting the list did not succeed: ")) {
		return;
	}

	if (result.status == 'True') {
		window.location = ('http://' + $.hosts.community + '/communityportal/List.aspx');
	}


	// removed for DMS_P00056947: creating a wishlist should now be a page-load, not asynchronous
	/*$('#ListMainContainer').html(result.output);

	$.global.SortList.refreshListObject();

	RefreshListSummaryNav ();
	*/
	

}



function updateTitleCallback(response) {


	if (isGeneralErrorFound(response, "", "SaveTitleFailed")) {
		return;
	}

	// obsolete as for 9/9/08? :
	if(response.status == "False" && response.output.length > 0) {
		if($("#listHeader div.errorMsg").get(0) == null) {
			$("#listHeader").append("<div class='errorMsg'>" + response.output + "</div>");
			$("#listHeader div.errorMsg").data("errorCount", 1);
		} else {
			var $errorMsg = $("#listHeader div.errorMsg");
			var errors = $errorMsg.data("errorCount");
			$errorMsg.data("errorCount", errors + 1);
		}
	} else {
		var $errorMsg = $("#listHeader div.errorMsg");
		var errors = $errorMsg.data("errorCount");
		if(errors == 1) {
			$errorMsg.remove();
		} else {
			$errorMsg.data("errorCount", errors - 1)
		}
	}
}

function updateDescCallback(response) {


	if (isLocalizedErrorFound(response, "", 'SaveDescFailed', '#listDescErrorMessage')) {
		return;
	}

}

function ListRemoveItemCallBack (response, errorMdgHolder) {

	if(isLocalizedErrorFound (response, "The item could not be removed: ", "SaveCommentFailed", errorMdgHolder)) {

		return;
	}

	//alert ("Item Removed");
	// Item already removed by Sortlist action
	AdjustListCountDisplay (-1);
}

function RefreshListSummaryNav () {
	CallServiceGetListSummary ();
}

function CallServiceGetListSummary () {

	if (ListOrFavProductFlagValue == "EssentiaList") {

		list_id_parameter = "&ListId=" + currentListId ;
		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: "page=List&uiAction=GetAllLists" + list_id_parameter + "&ce_sort=" + $("#listNavSortSelect").val(),
			callback: {name: "cbf", value: "GetListSummaryCallBack" }
		});

	}
	else {

		page_parameter = "page=FavoriteProducts";
		action_parameter = '&uiAction=GetAllListsFavoriteProducts';
		list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
		ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
			parameters: page_parameter + action_parameter + list_id_parameter + "&bnOutput=1",
			callback: {name: "cbf", value: "GetListFavoriteProductsSummaryCallBack" }
		});
	}

	return;
}


function GetListSummaryCallBack (result) {

	if (result.status == 'True') {
		$('#scrollArea_Lists').html(result.output);
	}

	return;
}

function GetListFavoriteProductsSummaryCallBack (result) {

	if (result.status) {
		$('#listNav ul').html(result.output);
	}

	return;
}

/*update box js, added by Kris 6/2/08*/

function initUpdateBoxes() {
	var orderingBoxes = $("div.ordering input");

	orderingBoxes.each(function() {
		this.onfocus = function() {
			if(this.parentNode.className.search('updateState') == -1) {
				var updateBoxes = $('div.updateState');
				updateBoxes.each(function() {this.className = 'ordering';});
				this.parentNode.className += " updateState";
			}
		};
	});

}



$(function() { // Set Up all ui Prompt overlays
		   CreateListPrompt_Content_Holder ='<div class="CreateListServiceError"></div>\
		   <div class="myCreateListPrompt" style="padding: 10px 20px 20px 20px; "> \
   			<span class="CreateListPrompt_LabelHolder" style="display:none;">Please name your EssentiaList:</span><br/>\
																		\
			<span style="font-weight:bold; font-size:10px;" class="CreateListPromptTitle"></span><br/>																								\
			<span class="CreateListPrompt_ErrorHolder" style="display:none;"><span style="color:#666; font-weight:bold">Please enter a title.</span></span> 										\
			<input type="text" class="new_listOnPage_inputTitle" maxlength="100" value="" style="width: 360px; height: 30px; color:#666; font-family: verdana, arial, sans-serif; font-size:16px; margin-top:4px;" />			\
			<br/>																																													\
			<br/>																																													\
			<span style="font-weight:bold; font-size:10px;">You may add a description of the list:</span>																							\
			<br />																																													\
			<textarea class="new_listOnPage_Description" style="width: 360px; height: 60px;color:#666666; font-size:12px;margin-top:4px; font-family: verdana, arial, sans-serif;"> </textarea>													\
			<br/>																																													\
			<br/>																																													\
			<button class="createOnPage_okay"><img src="' + $.hosts.resources + '/presources/community/images/btn_submit.gif" /></button>															\
			<button class="createOnPage_cancel"><img src="' + $.hosts.resources + '/presources/community/images/btn_cancel.gif" /></button>														\
		</div>																																														\
		';
	
	$.global.ReadyServiceCreateListPrompt = new $.Confirm({
	      heading: "Create a new EssentiaList",
	      id: "myCreateListPromptOnPage",
	      content: CreateListPrompt_Content_Holder,
	      cancel: {path: "button.createOnPage_cancel", action: function() {

				if ($('#create_list_popup_trigger').exists()) {
					window.location = "List.aspx";
				}
				return true;
	      }},
	      ok: {path: "button.createOnPage_okay", action: function() {
				return SubmitServiceCreateListPrompt();
	      }}
	});

/*	$('#myCreateListPrompt .overlayClose').click (function () {
		alert('here');
		$.global.ReadyServiceCreateListPrompt.close();															
	});
*/

	MakePromptsContent ();

	$.global.ReadyServiceDeleteListPrompt = new $.Confirm({
	      heading: "Delete an EssentiaList",
	      id: "myDeleteListPrompt",
	      content: DeleteListPrompt_Content_Holder,
	      cancel: {path: "button.delete_cancel", action: function() {

			  return true;
	      }},
	      ok: {path: "button.delete_okay", action: function() {
				return CallServiceDeleteList();
	      }}
	});

	$.global.ReadyServiceCancelListChangesPrompt = new $.Confirm({
	
	      heading: "Cancel My Edits",
	      id: "myCancelListChangesPrompt",
	      content: CancelListChangesPrompt_Content_Holder,
	      cancel: {path: "button.cancel_cancel", action: function() {

			  return true;
	      }},
	      ok: {path: "button.cancel_okay", action: function() {
				return CallServiceCancelListChanges();
	      }}
	});




	$.global.ReadyServiceSaveListforPennamePrompt = new $.Confirm({
	      heading: "Save Edits",
	      id: "mySaveListforPennamePrompt",
	      content: SaveListforPennamePrompt_Content_Holder,
	      cancel: {path: "button.save_cancel", action: function() {
			  return true;
	      }},
	      ok: {path: "button.save_okay", action: function() {
				CallServiceSaveListChanges('SaveListChangesForPennameCallBack');
				return true;
	      }}
	});
}); // END Set Up all UI Prompt overlays

function MakePromptsContent () {

	var tempTitle = "";

	if ($('input#inputTitle').exists()) {
		tempTitle = $('input#inputTitle').val();
	}
	else if ($('h4#inputTitle').exists()) {
		tempTitle = $('h4#inputTitle').text();
	}

	DeleteListPrompt_Content_Holder ='<div style="padding: 20px;"> \
			<span style="font-weight:bold; font-size:10px;">Are you sure you want to delete the list <i>' + tempTitle + '</i>? </span><br/>														\
			<br/>																																													\
			<button class="delete_okay"><img src="' + $.hosts.resources + '/presources/community/images/yes_green.png" /></button>															\
			<button class="delete_cancel"><img src="' + $.hosts.resources + '/presources/community/images/no_gray.png" /></button>														\
		</div>																																														\
		';
	CancelListChangesPrompt_Content_Holder ='<div style="padding: 20px;"> \
			<span style="font-weight:bold; font-size:10px;">Are you sure you want to cancel the changes to the list <i>' + tempTitle + '</i>? </span><br/>														\
			<br/>																																													\
			<button class="cancel_okay"><img src="' + $.hosts.resources + '/presources/community/images/yes_green.png" /></button>															\
			<button class="cancel_cancel"><img src="' + $.hosts.resources + '/presources/community/images/no_gray.png" /></button>														\
		</div>																																														\
		';
	SaveListforPennamePrompt_Content_Holder ='<div style="padding: 20px;"> \
			<span style="font-weight:bold; font-size:10px;">Please save changes to the list <i>' + tempTitle + '</i> before creating a Pen Name. </span><br/>														\
			<br/>																																													\
			<button class="save_okay"><img src="' + $.hosts.resources + '/presources/community/images/btn_saveChanges.gif" /></button>															\
			<button class="save_cancel"><img src="' + $.hosts.resources + '/presources/community/images/btn_cancel.gif" /></button>														\
		</div>																																														\
		';

	return;
}


function Activate_CreateListPrompt () {

	if (Number($('#ListCount').val()) >= 100) {
		showPopUpError ("You can create only 100 EssentiaLists. If you wish to start a new EssentiaList, delete an existing one to make room.",
						 "createListMaxError", "Unable to Create EssentiaList");
		return false;
	}
		
		//	createListErrorMessage

	$.global.ReadyServiceCreateListPrompt.prompt();
	$('.new_listOnPage_inputTitle').val('');
	$('.new_listOnPage_Description').val("");
	//alert ('text:' + $('.new_listOnPage_inputTitle').val());
	$('.CreateListPromptTitle').html( $('.CreateListPrompt_LabelHolder').html() );
	$('.CreateListServiceError').html('');
	return false;
}


function Activate_DeleteListPrompt () {

	$.global.ReadyServiceDeleteListPrompt.prompt();

	return false;
}

function SubmitServiceCreateListPrompt() {

	var new_title = "";
	var new_description = "";

	if (ListOrFavProductFlagValue == 'EssentiaList') {
		new_title = String($('.new_listOnPage_inputTitle').get(0).value);
		new_description = String($('.new_listOnPage_Description').get(0).value);
	} else {
		new_title = String($('.new_list_inputTitle').get(1).value);
		new_description = String($('.new_list_Description').get(1).value);
	}
	
	var no_error_found = true;

	//alert('new_title: ' + new_title);
	if (new_title.length > 0) {
		//alert ("Got Title (" + new_title + ")");
		CallServiceCreateNewList (new_title, new_description);
		// hide any old error:
		$('.CreateListPrompt_ErrorHolder').hide();
	}
	else {

		$('.CreateListPrompt_ErrorHolder').show();
		//alert ('Title missing');
		//$('.CreateListPromptTitle').html( $('.CreateListPrompt_ErrorHolder').html() );
		no_error_found = false;
	}
	//return no_error_found; //oboslete 9/16/08; now we should hold the prompt open until the service returns with no errors.
	
	return false;
}

function CallServiceCreateNewList (title, description) {

	// This is assumed to only be called from an EssentiaList page

	// removed for DMS_P00056947: creating a wishlist should now be a page-load, not asynchronous
	//var myParameters = "uiAction=CreateList&bnOutput=1&currentMode=WriteMode&page=List";

	var myParameters = "uiAction=CreateListForLinkOnly&ce_purpose=CreateListOnPage&PrivacyLevel=Public&bnOutput=1&page=List";


	if (String(title).length > 0){
		myParameters += "&title=" + encodeURIComponent(title);
	}

	if (String(description).length > 0){
		myParameters += "&desc=" + encodeURIComponent(description);
	}


	ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
		parameters: myParameters,
		errorMsgHolder: '.CreateListServiceError',
		callback: {name: "cbf", value: "CreateListCallBack" }
	});

	return false;
}

function CreateListCallBack (result, errorMsgHolder) {
	
	if (result.status == "False" && $(errorMsgHolder).exists()) {
		 isLocalizedErrorFound (result, "", "", errorMsgHolder);
		 return;
	}

	if (result.status == 'True') {
		//alert(result.output);	
		// could call byt there is a long delay with nothing happening otherwise; $.global.ReadyServiceCreateListPrompt.close();
		window.location = String(result.output + '&editMode=Y');
		
	}
	// removed for DMS_P00056947: creating a wishlist should now be a page-load, not asynchronous	
	/* $('#ListMainContainer').html(result.output);
	self.list = $('#list-items');
	$("div.first", $("#list-items")).removeClass("first");
	$("div.last", $("#list-items")).removeClass("last");
	$("div.list-item:first", $("#list-items")).addClass("first");
	$("div.list-item:last", $("#list-items")).addClass("last");

	CallServiceSetListToEdit (true);
	RefreshListSummaryNav ();
	return;
	*/
}

function CallServiceSetListToEdit (isListJustCreated) {


	var page_parameter = "";
	var action_parameter = "";
	var list_id_parameter = "";
	
	if (isListJustCreated) {
		page_parameter += 'ce_listJustCreated=True&';	
	}

	//alert ('shortPageTypeFlagValue: ' + shortPageTypeFlagValue);
	if (ListOrFavProductFlagValue == "EssentiaList") {
		page_parameter += "page=List";
		action_parameter = '&uiAction=SetListToEdit';
		list_id_parameter = "&ListId=" + currentListId ;
	}
	else {
		page_parameter = "page=FavoriteProducts";
		action_parameter = '&uiAction=SetListFavoriteProductsToEdit';
		list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
	}


	var myParameters = page_parameter + action_parameter + list_id_parameter + "&bnOutput=1";

	ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
		parameters: myParameters + "&ce_total="+$("#feedbackTotal").text()+"&ce_positive=" + $("#feedbackPositive").text(),
		callback: {name: "cbf", value: "SetListToEditCallBack" }
	});


	return false;
}


function promptDiscardChanges() {
    return "If you leave this page, any of your changes will be lost. Discard your changes?";
}

function SetListToEditCallBack (result) {
    //window.onbeforeunload = promptDiscardChanges;

	if (isGeneralErrorFound(result, "Starting to edit the list did not succeed: ")) {
		return;
	}


	$('#ListMainContainer').html(result.output);
	self.list = $('#list-items');
	$("div.first", $("#list-items")).removeClass("first");
	$("div.last", $("#list-items")).removeClass("last");
	$("div.list-item:first", $("#list-items")).addClass("first");
	$("div.list-item:last", $("#list-items")).addClass("last");
	initUpdateBoxes();

	//$.global.SortList = new $.SortList();
	$.global.SortList.refreshListObject();

	$('#inputTitle').maxLength(100, $('#inputTitle').next('div.charLimit'), 'Character remaining');
	$('#Description').maxLength(250, $('#Description').parent().next('div.charLimit'), 'Character remaining');
	$('textarea.list_comment').each(function(){
		$(this).maxLength(250, $(this).prev('span.charLimit'), 'Character remaining');
	})

	return;
}




function saveListChanges () {

	// Assume you are in Edit Mode
	var time_check = "";

	if ( $('.SaveTitleFailed').exists() || $('.SaveDescFailed').exists() ||  $('.SaveCommentFailed').exists()) {
	
		if (! WaitingOnceForListErrorsToClear) {
			time_check = time_check = setTimeout ("saveListChanges()", 1200);
			WaitingOnceForListErrorsToClear = true;
			return false;
	
		}
		else {
			showPopUpError ("Please revolve the remaining errors on the page before saving the list.", "errorsRemain",  "Errors Remain");
			WaitingOnceForListErrorsToClear = false;
			return false;
		}
		
	}
		
	// Last minute error checking for empty Title - will cancel serice if empty
	if (String($('#inputTitle').attr('value')).length <= 0) {
		showManualError ("Please enter a title before saving the list.", 'pageTitleMissing', '.pageErrorsDisplay');
		return false;
	}

	if ($('#choosePennameOnListFlag').exists() && $('#choosePennameOnListFlag').val() == 'true' && $('#radio_set_list_public:checked').exists()) {
		//alert('saving, but missing Pen Name...');
		//CallServiceSaveListChanges('SaveListChangesForPennameCallBack');
		
		$.global.PenNameSelector.open();
	}
	else {
		CallServiceSaveListChanges();	
	}
	
	return false;
}

function CallServiceSaveListChanges (specialCallBack) {



	var page_parameter = "";
	var action_parameter = "";
	var list_id_parameter = "";
	var myCallBack =  "SaveListChangesCallBack";
	
	// specialCallBack is used to override the regular call back for the saving.  It is now used to execute a special call back if the user just created a new penname before saving.
	if (specialCallBack != null && String (specialCallBack).length > 0) {
		myCallBack = specialCallBack;
	}


	//alert ('ListOrFavProductFlagValue ' + ListOrFavProductFlagValue );
	if (ListOrFavProductFlagValue == "EssentiaList") {
		page_parameter = "page=List";
		action_parameter = '&uiAction=SaveListChanges';
		if (original_ListId != ""){
			list_id_parameter = "&ListId=" + original_ListId;
		}
		else {
			list_id_parameter = "&ListId=" + currentListId;
		}
	}
	else {
		page_parameter = "page=FavoriteProducts";
		action_parameter = '&uiAction=SaveListFavoriteProductsChanges';
		list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
	}


	var myParameters = page_parameter + action_parameter + list_id_parameter;

	myParameters += "&bnOutput=1";




	ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
		parameters: myParameters,
		callback: {name: "cbf", value: myCallBack }
	});


	return false;
}

function SaveListChangesCallBack (result) {
	//window.onbeforeunload = null;
	/*alert('made it here: ' + result.output);*/
	if (isGeneralErrorFound(result, "Saving the list feedback did not succeed: ")) {
		return;
	}


	if (String(window.location).indexOf('listCreate') != -1) {
		$('#ListMainContainer').html('<h4 style="color: rgb(176, 163, 119); font-size: 16px; display: inline;">Reloading List...</h4>');
		$('body').append('<div style="display:none;">'+result.output+'</div>');
		//alert('saving after creating now. redirecting to: ' + $('#urlForThisListForServices').val());
		window.location = $('#urlForThisListForServices').val();

	}
	else {
		SaveListChangesCallBackHelper (result);
	}
	return;
}


function SaveListChangesForPennameCallBack (result) {

	SaveListChangesCallBackHelper (result);
	$.global.PenNameSelector.open();
}

function SaveListChangesAfterChoosingPennameCallBack (result) {

	if (isGeneralErrorFound(result, "Saving edits did not succeed: ")) {
		return;
	}

	window.location.reload(true);	
	
	return;	
}

function SaveListChangesCallBackHelper (result) {

	$('#ListMainContainer').html(result.output);
	
	// Find and apply any instance the BuyNow listner for any instance of eBook product
	BN.EBook.Util.setBuyNow($('#list-items .buyItemNowButtonFunc, #list-items .freeNowButtonFunc, #list-items .subscribeNowButtonFunc'));
	BN.EBook.Util.setFreeSample($('#list-items .freeSampleButtonFunc'));

	self.list = $('#list-items');
	$("div.first", $('#list-items')).removeClass("first");
	$("div.last", $('#list-items')).removeClass("last");
	$("div.list-item:first", $('#list-items')).addClass("first");
	$("div.list-item:last", $('#list-items')).addClass("last");
	$.global.SortList.refreshListObject();
	RefreshListSummaryNav ();
	
	$('#list-items .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
	$('#list-items .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );


}


function ReadyServiceCancelListChanges () {
	$.global.ReadyServiceCancelListChangesPrompt.prompt();
	return false;
}


function CallServiceCancelListChanges () {

	var page_parameter = "";
	var action_parameter = "";
	var list_id_parameter = "";

	if (ListOrFavProductFlagValue == "EssentiaList") {
		page_parameter = "page=List";
		action_parameter = '&uiAction=CancelListChanges';
		if (original_ListId != ""){
			list_id_parameter = "&ListId=" + original_ListId;
		}
		else {
			list_id_parameter = "&ListId=" + currentListId;
		}
	}
	else {
		page_parameter = "page=FavoriteProducts";
		action_parameter = '&uiAction=CancelListFavoriteProductsChanges';
		list_id_parameter = "&pageType=" + shortPageTypeFlagValue;
	}


	var myParameters = page_parameter + action_parameter + list_id_parameter ;


	ui.request({ baseURL: $.hosts.commServices + '?',
			queue: 'listRequests',
		parameters: myParameters + "&ce_total="+$("#feedbackTotal").text()+"&ce_positive=" + $("#feedbackPositive").text(),
		callback: {name: "cbf", value: "SaveListChangesCallBack" }
	});


	return true;
}

function CancelListChangesCallBack (result) {
	if (isGeneralErrorFound(result, "Canceling edits did not succeed: ")) {
		return;
	}

	$('#ListMainContainer').html(result.output);
	self.list = $('#list-items');
	$("div.first", self.list).removeClass("first");
	$("div.last", self.list).removeClass("last");
	$("div.list-item:first", self.list).addClass("first");
	$("div.list-item:last", self.list).addClass("last");

	//$.global.SortList = new $.SortList();
	$.global.SortList.refreshListObject();
	
	BN.EBook.Util.setBuyNow($('#list-items .buyNowButtonFunc'));
	BN.EBook.Util.setFreeSample($('#list-items .freeSampleButtonFunc'));

	
	$('#list-items .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
	$('#list-items .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );

	return;
}



function CallServiceSwitchToList () {
	// switch list is currently done with deep links
}

function AdjustListCountDisplay (change_value) {

		current_DOM_list_count_element = $(".ListCountDisplay:first").text();
		//alert ('$(".ListCountDisplay"): ' + current_DOM_list_count_element);
	  	eval ("var current_DOM_list_count = " + current_DOM_list_count_element);
		//alert ('current_DOM_list_count: ' + current_DOM_list_count);
		current_DOM_list_count += change_value;
		$(".ListCountDisplay").text(current_DOM_list_count);
		if(current_DOM_list_count == 1) {
			$(".ListCountDisplayLabel").text(' Item');
		}
		else if (current_DOM_list_count == 0 || current_DOM_list_count > 1){
			$(".ListCountDisplayLabel").text(' Items');
		}

}

function ListReOrderCallBack (result) {

	/*if (isGeneralErrorFound(result, "Re-ordering the list did not succeed: ")) {
			return;
	}*/


	return;
}

$(function() {

	if ($('#create_list_popup_trigger').exists()) {
		Activate_CreateListPrompt();
	}

});

function simpleSortListByTitle() {
    var link = $("a.list_simple_sort_by_title_link");

    var sortFunction = function(a, b) {
        var valA = a.find("h5.list-item-title a").text().toLowerCase();
        var valB = b.find("h5.list-item-title a").text().toLowerCase();
        if(valA > valB) return 1;
        else if(valA < valB) return -1;
        else return 0;
    }
    simpleSortList(sortFunction, link);
}

function simpleSortListByListOrder() {
    var link = $("a.list_simple_sort_by_list_order_link");

    var sortFunction = function(a, b) {
        var valA = parseInt(a.find("span.list-item-position").text());
        var valB = parseInt(b.find("span.list-item-position").text());
        if(valA > valB) return 1;
        else if(valA < valB) return -1;
        else return 0;
    }
    simpleSortList(sortFunction, link);
}

function simpleSortListByDate() {
    var link = $("a.list_simple_sort_by_date_link");

    var sortFunction = function(a, b) {
        var valA = getDate(a.find("span.list-item-date-added").text());
        var valB = getDate(b.find("span.list-item-date-added").text());;
        if(valA > valB) return -1;
        else if(valA < valB) return 1;
        else return 0;
    }
    simpleSortList(sortFunction, link);
}

function simpleSortList(sortFunction, link) {
        var linkId = link.attr('id');
		var sortedArray = new Array();
        var sortDown = link.hasClass("down-arrow");

        if(sortDown) {
            link.each(function() {
                $(this).removeClass("down-arrow").addClass("up-arrow");
            });
        }
        else {
            link.each(function() {
                $(this).removeClass("up-arrow").addClass("down-arrow");
            });
        }

        var listOrderLink = $("a.list_simple_sort_by_list_order_link");
        var dateLink = $("a.list_simple_sort_by_date_link");
        var titleLink = $("a.list_simple_sort_by_title_link");

        //clear the arrows for any of the other sorting links
        if(linkId != listOrderLink.attr('id')) {
            listOrderLink.each(function() {
                $(this).removeClass("down-arrow").removeClass("up-arrow");
            });
        }
        if(linkId != dateLink.attr('id')) {
            dateLink.each(function() {
                $(this).removeClass("down-arrow").removeClass("up-arrow");
            });
        }
        if(linkId != titleLink.attr('id')) {
            titleLink.each(function() {
                $(this).removeClass("down-arrow").removeClass("up-arrow");
            });
        }


		$('div.list-item').each (function (index, item) {
            sortedArray.push($(item));
		});

		sortedArray.sort(sortFunction);
        if(!sortDown) sortedArray.reverse();

		for (i = (sortedArray.length - 1); i >= 0 ; i--) {
			$('div#list-items').append($(sortedArray[i]))
		}

        //reset first and last classes for borders and such
		$("#list-items .first").removeClass("first");
		$("#list-items .last").removeClass("last");

        $("div.list-item:first", self.list).addClass("first");
        $("div.list-item:last", self.list).addClass("last");
}

addEventSimple(window,"load",initUpdateBoxes);
//window.onload = getListFeedback;

$(function() {   
	// Coremetrics: Page views for essentiaList and favorite types(books, cds, dvds).
	if(typeof cmCreatePageviewTag !== "undefined"){
		try{
			var cmPenName = "";
			var cmPenNameDisplay = "";
			if($("#context #profilePenName").text()){
				cmPenName = $("#context span#profilePenName").text();
				cmPenNameDisplay = ": "+cmPenName;
			}
			if (ListOrFavProductFlagValue == "EssentiaList") {
				var currentTitle = $('#inputTitle').text();
				cmCreatePageviewTag ("COMM-ESSENTIALIST: " + currentTitle + "(" + currentListId + ")", "COMMUNITY ESSENTIALIST"); 	
			}else if(ListOrFavProductFlagValue == "FavoriteProducts" && shortPageTypeFlagValue == "favBK"){
				cmCreatePageviewTag ("COMM-FAVORITEBOOKS" +cmPenNameDisplay+ "", "COMMUNITY FAVORITELIST"); 
			}
			else if(ListOrFavProductFlagValue == "FavoriteProducts" && shortPageTypeFlagValue == "favMU"){
				cmCreatePageviewTag ("COMM-FAVORITECDS" +cmPenNameDisplay+ "", "COMMUNITY FAVORITELIST"); 
			}
			else if(ListOrFavProductFlagValue == "FavoriteProducts" && shortPageTypeFlagValue == "favDV"){
				cmCreatePageviewTag ("COMM-FAVORITEDVDS" +cmPenNameDisplay+ "", "COMMUNITY FAVORITELIST"); 
			}
			else if(ListOrFavProductFlagValue == "FavoriteProducts" && shortPageTypeFlagValue == "favRN"){
				cmCreatePageviewTag ("COMM-READINGNOWLIST" +cmPenNameDisplay+ "", "COMMUNITY FAVORITELIST"); 
			}
		}
		catch(e){}
	}
});
