///
///Enums
///

//
var PhotoGalleryMode =
{
	Gallery: 0,
	Slideshow: 1
};

//Bit flags
var SlideshowNavigationBarLayout =
{
	None: 0,
	Bottom: 1,
	Top: 2,
	TopBottom: 3
};

///
/// Photo gallery structures for storing settings and content data
///
function SlideshowImageLinkSettings()
{
	this.fileId = 0;
	this.navigateUrl = "";
	this.target = "_blank";
	this.description = "";
}

function SlideshowSettings()
{
	this.transitionType = "fade";
	this.transitionTime = 2;
	this.syncTransitions = true;
	this.navigationBarPosition = SlideshowNavigationBarLayout.Bottom;
	this.showImageDescription = true;
	this.showPager = false;
}

function GallerySettings()
{
	this.showImageNumbering = true;
	this.showImageDescription = true;
}

function PhotoGallerySettings()
{
	this.mode = PhotoGalleryMode.Gallery;
	this.useCustomMeasurements = false;
	this.customMeasurementWidth = 0;
	this.customMeasurementHeight = 0;
	this.thumbnailType = 0;
	this.gallerySettings = new GallerySettings();
	this.slideshowSettings = new SlideshowSettings();
}

function PhotoGalleryContentSettings()
{
	this.folderId = 0;
	this.imageLinks = [];
}

///
/// UTILITY FUNCTIONS
///

// Utility function for mapping properties from an object to another
function MapProperties(from, to)
{
	for (var i in from)
	{
		//Perform mapping only if the property in the From object also exists in the To object
		if (i in to && from[i] != null)
		{
			//Perform a recursive mapping if the property is a complex type
//			if (typeof from[i] == "object")
//				to[i] = MapProperties(from[i], to[i]);
//			else
				to[i] = from[i];
		}
	}

	return to;
}

//
function CreateSettings(content)
{
	var originalSettings;
	try
	{
		originalSettings = JSON.parse(content);
	}
	catch (e)
	{
		//couldn't deserialize content, return a default set
		return new PhotoGallerySettings();
	}
	var settings = new PhotoGallerySettings();

	settings = MapProperties(originalSettings, settings);

	return settings;
}

//
function CreateContentSettings(content)
{
	var originalContentData;
	try
	{
		originalContentData = JSON.parse(content);
	}
	catch (e)
	{
		//couldn't deserialize content, return a default set
		return new PhotoGalleryContentSettings();
	}
	var contentData = new PhotoGalleryContentSettings();

	contentData = MapProperties(originalContentData, contentData);

	return contentData;
}

//
function InitializePhotoGallery(contentType, controlID, containerID)
{
	var control = eval("_" + controlID);
	control.OnInitialized = PhotoGalleryControlInit;
	control.GeneratePhotoGalleryControl = GeneratePhotoGalleryControl;

	embeddedControl_PresentationControls[controlID] = $get(containerID);

	if (!TemplateFunctions.IsViewMode(contentType))
	{
		control.GetEditorControlID = function () { return "GalleryEditor"; }
		control.ContentUpdated = OnPhotoGalleryDataUpdated;
		control.ExtendedPropertiesUpdated = OnPhotoGalleryDataUpdated;
		control.OnContextMenu = PhotoGalleryControlContextMenu;
		control.PreProcessEditorContent = PreProcessPhotoGalleryContent;
		control.GetCustomContent = function () { return [control.GetContent(), control.GetCustomProperties()];}
	}
}

//
function PhotoGalleryControlInit()
{
	var self = this;
	Page.AddOnPageLoaded(function ()
	{
		self.GeneratePhotoGalleryControl();
	});
}

//
function OnPhotoGalleryDataUpdated(e)
{
	if (!this.suppressPostback)
		doPostBack('', '');

	this.suppressPostback = false;
}

// ----------------------------------------------------------------------------
function PhotoGalleryControlContextMenu(contentType)
{
	if (contentType == "EditDesign")
		return CONTROLCONTEXTMENU_ENABLEDISABLE | CONTROLCONTEXTMENU_CLEAR | CONTROLCONTEXTMENU_EDIT | CONTROLCONTEXTMENU_PROPERTIES | CONTROLCONTEXTMENU_DEPTHORDERING | CONTROLCONTEXTMENU_DELETERESTORE;
	else if (contentType == "EditContent")
		return CONTROLCONTEXTMENU_CLEAR | CONTROLCONTEXTMENU_EDIT | CONTROLCONTEXTMENU_DELETERESTORE;
	return 0;
}

//
function PreProcessPhotoGalleryContent(obj)
{
    if (typeof obj == "object" && obj.length)
    {
		//Update extended properties only if we're in EditDesign mode
		if (Template.GetContentType() == "EditDesign")
		{
			if (this.HasExtendedPropertiesChanged(obj[1]))
			{
				//if content has changed aswell then we need to make sure the postback event OnPhotoGalleryDataUpdated is not called twice
				if (this.HasContentChanged(obj[0]))
					this.suppressPostback = true;
				this.SetExtendedProperties(obj[1]);
			}
		}

        return obj[0];
    }
    return obj;
}

//
function GeneratePhotoGalleryControl()
{
	var container = embeddedControl_PresentationControls[this.controlObject.id];
	var contentData = CreateContentSettings(this.GetContent());
	var settings = CreateSettings(this.GetExtendedProperties());

	switch (settings.mode)
	{
		case PhotoGalleryMode.Slideshow:
			GenerateSlideshow(container, contentData, settings.slideshowSettings);
			break;

		default:
			GenerateGallery(container, contentData, settings.gallerySettings);
			$(String.format("#{0}", container.id)).css("height", "100%").css("width", "100%").css("visibility", "visible").css("display", "block");
			break;
	}
}

//
function GenerateGallery(container, contentData, settings)
{
	$(container).addClass("ContainerStyle");
	//the Gallery mode currently doesn't have many settings
	$(String.format("#{0} a[rel^=lightbox]", container.id)).slimbox(
		  {
		  	/* Put custom options here */
		  	overlayOpacity: 0.8,
		  	captionAnimationDuration: 1,
		  	counterText: settings.showImageNumbering ? "{x}/{y}" : "",
		  	closeKeys: [27, 88],
		  	nextKeys: [39, 78],
		  	prevKeys: [37, 80]
		  },
		  null,
		  function (el)
		  {
		  	return (this == el) || ((this.rel.length >= 8) && (this.rel == el.rel));
		  });
}

//
function GetSlideshowOptions(container, settings)
{
	var options =
	{
		fx: settings.transitionType,
		sync: settings.syncTransitions,
		cleartypeNoBg: true,
		cleartype: !$.support.opacity,
		speed: 2000,
		timeout: settings.transitionTime * 1000,
		prev: String.format("#{0}_TopPrev, #{0}_BottomPrev", container.id),
		next: String.format("#{0}_TopNext, #{0}_BottomNext", container.id),
		easing: "easeOutExpo",
		activePagerClass: "ActivePager",

		before: function ()
		{
			var link = $(this);

			if (link.children("img").attr("alt").indexOf("http://") != -1)
			{
				var navigateUrl = "";
				var desc = "";
				var array = link.children("img").attr("alt").split('\n');
				if (array.length > 0)
				{
					navigateUrl = array[0];
					for (var i = 1; i < array.length; i++)
					{
						desc = desc + array[i];
					}
				}

				link.attr("href", navigateUrl);

				$(String.format("#{0}Description", container.id)).html("<span><a href='" + navigateUrl + "'>" + desc + "</a></span>");
				link.attr("title", desc);
			}
			else
				$(String.format("#{0}Description", container.id)).html("<span>" + link.attr("title") + "&nbsp;</span>");
		}
	};

	if (settings.showPager)
		options.pager = String.format("#{0}Pager", container.id);

	return options;
}

function AddSlideshowNavigationBarAndButtons(container, settings)
{
	var navigationBarTag = "<div id='{0}SlideshowNavigation' class='SlideshowNavigation{1}'>"
					+ "<img src='/images/NavigateLeft.png' id='{0}Prev' class='SlideshowPrev' />"
					+ "<img src='/images/NavigateRight.png' id='{0}Next' class='SlideshowNext'/>"
					+ "</div>";

	// the parent element should be the table cell containing the fotogallery
	var parent = $(container).parent();
	parent.css("position", "relative"); 	//special case - resolves the description bar becoming too wide

	var imageCount = $(String.format("#{0} img", container.id)).size();
	//special case for firefox
	//Ensures that the navigation bars and buttons are positioned relative to the control istead of the template
	if ($.browser.mozilla)
	{
		parent.css("display", "block");		//the td containing the photogallery
		var tbody = parent.parent().parent();
		tbody.css("height", "0%");
	}

	if ((settings.navigationBarPosition & SlideshowNavigationBarLayout.Top) && imageCount > 1)
	{
		var topNavigation = $(String.format(navigationBarTag, String.format("{0}_Top", container.id), " AlignTop"));
		topNavigation.appendTo(parent);
	}

	if ((settings.navigationBarPosition & SlideshowNavigationBarLayout.Bottom) && imageCount > 1)
	{
		var className = settings.showImageDescription ? " AlignBottom" : " AlignBottomNoDescription";
		var bottomNavigation = $(String.format(navigationBarTag, String.format("{0}_Bottom", container.id), className));
		bottomNavigation.appendTo(parent);
	}

	if (settings.showImageDescription)
	{
		var descriptionBar = $(String.format("<div class='SlideshowDescription' id='{0}Description'></div>", container.id));
		descriptionBar.appendTo(parent);
	}

	if (settings.showPager)
	{
		var pager = $(String.format("<div class='SlideshowPager' id='{0}Pager'></div>", container.id));
		pager.appendTo(parent);
	}
}

function WebkitFix(id, options)
{
	if (/loaded|complete/.test(document.readyState))
	{
		$(String.format("#{0}", id)).css("visibility", "visible").css("display", "block").cycle(options);
		$(String.format("#{0}", id)).height($(String.format("#{0}", id)).parent().height());
		//UpdateFooters();
	}
	else
	{
		setTimeout(function () { WebkitFix(id, options); }, 10);
	}
}

//
function GenerateSlideshow(container, contentData, settings)
{
	$(container).addClass("SlideshowStyle");

	//
	AddSlideshowNavigationBarAndButtons(container, settings);

	var options = GetSlideshowOptions(container, settings);

	if (!$.browser.webkit)
		$(String.format("#{0}", container.id)).css("visibility", "visible").css("display", "block").cycle(options);
	else
	{
		setTimeout(function ()
		{
			WebkitFix(container.id, options);
		}, 10);
	}
}
// ----------------------------------------------------------------------------

///
/// Utilitity functions for converting legacy configurations 
///
function ConvertLegacyGalleryConfig(legacyConfig)
{
	var values = legacyConfig.split("|");
	var settings = new PhotoGallerySettings();
	settings.mode = PhotoGalleryMode.Gallery;

	if (values.length > 0)
		settings.folderId = parseInt(values[0]);

	if (values.length > 2)
		settings.gallerySettings.showImageDescription = parseInt(values[2]) == 1;

	if (values.length > 3)
		settings.gallerySettings.showImageNumbering = parseInt(values[3]) == 1;

	return settings;
}

function ConvertLegacySlideshowConfig(legacyConfig)
{
	var values = legacyConfig.split("|");
	var settings = new PhotoGallerySettings();
	settings.mode = PhotoGalleryMode.Slideshow;

	if (values.length > 0)
		settings.folderId = parseInt(values[0]);

	if (values.length > 6)
		settings.slideshowSettings.transitionType = values[6];

	if (values.length > 7)
		settings.slideshowSettings.syncTransitions = parseInt(values[7]) == 1;

	if (values.length > 8)
		settings.slideshowSettings.showImageDescription = parseInt(values[8]) == 1;

	if (values.length > 9)
	{
		settings.slideshowSettings.transitionTime = parseInt(values[9]);
		if (isNaN(settings.slideshowSettings.transitionTime))
			settings.slideshowSettings.transitionTime = 2;
	}

	if (values.length > 10)
		settings.slideshowSettings.navigationBarPosition = values[10];

	if (values.length > 11)
		settings.slideshowSettings.showPager = !isNaN(parseInt(values[11])) && parseInt(values[11]) > 0;

	return settings;
}

function ConvertLegacyConfig(legacyConfig)
{
	if (legacyConfig != null)
	{
		var data = legacyConfig.split("|");
		var settings = data.length > 5 && parseInt(data[5]) == 1 ? ConvertLegacySlideshowConfig(legacyConfig) : ConvertLegacyGalleryConfig(legacyConfig);

		if (data.length > 1)
		{
			settings.thumbnailType = data[1];
			settings.useCustomMeasurements = data[1] == -1;
		}

		if (data.length > 4)
		{
			var measurementData = data[4].split(";");
			if (measurementData.length > 0)
			{
				settings.useCustomMeasurements = parseInt(measurementData[0]) == 1;
				settings.customMeasurementWidth = parseInt(measurementData[1]);
				settings.customMeasurementHeight = parseInt(measurementData[2]);

				if (isNaN(settings.customMeasurementWidth))
					settings.customMeasurementWidth = 250;
				if (isNaN(settings.customMeasurementHeight))
					settings.customMeasurementHeight = 250;
			}
		}

		if (settings.useCustomMeasurements && settings.thumbnailType != -1)
		{
			settings.thumbnailType = -1;
		}

		return settings;
	}

	return new PhotoGallerySettings();
}
