// JavaScript Document

function CallServiceAddWishListItem (e) {
	e.preventDefault(e);

	var values = $(e.target).get(0).id.split("_");
	var pt = values[0];
	var ean = values[1];


	page_parameter = "page=WishList";
	action_parameter = '&uiAction=AddItemToWishList';
	list_id_parameter = "";
	
	if(currentListId != 0) {
	 	list_id_parameter += "&"+currentListItemParam+"=" + currentListId;
	}
	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters:  page_parameter + list_id_parameter + action_parameter + "&bnOutput=1&ean="+ ean +"&productCode=" + pt,
		errorMsgHolder: $('#searchWidget-resultArea'),
		callback: {name: "cbf", value: "AddWishListItemCallback"}

	});
}

function AddWishListItemCallback (response, errorMsgHolder) {

		if (isLocalizedErrorFound (response, "", "AddItemFailed", errorMsgHolder)) {
			return;
		}
		// check because adding duplicate now returns true with no output, so in that case we don't want anything to happen. 
		if(response.output != "") {
			if (Number($('#pageOffset').val() > 0) ||  $('#sortOrderCode').val() > 0) { 
				/* 
					if not one page-one or DateDescending sort, then trigger that to show the new item add to the begining of the list and all the page-info 
					updating will occur from the result of calling the sort service
				*/
				sortWishListByDate ("ForNewItem");
				return;
			}
			
			/* else, then this is the page to add item directly and it will match the database order directly, so show the item at the top of the list
				which out changing anything else: 
			*/
										
	
			$('#wishlist-items').prepend($(response.output));
		
			// Find and apply any instance the BuyNow listner for any instance of eBook product
			BN.EBook.Util.setBuyNow ($('#wishlist-items:first .buyNowButtonFunc'));
			BN.EBook.Util.setFreeSample ($('#wishlist-items:first .freeSampleButtonFunc'));
			$('#wishlist-items:first .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
			$('#wishlist-items:first .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );
			
			$(".wishlist_priority_select:first").change(function(e) {saveWishListItemPriority(e)});
			
			$("div.first").removeClass("first");
			$("div.last").removeClass("last");
			$("div.wishlist-item:first").addClass("first");
			$("div.wishlist-item:last").addClass("last");
	
			$('#NumberOfItemsFlag').val(Number($('#NumberOfItemsFlag').val()) + 1);
			$('.totalItemIndexDisplay').text($('#NumberOfItemsFlag').val());
			if(Number($('#lastItemIndex').val()) < Number($('#NumberOfItemsFlag').val())  && Number($('#NumberOfItemsFlag').val()) > Number($('#pageSize').val())) { 
				// Then the last item has to be hacked off to make room for the new item
				
				$('.wishListItems .wishListItem:last').remove();
			
			}
			else {
				$('#lastItemIndex').val(Number($('#lastItemIndex').val()) + 1);
				$('.lastItemIndexDisplay').text ($('#lastItemIndex').val());
			}
			$('.firstItemIndexDisplay').text('1');
			
			$('.unpopulatedListMessage').remove();
			
			$('.bottom.wishListSortContainer').show();
			
			initCheckStore();
		}
}


var WLSort =  {

        /// Most Recent first
        DateAddedDesc: 0,

        ///  Oldest First
        DateAddedAsc: 1,

        /// By Title, Z-A
        TitleDesc: 2,

        /// By Title , A-Z
        TitleAsc: 3,

        /// By Author, Z-A
        ContributorDesc: 4,

        /// By Author, A-Z
        ContributorAsc:5,

        /// By Rating, Highest first
        RatingDesc: 6,

        /// By Rating, Lowest First
        RatingAsc: 7,


        // User Specified ordering - now used to hold the Priority of the item (low, medium, high).
	    SortRankDesc: 8,
		PriorityDesc: 8,
        /// User Specified ordering - now used to hold the Priority of the item (low, medium, high).
        SortRankAsc: 9,
		PriorityAsc: 9
	};


$(function() { //main invocation container 

	$('#inputDescription').maxLength(250, $('#inputDescription').next('span.charLimit'), 'Characters remaining');
	var $inputTitle = $('#inputTitle');
	$inputTitle.maxLength(100, $('#inputTitle').next('span.charLimit'), 'Characters remaining');
	$inputTitle.keydown(function(e) {
		if(e.keyCode == 13) {
			e.preventDefault(e);
		}
	});


	// Start of WishList invocation container: ---------------------------------------------------------------
	if ($('#pageTypeFlag') &&  String($('#pageTypeFlag').val()).indexOf('wishlist') != -1 ) {

	$.global.wishList = new Object ();

	$.global.wishList.wishListTypeFlagValue = $('#wishListTypeFlag').val();
	$.global.wishList.currentWishList = "";


	// will be set with values from the markup
	$.global.wishList.currentPageSize = 0;
	$.global.wishList.currentSortOffset = 0;

	$.global.wishList.currentItemCount = Number($('#NumberOfItemsFlag').val());

	$.global.wishList.SearchOptions = ["Books",	"DigAudio","DVD", "Music", "Magazines", "Video_Games", "Toys_Games", "Home_Gifts"];
	
	if ($.global.wishList.wishListTypeFlagValue == 'EWL') {
		$.global.wishList.SearchOptions = ["eBooks"];
	}

	$.global.wishList.searchWidget = new $.SearchWidget({
			heading: "Add to Wish List",
			add: CallServiceAddWishListItem,
			refresh: function() {
				//alert('refresh');
				/*refresh();*/
			},
			cbf: "jQuery.global.wishList.searchWidget.displayResults",
			productTypes: $.global.wishList.SearchOptions
		});

		 // Set Up all ui Prompt overlays
			   CreateWishListPrompt_Content_Holder ='<div class="myCreateWishListPrompt" style="padding: 20px;"> \
				<span class="CreateWishListPrompt_ErrorHolder" style="display:none;"><br/><span style="color:#DD0000; font-weight:bold">Please enter a title.</span></span> \
				<span class="CreateWishListPrompt_ErrorHolderTitle" style="display:none;"><br/><span style="color:#DD0000; font-weight:bold">A Wish List by this name already exists.</span></span> \
				<span class="CreateWishListPrompt_LabelHolder" style="font-weight:bold; font-size:10px;">Please name your Wish List:</span>																					\
				<span style="font-weight:bold; font-size:10px;" class="CreateWishListPromptTitle"></span><br/>																								\
				<input type="text" class="new_WishList_inputTitle" maxlength="100" value="" style="width: 360px; height: 30px; color:#666;font-size:16px; font-family: verdana, arial; 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_WishList_Description" style="width: 360px; height: 60px;color:#666; font-size:12px;margin-top:4px; font-family: verdana, arial;"> </textarea>													\
				<br/>																																													\
				<br/>																																													\
				<button class="create_okay"><img src="' + $.hosts.resources + '/presources/community/images/btn_submit.gif" /></button>															\
				<button class="create_cancel"><img src="' + $.hosts.resources + '/presources/community/images/btn_cancel.gif" /></button>														\
			</div>																																														\
			';



		$.global.ReadyServiceCreateWishListPrompt = new $.Confirm({
			  heading: "Create a new Wish List",
			  id: "myCreateWishListPrompt",
			  content: CreateWishListPrompt_Content_Holder,
			  cancel: {path: "button.create_cancel", action: function() {

					if ($('#create_WishList_popup_trigger').exists()) {
						window.location = "WishList.aspx";
					}
					return true;
			  }},
			  ok: {path: "button.create_okay", action: function() {
					return SubmitServiceCreateWishListPrompt();
			  }}
		});
		var DeleteWishListPrompt_Content_Holder ='<div style="padding: 20px;"> \
				<span style="font-weight:bold; font-size:10px;">Are you sure you want to delete the wish list <i id="DeleteWishListPromptListTitle">' + $('#inputTitle').val() + '</i>? </span><br/>														\
				<br/>																																													\
				<button class="delete_okay"><img src="' + $.hosts.resources + '/presources/community/images/btn_submit.gif" /></button>															\
				<button class="delete_cancel"><img src="' + $.hosts.resources + '/presources/community/images/btn_cancel.gif" /></button>														\
			</div>																																														\
			';
		$.global.ReadyServiceDeleteWishListPrompt = new $.Confirm({
			  heading: "Delete a Wish List",
			  id: "myDeleteWishListPrompt",
			  content: DeleteWishListPrompt_Content_Holder,
			  cancel: {path: "button.delete_cancel", action: function() {

				  return true;
			  }},
			  ok: {path: "button.delete_okay", action: function() {
					return CallServiceDeleteWishList();
			  }}
		});

		var CancelWishListChangesPrompt_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 wish list <i>' + $('#inputTitle').val() + '</i>? </span><br/>														\
				<br/>																																													\
				<button class="cancel_okay"><img src="' + $.hosts.resources + '/presources/community/images/btn_submit.gif" /></button>															\
				<button class="cancel_cancel"><img src="' + $.hosts.resources + '/presources/community/images/btn_cancel.gif" /></button>														\
			</div>																																														\
			';
		$.global.ReadyServiceCancelWishListChangesPrompt = new $.Confirm({
			  heading: "Cancel My Edits",
			  id: "myCancelWishListChangesPrompt",
			  content: CancelWishListChangesPrompt_Content_Holder,
			  cancel: {path: "button.cancel_cancel", action: function() {

				  return true;
			  }},
			  ok: {path: "button.cancel_okay", action: function() {
					return CallServiceCancelWishListChanges();
			  }}
		});

		$('#printLink').click (function() {
				//alert('printg: ' + $.hosts.community + "/communityportal/wishlist.aspx?pageType=wishlistPring&listId=" + currentListId);
				window.open('http://' + $.hosts.community + "/communityportal/wishlist.aspx?pageType=wishlistPrint&pageSize=500&"+currentListItemParam+"=" + currentListId);
		});

	}



	// End of WishList invocation container ---------------------------------------------------------------
	Init_WishList ();

}); // End of main invocation container


function startAddItems () {

	$("div.errorMsg.AddItemFailed").remove();
	
	if ( Number($('#NumberOfItemsFlag').val()) >=500) {
		errorMessage = "Your Wish List has reached its limit of 500 titles. If you wish to add this item, delete an existing title to make room.  ";
		showManualError (errorMessage,"AddItemFailed", $('.wishListItems'));
		return;
	}

	$.global.wishList.searchWidget.addItems();


}

function Init_WishList () {
	// General Wish List listeners

	$('.listMain').unbind();
	$('.listMain').delegate("click", {
		  "#btn_create_wishlist": Activate_CreateWishListPrompt,
		  ".btn_create_wishlist": Activate_CreateWishListPrompt,  // There are two listners, the id for FF, IE (clicking or tabbing and hiting enter) and the class for safari and chrome. 
		  "a.removeIcon": removeWishListItem,
		  //"button.addItems": startAddItems,
		  //"button#btn_save_wishlist_attr": saveWishListAttributes,
		  //"button#cancel_wishlist_attr": cancelWishListAttributes,
		  "input#radio_set_wishlist_private": saveWishListAsPrivate,
		  "input#radio_set_wishlist_public": saveWishListAsPublic,
		  "a#sort_wish_list_by_title": sortWishListByTitle,
		  "a#sort_wish_list_by_date": sortWishListByDate,
		  "a#sort_wish_list_by_priority": sortWishListByPriority,
		  "#inputTitle": setTitleStyleToEditLook,
		  "#inputDescription": setDescStyleToEditLook
	});
	
	$("button.addItems").click(function(e) { startAddItems(e) });
	$("button#btn_save_wishlist_attr").click(function(e) { 
		e.preventDefault(e);
		saveWishListAttributes(e) 
	});
	$("button#cancel_wishlist_attr").click(function(e) { cancelWishListAttributes(e) });
	
	
	$('.nextWishListPageLink').unbind();
	$('.nextWishListPageLink').click (function(e) {goToNextWishListPage(e)});

	$('.prevWishListPageLink').unbind();
	$('.prevWishListPageLink').click (function(e) {goToPrevWishListPage(e)});

	$(".wishlist_priority_select").unbind();
	$(".wishlist_priority_select").change(function(e) {saveWishListItemPriority(e)});


	$('#DeleteWishListPromptListTitle').text($('#inputTitleHolder').text());

	currentListId = ''
	currentListItemParam = ''
	
	if ($.global.wishList.wishListTypeFlagValue == 'EWL') {
		currentListItemParam = "listType=EWL&CommId";
		currentListId = $('#creatorId').text();	
	}	
	else if ($('#ListId').val() != '0' ) {
		currentListId = $('#ListId').val();
		currentListItemParam = "ListID"
	} 
	else { // assume wishList Type == 'WL'
		currentListId = $('#creatorId').text();
		currentListItemParam = "CommId"
	}
	
	
}

function getWishListSizeParam () {
	return String('&' + 'pageSize=' + $('#pageSize').val());
}


function getWishListSortParam () {
	return String('&' + 'ce_SortOrderCode=' + $('#sortOrderCode').val() + '&' + 'listItemSortOrder=' + $('#sortOrderCode').val());
}

function getWishListNextPageAndSortParam () {
	return getWishListSizeParam () + String('&pageOffSet=' + (Number($('#pageOffset').val()) + 1))	+ getWishListSortParam();
}

function getWishListPrevPageAndSortParam () {
	return getWishListSizeParam () + String('&pageOffSet=' + (Number($('#pageOffset').val()) - 1))	+ getWishListSortParam();
}


function goToNextWishListPage (e) {
	
	e.preventDefault(e);
	page_parameter = "page=WishList&bnOutput=1";
	action_parameter = '&uiAction=GetClickWishList&ce_callPurpose=NextPage';
	action_parameter += getWishListNextPageAndSortParam ();
	
	//'&pageSize=' + $('#pageSize').val();
	//action_parameter += '&pageOffSet=' + (Number($('#pageOffset').val()) + 1);

	list_id_parameter = "";

	if(currentListId != 0) {
	 	list_id_parameter += "&"+currentListItemParam+"=" + currentListId;
	}
	var myParameters = page_parameter + action_parameter + list_id_parameter ;

	myParameters += "";

	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		callback: {name: "cbf", value: "goToWishListPageCallBack" }
	});

	return false;
}


function goToPrevWishListPage (e) {
	
	e.preventDefault(e);
	page_parameter = "page=WishList&bnOutput=2";
	action_parameter = '&uiAction=GetClickWishList&ce_callPurpose=PrevPage';
	action_parameter += getWishListPrevPageAndSortParam ();

	list_id_parameter = "";

	if(currentListId != 0) {
	 	list_id_parameter +=  "&"+currentListItemParam+"=" + currentListId;
	}
	var myParameters = page_parameter + action_parameter + list_id_parameter ;

	myParameters += "";

	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		callback: {name: "cbf", value: "goToWishListPageCallBack" }
	});

	return false;
}






function setWishListSortClasses () {
	
	switch (Number($('#sortOrderCode').val())) {
		/// Most Recent first
		case WLSort.DateAddedDesc: 
			$('a.sort_wish_list_by_date').each(function() {
				$(this).removeClass('up-arrow').removeClass('underline').addClass('down-arrow');
			});
			$.global.wishList.currentWishList = WLSort.DateAddedDesc;

		break;		

		///  Oldest First
		case WLSort.DateAddedAsc:
			$('a.sort_wish_list_by_date').each(function() {
				$(this).removeClass('down-arrow').removeClass('underline').addClass('up-arrow');
			});
			$.global.wishList.currentWishList = WLSort.DateAddedAsc;
		break;		

		/// By Title, Z-A
		case WLSort.TitleDesc: 
			$('a.sort_wish_list_by_title').each(function() {
				$(this).removeClass('down-arrow').removeClass('underline').addClass('up-arrow');
			});		
	        $.global.wishList.currentWishList = WLSort.TitleDesc;			
		break;		
		
		/// By Title , A-Z
		case WLSort.TitleAsc: 
			$('a.sort_wish_list_by_title').each(function() {
				$(this).removeClass('up-arrow').removeClass('underline').addClass('down-arrow');
			});
	        $.global.wishList.currentWishList = WLSort.TitleAsc;
		break;		
		
		// Not used in Wishlists:
		/// By Author, Z-A
		case WLSort.ContributorDesc: 
		/// By Author, A-Z
		case WLSort.ContributorAsc:
		/// By Rating, Highest first
		case WLSort.RatingDesc:
		/// By Rating, Lowest First
		case WLSort.RatingAsc: 
		break;		
		
		// User Specified ordering - now used to hold the Priority of the item (low, medium, high).
		case WLSort.SortRankDesc: 
		case WLSort.PriorityDesc: 
			$.global.wishList.currentWishList = WLSort.PriorityDesc;
			$('a.sort_wish_list_by_priority').each(function() {
				$(this).removeClass('down-arrow').removeClass('underline').addClass('up-arrow');
			});
		break;

		/// User Specified ordering - now used to hold the Priority of the item (low, medium, high).
		case WLSort.SortRankAsc: 
		case WLSort.PriorityAsc: 

			$('a.sort_wish_list_by_priority').each(function() {
				$(this).removeClass('up-arrow').removeClass('underline').addClass('down-arrow');
			});

			$.global.wishList.currentWishList = WLSort.PriorityAsc;	
		break;
	}

}

function goToWishListPageCallBack (result) {

	if (isGeneralErrorFound(result, "Unable to go to next page : ")) {
		return;
	}

	$('.wishListItems').html(result.output)
	
	
	// Find and apply any instance the BuyNow listner for any instance of eBook product
	BN.EBook.Util.setBuyNow ($('.wishListItems .buyNowButtonFunc'))
	BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
	$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
	$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );

	Init_WishList ();
	resetWishListSortClasses ();
	setWishListSortClasses ();
	BN.EBook.Util.setBuyNow ($('.wishListItems .buyNowButtonFunc'))
	BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
	$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
	$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );
}

function sortWishListByTitle () {
	var myParameters = "uiAction=GetClickWishList&page=WishList&pageType=WishList";

    if(currentListId != 0) {
        myParameters +=  "&"+currentListItemParam+"=" + currentListId;
    }

	var callBackToUse = "";
	
	myParameters += getWishListSizeParam ();

	if ($.global.wishList.currentWishList !=  WLSort.TitleAsc) {

		myParameters += "&listItemSortOrder=" + WLSort.TitleAsc;
		myParameters += "&" + "ce_SortOrderCode=" + WLSort.TitleAsc;
		callBackToUse = "sortWishListByTitleAscCallBack";

	}
	else {
		myParameters += "&" + "ce_SortOrderCode=" +  WLSort.TitleDesc;
		myParameters += "&listItemSortOrder=" + WLSort.TitleDesc;
		callBackToUse = "sortWishListByTitleDescCallBack";
	}

	ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters,
			callback: {name: "cbf", value: callBackToUse }
	});

	return false;
}

function sortWishListByTitleAscCallBack (result) {
	if (isGeneralErrorFound(result, "Sorting the Wish List not succeed: ")) {
		return;
	}
	if(result.status == 'True') {
		//alert('Response: ' + result.output);
		$('div.wishListItems').html(result.output);
	
		// Find and apply any instance the BuyNow listner for any instance of eBook product
		BN.EBook.Util.setBuyNow ($('div.wishListItems .buyNowButtonFunc'))
		BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
		$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
		$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );
		
		Init_WishList ();
		resetWishListSortClasses ();
		$('a.sort_wish_list_by_title').each(function() {
            $(this).removeClass('up-arrow').addClass('down-arrow');
        });
		$.global.wishList.currentWishList = WLSort.TitleAsc;
	}
	return;
}

function sortWishListByTitleDescCallBack (result) {

	if (isGeneralErrorFound(result, "Sorting the Wish List not succeed: ")) {
		return;
	}

	if(result.status == 'True') {
		//alert('Response: ' + result.output);
		$('div.wishListItems').html(result.output);
		
				
		// Find and apply any instance the BuyNow listner for any instance of eBook product
		BN.EBook.Util.setBuyNow ($('.wishListItems .buyNowButtonFunc'));
		BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
		$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
		$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );
		
		Init_WishList ();
		resetWishListSortClasses ();
		$('a.sort_wish_list_by_title').each(function() {
            $(this).removeClass('down-arrow').addClass('up-arrow');
        });
        $.global.wishList.currentWishList = WLSort.TitleDesc;
	}
	return;
}

function sortWishListByDate (restartingSortToAddItem) {

	var myParameters = "uiAction=GetClickWishList&page=WishList&pageType=WishList";

    if(currentListId != 0) {
        myParameters +=  "&"+currentListItemParam+"=" + currentListId;
    }

	var callBackToUse = "";

	myParameters += getWishListSizeParam ();

	if ($.global.wishList.currentWishList !=  WLSort.DateAddedDesc || String(restartingSortToAddItem) == "ForNewItem") {
		myParameters += "&" + "ce_SortOrderCode=" + WLSort.DateAddedDesc;
		myParameters += "&listItemSortOrder=" + WLSort.DateAddedDesc;
		callBackToUse = "sortWishListByDateDescCallBack";
	}
	else {
		myParameters += "&" + "ce_SortOrderCode=" + WLSort.DateAddedAsc;
		myParameters += "&listItemSortOrder=" + WLSort.DateAddedAsc;
		callBackToUse = "sortWishListByDateAscCallBack";
	}

	ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters,
			callback: {name: "cbf", value: callBackToUse }
	});

	return false;
}

function sortWishListByDateAscCallBack (result) {

	if (isGeneralErrorFound(result, "Sorting the Wish List not succeed: ")) {
		return;
	}

	if(result.status == 'True') {
		//alert('Response: ' + result.output);
		$('div.wishListItems').html(result.output);
		// Find and apply any instance the BuyNow listner for any instance of eBook product
		BN.EBook.Util.setBuyNow ($('div.wishListItems .buyNowButtonFunc'))
		BN.EBook.Util.setFreeSample ($('div.wishListItems .freeSampleButtonFunc'));
		$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
		$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );
	
		Init_WishList ();
		resetWishListSortClasses ();
        $('a.sort_wish_list_by_date').each(function() {
            $(this).removeClass('down-arrow').removeClass('underline').addClass('up-arrow');
        });
		$.global.wishList.currentWishList = WLSort.DateAddedAsc;
	}
	return;
}

function sortWishListByDateDescCallBack (result) {

	if (isGeneralErrorFound(result, "Sorting the Wish List not succeed: ")) {
		return;
	}


	if(result.status == 'True') {
		//alert('Response: ' + result.output);
		$('div.wishListItems').html(result.output);
						
		// Find and apply any instance the BuyNow listner for any instance of eBook product
		BN.EBook.Util.setBuyNow ($('.wishListItems .buyNowButtonFunc'));
		BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
		$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
		$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );
		
		Init_WishList ();
		resetWishListSortClasses ();
        $('a.sort_wish_list_by_date').each(function() {
            $(this).removeClass('up-arrow').addClass('down-arrow');
        });
		$.global.wishList.currentWishList = WLSort.DateAddedDesc;
	}
	return;
}

function sortWishListByPriority	() {
	var myParameters = "uiAction=GetClickWishList&page=WishList&pageType=WishList";

    if(currentListId != 0) {
        myParameters +=  "&"+currentListItemParam+"=" + currentListId;
    }

	var callBackToUse = "";

	myParameters += getWishListSizeParam ();

	if ($.global.wishList.currentWishList !=  WLSort.PriorityAsc) {
		myParameters += "&" + "ce_SortOrderCode=" +  WLSort.PriorityAsc;
		myParameters += "&listItemSortOrder=" + WLSort.PriorityAsc;
		callBackToUse = "sortWishListByPriorityAscCallBack";

	}
	else {
		myParameters += "&" + "ce_SortOrderCode=" + WLSort.PriorityDesc;
		myParameters += "&listItemSortOrder=" + WLSort.PriorityDesc;
		callBackToUse = "sortWishListByPriorityDescCallBack";
	}

	ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters,
			callback: {name: "cbf", value: callBackToUse }
	});

	return false;
}

function sortWishListByPriorityAscCallBack (result) {

	if (isGeneralErrorFound(result, "Sorting the Wish List not succeed: ")) {
		return;
	}

	if(result.status == 'True') {
		//alert('Response: ' + result.output);
		$('div.wishListItems').html(result.output);
				
		// Find and apply any instance the BuyNow listner for any instance of eBook product
		BN.EBook.Util.setBuyNow ($('.wishListItems .buyNowButtonFunc'));
		BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
		$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
		$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );

		Init_WishList ();
		resetWishListSortClasses ();
		$.global.wishList.currentWishList = WLSort.PriorityAsc;
        $('a.sort_wish_list_by_priority').each(function() {
            $(this).removeClass('underline').addClass('down-arrow');
        });
	}
	return;
}

function sortWishListByPriorityDescCallBack (result) {

	if (isGeneralErrorFound(result, "Sorting the Wish List not succeed: ")) {
		return;
	}

	if(result.status == 'True') {
		//alert('Response: ' + result.output);
		$('div.wishListItems').html(result.output);

		// Find and apply any instance the BuyNow listner for any instance of eBook product
		BN.EBook.Util.setBuyNow ($('.wishListItems .buyNowButtonFunc'));
		BN.EBook.Util.setFreeSample ($('.wishListItems .freeSampleButtonFunc'));
		$('.wishListItems .about-buying-ebooks-comm').click($.global.aboutBuyingEbooksPopup );
		$('.wishListItems .learn-more-sample-ebooks-comm').click($.global.learnMoreSampleEbooks );

		Init_WishList ();
		resetWishListSortClasses ();
		$.global.wishList.currentWishList = WLSort.PriorityDesc;
        $('a.sort_wish_list_by_priority').each(function() {
            $(this).removeClass('underline').addClass('up-arrow');
        });
	}
	return;
}
function resetWishListSortClasses () {
	$('.wishListSort a').removeClass('up-arrow').removeClass('down-arrow').addClass('underline');
}





function saveWishListItemPriority (e) {

	var listItem = $(e.target).parents("div.wishListItem");

	var page_parameter = "";
	var action_parameter = "";
	var list_id_parameter = "";


	page_parameter = "page=WishList";
	action_parameter = '&uiAction=UpdateListItemPriority';
	list_id_parameter = "";

	if(currentListId != 0) {
	 	list_id_parameter +=  "&"+currentListItemParam+"=" + currentListId;
	}
	var myParameters = page_parameter + action_parameter + list_id_parameter ;


	myParameters += '&ListItemId=' + String(listItem.attr('id')).split('_')[1];
	myParameters += '&Rank=' + $(e.target).val();

	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		callback: {name: "cbf", value: "UpdateListItemPriorityCallBack" }
	});



	return;
}

function UpdateListItemPriorityCallBack () {
	return;
}

function Activate_CreateWishListPrompt () {
	if ($('#NumberOfWishListsFlag').exists()) {
		if (Number($('#NumberOfWishListsFlag').val()) < 25 ) {
			
			
			if ($('.wishListMaxExceed').exists()) {
				$('.wishListMaxExceed').remove();
			}
			
			$('.CreateWishListPromptTitle').html('');
			$.global.ReadyServiceCreateWishListPrompt.prompt();
			$('#myCreateWishListPrompt .errorMsg').remove();
			var newListName = "";
			var newListNumber= Number($('#NumberOfWishListsFlag').val()) + 1;
			
			//if wishlist already contains 'New Wish List #' title then check the number following 'New Wish List ' string
			//and if it's greater then current newListNumber value (defined above) then set newListNumber to this new value
			$('#DropDown_subList_source li a:contains(' + newListName + ')').each(function(i)
			{
				
				if(String($(this).text().indexOf('New Wish List ')) != -1)
				{
					if (Number(String($(this).text()).substring(14, $(this).text().length)) >= Number(newListNumber))
					{
						newListNumber = Number(String($(this).text()).substring(14, $(this).text().length)) + 1;
					}
				}
			}
			)
			
			newListName = 'New Wish List ' + newListNumber;
			
			
	
			$('.new_WishList_inputTitle').val(newListName);
			$('.new_WishList_Description').val("");
			if (!$('.new_WishList_Description').data('maxed')) $('.new_WishList_Description').maxLength(250).data('maxed', true);
			//alert ('text:' + $('.new_list_inputTitle').val());
			$('.CreateListPromptTitle').html( $('.CreateListPrompt_LabelHolder').html() );
		}
		else {

			showManualError ("You can create only 25 Wish Lists. If you'd like to create a new Wish List, delete an existing one to make room.", 'wishListMaxExceed', $('.pageErrorsDisplay'));

		}
	}

	return false;
}

function SubmitServiceCreateWishListPrompt() {

	var new_title = String($('.new_WishList_inputTitle').get(0).value);
	var new_description = String($('.new_WishList_Description').val());
	var no_error_found = true;
	
	//alert('new_title: ' + new_title);
	if (new_title.length > 0) {
		//check if title already exists
		$('#DropDown_subList_source li a.iconWishList').each(function(i)
		{
			if (new_title == $(this).text())
			{
				$('.CreateWishListPromptTitle').html( $('.CreateWishListPrompt_ErrorHolderTitle').html() );
				no_error_found = false;
			}
		}
		)
		if(no_error_found != false)
		{
			CallServiceCreateNewWishList (new_title, new_description);
		}
	}
	else {
		//alert ('Title missing');
		$('.CreateWishListPromptTitle').html( $('.CreateWishListPrompt_ErrorHolder').html() );
		no_error_found = false;
	}
	return false; // Prompt now does not close until callback returns.
}

function CallServiceCreateNewWishList (title, description) {

	// removed for DMS_P00056947: creating a wishlist should now be a page-load, not asynchrous
	// var myParameters = "uiAction=CreateWishList&page=WishList&pageType=wishlistCreate";
	
	var myParameters = "uiAction=CreateWishListForLinkOnly&ce_purpose=CreateWishListOnPage&page=WishList&pageType=wishlistCreate";

	if (String(title).length > 0){
		myParameters += "&title=" + encodeURIComponent(title);
	}

	if (String(description).length > 0){
		myParameters += "&desc=" + encodeURIComponent(description);
	}


	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		errorMsgHolder: $('#myCreateWishListPrompt .overlayContent'),
		callback: {name: "cbf", value: "CreateWishListCallBack" }
	});

	return false;
}


function CreateWishListCallBack (result, errorMsgHolder) {

	if (result.status == "False" && $(errorMsgHolder).exists()) {
		 isLocalizedErrorFound (result, "", "error_66", errorMsgHolder);
		 return;
	}
	else if (isGeneralErrorFound(result, "Creating a new Wishlist did not succeed: ")) {
		return;
	}

	$.global.ReadyServiceCreateWishListPrompt.close();

	// creating a wishlist should now be a page-load, not asynchrous
	window.location = (result.output);

	
	return;
}

function Activate_DeleteWishListPrompt () {

	$.global.ReadyServiceDeleteWishListPrompt.prompt();

	return false;
}

function CallServiceDeleteWishList() {


	var myParameters = "uiAction=DeleteWishList&bnOutput=1&page=WishList";
    if(currentListId != 0) {
	 	myParameters +=  "&"+currentListItemParam+"=" + currentListId;
	}

	myParameters += '&ListIDtoBeSelected=0'; //ie: the next list to be displayed will always be the Default wish list (id = 0).  Currently does not work

	//alert ("currentListId:" + currentListId + ", next list: " + $('#listNavLink_'+ currentListId + ' ~ li').attr('id') + ", " + myParameters);

	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		callback: {name: "cbf", value: "DeleteWishListCallBack" }
	});

	return true;
}

function DeleteWishListCallBack  (result){
	//alert ("WishList Deleted");

	if (isGeneralErrorFound(result, "Deleting this Wish List did not succeed: ")) {
		return;
	}
	
	// removed for DMS_P00056947: creating a wishlist should now be a page-load, not asynchrous
	/*$('#WishListMainContainer').html(result.output);
	UpdateWishListSummary  ();
	Init_WishList ();
	*/
	window.location = ('http://' + $.hosts.community + '/communityportal/WishList.aspx');
}

function removeWishListClasses() {
	//alert('removing classes');
	$("#wishlist-items .first").removeClass("first");
	$("#wishlist-items .last").removeClass("last");
}

function removeWishListItem (e) {
		removeWishListClasses();
		var listItem = $(e.target).parents("div.wishListItem");
		//alert ('item to remove: ' + listItem.attr('id'));

		var page_parameter = "";
		var action_parameter = "";
		var list_id_parameter = "";


		page_parameter = "page=WishList";
		action_parameter = '&uiAction=RemoveWishListItem';
	    if(currentListId != 0) {
			list_id_parameter =  "&"+currentListItemParam+"=" + currentListId ;
		}


		var myParameters = page_parameter + action_parameter + list_id_parameter ;


		myParameters += '&ListItemId=' + String(listItem.attr('id')).split('_')[1];

		ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters,
			callback: {name: "cbf", value: "WishListRemoveItemCallBack" }
		});


		listItem.remove();

		$("div.wishListItem:first").removeClass("first").addClass("first");
		$("div.wishListItem:last").addClass("last");

		
		return false;

}


function WishListRemoveItemCallBack (result) {

	if (isGeneralErrorFound(result, "Removing this Wish List item did not succeed: ", "WishListRemoveItemFailed")) {
		return;
	}

	$('#NumberOfItemsFlag').val( Number($('#NumberOfItemsFlag').val()) - 1)
	$('.totalItemIndexDisplay').text($('#NumberOfItemsFlag').val());
	
	if(Number($('#lastItemIndex').val()) < Number($('#NumberOfItemsFlag').val())) { 
		// Then the the first item of the next page has to be obtained:
		getItemFromNextPage ();	
	}
	else {

		$('#lastItemIndex').val( Number($('#lastItemIndex').val()) - 1);
		$('.lastItemIndexDisplay').text($('#lastItemIndex').val());
				
		if (!$("div.wishListItem").exists()) {
			$(".firstItemIndexDisplay").text('0');
		}
	}

}


function getItemFromNextPage () {

	page_parameter = "page=WishList&bnOutput=1";
	action_parameter = '&uiAction=GetClickWishList&ce_callPurpose=getItemFromNextPage';
	action_parameter += "&pageSize=1&pageOffSet=" + Number(Number($('#lastItemIndex').val()) - 1) + getWishListSortParam ();
	
	//'&pageSize=' + $('#pageSize').val();
	//action_parameter += '&pageOffSet=' + (Number($('#pageOffset').val()) + 1);

	list_id_parameter = "";

	if(currentListId != 0) {
		list_id_parameter +=  "&"+currentListItemParam+"=" + currentListId;
	}
	var myParameters = page_parameter + action_parameter + list_id_parameter ;

	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		callback: {name: "cbf", value: "getItemFromNextPageCallBack" }
	});
}

function getItemFromNextPageCallBack (response) {

	if (response.status == 'True') {
		$('#wishlist-items').append (response.output);
		Init_WishList ();
	}
	
}


function UpdateWishListSummary  (){

	var myParameters = "uiAction=GetWishListSummary&page=WishList";


	ui.request({ baseURL: $.hosts.commServices + '?',
		parameters: myParameters,
		callback: {name: "cbf", value: "getWishListSummaryCallBack" }
	});


	return;
}

function getWishListSummaryCallBack (result) {

	if (isGeneralErrorFound(result, "Retrieving updated Wish List navigation the did not succeed: ")) {
		return;
	}

	if (result.status) {

		$('#DropDown_subList_source').replaceWith(result.output);
	}

}

function saveWishListAsPrivate() {

	saveWishListPrivacy('Private');
}
function saveWishListAsPublic() {

	saveWishListPrivacy('Public');
}

function saveWishListPrivacy (newLevel) {
		var myParameters = "uiAction=UpdateWishListAttributes&page=WishList&pageType=WishList"

		var list_id_parameter = "";

		if ($.global.wishList.wishListTypeFlagValue == 'WLC' || $.global.wishList.wishListTypeFlagValue == 'EWL') {
			list_id_parameter = "&" + currentListItemParam + currentListId;
		} 
		

		myParameters += "&PrivacyLevel=" + newLevel;

		ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters + list_id_parameter,
			callback: {name: "cbf", value: "saveWishListPrivacyCallBack" }
		});
		return false;
}

function saveWishListPrivacyCallBack(response) {

	if (isGeneralErrorFound(response, "Saving the new Wish List privacy did not succeed: ")) {
		return;
	}

	if($("#radio_set_wishlist_public:checked").exists()) {
		$("#context span#profilePrivacyLevel").text("Public");
		restoreCommunityNavLink();
		
	}
	else if ($("#radio_set_wishlist_private:checked").exists()) {
		$("#context span#profilePrivacyLevel").text("Private");
		disableCommunityNavLink();
	}
	
	


	return;
}

function setDescStyleToEditLook () {
	$("#inputDescription").removeClass("unFocused");
}

function setTitleStyleToEditLook () {
	$("#inputTitle").removeClass("unFocused");
}



function saveWishListAttributes () {
	// save the current values if the user hits cancel later

	if ($('#wishlistErrorsDisplay #errorMsg_68').exists()) {

		$('#wishlistErrorsDisplay #errorMsg_68').remove();
	}

	if($('#inputTitle').val() == "") {

		$('#wishlistErrorsDisplay').append('<div id="errorMsg_68" class="errorMsg" style="display:block">Please enter a title.</div>');

		return false;
	}


	$('#inputTitleHolder').html($('#inputTitle').val());
	$('#inputDescriptionHolder').html($('#inputDescription').val());

	var myParameters = "uiAction=UpdateWishListAttributes&page=WishList&pageType=WishList";

	if(currentListId != 0) {
	 	myParameters +=  "&"+currentListItemParam+"=" + currentListId;
	}
	var myCallBack =  "saveWishListAttributesCallBack";

	if ($.global.wishList.wishListTypeFlagValue == 'WLC') {
		myParameters += "&Title=" + encodeURIComponent($('#inputTitle').val());
		 myCallBack = "saveWishListAttributesWithTitleCallBack";
	}

	//alert ("$.global.wishList.wishListTypeFlagValue: " + $.global.wishList.wishListTypeFlagValue);

	myParameters += "&desc=" + encodeURIComponent($('#inputDescription').attr('value'));
	if ($('#radio_set_wishlist_public:checked').exists()) {
		myParameters += "&PrivacyLevel=Public";
	}
	else {
		myParameters += "&PrivacyLevel=Private";
	}


	ui.request({ baseURL: $.hosts.commServices + '?',
			parameters: myParameters,
			errorMsgHolder: $("#WishListMainContainer"),
			callback: {name: "cbf", value:  myCallBack }
	});
	return false;

}

function cancelWishListAttributes () {
	// save the current values if the user hits cancel later
	$('#inputTitle').val($('#inputTitleHolder').html());
	$('#inputDescription').val($('#inputDescriptionHolder').html());
	$("#inputTitle").addClass("unFocused");
	$("#inputDescription").addClass("unFocused");
	return false;
}

function saveWishListAttributesWithTitleCallBack(result) {

	if (isGeneralErrorFound(result, "", "WishListAttributesFailed")) {
		return;
	}

	$('#myWishListHeader').html($('#inputTitle').val());
	$("#inputTitle").addClass("unFocused");
	$("#inputDescription").addClass("unFocused");
	
	UpdateWishListSummary  ();

}

function saveWishListAttributesCallBack (response) {
	//alert ('Title+Description saved.');

	// isGeneralErrorFound not used in place of the following error handling:


	if(response.status == "False" && String(response.output).length > 0) {
		$("form.listNameDescription div.errorMsg").remove();
		$("form.listNameDescription").prepend("<div class='errorMsg' style='display:block'>" + response.output + "</div>");
	} else {
		$("form.listNameDescription div.errorMsg").remove();
		$("#inputDescription").addClass("unFocused");
	}
}

$(function() {

	if ($('#create_wishlist_popup_trigger').exists()) {
		Activate_CreateWishListPrompt();
	}
	
	// Coremetrics: Page views for wishlists.
	if(typeof cmCreatePageviewTag !== "undefined"){
		try{
			var cmPenName = "";
			var cmPenNameDisplay = "";
			var wishlistTitle = "";
			var cmListID = $('#ListId').val();
			if($("#context #profilePenName").text()){
				cmPenName = $("#context span#profilePenName").text();
				cmPenNameDisplay = ": "+cmPenName;
			}
			if($.global.wishList.wishListTypeFlagValue == "WL"){
				cmCreatePageviewTag ("COMM-DEFAULTWISHLIST"+cmPenNameDisplay+" ("+cmListID+")", "COMMUNITY WISHLIST");
			}else if($.global.wishList.wishListTypeFlagValue == "WLC"){
				if($("#myWishListHeader").text()){ wishlistTitle = $("#myWishListHeader").text();}
				cmCreatePageviewTag ("COMM-CUSTOMWISHLIST"+cmPenNameDisplay+" "+wishlistTitle+" ("+cmListID+")", "COMMUNITY WISHLIST");
			}else if($.global.wishList.wishListTypeFlagValue == "EWL"){
				cmCreatePageviewTag ("COMM-EWISHLIST"+cmPenNameDisplay+" ("+cmListID+")", "COMMUNITY WISHLIST");
			}
		}
		catch(e){}
	}
});