/*
*	This file contains the javascript functionality for adding notes to member applications
*	on the ListingApplicants page.
*/

(function($) {

	var ajaxMgr = $.manageAjax.create('memberPhotosAjaxMgr', { queue: true, cacheResponse: true, maxRequests: 1 });

	$.memberPhotos = function(o) {
		o = $.extend({
			memberId: null,
			applicationId: null,
			container: null,
			nextButton: null,
			previousButton: null,
			headshot: null,

			isMinor: null,
			imageServer: null
		}, o || {});

		var photos, restrictedEnabled;

		// Hide the carousel until we've loaded the images via ajax.
		$(o.container).append("<ul style=\"visibility: hidden\"></ul>");
		// display the loading animated gif
		$(o.container).append('<img id=\"memberPhotosLoadingImage\" src=\"/images/loading.gif\" width=\"32\" height=\"32\" />');
		$(o.container).addClass('memberPhotosLoading');

		ajaxMgr.add({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			url: "/Services/MembershipService.asmx/GetMemberPhotos",
			data: '{"memberId":"' + o.memberId + '"}',
			dataType: "json",
			async: true,
			success: function(data, status) {
				$('#memberPhotosLoadingImage').src = "/images/loading.gif";
				// first things first, we preload the images and once the preloader has finished it will call the 
				// loadPhotos function.
				photos = data.d;
				var images = [];
				for (var i = 0; i < photos.length; i++)
				{
					images[i] = photos[i].ThumbUrl;
				}
				$.preLoadImages(images, loadPhotos(photos));
			},
			error: function(e) {
				var i = 0;
				// add error message to container control
			}
		});


		function loadPhotos(photos) {

			// check the users session variable (or setting for logged in users) to see if they have selected to view restricted images.
			restrictedEnabled = restrictedCheck();

			$(o.container + " ul li").remove();
			if ($(o.container + " ul").jCarouselLite !== undefined) {
				$(o.container + " ul").removejCarouselLite();
			}
			var containsRestricted = false;
			for (var i = 0; i < photos.length; i++) {
				var a = null;
				if (photos[i].IsRestricted && !restrictedEnabled) {
					containsRestricted = true;
					a = $('<a href=\"' + photos[i].ImageUrl + '\" rel=\"lightbox\"><img src=\"/images/restricted_100.jpg\" width=\"100\" height=\"100\" /></a>');
				} else {
					a = $('<a href=\"' + photos[i].ImageUrl + '\" rel=\"lightbox\"><img src=\"' + photos[i].ThumbUrl + '\" width=\"' + photos[i].ThumbWidth + '\" height=\"' + photos[i].ThumbHeight + '\"/></a>');
				}
				var div = $('<div></div>').append(a);
				var li = $('<li></li>').append(div);
				$(o.container + " ul").append(li);
			}

			// set up event to handle the enable restricted call back from slimbox. All carousels subscribe to this event, so the first time
			// the user agrees to see restricted images, all carousels that contain restricted images are reloaded.
			$(o.container + " ul").bind('reload', { 'p': photos, 'requiresReload': containsRestricted }, function(e) {
				if (e.data.requiresReload) {
					enableRestricted(e.data.p);
				}
			});

			// remove the animated gif and display the now preloaded carousel
			$('#memberPhotosLoadingImage').remove();
			$(o.container).removeClass('memberPhotosLoading');
			$(o.container + " ul").css("visibility", "visible");

			$(o.container).jCarouselLite({
				btnNext: o.nextButton,
				btnPrev: o.previousButton
			});

			// hook up the slimbox display
			$(o.container + " ul li div a").unbind('click').click(function(e) {
				e.preventDefault();
				var url = $(this).attr("href");
				launchSlimbox(url, slimboxOptions, 0, photos);

				return false;
			});

			// attach a click event to the headshot image (if passed in) to launch slimbox
			if (o.headshot !== null && o.headshot !== undefined) {
				var el = $("#" + o.headshot);
				el.click(function(e) {
					e.preventDefault();
					var url = $(this).attr("src");
					launchSlimbox(url, slimboxOptions, 0, photos);

					return false;
				});
			}

			var slimboxOptions = {
				canViewRestricted: restrictedEnabled,
				enableRestrictedCallback: function() { $.event.trigger('reload'); },
				isMinor: o.isMinor,
				restrictedPlaceHolder: o.imageServer + '/images/restricted_500.jpg',
				loop: true,
				m_id: o.memberId,
				application_id: o.applicationId
			};

			var launchSlimbox = function(url, options, startIndex, photos) {
				var regEx = new RegExp("/[0-9]+_([0-9]+).jpg");
				var match = regEx.exec(url.match(regEx));
				var i;
				if (match !== null) {
					for (i = 0; i < photos.length; i++) {
						if (photos[i].ImageUrl.indexOf(match[1]) > -1) {
							startIndex = i;
							break;
						}
					}
				}
				jQuery.slimbox(photos, startIndex, options);
			};
		}

		// This function makes a syncronous ajax call to a webservice to check if the current user 
		// can view restricted content
		var restrictedCheck = function() {
			var result = false;
			// ajax call to set session variable
			$.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: "/services/MembershipService.asmx/CanViewRestrictedContent",
				data: "{}",
				dataType: "json",
				async: false,
				success: function(data, status) {
					result = data.d;
				},
				error: function(e) {
					var i = 0;
				}
			});

			return result;
		};

		var enableRestricted = function(photos) {

			// ajax call to set session variable
			$.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: "/services/MembershipService.asmx/EnableRestrictedContent",
				data: "{}",
				dataType: "json",
				success: function(data, status) {
					// reload thumbnail carousels displaying all images instead of restricted placeholders.
					loadPhotos(photos);
				}
			});
		};
	};
})(jQuery);
