(function($) {
	$.fn.imageStrip = function(options) {
		var opt = $.extend({}, $.fn.imageStrip.defaults, options),
				popupEl,
				titleEl,
				closeButton,
				imagesEl,
				popupMaskEl,
				paginationEl,
				popupInnerEl,
				overlayMaskEl,
				activatedPopupEl;

		opt.elemContainers = this;

		var popupData = {
			popupMask: opt.popupMask,
			popupContainer: opt.popupContainer,
			imagesContainer: opt.imagesContainer,
			paginationContainer: opt.paginationContainer,
			imgpopup: opt.popup,
			popupOverlay: opt.overlayMask,
			imageTitle: 'title',
			closeBtn: 'close-btn',
			closeBtnTxt: 'Закрыть',
			closeBtnHelper: 'Нажмите ESC чтоб закрыть изображение',
			paginationHelper: 'Для переключения изображений нажмите стрелку влева/вправо'

		};

		if (opt.elemContainers.length) {
			prepareContainer();
			createPopup();
			setListeners();
		}

		function preparePopup(container) {
			var elems = $('a', container),
					link, title, images, pages;

			opt.images = [];

			/* Fill out opt.imagse array with image - link, title values */
			$.each(elems, function(key, value) {
				link = $(value).attr('href');
				title = $(value).attr('title');
				opt.images.push({
							"link": link,
							"title": title
						});
			});

			/* create image elements for popup */
			for (var i=0, len= opt.images.length; i < len; i++) {
				var image = $('<img/>');
				image.attr('src', opt.images[i].link);
				image.attr('alt', opt.images[i].title);
				image.attr('class', opt.imageClass + i);
				images = images ? images.add(image) : image;

				/* create pages for pagination */
				if (len > 1) {
					var page = $('<li><a></a></li>');
					var pageLink = page.find('a');

					pageLink.attr('rel', i);
					pageLink.attr('title', opt.images[i].title);
					pageLink.html(i + 1);
					pages = pages ? pages.add(page) : page;
				}
			}

			/* append images and pages to popup */
			$(imagesEl, popupEl).append(images);
			if (pages) {
				$(paginationEl, popupEl).append(pages);
			}

			/* showPopup */
			showPopup();
			/* show first image in popup*/
			changeImage(0);
		};

		function changeImage(id) {
			id = id || 0;

			switch (id) {
				case "prev":
					id = (opt.currentImage == 0) ? (opt.images.length - 1) : opt.currentImage - 1;
				break;
				case "next":
					id = (opt.currentImage == (opt.images.length - 1)) ? 0 : opt.currentImage + 1;
				break;
				default:
					id = parseInt(id);
				break;
			};

			var imgPreloader = new Image();
		  imgPreloader.src = opt.images[id].link;

			imgPreloader.onload = function() {
				var newWidth = imgPreloader.width;
				var newHeight = imgPreloader.height;
				$('.' + opt.imageClass + id).
					width(newWidth).
					height(newHeight);
				resizeImageContainer(newWidth, newHeight);
			};

			imgPreloader.onerror = function() {
				changeImage("next");
			};

			/*show title*/
			$(titleEl, popupEl).html(opt.images[id].title);

			/* hide current image */
			if (typeof opt.currentImage !== "undefined") {
				$('.' + opt.imageClass + opt.currentImage).hide();
			}

			/* show image */
			$('.' + opt.imageClass + id).show();
			opt.currentImage = id;

			/*set current page class*/
			var currentElement = $('.' + opt.currentPageClass);
			/* remove current class and set current to id element  */
			if (currentElement.length) {
				$('.' + opt.currentPageClass).removeClass(opt.currentPageClass);
				var pages = paginationEl.find('a');

				$.each(pages, function(key, value) {
					if ($(value).attr('rel') == id) {
						$(value).addClass(opt.currentPageClass);
					}
				});
			} else {
				paginationEl.find('a').eq(0).attr('class', opt.currentPageClass);
			}
		};

		function createPopup() {
			var popupTemplate = '' +
					'<div class="{{popupOverlay}}"></div>' +
					'<div class="{{popupMask}}">' +
						'<div class="{{popupContainer}}">' +
							'<div class="{{imgpopup}}">' +
								'<div class="images-container">' +
									'<div class="{{imagesContainer}}">' +
										'' +
									'</div>' +
								'</div>' +
								'<p class="{{imageTitle}}"></p>' +
								'<ul class="{{paginationContainer}}">' +
									'' +
								'</ul>' +
								'<div class="{{closeBtn}}"><a href="#" title="{{closeBtnHelper}}"><span class="close-sign">&times;</span>{{closeBtnTxt}}</a></div>' +
							'</div>' +
						'</div>' +
					'</div>' +
					'';

				var html = Mustache.to_html(popupTemplate, popupData);
				$(opt.parentContainer).append(html);

				popupMaskEl = $('.' + opt.popupMask);
				overlayMaskEl = $('.' + opt.overlayMask);
				popupEl = $('.' + opt.popupContainer);
				titleEl = $('.' + popupData.imageTitle);
				closeButton = $('.' + popupData.closeBtn);
				imagesEl = $('.' + opt.imagesContainer);
				paginationEl = $('.' + opt.paginationContainer);
				popupInnerEl = $('.' + opt.popup);
				activatedPopupEl = $('.' + opt.activatedPopup);
			};

			function setListeners() {
				$('img', activatedPopupEl).bind('click.img_strip', function(e) {
					var container = $(e.target).parent();
					preparePopup(container);
				});

				$(closeButton, popupEl).bind('click.close_popup', function() {
					closePopup();
					return false;
				});

				$(document).bind('keydown', keyboardAction);

				$(document).bind('click.close_popup_ext', function(e) {
					/*if clicked not on popup*/
					console.log($(e.target));
					if ($(e.target).hasClass(opt.overlayMask) || $(e.target).hasClass(opt.popupMask)) {
						closePopup();
					}
				});

				$(paginationEl, popupEl).find('a').live('click.switchpage', function(e) {
					var elemId = $(e.target).attr('rel');
					changeImage(elemId);
					return false;
				});
			};

			function keyboardAction(e) {
				var keycode = e.keyCode;
				var escapeKey = 27;

				var key = String.fromCharCode(keycode).toLowerCase();

				// close popup
				if ((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)) {
					closePopup();

				// display previous image
				} else if ((key == 'p') || (keycode == 37)) {
					changeImage("prev");
				} else if ((key == 'n') || (keycode == 39)) {
					changeImage("next");
				}
			};

			function showPopup() {
				overlayMaskEl.show();
				popupEl.show();
				popupMaskEl.stop(true,true).fadeIn();
			};

			function closePopup() {
				overlayMaskEl.hide();
				popupEl.hide();
				popupMaskEl.stop(true, true).fadeOut('fast');
				$(titleEl, popupEl).empty();
				$(imagesEl, popupEl).empty();
				$(paginationEl, popupEl).empty();
			};

		/**
		 * Hides extra links with other images;
		 * Set cursor to "hand" if there are any big picture
		 */
			function prepareContainer() {
				$.each(opt.elemContainers, function(key, value) {
					var extraLinks = $(value).find('a');

					if (extraLinks.length) {
						extraLinks.hide();
						$(value).find('img').css('cursor', 'pointer');
						$(value).addClass(opt.activatedPopup);
					}
				});
			};

			function resizeImageContainer(imgWidth) {
				popupMaskEl.height( overlayMaskEl.height() );
				var posTop = parseInt(( $(window).height() - popupInnerEl.outerHeight() ) / 2 + $(window).scrollTop() + "px");

				popupEl.css({
					'margin-left': -parseInt(imgWidth / 2 + 40),
					'top': (posTop < 40) ? 40 : posTop
				});

				popupInnerEl.animate({
					width: imgWidth
				}, opt.resizeSpeed, 'linear');
			};
		};


	$.fn.imageStrip.defaults = {
		elemContainers: null,
		images: null,
		currentImage: null,
		resizeSpeed: 0,
		parentContainer: 'body',
		layoutWrapper: '#wrapper',
		overlayMask: 'popup-overlay-mask',
		popupMask: 'popup-overlay',
		popupContainer: 'img-popup-container',
		popup: 'img-popup',
		imagesContainer: 'popup-images',
		paginationContainer: 'popup-pagination',
		imageClass: 'stripImage',
		currentPageClass: 'popup-current-page',
		activatedPopup: 'popup-preview-activated'
	};

})(jQuery);
