
var communityHost = "http://my.barnesandnoble.com/communityportal/";

$(document).ready(function() {
    initNavBarLinks();
	
if ($("#ListOrFavProductFlag").val() != "EssentiaList") { //make sure this isn't an essentiaList page
	if ($("#communityNav").exists()) {
		var pageLoadPrivacySetting = $('#thisPagePrivacyLevel').text().toLowerCase();
		//alert(pageLoadPrivacySetting)
		if (pageLoadPrivacySetting == 'private') {
			disableCommunityNavLink();
		}
	}
}
	
	if ($('#selectPenName').exists()) {
		$('input.profileNavRadio').click(showPrivacyError);		
		return;
	}
	else {
		privacySettingChanged();
		$('input.profileNavRadio').click(privacySettingChanged);
		
	}
});

function initNavBarLinks() {
    $("#favoritesLink").click(function() {
        addFavorite();
    });
	$("#removeFavoritesLink").click(function() {
        removeFavorite();
    });	

    $("#printLink").click(function() {
        doPrintPage();
    });

    $("#whatsThisLink").click(function() {
        showWhatsThis();
    });
    
    $("#whatsThisLinkWishLink").click(function() {
        showWhatsThis('wishlist');
    });
}

function showWhatsThis(id) {
	
	var heading = "Privacy Settings"
	
	if (id=='BookClubLaurels'){
		heading = "B&N Book Club Laurels";
	}
	
	var o = new $.Overlay({
        useHeading: 1,
        heading: heading,
        block: 0
    });
	
    if (id=="wishlist") {
        o.set.content($("#whatsThisContentWishList").html());
    }
	else if (id=='BookClubLaurels') {
	   o.set.content($("#whatsThisContentLaurels").html());
	}
    else {
    	o.set.content($("#whatsThisContent").html());
	}
	o.set.id("overlay_whatsThis");
	o.set.width(450);
	
	o.element.find("a.overlayClose").click(function(e) { e.preventDefault(e); o.close(); });
    
	o.open();

}

function showEmailSharePrivacyError(type) {
	var content = $("#shareEmailDialogContent");
	
	if (type == "Email") {
		content.find(".shareOrEmail").text("e-mail");
		content.find(".sharedOrEmailed").text("e-mailed");
	} else {
		content.find(".shareOrEmail").text("share");
		content.find(".sharedOrEmailed").text("shared");
	}

	var html = content.html();

    var o = new $.Overlay({
        useHeading: 1,
        heading: "Privacy Settings",
        block: 0
    });
    o.set.content(html);
    o.set.id("overlay_shareEmailPrivacyError");
    o.set.width(300);

    o.element.find("a.overlayClose").click(function() { o.close(); });
    o.open();



	
}


function addFavorite() {
    var id = $("#creatorId").text();
    var profileName = $("#creatorName").text();
    var params = "page=FavoriteBookmarks&uiAction=AddBookmark&type=0&favoriteId=" + id + "&title=" + profileName;

    ui.request({
        baseURL: communityHost + "ServiceRequest.aspx?",
        parameters: params,
        callback: {name: "cbf", value: "addToFavoritesCallback"}
    });
}

function removeFavorite() {

    var params = "page=FavoriteBookmarks&uiAction=RemoveBookmark&type=0&favoriteId=" + $.global.followingProfileId;

    ui.request({
        baseURL: communityHost + "ServiceRequest.aspx?",
        parameters: params,
        callback: {name: "cbf", value: "removeFavoriteCallback"}
    });
}


function doPrintPage() {

	// if this is not a wishlist page, then print.  Printing on a wishlist page occurs in wishlist.js
   	if ($('#pageTypeFlag') &&  String($('#pageTypeFlag').val()).indexOf('wishlist') == -1 ) {
		window.print();
	}
}

function showPrivacyError(){
	
	$($("input[name='Privacy']")).attr("disabled", "disabled");
	

	
	if ( $("input[name='Privacy']:checked").val() == 'public' ) {
		$("input[name='Privacy']:checked").removeAttr('checked')
		$("input[name='Privacy']").val(['private']);
	}

	
	var errorMessage = "We're sorry, you must have a Pen Name to set your Profile to \"Public\".  Click the \"Create a Pen Name\" button to create your own Pen Name. Then you can set your Profile to \"Public\".";	
	
	showPopUpError(errorMessage, "penNameReq")
	
	//showManualError(errorMessage, "penNameRequired", $('.pageErrorsDisplay'));
}


function privacySettingChanged () {

		//newPrivacySetting = $('[name=Privacy]:checked').val();
		// variable privacySetting is global defined in HTML
		var newPrivacySetting = (typeof privacySetting != 'undefined') ? privacySetting : $('[name=Privacy]:checked').val();
		if (newPrivacySetting != '' && typeof newPrivacySetting != 'undefined') {
			var myParameters = '?uiAction=UpdatePrivacySetting&status=' + newPrivacySetting + '&page=userprofile'

			ui.request({
				baseURL: communityHost + "ServiceRequest.aspx",
				parameters: myParameters,
				callback: {
					name: "cbf",
					value: "privacySettingCallBack"
				}
			});
		}
	
}




/* callbacks */




function addToFavoritesCallback(response) {

	if (isGeneralErrorFound(response, "")) {
		return;
	}
	$.global.checkIfFollowing();// Call this again to get the communityID of the person you are now following (it is not available in the first service call 
    $("#favoritesLink").hide();
	$("#removeFavoritesLink").show();
}

function removeFavoriteCallback (response) {
	if (response.status == "True") {
		$("#removeFavoritesLink").hide();
		$("#favoritesLink").show();
	}
}

function disableCommunityNavLink() {
	if ($('#isWishlistHidden').text() == 'false') { 
		$("#email").hide();
		$("#emailDisabled").show();
		$("#share").hide();
		$("#shareDisabled").show();
	}
}

function restoreCommunityNavLink() {
	if ($('#isWishlistHidden').text() == 'false') { 
		$("#emailDisabled").hide();
		$("#email").show();
		$("#shareDisabled").hide();
		$("#share").show();
	}
}

function privacySettingCallBack(response){

	if (response.status == "True") {
	
		//uncomment when XML is returned from service properly, to update communityNav by ajax when pvc settnig changed
		//$("#communityNavContainer").html('');	
		$("#communityNavContainer").append(response.output);
		
		newPrivacySetting = $('[name=Privacy]:checked').val();
		var newVal;
		if (newPrivacySetting == "public") {
			newVal = "Public";
			context.profilePrivacyLevel = 'Public';

		}
		else {
			newVal = "Private";
			context.profilePrivacyLevel = 'Private';
	
			if (! $.global.areAllRealLinkBounded) { // ie: don't repeat the following if it has already been done

				$.global.privacyPopUpQuestion = new $.PrivacyPopUpQuestion();	
				$.global.penNamePopUpQuestion = new $.PenNamePopUpQuestion();
			
				if ($.global.penNamePopUpQuestion.shouldAskQuestion()){ 
					//alert ('Bounding PanName Links Dynamically');					
					$.preventDepatureOnAllRealLinks ($.global.penNamePopUpQuestion);
					
				}	
				else if ($.global.privacyPopUpQuestion.shouldAskQuestion()) { 
					//alert ('Bounding Privacy Links Dynamically');										
					$.preventDepatureOnAllRealLinks ($.global.privacyPopUpQuestion);
				
				}	
			}

			
		}
		
		$("#context span#privacyLevel").text(newVal);
		
		
		if (newVal == 'Private') {
			$("#sharePageLink").addClass("disableCommunityNavLink")
			$("#emailAFriend").addClass("disableCommunityNavLink")
		} else if (newVal == 'Public') {
			$("#sharePageLink").removeClass("disableCommunityNavLink")
			$("#emailAFriend").removeClass("disableCommunityNavLink")
		}
		
	}
}

/* helpers */

function isCreator() {
    var c = $("#isCreator");
    if(c.text() == "private")
        return true;
    return false;
}
