﻿$(function () {

	if (typeof (SVG) == 'undefined') { SVG = {}; }
	if (typeof (SVG.FlyerBoard) == 'undefined') { SVG.FlyerBoard = {}; }

	SVG.FlyerBoard.Images = { //@todo: Switch to SVG.FlyerBoard.Image

		Images: [],
		Rows: 2,
		FlyerHeight: 150,
		FlyerWidth: 168,
		RightMostImage: 20,
		ImageSpacingWidth: 0,
		ImageSpacingHeight: 0,
		AddedExpandHeight: 5, //@percent
		AddedExpandWidth: 5, //@percent
		ExpandSpeed: 200,
		Expanded: false,
		External: false,
		ImagesLoaded: 0,


		Add: function (image) {

			var canvas = SVG.FlyerBoard.Canvas;
			var imageLink = this.GetNewElement(image);
			var img = $(imageLink).children('img');
			var imageContainer = canvas.ImageContainer;
			imageContainer.append(imageLink);

			var main = this;
			img //@note: get image dimensions after load
            .load(function () {
            	$(this).attr('originalWidth', $(this).width());
            	$(this).attr('originalHeight', $(this).height());
            	main.ImagesLoaded += 1;
            })
            .each(function () { //@note: cache fix for browsers that don't trigger .load()
            	if (this.complete) {
            		$(this).trigger('load');
            	}
            })
            .error(function () {
            	main.ImagesLoaded += 1;
            });

			this.Images.push({
				imageObject: image,
				imageElement: imageLink
			});

			var isEven = this.Images.length % 2;    //Only want to do it every other image
			if (isEven) { this.RightMostImage += this.FlyerWidth; }
			if (this.RightMostImage < canvas.Width) { return; }

			var imageContainerWidth = ((this.FlyerWidth + this.ImageSpacingWidth) * isEven) + $(imageContainer).width();
			$(imageContainer).width(imageContainerWidth);

		},

		Clear: function () {
			var flyerBoard = SVG.FlyerBoard
			var canvas = flyerBoard.Canvas;
			var images = flyerBoard.Images;
			images.Images = [];
			images.RightMostImage = 20;
			canvas.ImageContainer.html("");
			canvas.ImageContainer.width(canvas.Width - (canvas.BorderWidth * 2));
			canvas.ImageContainer.css("left", "0px");

		},

		GetImageByEventID: function (eventID) {
			var images = SVG.FlyerBoard.Images.Images;
			for (var i = 0; i < images.length; i++) {
				if (images[i].imageObject.EventID == eventID) { return images[i]; }
			}
		},

		ResizeImage: function (el, expand) {

			if (SVG.FlyerBoard.Canvas.Scrolling) { return; }

			var newHeight, newWidth;
			var images = SVG.FlyerBoard.Images;
			var image = images.GetImageByEventID(el.id);
			el = $(el);
			image.width = el.attr('originalWidth');
			image.height = el.attr('originalHeight');

			if (!image || !image.height || !image.width) return;

			var alreadyExpanding = el.attr("expanding") == "true";
			var oldZ = el.css("z-index");
			if (!oldZ) { oldZ = 10; }

			if (expand && !alreadyExpanding) {
				el.attr("expanding", "true");
				newHeight = (image.height * (1 + (images.AddedExpandHeight / 100))) + "px",
                newWidth = (image.width * (1 + (images.AddedExpandWidth / 100))) + "px"
				el.attr("oldX", oldZ);
				el.css("z-index", 1000);
			} else {
				oldZ = el.css("oldX");
				if (!oldZ) { oldZ = 10; }
				el.css("z-index", oldZ);
				newWidth = image.width + "px",
                newHeight = image.height + "px"
			}

			el.animate({
				height: newHeight,
				width: newWidth
			}, images.ExpandSpeed
             , function () {
             	el.attr("expanding", "false");
             	if (expand) {
             		el.addClass('zoomed');
             	} else {
             		el.removeClass('zoomed');
             	}
             });

			return false;

		},

		GetNewElement: function (image) {

			var spacingHeight = this.ImageSpacingHeight;
			var spacingWidth = this.ImageSpacingWidth;
			if ($.isArray(this.ImageSpacingHeight)) {
				var randomIndex = Math.floor(Math.random() * (this.ImageSpacingHeight.length - 1));
				spacingHeight = this.ImageSpacingHeight[randomIndex];
			}
			if ($.isArray(this.ImageSpacingWidth)) {
				var randomIndex = Math.floor(Math.random() * (this.ImageSpacingWidth.length - 1));
				spacingWidth = this.ImageSpacingWidth[randomIndex];
			}

			var imageCount = this.Images.length;
			var currentRow = (imageCount % this.Rows);
			var currentColumn = Math.floor(imageCount / this.Rows);
			var leftOffset = (currentColumn * (this.FlyerWidth + spacingWidth));
			var topOffset = (currentRow * (this.FlyerHeight + spacingHeight));
			var canvas = SVG.FlyerBoard.Canvas;
			var images = this;
			var zIndex = Math.random() * 8; //@todo: = Math.ceil(canvas.Width % (images.FlyerWidth + images.imageSpacingWidth));

			var link = $("<a/>");
			link.attr({
				"href": SVG.URLS.EventPopup + image.EventID,
				"target": "_blank"
			}).css({
				"border": "none",
				"cursor": "hand"
			}).click(function () {
				if (canvas.Scrolling) {
					canvas.Scrolling = false;
					canvas.TurnMouseScrollingOff();
					return false;
				}
			});

			if (!this.External) {
				link.colorbox({
					close: "Close Dialog",
					initialHeight: 300,
					initialWidth: 566,
					opacity: 0.2,
					width: 616,
					onOpen: function () {
						$('#cboxClose')
							.attr({ 'role': 'link', 'tabindex': '0' })
							.appendTo('#cboxWrapper')
							.bind('keyup', function (e) { // Trigger close using keyboard 'enter' and 'space'
								if (e.which == 13 || e.which == 32) {
									$(this).click();
								}
							});
						$('#cboxWrapper').attr('role', 'alert');
					},
					onComplete: function () {
						$('#aria-label-eventModal').focus();
					}
				})
			}

			var img = $("<img/>");
			img.attr({
				"id": image.EventID,
				"alt": image.Name,
				"src": image.EventFlyerBoardImagePath,
				"tabindex": -1
			}).css({
				"border": "none",
				"top": topOffset,
				"z-index": zIndex,
				"left": leftOffset,
				"position": "absolute"
			});

			img.mouseenter(function (event) {

				img.stop(true, true); //@note: preventing animation queues

				img.addClass('hovered');

				if (img.hasClass('hovered')) {
					canvas.Block(img.attr("alt"), false);
					images.ResizeImage(this, true);
				}

				//@note: making sure other images zoom out
				var currentImg = this;
				$(this).parent().parent().find('img.zoomed').each(function (i, el) {
					if (currentImg != el) {
						images.ResizeImage(this, false);
					}
				});

			});

			img.mouseleave(function (event) {

				img.removeClass('hovered');

				var imgLeft = $(this).offset().left;
				var imgRight = imgLeft + $(this).width();
				var imgTop = $(this).offset().top;
				var imgBottom = imgTop + $(this).height();

				var mouseX = event.pageX;
				var mouseY = event.pageY;

				//@note: double-check mouseleave b/c of blockUI
				if ((mouseX > imgLeft && mouseX < imgRight) && (mouseY > imgTop && mouseY < imgBottom)) {
					//@note: don't resize b/c mouse is still over flyer
				} else {
					images.ResizeImage(this, false);
					canvas.Unblock();
				}

			});

			img.mouseup(function () { canvas.TurnMouseScrollingOff(); });
			img.mousedown(function (e) {
				if (SVG.IsRightClick(e)) { return false; }
				canvas.Unblock();
				images.ResizeImage(this, false);
				canvas.TurnMouseScrollingOn();
				return false;
			}).appendTo(link);

			return link;

		}
	};
});
