//$(function(){
//    $('.b-gallery').gallery({
//        maxHeight: 180,
//        interval: 10,
//        data: galleryData
//    });
//});

(function($) {
	$.fn.gallery = function(options, basepath) {

		var getGalleryContWidth = function() {
			return galleryCont.width();
		};

		var thumbWidthIsReady = function(photoData) {
			if (!photoData)
				return false;
			return (photoData.thumb_width != undefined)
					&& !isNaN(photoData.thumb_width)
					&& (photoData.thumb_width > 0);
		};

		var thumbHeightIsReady = function(photoData) {
			if (!photoData)
				return false;
			return (photoData.thumb_height != undefined)
					&& !isNaN(photoData.thumb_height)
					&& (photoData.thumb_height > 0);
		};

		var thumbIsReady = function(photoData) {
			if (!photoData)
				return false;
			return thumbWidthIsReady(photoData)
					&& thumbHeightIsReady(photoData);
		};

		var obeyConstraints = function() {
			for ( var i = 0, n = data.photos.length, photos = data.photos; i < n; i++) {
				if (!thumbIsReady(photos[i]))
					continue;
				var width = photos[i].thumb_width;
				var height = photos[i].thumb_height;
				width *= options.maxHeight / height;
				height = options.maxHeight;
				if (width > galleryContWidth) {
					height = height * galleryContWidth / width;
					width = galleryContWidth;
				}

				// фиксируем высоту контейнера
				photos[i].thumb_cont_height = options.maxHeight;

				photos[i].thumb_fixed_width = width;
				photos[i].thumb_fixed_height = height;
			}
		};

		var removeInitialThumbDimention = function() {
			for ( var i = 0, n = data.photos.length, photos = data.photos; i < n; i++) {
				if (thumbIsReady(photos[i])) {
					photos[i].thumb_width = -1;
					photos[i].thumb_height = -1;
				}
			}
		};

		var splitByRows = function() {
			var curImagesWidth = 0;
			var firstInRow = 0;
			var j, k;
			for ( var i = 0, n = data.photos.length, photos = data.photos; i < n; i++) {
				if (!thumbIsReady(photos[i]))
					continue;
				photos[i].thumb_inrow_width = photos[i].thumb_fixed_width;
				photos[i].thumb_inrow_height = photos[i].thumb_fixed_height;
				photos[i].firstInRow = false;
				curImagesWidth += photos[i].thumb_fixed_width
						+ options.interval;
				if (curImagesWidth >= galleryContWidth) {
					// k = (curImagesWidth - (i-firstInRow-1)*options.interval)
					// / (galleryContWidth - (i-firstInRow+1)*options.interval);
					k = (galleryContWidth - (i - firstInRow - 1)
							* options.interval)
							/ curImagesWidth;

					for (j = firstInRow; j <= i; j++) {

						photos[j].thumb_inrow_width = Math
								.round(photos[j].thumb_fixed_width * k);
						photos[j].thumb_inrow_height = Math
								.round(photos[j].thumb_fixed_height * k);
						if (photos[j].thumb_cont_width) {
							photos[j].thumb_cont_width = Math
									.round(photos[j].thumb_cont_width * k);
						}
						if (photos[j].thumb_cont_height) {
							photos[j].thumb_cont_height = Math
									.round(photos[j].thumb_cont_height * k);
						}
					}
					photos[firstInRow].firstInRow = true;
					curImagesWidth = 0;
					firstInRow = i + 1;
				}
			}
		};

		var createImages = function() {
			var image, link;
			for ( var i = 0, n = data.photos.length, photos = data.photos; i < n; i++) {
				image = $('<img/>');
				image.data("imageIndex", i);
				link = $('<a/>');
				if (thumbIsReady(photos[i])) {
					image.attr({
						src : photos[i].thumb_src,
						width : photos[i].thumb_inrow_width,
						height : photos[i].thumb_inrow_height,
						'class' : 'b-gallery__item',
						id : 'photo_' + i
					});
					if (isCanvasSupported()) {
						image.imagesLoaded().done(
								function(images) {
									var jImage = $(images[0]);
									replaceImageToCanvas(jImage, jImage
											.data("imageIndex"));
								});
					}
				} else {
					image.attr({
						src : photos[i].thumb_src,
						'class' : 'b-gallery__item',
						id : 'photo_' + i
					});
					image.imagesLoaded().done(
							function(images) {
								var jImage = $(images[0]);
								handleImageAfterLoading(jImage, jImage
										.data("imageIndex"));
							});
				}
				link.attr('href', photos[i].src);
				link.append(image);
				image.hide();
				galleryCont.append(link);
			}
			galleryCont.append('<div class="clearer"></div>');
			setInrowSizes();
		};

		var handleImageAfterLoading = function(image, index) {
			image.show();
			var htmlImage = image[0];
			
			if (!thumbWidthIsReady(data.photos[index])) {
				var w = htmlImage.width || htmlImage.innerWidth
				|| htmlImage.naturalWidth;
				data.photos[index].thumb_width = w;
			}
			
			if (!thumbHeightIsReady(data.photos[index])) {
				var h = htmlImage.height || htmlImage.innerHeight
				|| htmlImage.naturalHeight;
				data.photos[index].thumb_height = h;
			}
			
			if (isCanvasSupported())
				replaceImageToCanvas(image, index);
			refreshGallery();
		};

		var replaceImageToCanvas = function(image, index) {
			if (!image)
				image = $(this);
			var canvas = document.createElement('canvas');
			if (!image || !image.context || !image.context.width
					|| !thumbIsReady(data.photos[index])) {
				$(canvas).hide();
			} else {
				canvas.width = image.width();
				canvas.height = image.height();
				$(canvas).css('margin-top', image.css('margin-top'));

				var ctx = canvas.getContext('2d');
				ctx.drawImage(image.context, 0, 0, image.width(), image
						.height());
				image.after(canvas);
				image.hide();
			}
		};

		var setInrowSizes = function(updateCanvas) {
			var photos = galleryData.photos;
			galleryCont
					.find('img')
					.each(
							function(i) {
								if (!thumbIsReady(photos[i]))
									return;
								$(this).attr({
									width : data.photos[i].thumb_inrow_width,
									height : data.photos[i].thumb_inrow_height
								});
								if (photos[i].thumb_cont_width
										|| photos[i].thumb_cont_height) {
									$(this).parent().css('width',
											photos[i].thumb_cont_width);
									$(this).parent().css('height',
											photos[i].thumb_cont_height);
									if (photos[i].thumb_cont_height > photos[i].thumb_inrow_height) {
										$(this)
												.css(
														'margin-top',
														(photos[i].thumb_cont_height - photos[i].thumb_inrow_height) / 2);
									}
								}
								if (updateCanvas && isCanvasSupported()) {
									$(this).show();
									$(this).parent().find('canvas').remove();
									replaceImageToCanvas.apply(this, [ $(this),
											i ]);
								}
								if (data.photos[i].firstInRow)
									$(this)
											.parent()
											.before(
													'<div class="clearer js_galery_clearer"></div>');
							});
		};

		var _isCanvasSupported = null;

		var isCanvasSupported = function() {
			if (_isCanvasSupported === null) {
				var canvas = document.createElement('canvas');
				_isCanvasSupported = !!canvas.getContext
						&& !!canvas.getContext('2d');
			}
			return _isCanvasSupported;
		};

		$(window).resize(function() {
			refreshGallery();
		});

		var refreshGallery = function() {
			$('.js_galery_clearer').remove();

			galleryContWidth = getGalleryContWidth();
			obeyConstraints();
			splitByRows();
			setInrowSizes(true);
		};

		var validateImages = function() {
			var folder;
			var filename;
			for ( var i = 0, n = data.photos.length, photos = data.photos; i < n; i++) {
				if (!photos[i].src) {
					var newSrc = basepath + photos[i].user
							+ "/protected/myphotos";
					folder = photos[i].folder;
					folder = folder.replace(/\\/g, "/");
					folder = "/" + folder + "/";
					folder = folder.replace(/\/+/g, "/");
					newSrc = newSrc + folder + "pwd/" + photos[i].pwd + "/";
					filename = photos[i].file;
					if (filename
							&& (filename.indexOf("/") == 0 || filename
									.indexOf("\\") == 0)) {
						filename = filename.replace(/\\/, "");
						filename = filename.replace(/\/+/g, "");
					}
					newSrc = newSrc + filename;
					photos[i].src = newSrc;
				}
				if (!photos[i].thumb_src) {
					var actualUser = photos[i].user;
					if (actualUser.indexOf("~") == 0)
						actualUser = actualUser.substring(1);
					var thumbSrc = basepath + "sys/gallery.wcgp?USR="
							+ actualUser + "&PWD=" + photos[i].pwd + "&PTH=";
					var folderPath = "/private/myphotos";
					folder = photos[i].folder;
					folder = folder.replace(/\\/g, "/");
					folder = "/" + folder + "/";
					folder = folder.replace(/\/+/g, "/");
					folderPath = folderPath + folder;
					filename = photos[i].file;
					if (filename
							&& (filename.indexOf("/") == 0 || filename
									.indexOf("\\") == 0)) {
						filename = filename.replace(/\\/, "");
						filename = filename.replace(/\/+/g, "");
					}
					folderPath = folderPath + filename;
					thumbSrc = thumbSrc + folderPath + "&CMD=getpreview";
					photos[i].thumb_src = thumbSrc;
				}
			}
		};

		var galleryCont = this;
		var galleryContWidth = getGalleryContWidth();
		var data = options.data;
		removeInitialThumbDimention();
		obeyConstraints();
		splitByRows();
		validateImages();
		createImages();
		$('.b-pane__title_text').text(galleryData.title);
		$('.b-pane__photos-count_number').text(galleryData.photos.length);
		$(document).attr("title", "CommuniGate Pronto - " + galleryData.title);

		return this;
	};
})(jQuery);
