/*! Fotorama 1.5 (v1251) | http://fotoramajs.com/license.txt */

/* Modernizr 2.0.6 (Custom Build) | MIT & BSD
 * Build: http://www.modernizr.com/download/#-csstransforms3d-csstransitions-teststyles-testprop-testallprops-prefixes-domprefixes
 */
;window.Mdrnzr=function(a,b,c){function B(a,b){var c=a.charAt(0).toUpperCase()+a.substr(1),d=(a+" "+n.join(c+" ")+c).split(" ");return A(d,b)}function A(a,b){for(var d in a)if(j[a[d]]!==c)return b=="pfx"?a[d]:!0;return!1}function z(a,b){return!!~(""+a).indexOf(b)}function y(a,b){return typeof a===b}function x(a,b){return w(m.join(a+";")+(b||""))}function w(a){j.cssText=a}var d="2.0.6",e={},f=b.documentElement,g=b.head||b.getElementsByTagName("head")[0],h="Mdrnzr",i=b.createElement(h),j=i.style,k,l=Object.prototype.toString,m=" -webkit- -moz- -o- -ms- -khtml- ".split(" "),n="Webkit Moz O ms Khtml".split(" "),o={},p={},q={},r=[],s=function(a,c,d,e){var g,i,j,k=b.createElement("div");if(parseInt(d,10))while(d--)j=b.createElement("div"),j.id=e?e[d]:h+(d+1),k.appendChild(j);g=["&shy;","<style>",a,"</style>"].join(""),k.id=h,k.innerHTML+=g,f.appendChild(k),i=c(k,a),k.parentNode.removeChild(k);return!!i},t,u={}.hasOwnProperty,v;!y(u,c)&&!y(u.call,c)?v=function(a,b){return u.call(a,b)}:v=function(a,b){return b in a&&y(a.constructor.prototype[b],c)};var C=function(a,c){var d=a.join(""),f=c.length;s(d,function(a,c){var d=b.styleSheets[b.styleSheets.length-1],g=d.cssRules&&d.cssRules[0]?d.cssRules[0].cssText:d.cssText||"",h=a.childNodes,i={};while(f--)i[h[f].id]=h[f];e.csstransforms3d=i.csstransforms3d.offsetLeft===9},f,c)}([,["@media (",m.join("transform-3d),("),h,")","{#csstransforms3d{left:9px;position:absolute}}"].join("")],[,"csstransforms3d"]);o.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},o.csstransforms3d=function(){var a=!!A(["perspectiveProperty","WebkitPerspective","MozPerspective","OPerspective","msPerspective"]);a&&"webkitPerspective"in f.style&&(a=e.csstransforms3d);return a},o.csstransitions=function(){return B("transitionProperty")};for(var D in o)v(o,D)&&(t=D.toLowerCase(),e[t]=o[D](),r.push((e[t]?"":"no-")+t));w(""),i=k=null,e._version=d,e._prefixes=m,e._domPrefixes=n,e.testProp=function(a){return A([a])},e.testAllProps=B,e.testStyles=s;return e}(this,this.document);

/*!
 * Bez v1.0.10-g5ae0136
 * http://github.com/rdallasgray/bez
 *
 * A plugin to convert CSS3 cubic-bezier co-ordinates to jQuery-compatible easing functions
 *
 * With thanks to Nikolay Nemshilov for clarification on the cubic-bezier maths
 * See http://st-on-it.blogspot.com/2011/05/calculating-cubic-bezier-function.html
 *
 * Copyright 2011 Robert Dallas Gray. All rights reserved.
 * Provided under the FreeBSD license: https://github.com/rdallasgray/bez/blob/master/LICENSE.txt
*/
jQuery.extend({bez:function(a){var b="bez_"+$.makeArray(arguments).join("_").replace(".","p");if(typeof jQuery.easing[b]!="function"){var c=function(a,b){var c=[null,null],d=[null,null],e=[null,null],f=function(f,g){return e[g]=3*a[g],d[g]=3*(b[g]-a[g])-e[g],c[g]=1-e[g]-d[g],f*(e[g]+f*(d[g]+f*c[g]))},g=function(a){return e[0]+a*(2*d[0]+3*c[0]*a)},h=function(a){var b=a,c=0,d;while(++c<14){d=f(b,0)-a;if(Math.abs(d)<.001)break;b-=d/g(b)}return b};return function(a){return f(h(a),1)}};jQuery.easing[b]=function(b,d,e,f,g){return f*c([a[0],a[1]],[a[2],a[3]])(d/g)+e}}return b}});


/* Заглушка консоли */
/*if (typeof(console) == 'undefined') {
	console = {log: function(){}};
}*/

(function($){
	var touchFLAG = ('ontouchstart' in document);
	var csstrFLAG = Mdrnzr.csstransforms3d && Mdrnzr.csstransitions;
	var ieFLAG = $.browser.msie;
	var quirksFLAG = document.compatMode != 'CSS1Compat' && ieFLAG;

	var o__dragTimeout = 300;
	var o__bez = $.bez([.1,0,.25,1]);
	var o__transitionDuration = 333;

	var F = 'fotorama';

	var $window = $(window);
	var $document = $(document);
	
	var _options = [
		['data', 'array', null],
		['width', 'number', null],
		['height', 'number', null],
		['startImg', 'number', 0],
		['transitionDuration', 'number', o__transitionDuration],
		['touchStyle', 'boolean', true],
		['pseudoClick', 'boolean', true],
		['loop', 'boolean', false],
		['backgroundColor', 'string', null],
		['margin', 'number', 5],
		['minPadding', 'number', 10],
		['alwaysPadding', 'boolean', false],
		['preload', 'number', 3],
		['resize', 'boolean', false],
		['fitToWindowHeight', 'boolean', false],
		['zoomToFit', 'boolean', true],
		['cropToFit', 'boolean', false],
		['vertical', 'boolean', false],
		['verticalThumbsRight', 'boolean', false],
		['arrows', 'boolean', true],
		['arrowsColor', 'string', null],
		['arrowPrev', 'string', null],
		['arrowNext', 'string', null],
		['thumbs', 'boolean', true],
		['thumbsTop', 'boolean', false],
		['thumbsBackgroundColor', 'string', null],
		['thumbColor', 'string', null],
		['thumbsPreview', 'boolean', true],
		['thumbSize', 'number', null],
		['thumbMargin', 'number', 5],
		['thumbBorderWidth', 'number', 3],
		['thumbBorderColor', 'string', null],
		['caption', 'boolean', false],
		['html', 'array', null],
		['onShowImg', 'function', null],
		['shadows', 'boolean', true],
		['detachSiblings', 'boolean', true]
	];

	function collectOptions(block) {
		var options = {};
		for (var _i = 0; _i < _options.length; _i++) {
			var name = _options[_i][0];
			var type = _options[_i][1];
			if (block) {
				var attr = block.attr('data-'+name);
				if (attr) {
					if (type == 'number') {
						attr = Number(attr);
						if (!isNaN(attr)) {
							options[name] = attr;
						}
					} else if (type == 'boolean') {
						//console.log(name, type, attr);
						if (attr == 'true') {
							options[name] = true;
						} else if (attr = 'false') {
							options[name] = false;
						}
					} else if (type == 'string') {
						options[name] = attr;
					}
				}
			} else {
				options[name] = _options[_i][2];
			}
		}
		return options;
	}

	$.fn[F] = function(options) {
		if (typeof(fotoramaDefaults) == 'undefined') {
			fotoramaDefaults = {};
		}

		var o = $.extend({}, collectOptions(), $.extend({}, fotoramaDefaults, options));

		this.each(function(){
			var fotorama = $(this);
			if (!fotorama.data('ini')) {
				doFotorama(fotorama, o);
			}
		});

		//Chainability
		return this;
	}

	$(function(){
		// Авто-инициализация по классу.
		$('.'+F).each(function(){
			var $this = $(this);
			$this[F](collectOptions($this));
		});
	});

	var _prefix = ['-webkit-', '-moz-', '-o-', '-ms-', ''];

	function getCSS(prop, val) {
		var obj = {};
		for (var _i = 0; _i < _prefix.length; _i++) {
			obj[_prefix[_i]+prop] = val;
		}
		return obj;
	}

	function getTranslate(pos, vert) {
		if (csstrFLAG) {
			return getCSS('transform', vert ? 'translate3d(0,' + pos + 'px,0)' : 'translate3d(' + pos + 'px,0,0)');
		} else {
			var obj = {};
			obj[vert ? 'top' : 'left'] = pos;
			return obj;
		}
	}

	function preventClick() {
		return false;
	}

	function getDuration(time) {
		return getCSS('transition-duration', time+'ms');
	}

	function disableSelection(target) {
		target
			.mousemove(function(e){
				e.preventDefault();
			})
			.mousedown(function(e){
				e.preventDefault();
			});
	}

	var _SPINNER = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAGoCAMAAAAQMBfHAAABtlBMVEX///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////8cWrVBAAAAkXRSTlMAKUfghaPCZkAlPw7nsHiUy1w3VBcoLEoiNsAw/EbdoYNlGSYIFEUdDEgS2yENIMi9CnfkLhUnkhutW5/5gGSCAgsyaZlEsVA4yQQfAxM9Khh/AWEPm7nVEfNCtB4kNDnGSU+JM5dznmAtXkuQO3JnTlhiWp2nIwf2rtgcPha7UYxf4avt0DUGpjp1eXwvTBBjhUW/zwAABtxJREFUeF7tmtlXE0kUxm/2zr5gwhI3QiAsCXtCQFED4gKCIKIgoo7ruI0zOjNuo7Pva/7jqTq3iy9dOc05eclT/94434/qk6fbt74mK6GLF0N0EJF6PXKgUBcgAJfLzcJyHvkjz/VOXQhXXAWVX/Z4PCOdViHsEqgz1q+zAYHzyjKZdB4VxtEbIpiq16dEPuiShEkCIyGSoUhkSAh7Ik6bOYwx/BlUORhIJNYg1ILBErWP7Fm/5GzWGgxfcEsuDFPUz0StguFmDJo1hVmrEDKFEKX4iGjKKvTzEUY/tY/pjY00gkLy+z1r3n3M54tD+CIQ6O3Tc9+MSIqLi0UWlIH8WFYkMa83Jh9xymKUtkR+oluqXgEJRqVxqkbMCucQlNFPzJmHvi85h0BdLwP/XCFFcZt0gWr9yAEEGya93skDhb5YrI9aw8HBIXXuXOpAIcFzxR6PAAEIDjcL61nk9/zXDF3o2KnvqjwoxsG4YRU6DosBqc4oX2MDAuc7VTIxeoTRc1sEYzz8nsr8cAcRDHOkhBKJkBB+EPlJzmE0jpQplYPn0egtCAORyOfUPtLzPsl82hpMjLokoxMU9zFxDjD/mSDNmMKMnTDNR8SnrcIgG8FBah99L14UGyf3jZw1zxzncWey5nYfqWo5T5Lc+fM5FpSB/HhFJMlAICkfMWAxahsiP52RakBAgkPSGMgTk+McgjLCam4+8c5nCAIbS+5fMBeryoVA+TByAMGGuUBg7kChkEwWyMHBodV9hVcVW6I8V+zxCxCAlavNQvky8oe+rW5d6LzueUT6qzsLWA/VGdtbbEDg/Pp68/owy8PvhsyPdhLBMEdKKir3KbqDJRdG40gZUzlYiMczENYSiQFqH8VFr2SxqF8j1CUXQxTzMjH9GoGJ0CTn+mIyZQpT1MdH6IvJEB8RGaL2Ubh7N9c4ufu01b+rl8edyddirl/Vcp4kwxcuDLOgDOS9N3kfN+Qj0hYjvymXyy6pugUkKEkjvUzMKucQlJEn5spQ4CXnECicdt0kLPI1goCLGh0I9oTkfcFB9Bst3xc4ODik53lVsSXOc8UenwAByJWaheEg8ifejYwuGNf890h/dWcB66E6I7zBBgTOr5Wb14cZHn63Zd5jEMEwR8p0XO5T9COWXBiNI2VW5cAVi+1BuBWNPqf2kTsfkJzP6dcIHsm5FCUDTFK/RmASNMe5vpiMmcIYFfgIfTEJ8RGJELWP/lRquHFy//TKmh86wuPOZERcLnyq5TxJJkZHJ1hQBvIjZV63g/IRJy3Gr0siHzgkVZeABN9K42SVmBLnEJRxX83NBfcS5xCo4019/BIpwnnSBareRw4gAIBfYc9gsLX7AgcHBxQ99nDRo2ihZFmdaBauriAfCmx26UL3lu8h6a/uLGA9VGfUNtmAwPnWtrY+oOjJyvwYL7Ewkih6nmHJhdE4UmZUDlaSyfcQMvH4ArUNFJl2tSeKTAuoPVFkWkDtaVNkovZsH4Ny3BEm9893kal+OwihR7TbHVrOAtf6QmADuWQQtX5oxGJcqpj9Nyp1tzRG1onJcw5BGY/JpKByCNT5zvMb5mJ+mXSB1h8jBxAAQK1vC9f6LeDg4ICixx4uehQtlCyl181CKYccL94QMhveJ6S/urOA9VCdkV9iAwLnG2FtfUDRU5H58Yy2YBgoev7AkgujcaRMqhx8MIxVCHuxmIvaBopMu9oTPaUF1J42AmpPmyITtWf7GLpzJ9Q4uXeXkKl+OwLhK9Fuf6Ln9SnU+kJQBvLDT1Hrp8YtRnnH7L9RqX8jjfEyMVnOISijoibvbv0N5xDI+Oh/doYU96ukC1SuIAcQAECtbwNq/RZwcHDgoscWFD1MKyVLfrlZmFhFXnBVwrrQtRkYIv3VnQWsh+qM5QobEDjfrGnrA4qemzLv7dIXEBQ9r3iFtV9h5lQOSsFgDcL7ZHKF2gaKTLvaE0WmBdSeKDItoPa0KTJRe7aP0Nu3qcbJ/eB3ZKrfTkD4TrTba3ruGUOtLwQY+AAbtf70CYsxrD7hRqV+SxontvWPwCGwUVRz85HnHecQqPtL35+Yi4/XSRdou4gcQAAAtb4tXOu3goODAxc9LVQkLZQs2fVm4XUJ+W59pwPC/oeFC6S/urOA9VCdUd1hAwLnS3ltfcCvKMv8CC+xMCIoekJYcmFgpAhB5eDzSGQAwqphfKC2gSLTrvZEkWkBtSeKTAuoPW2KTNSe7SP14EG2cXL/9Tcy1W9HIXwm2u0FPffPotYXAgx8gI1av++0xfhXfcKNSv2yNE6H9Y/AIbBRJebMPf9HziFQZt77H+ZipUy6QOEqcgABANT6NqDWB/Q/YZc7Ll94G0kAAAAASUVORK5CYII=';
	var _ERROR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAAAAABWESUoAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAEQHIkixAAABv0lEQVQYGWXBQWcjcRzH4d+L+xpDRVRYETGXqt5W9FI9xFIVvfae64i11IgosfoGeqtaZawcwlgrlxE1Qvx99j+zk5lUn8fU6N48pmtc+vpwrZapNkgKGtvFUDVTJYgdH+xnJ6qYStEbn6wGKpm8wYZSHl+fS9Hl9w2l7bk8k9TP8HZ3oQ4mG7w8kmRSuKIyU6uzxHsLJZOm1CY6kuDFkqlfAE9vwH6kI0vADWRaAH86/Q2QR2p1MiCRdQrgVrrYAauuWjdAcWoTIAskjfGeAzWCDBjbHJipNMWbqxUDc/sFjFRZ4t2rMQJSy4EvqoQvgLvSQQ/IbQ8u0H+9DHg/Uy1w4MyBC1Q7eweynmp72FsO9HRw5YCXUJUusLUUGKlxj/dTlRGQ2hyI1UrwpirNgIWNgXWgRvCMN5a3BiZ2WgDf1OqugN2FNAaKjikBso5aUQ5s+p01sJBp4IBHHfm6B9InoOjLpBjvQUcm1KaSSWGKtzxRa0ZlFUomKcrx1mMdhHc7vKwvyeRdbCn9jS+H0vl1nFPaDOWZStGaT35HKpkqJz8cH7g4VMVUGz4WNHbJUDVTo3uTvKaOLF3enqrxD+aQUnwgKhDtAAAAAElFTkSuQmCC';
	var base64Test = new Image();
	var BASE64FLAG = true;
	base64Test.onerror = function(){
		if(this.width != 1 || this.height != 1){
			BASE64FLAG = false;
		}
	}
	base64Test.src = _ERROR;

	function doFotorama(fotorama, o) {
		fotorama.data({ini: true});

		var fotoramaState;

		var timestamp = new Date().getTime();

		/*$('a', fotorama).live('click', function(e){
			e.preventDefault();
		});*/

		// Все изображения
		var img;
		var dataFLAG = o.data && typeof(o.data) == 'object';
		if (!dataFLAG) {
			img = fotorama.find('a').filter(function(){
				var thisChild = $(this);
				return ((thisChild.is('a') && thisChild.children('img').size()) || thisChild.is('img')) && (thisChild.attr('href') || thisChild.attr('src') || thisChild.children().attr('src'));
			});
		} else {
			img = $(o.data).filter(function(){
				return this.img;
			});
		}
		var size = img.size();

		fotorama.data({size: size});
		if (o.startImg > size - 1 || typeof(o.startImg) != 'number') {
			o.startImg = 0
		}
	//	img.each(function(i){
	//		alert($(this).attr('href'));
	//	});
		
	//	alert(fotorama.find('a').get(0).tagName);
		
		var src = [];
		img.each(function(i){
			if (!dataFLAG) {
				var thisImg = $(this);
				src[i] = {imgHref: thisImg.attr('href'), imgSrc: thisImg.attr('src'), thumbSrc: thisImg.children().attr('src')};
				if (o.caption) {
				this.caption = thisImg.attr('alt') || thisImg.children().attr('alt');
				}
			} else {
				src[i] = {imgHref: this.img, thumbSrc: this.thumb};
			}		
		}); 


		// Очищаем DOM, присваиваем классы
		fotorama.html('').addClass(F + ' ' + (o.vertical ? F + '_vertical' : F +'_horizontal'));

		if (o.touchStyle) {
			o.loop = false;
		} else if (!o.arrows) {
			o.loop = true;
		}

		var srcState = [];

		var wrapSize, wrapSize2;
		var wrapWidth = o.width;
		var wrapHeight = o.height;
		var wrapRatio, wrapRatioIdeal, wrapRatioForced;
		var wrapWidthLast, wrapHeightLast, wrapRatioLast;
		var wrapIsSetFLAG = false;
		var wrapSizeFromFirstFLAG;
		var forcedRatioFLAG = false;
		var loadTimeout;
		/*var stopRescaleFLAG = false;*/

		var animatingFLAG = false, setAnimatingFLAG;

		if (o.touchStyle) {
			var shaftSize = 0,
				shaftSize2;

			var shaftGrabbingFLAG = false;
			var shaftMouseDownFLAG = false;
			var setShaftGrabbingFLAGTimeout;
		}

		if (o.thumbs && o.thumbsPreview) {
			var thumbsShaftMouseDownFLAG = false;
			var thumbsShaftDraggedFLAG = false;
			var thumbsShaftJerkFLAG = false;
			var thumbsShaftGrabbingFLAG = false;
			var setThumbsShaftGrabbingFLAGTimeout;
			var thumbsReadyFLAG = false;
			var thumbsReadySize = 0;
		}


		var _pos, _pos2, _coo, _coo2, _size, _size2;
			if (!o.vertical) {
				_pos = 'left';
				_pos2 = 'top';
				_coo = 'pageX';
				_coo2 = 'pageY';
				_size = 'width';
				_size2 = 'height';
			} else {
				_pos = 'top';
				_pos2 = 'left';
				_coo = 'pageY';
				_coo2 = 'pageX';
				_size = 'height';
				_size2 = 'width';
			}

		var wrap = $('<div class="'+F+'__wrap"></div>').appendTo(fotorama);
		var shaft = $('<div class="'+F+'__shaft"></div>').appendTo(wrap);

		// Запрещаем выделять фотораму
		if (!o.touchStyle) {
			disableSelection(wrap);
			disableSelection(shaft);
		}

		var stateIcon = $('<div class="'+F+'__state"></div>').appendTo(shaft);
		var stateIconSpinnerInterval;
		var stateIconSpinnerIntervalI = 0;
		var stateIconPositionTimeout;

		function stateIconSpinner() {
			stateIcon.css({backgroundPosition: '24px ' + (24 - 56*stateIconSpinnerIntervalI) + 'px'});
			stateIconSpinnerIntervalI++;
			if (stateIconSpinnerIntervalI > 7) stateIconSpinnerIntervalI = 0;
		}

		if (touchFLAG) {
			fotorama.addClass(F+'_touch');
			o.shadows = false;
		}
		if (o.touchStyle) {
			wrap.addClass(F+'__wrap_style_touch');
			if (o.shadows) {
				wrap.append('<i class="'+F+'__shadow '+F+'__shadow_prev"></i><i class="'+F+'__shadow '+F+'__shadow_next"></i>');
			}
		} else {
			wrap.addClass(F+'__wrap_style_fade');
		}

		if (csstrFLAG) {
			fotorama.addClass(F+'_csstransitions');
		}

		if (o.arrows) {
			var _arrPrev, _arrNext;
			if (!o.vertical) {
				_arrPrev = o.arrowPrev ? o.arrowPrev : '&#9668;';
				_arrNext = o.arrowNext ? o.arrowNext : '&#9658;';
			} else {
				_arrPrev = o.arrowPrev ? o.arrowPrev : '&#9650;';
				_arrNext = o.arrowNext ? o.arrowNext : '&#9660;';
			}

			var arrs = $('<i class="'+F+'__arr '+F+'__arr_prev">'+_arrPrev+'</i><i class="'+F+'__arr '+F+'__arr_next">'+_arrNext+'</i>').appendTo(wrap);
			var arrPrev = arrs.eq(0);
			var arrNext = arrs.eq(1);

			if (!touchFLAG) {
				if ((o.touchStyle && o.pseudoClick && o.arrows) || (!o.touchStyle && o.arrows)) {
					var wrapMouseCoo, wrapMouseMoveTimeout;
					function hiliteArrs() {
						clearTimeout(wrapMouseMoveTimeout);
						wrapMouseMoveTimeout = setTimeout(function(){
							var forwardFLAG = wrapMouseCoo >= wrapSize/2;
							//if (forwardFLAG != forwardFLAGLast) {
								arrNext[!forwardFLAG ? 'removeClass' : 'addClass'](F+'__arr_hover');
								arrPrev[forwardFLAG ? 'removeClass' : 'addClass'](F+'__arr_hover');

								if (!o.touchStyle) {
									shaft.css({cursor: (forwardFLAG && arrNext.data('disabled')) || (!forwardFLAG && arrPrev.data('disabled')) ? 'default' : ''});
								}
						}, 10);
					}

					wrap.mousemove(function(e){
						wrapMouseCoo = e[_coo] - wrap.offset()[_pos];
						hiliteArrs();
					});
				}
				
				// Стрелочки при наведении на фотораму
				var wrapEnteredFLAG = false;
				var wrapLeaveTimeout;
				function wrapEnter() {
					wrapEnteredFLAG = true;
					clearTimeout(wrapLeaveTimeout);
					arrs.css(getDuration(0));
					wrap.removeClass(F+'__wrap_mouseout');
					setTimeout(function(){
						arrs.css(getDuration(o.transitionDuration));
						setTimeout(function(){
							wrap.addClass(F+'__wrap_mouseover');
						},1);
					},1);
				}
				function wrapLeave() {
					clearTimeout(wrapLeaveTimeout);
					wrapLeaveTimeout = setTimeout(function(){
						if (!shaftGrabbingFLAG && !wrapEnteredFLAG) {
							wrap
									.removeClass(F+'__wrap_mouseover')
									.addClass(F+'__wrap_mouseout');
						}
					}, o.transitionDuration*3);
				}
				wrap.mouseenter(function(){
					wrapEnter();
				});
				wrap.mouseleave(function(){
					wrapEnteredFLAG = false;
					wrapLeave();
				});
			}
		}

		var activeImg, activeIndex;

		var imgFrame = $();
		img.each(function(i){
			// Заготавливаем фреймы под фотки
			var _imgFrame = $('<div class="'+F+'__frame" style="visibility: hidden;"></div>');
			imgFrame = imgFrame.add(_imgFrame);
		});

		if (o.thumbs) {
			var o__thumbSize = o.thumbSize;
			if (!o__thumbSize) {
				o__thumbSize = o.vertical ? 64 : 48;
			}
			// Если тумбсы или превьюшки
			var activeThumb;
			var activeThumbPrevIndex = 0;
			// Контейнер для тумбсов-переключалок
			var thumbs = $('<div class="'+F+'__thumbs" style="visibility: hidden;"></div>')[o.thumbsTop ? 'prependTo': 'appendTo'](fotorama);
			var thumbsSize2;

			if (o.thumbsPreview) {
				thumbsSize2 = o__thumbSize + o.thumbMargin*2;
				thumbs
						.addClass(F+'__thumbs_previews')
						.css(_size2, thumbsSize2);
			}

			var thumbsShaft = $('<div class="'+F+'__thumbs-shaft"></div>').appendTo(thumbs);
			if (o.thumbsPreview) {
				var thumbsShaftSize = 0;
				var thumbsShaftPos = undefined;
				if (o.shadows) {
					$('<i class="'+F+'__shadow '+F+'__shadow_prev"></i><i class="'+F+'__shadow '+F+'__shadow_next"></i>').appendTo(thumbs);
				}

				var thumbBorderSize2 = o__thumbSize - (quirksFLAG ? 0 : o.thumbBorderWidth*2);
				var thumbBorderPos2 = o.thumbMargin;
				var _css = {};
				_css[_size2] = thumbBorderSize2;
				_css[_pos2] = thumbBorderPos2;
				_css.borderWidth = o.thumbBorderWidth;
				var thumbBorder = $('<i class="'+F+'__thumb-border"></i>').hide().css(_css).appendTo(thumbsShaft);
			}

			// Создаём точки и превьюшки
			img.each(function(i){
				// Одна точка-переключалка
				var _thumb;
				if (o.thumbsPreview) {
					_thumb = $('<div class="'+F+'__thumb"></div>');
					var _css = {};
					_css[_size2] = o__thumbSize;
					_css.margin = o.thumbMargin;
					_thumb.css(_css);
				} else {
					_thumb = $('<i class="'+F+'__thumb"><i class="'+F+'__thumb__dot"></i></i>');
				}
				_thumb.appendTo(thumbsShaft);
			});

			var thumb = $('.'+F+'__thumb', fotorama);

			if (o.thumbsPreview) {
				// Загружаем превьюшки
				function thumbOnLoad(thisThumbNew, thumbWidth, thumbHeight, thumbRatio, srcKey, i) {
					var $thisThumbNew = $(thisThumbNew);
					// Одна точка-переключалка на загрузке
					var _thumbSize = o.vertical ? Math.round(o__thumbSize / thumbRatio * 1000) : Math.round(o__thumbSize * thumbRatio / 1000);

					if (Mdrnzr.canvas) {
						$thisThumbNew.remove();
						$thisThumbNew = $('<canvas class="'+F+'__thumb__img"></canvas>');
						$thisThumbNew.appendTo(thumb.eq(i));
					} else {
						$thisThumbNew.addClass(F+'__thumb__img');
					}

					var _css = {};
					_css[_size] = _thumbSize;
					_css[_size2] = o__thumbSize;
					$thisThumbNew.attr(_css).css(_css).css({visibility: 'visible'});

					if (Mdrnzr.canvas) {
						var ctx = $thisThumbNew[0].getContext('2d');
						$thisThumbNew[0].getContext('2d').drawImage(thisThumbNew, 0, 0, o.vertical ? o__thumbSize : _thumbSize, o.vertical ? _thumbSize : o__thumbSize);
					}

					thumbsShaftSize += _thumbSize + o.thumbMargin - (o__thumbSize + o.thumbMargin);
					thumbsShaft.css(_size, thumbsShaftSize);
					_css[_size2] = null;
					thumb.eq(i).css(_css).data(_css);

					setThumbsShaft();
				}

				function loadThumb(i) {
					if (!thumbsShaftGrabbingFLAG && !thumbsShaftMouseDownFLAG && !shaftMouseDownFLAG && !animatingFLAG) {
						if (!i) i = 0;
						loadImg(i, thumb.eq(i), thumbOnLoad, 'thumb');

						// Если включены превьюшки, придётся загружать все картинки разом
						// Будем делать это порциями по 20 в секунду
						setTimeout(function(){
							if (i+1 < size) {
								loadThumb(i+1);
							}
						}, 50);
					} else {
						setTimeout(function(){
							loadThumb(i);
						},100);
					}
				}
			}

		}

		if (o.caption) {
			var caption = $('<p class="'+F+'__caption"></p>');
			caption.appendTo(fotorama);
		}

		function getRatioWidthHeight() {
			if (!wrapRatio) {
				wrapRatio = wrapWidth / wrapHeight * 1000;
				wrapRatioIdeal = wrapRatio;
				wrapRatioForced = wrapRatio;
			}
			if (o.thumbs && !thumbsSize2) {
				thumbsSize2 = o.vertical ? thumbs.width() : thumbs.height();
			}
			////if (o.resize) {

			if (!forcedRatioFLAG) {
				wrapRatio = wrapRatioIdeal;
			} else {
				wrapRatio = wrapRatioForced;
			}

			if (o.resize) {
				wrapWidth = fotorama.width() - (o.vertical && thumbsSize2  ? thumbsSize2 : 0);
			}

			wrapHeight = Math.round(wrapWidth / wrapRatio * 1000);

			if (o.fitToWindowHeight) {
				var windowHeight = $window.height();
				if (wrapHeight > windowHeight - 20 - (!o.vertical && thumbsSize2 ? thumbsSize2 : 0)) {
					wrapHeight = windowHeight - 20 - (!o.vertical && thumbsSize2 ? thumbsSize2 : 0);
					wrapRatio = wrapWidth / wrapHeight * 1000;
				}
			}
			////}
		}

		var resizeStack = [];

		function setFotoramaSize(forceResize) {
			//if (wrapWidth && wrapHeight && (!wrapIsSetFLAG || forceResize)) {
				//if (!forceRatioWidthHeight) {
					getRatioWidthHeight();
				//}

				var needToResizeFLAG = forceResize || wrapWidth != wrapWidthLast || wrapHeight != wrapHeightLast || wrapRatio != wrapRatioLast;

				//console.log('needToResizeFLAG', needToResizeFLAG);

				if (needToResizeFLAG) {
					//console.log('Resize!!!');

					if (!o.vertical) {
						wrapSize = wrapWidth;
						wrapSize2 = wrapHeight;
					} else {
						wrapSize = wrapHeight;
						wrapSize2 = wrapWidth;
					}

					wrap.add(imgFrame).css({width: wrapWidth, height: wrapHeight});

					if (o.vertical && o.thumbs) {
						if (!o.verticalThumbsRight) {
							wrap.css({left: thumbsSize2});
						} else {
							thumbs.css({left: wrapWidth});
						}
					}

					if (!o.touchStyle) {
						shaft.css({width: wrapWidth, height: wrapHeight});
					} else {
						shaftSize = (wrapSize+o.margin)*size - o.margin;
						shaftSize2 = wrapSize2;

						var _css = {};
						_css[_size] = shaftSize;
						_css[_size2] = shaftSize2;
						shaft.css(_css).data(_css).data({minPos: -(shaftSize - wrapSize), maxPos: 0});
					}
					if (o.thumbs) {
						if (o.thumbsPreview || !o.vertical) {
							thumbs.css(_size, wrapSize);
						}
						thumbs.css({visibility: 'visible'});
					}

					if (ieFLAG && !o.vertical) {
						if (o.arrows) {
							arrs.css({top: wrapHeight / 2});
						}

						stateIcon.css(_pos2, wrapSize2 / 2);
					}

					if (fotoramaState == 'loading' || fotoramaState == 'error') {
						stateIcon.css(_pos, activeIndex*(wrapSize+o.margin)+wrapSize/2);
					}

					setThumbsShaft();

					if (activeImg) {
						if (o.touchStyle) {
							var pos = -activeIndex*(wrapSize+o.margin);
							animate(shaft, pos, 0);
						}
					}

					wrapIsSetFLAG = true;

					//if (forceResize) {
						//console.log('setImgSize from setFotoramaSize', activeImg, activeIndex);
						setImgSize(activeImg, activeIndex);
						var interval = 0;
						$(resizeStack).each(function(){
							clearTimeout(this);
						});
						resizeStack = [];
						imgFrame.each(function(i){
							if (i != activeIndex) {
								var thisImgFrame = $(this);
								var thisImg = thisImgFrame.data('img');
								if (thisImg) {
									thisImgFrame.data('img').css({visibility: 'hidden'});
								}

								//Ресайзим порциями, чтобы не падали слабенькие Айпады
								var timeout = setTimeout(function() {
									////console.log(i);
									setImgSize(thisImgFrame, i);
								}, interval*50+50);
								resizeStack.push(timeout);
								interval++;
							}
						});
					//}
				}
			//}

			wrapWidthLast = wrapWidth;
			wrapHeightLast = wrapHeight;
			wrapRatioLast = wrapRatio;
		}

		function setFotoramaState(state, index, time) {
			clearTimeout(stateIconPositionTimeout);
			function stateIconPosition() {
				//if (wrapIsSetFLAG) {
					if (!o.touchStyle) {
						index = 0;
					}
					stateIcon.css(_pos, index*(wrapSize+o.margin)+wrapSize/2);
					stateIconPositionTimeout = setTimeout(function(){
						stateIcon.stop().show().fadeTo(0,1);
					},100);
				//}
			}
			switch (state) {
				case 'loading':
					stateIconPosition();
					fotorama.addClass(F+'_loading').removeClass(F+'_error');
					clearInterval(stateIconSpinnerInterval);
					if (BASE64FLAG) {
						stateIcon.css({backgroundImage: 'url('+_SPINNER+')'});
						stateIconSpinnerInterval = setInterval(stateIconSpinner,100);
					} else {
						stateIcon.html('<span>&middot;&middot;&middot;</span>');
					}

				break;
				case 'error':
					stateIconPosition();
					fotorama.addClass(F+'_error').removeClass(F+'_loading');
					clearInterval(stateIconSpinnerInterval);
					if (BASE64FLAG) {
						stateIcon.css({backgroundImage: 'url('+_ERROR+')', backgroundPosition: '24px 24px'});
					} else {
						stateIcon.text('?');
					}
				break;
				case 'loaded':
					fotorama.removeClass(F+'_loading '+F+'_error');
					stateIcon.stop().fadeTo(time,0,function(){
						stateIcon.hide();
					});
					clearInterval(stateIconSpinnerInterval);
				break;
			}
			fotoramaState = state;
		}

		function clearBackAnimate(block) {
			clearTimeout(block.data('backAnimate'));
		}

		function animate(block, pos, time, overPos) {
			var POS = isNaN(pos) ? 0 : pos;
			clearBackAnimate(block);
			if (overPos) {
				POS = overPos;
				block.data({
					backAnimate: setTimeout(function(){
						animate(block, pos, Math.max(o__transitionDuration, time/2));
					}, time)
				});
			}


			if (time) {
				clearTimeout(setAnimatingFLAG);
				animatingFLAG = true;
			}
			if (csstrFLAG) {
				block.css(getDuration(time));
				setTimeout(function() {
					block.css(getTranslate(POS, o.vertical));
				}, 1);
			} else {
				block.stop().animate(getTranslate(POS, o.vertical), time, o__bez);
			}

			setAnimatingFLAG = setTimeout(function(){
				animatingFLAG = false;
			},time);
		}

		// Прокручиваем ленту превьюшек
		function slideThumbsShaft(time, x, auto) {
			if (thumbsShaftSize) {
				if (!auto || thumbsShaftSize < wrapSize) {
					thumbsShaftDraggedFLAG = false;
				}

				var thumbPos = activeThumb.position()[_pos];
				var thumbSize = activeThumb.data()[_size];
				if (!thumbSize) {
					thumbBorder.hide();
				} else {
					thumbBorder.show();
					if (thumbsShaftSize > wrapSize) {
						var thumbCenter = thumbPos + thumbSize / 2;
						var thumbPlace = wrapSize / 2;
						var index = thumb.index(activeThumb);
						var direction = index - activeThumbPrevIndex;
						if (thumbsShaftPos == undefined) {
							thumbsShaftPos = thumbsShaft.position()[_pos];
						}
						if (thumbsReadyFLAG && x && x > Math.max(36, o.thumbMargin*2) && x < wrapSize - Math.max(36, o.thumbMargin*2) && ((direction > 0 && x > thumbPlace * .75) || (direction < 0 && x < thumbPlace * 1.25))) {
							var i;
							if (direction > 0) {
								i = index + 1;
							} else {
								i = index - 1;
							}
							if (i < 0) {
								i = 0;
							} else if (i > size - 1) {
								i = size - 1;
							}
							if (index != i) {
								var nextThumb = thumb.eq(i);
								thumbCenter = nextThumb.position()[_pos] + nextThumb.data()[_size] / 2;
								thumbPlace = x;
							}
						}
						var minPos = -(thumbsShaftSize-wrapSize);
						var newPos = Math.round(-(thumbCenter - thumbPlace) + o.thumbMargin);

						if ((direction > 0 && newPos > thumbsShaftPos) || (direction < 0 && newPos < thumbsShaftPos)) {
							if (thumbPos + thumbsShaftPos < o.thumbMargin) {
								newPos = -(thumbPos - o.thumbMargin);
							} else if(thumbPos + thumbsShaftPos + thumbSize > wrapSize) {
								newPos = -(thumbPos*2 - wrapSize + thumbSize + o.thumbMargin);
							} else {
								newPos = thumbsShaftPos;
							}
						}

						if (newPos <= minPos) {
							newPos = minPos;
						} else if (newPos >= o.thumbMargin) {
							newPos = o.thumbMargin;
						}
						thumbsShaft.data({minPos: minPos});
						setThumbsShadow(newPos);

						if (!thumbsShaftMouseDownFLAG) {
							thumbsShaft.data({maxPos: o.thumbMargin});
						}
					} else {
						newPos = wrapSize/2 - thumbsShaftSize/2;
						thumbsShaft.data({minPos: newPos});
						if (!thumbsShaftMouseDownFLAG) {
							thumbsShaft.data({maxPos: newPos});
						}
					}

					if (!thumbsShaftDraggedFLAG && !thumbsShaftMouseDownFLAG) {
						animate(thumbsShaft, newPos, time);
						if (thumbsShaftJerkFLAG) {
							thumbsShaftDraggedFLAG = true;
						}
						thumbsShaftPos = newPos;
					} else {
						thumbsShaftJerkFLAG = true;
					}

					var thumbBorderSize = thumbSize - (quirksFLAG ? 0 : o.thumbBorderWidth*2);
					var thumbBorderPos = thumbPos;

					if (csstrFLAG) {
						thumbBorder.css(getDuration(time));
						setTimeout(function(){
							thumbBorder
									.css(getTranslate(thumbBorderPos, o.vertical))
									.css(_size, thumbBorderSize);
						},1);
					} else {
						if (!o.vertical) {
							thumbBorder.stop().animate({left: thumbBorderPos, width: thumbBorderSize}, time, o__bez);
						} else {
							thumbBorder.stop().animate({top: thumbBorderPos, height: thumbBorderSize}, time, o__bez);
						}
					}
				}
			}
		}

		function setThumbsShadow(pos) {
			if (o.shadows) {
				if (thumbsShaftSize > wrapSize) {
					// TODO: Тут могут возникнуть проблемы если превьюшек мало, но их дотащить до края (тени не будет, а должна). Передумать.
					thumbs.addClass(F+'__thumbs_shadow');
					if (pos <= thumbsShaft.data('minPos')) {
						thumbs.removeClass(F+'__thumbs_shadow_no-left').addClass(F+'__thumbs_shadow_no-right');
					} else if (pos >= o.thumbMargin) {
						thumbs.removeClass(F+'__thumbs_shadow_no-right').addClass(F+'__thumbs_shadow_no-left');
					} else {
						thumbs.removeClass(F+'__thumbs_shadow_no-left '+F+'__thumbs_shadow_no-right');
					}
				}
			}
		}

		function setThumbsShaft() {
			if (!thumbsShaftGrabbingFLAG && !thumbsShaftMouseDownFLAG && !shaftMouseDownFLAG && !animatingFLAG) {
				setThumbsShadow();
				slideThumbsShaft(0, false, true);
			}
		}

		function setImgSize(thisImgFrame, index) {
			//if (!index) index = imgFrame.index(thisImgFrame);
			var thisImg = thisImgFrame.data('img');
			////console.log(thisImg, index);
			var detachedFLAG = thisImgFrame.data('detached');
			//console.log('setImgSize in', index, thisImg, detachedFLAG);
			if (thisImg && !detachedFLAG) {
				//console.log('setImgSize work', index);
				var srcKey = thisImgFrame.data('srcKey');
				var thisImgWidth = src[srcKey].imgWidth;
				var thisImgHeight = src[srcKey].imgHeight;
				var thisImgRatio = src[srcKey].imgRatio;

				var thisImgTop = 0, thisImgLeft = 0;
				if (o.touchStyle) {
					thisImgFrame.css(_pos, index * (wrapSize + o.margin));
				}

				if (thisImgWidth != wrapWidth || thisImgHeight != wrapHeight || o.alwaysPadding) {
					var minPadding = 0;
					if (Math.round(thisImgRatio) != Math.round(wrapRatio) || o.alwaysPadding) {
						minPadding = o.minPadding * 2;
					}

					if (thisImgRatio >= wrapRatio) {
						if (!o.cropToFit) {
							thisImgWidth = Math.round(wrapWidth - minPadding) < thisImgWidth || o.zoomToFit ? Math.round(wrapWidth - minPadding) : thisImgWidth;
							thisImgHeight = Math.round((thisImgWidth) / thisImgRatio * 1000);
						} else {
							thisImgHeight = wrapHeight;
							thisImgWidth = Math.round((thisImgHeight) * thisImgRatio / 1000);
						}

					} else {
						if (!o.cropToFit) {
							thisImgHeight = Math.round(wrapHeight - minPadding) < thisImgHeight || o.zoomToFit ? Math.round(wrapHeight - minPadding) : thisImgHeight;
							thisImgWidth = Math.round((thisImgHeight) * thisImgRatio / 1000);
						} else {
							thisImgWidth = wrapWidth;
							thisImgHeight = Math.round((thisImgWidth) / thisImgRatio * 1000);
						}

					}
				}

				thisImg.css({visibility: 'visible'});

				if (thisImgWidth && thisImgHeight) {
					var _css = {width: thisImgWidth, height: thisImgHeight};
					thisImg.attr(_css).css(_css);

					if (thisImgHeight != wrapHeight) {
						thisImgTop = Math.round((wrapHeight - thisImgHeight) / 2);
					}
					if (thisImgWidth != wrapWidth) {
						thisImgLeft = Math.round((wrapWidth - thisImgWidth) / 2);
					}
					thisImg.css({top: thisImgTop, left: thisImgLeft});
				}
			} else if (thisImg && detachedFLAG) {
				//console.log('set needToResize FLAG', index);
				thisImgFrame.data({needToResize: true});
			}
		}

		function loadImg(index, container, callback, type) {
			var thisImgFrame = imgFrame.eq(index);
			var thisImgNew = new Image();
			var $thisImgNew = $(thisImgNew);
			var _src = [];
			var _srcI = 0;
			var imgHref = src[index].imgHref;
			var imgSrc = src[index].imgSrc;
			var thumbSrc = src[index].thumbSrc;
			if (type == 'img') {
				if (imgHref) {
					_src.push(imgHref);
					_src.push(imgHref + '?' + timestamp);
				}
				if (imgSrc) {
					_src.push(imgSrc);
					_src.push(imgSrc + '?' + timestamp);
				}
				if (thumbSrc) {
					_src.push(thumbSrc);
					_src.push(thumbSrc + '?' + timestamp);
				}
			} else {
				if (thumbSrc) {
					_src.push(thumbSrc);
					_src.push(thumbSrc + '?' + timestamp);
				}
				if (imgSrc) {
					_src.push(imgSrc);
					_src.push(imgSrc + '?' + timestamp);
				}
				if (imgHref) {
					_src.push(imgHref);
					_src.push(imgHref + '?' + timestamp);
				}
			}

			function loadScope(imgSrc) {
				function loadStart() {
					$thisImgNew.css({visibility: 'hidden'});
					thisImgNew.src = imgSrc;

					if (_srcI == 0) {
						$thisImgNew.appendTo(container);

						if (type == 'thumb') {
							thumbsShaftSize += o__thumbSize + o.thumbMargin;
							thumbsShaft.css(_size, thumbsShaftSize).data(_size, thumbsShaftSize);
							container.css(_size, o__thumbSize).data(_size, o__thumbSize);
						}
					}
				}
				function plusThumb() {
					thumbsReadySize++;
					if (thumbsReadySize == size) {
						thumbsReadyFLAG = true;
					}
				}
				function loadFinish() {
					srcState[imgSrc] = 'loaded';
					container.trigger('load.'+F).data({state: 'loaded'});

					setTimeout(function(){
						if (!src[imgSrc]) {
							src[imgSrc] = [];
							src[imgSrc].imgWidth = $thisImgNew.width();
							src[imgSrc].imgHeight = $thisImgNew.height();
							src[imgSrc].imgRatio = src[imgSrc].imgWidth / src[imgSrc].imgHeight * 1000;
						}

						callback(thisImgNew, src[imgSrc].imgWidth, src[imgSrc].imgHeight, src[imgSrc].imgRatio, imgSrc, index);
					}, 100);
					if (type == 'thumb') {
						plusThumb();
					}
				}
				function loadError(primary) {
					srcState[imgSrc] = 'error';
					$thisImgNew.unbind('error load');
					if (_srcI < _src.length && primary) {
						loadScope(_src[_srcI]);
						_srcI++;
					} else {
						container.trigger('error.'+F).data({state: 'error'});
						if (type == 'thumb') {
							plusThumb();
						}
					}
				}
				if (!srcState[imgSrc]) {
					srcState[imgSrc] = 'loading';
					thisImgFrame.data({loading: true});
					$thisImgNew
							.unbind('error load')
							.error(function(){
								loadError(true);
							})
							.load(loadFinish);
					loadStart();
				} else {
					function justWait() {
						if (srcState[imgSrc] == 'error') {
							loadError(false);
						} else if (srcState[imgSrc] == 'loaded') {
							loadFinish();
						} else {
							setTimeout(justWait, 100);
						}
					}
					loadStart();
					justWait();
				}
			}


			loadScope(_src[_srcI]);
			_srcI++;
		}

		// Загружаем, отрисовываем
		function loadDraw(newImg, index) {
			//if (!index) index = imgFrame.index(newImg);
			if (!newImg.data('wraped')) {
				shaft.append(newImg);

				function onLoad(thisImgNew, imgWidth, imgHeight, imgRatio, srcKey) {
					var $thisImgNew = $(thisImgNew);

					$thisImgNew.addClass(F+'__img');
					newImg.data({img: $thisImgNew, srcKey: srcKey});
					//console.log($thisImgNew, newImg.data('img'), index);

					var justSetWrapSizeFLAG = false;

					if (((!wrapWidth || !wrapHeight) && !wrapIsSetFLAG) || (!wrapSizeFromFirstFLAG && index == 0)) {
						//Задаём размер всей Фотораме по первой загруженной картинке, если он не задан в опциях
						//console.log('Задаём размер всей Фотораме по первой загруженной картинке');
						wrapWidth = imgWidth;
						wrapHeight = imgHeight;
						justSetWrapSizeFLAG = true;
						wrapSizeFromFirstFLAG = index == 0;
						//getRatioWidthHeight();
					}

					newImg.css({visibility: 'visible'});
					if (justSetWrapSizeFLAG) {
						//console.log('setFotoramaSize', index);
						setFotoramaSize(wrapSizeFromFirstFLAG);
					} else {
						//console.log('setImgSize', index);
						setImgSize(newImg, index);
					}

				}

				newImg.data({wraped: true, detached: false});

				loadImg(index, newImg, onLoad, 'img');

				if ((dataFLAG && img[index].html && img[index].html.length) || (o.html && o.html[index] && o.html[index].length)) {
					var html = img[index].html || o.html[index];
					newImg.append(html);
				}
			} else if (o.detachSiblings && newImg.data('detached')) {
				newImg.data({detached: false}).appendTo(shaft);
				if (newImg.data('needToResize')) {
					//console.log('needToResize', index);
					setImgSize(newImg, index);
					newImg.data({needToResize: false});
				}
			}
		}

		function preloadSiblings(newImg, index) {
			//if (!index) index = imgFrame.index(newImg);
			var sizeToLoad = 0;
			var limitFLAG = false;
			var indexNew = [];
			for (i=0;i<o.preload*2+1;i++) {
				var _indexNew = index - o.preload + i;
				if (_indexNew >= 0 && _indexNew < size) {
					if (!imgFrame.eq(_indexNew).data('wraped') || imgFrame.eq(_indexNew).data('detached')) {
						sizeToLoad++;
						indexNew.push(_indexNew);
					}
				} else {
					limitFLAG = true;
				}
			}

			if (sizeToLoad >= o.preload || limitFLAG) {
				$(indexNew).each(function(i){
					// Порциями опять же
					var interval = i*50;
					setTimeout(function(){
						loadDraw(imgFrame.eq(indexNew[i]), indexNew[i]);
					},interval);
				});

				if (o.detachSiblings) {
					var leftEdge = index - o.preload;
					if (leftEdge < 0) leftEdge = 0;
					var rightEdge = index + o.preload + 1;
					if (rightEdge > size - 1) rightEdge = size - 1;
					imgFrame.slice(0,leftEdge).add(imgFrame.slice(rightEdge, size - 1)).data({detached: true}).detach();
				}
			}
		}

		function setArrows() {
			if ((activeIndex == 0 || size < 2) && !o.loop) {
				arrPrev.addClass(F+'__arr_disabled').data('disabled', true);
			} else {
				arrPrev.removeClass(F+'__arr_disabled').data('disabled', false);
			}
			if ((activeIndex == size - 1 || size < 2) && !o.loop) {
				arrNext.addClass(F+'__arr_disabled').data('disabled', true);
			} else {
				arrNext.removeClass(F+'__arr_disabled').data('disabled', false);
			}
		}

		// Показываем картинки, выделяем тумбсы
		function showImg(newImg, e, x, reset, time, overPos) {
			var prevActiveImg, prevActiveThumb;
			var captionText;
			var prevIndex;
			var newIndex = imgFrame.index(newImg);

			imgFrame.each(function(){
				$(this).unbind('load.'+F+' error.'+F);
			});


			if (!time) {
				if (reset) {
					time = 0;
				} else {
					time = o.transitionDuration;
				}
			}

			if (!reset && e && e.altKey) {
				time = time*10;
			}

			function setCaption() {
				if (o.caption) {
					captionText = img[newIndex].caption;
					if (captionText) {
						caption.html(captionText).show();
					} else {
						caption.html('').hide();
					}
				}
			}

			var state = newImg.data('state');
			if (state == 'loading' || !state) {
				setFotoramaState('loading', newIndex, time);

				newImg.one('load.'+F, function(){
					setFotoramaState('loaded', newIndex, time);
					setCaption();
				});
				newImg.one('error.'+F, function(){
					setFotoramaState('error', newIndex, time);
					setCaption();
				});
			} else if (state == 'error') {
				setFotoramaState('error', newIndex, time);
			} else if (state != fotoramaState) {
				setFotoramaState('loaded', newIndex, 0);
			}
			setCaption();

			if (activeImg) {
				prevActiveImg = activeImg;
				prevIndex = activeIndex;
				if (o.thumbs) {
					prevActiveThumb = activeThumb;
				}
			} else {
				prevActiveImg = imgFrame.not(newImg);
				if (o.thumbs) {
					prevActiveThumb = thumb.not(thumb.eq(newIndex));
				}
			}
			if (o.thumbs) {
				activeThumb = thumb.eq(newIndex);
				if (prevIndex) {
					activeThumbPrevIndex = prevIndex;
				}
				prevActiveThumb
						.removeClass(F+'__thumb_selected')
						.data('disabled', false);
				activeThumb
						.addClass(F+'__thumb_selected')
						.data('disabled', true);
			}

			function setActiveClass() {
				if (o.shadows || !o.touchStyle) {
					prevActiveImg.removeClass(F+'__frame_active');
					newImg.addClass(F+'__frame_active');
				}
			}

			if (o.thumbs && o.thumbsPreview && (prevIndex != newIndex)) {
				slideThumbsShaft(time, x);
			}

			if (o.touchStyle) {
				var pos = -newIndex*(wrapSize+o.margin);
				setActiveClass();
				animate(shaft, pos, time, overPos);
			} else {
				function crossFade(error) {
					if (prevIndex != newIndex) {
						var inTime = time;
						var outTime = 0;
						if (error) {
							inTime = 0;
							outTime = time;
						}
						imgFrame.not(prevActiveImg.stop()).stop().fadeTo(0, 0);
						setTimeout(function() {
							setActiveClass();
							newImg.stop().fadeTo(inTime, 1, function() {
								prevActiveImg.stop().fadeTo(outTime, 0);
							});
						}, 10);
					}
				}

				if (state == 'loaded') {
					crossFade();
				} else if (state == 'error') {
					crossFade('error');
				} else {
					newImg.one('load.'+F, function(){
						crossFade();
					});
					newImg.one('error.'+F, function(){
						crossFade('error');
					});
				}
			}

			activeImg = newImg;
			activeIndex = newIndex;

			if (o.arrows) {
				setArrows();
			}

			var readyFLAG = newImg.data('detached') || newImg.data('wraped');

			clearTimeout(loadTimeout);
			loadTimeout = setTimeout(function(){
				if (!readyFLAG && newIndex != o.startImg) {
					loadDraw(newImg, newIndex);
					if (o.onShowImg) {
						var data = {index: newIndex, img: activeImg, thumb: activeThumb, caption: captionText};
						o.onShowImg(data);
					}
				}
				preloadSiblings(newImg, newIndex);
			}, time+10);
			if (readyFLAG || newIndex == o.startImg) {
				loadDraw(newImg, newIndex);
				if (o.onShowImg) {
					var data = {index: newIndex, img: activeImg, thumb: activeThumb, caption: captionText};
					o.onShowImg(data);
				}
			}
		}

		showImg(imgFrame.eq(o.startImg), false, false, true);

		if (wrapWidth && wrapHeight) {
			wrapSizeFromFirstFLAG = true;
			setFotoramaSize();
		}



		if (o.thumbs && o.thumbsPreview) {
			loadThumb(0);
		}

		if (o.thumbs) {
			if (o.thumbColor && !o.thumbsPreview) {
				// Если переназначен цвет тумбсов
				thumb.children().css({backgroundColor: o.thumbColor});
			}

			if (o.thumbsBackgroundColor) {
				// Если переназначен фон под тумбсами или превьюшками
				thumbs.css({backgroundColor: o.thumbsBackgroundColor});
			}

			if (o.thumbsPreview) {
				if (o.thumbBorderColor) {
					// Если переназначен цвет рамочки вокруг активной превьюшки
					thumbBorder.css({borderColor: o.thumbBorderColor});
				}
			}
		}

		if (o.backgroundColor) {
			// Если переназначен цвет фона
			wrap.add(imgFrame).css({backgroundColor: o.backgroundColor});
		}

		if (o.arrowsColor && o.arrows) {
			// Если переназначен цвет стрелок
			arrs.css({color: o.arrowsColor});
		}

		function callShowImg(delta, e) {
			e.stopPropagation();
			e.preventDefault();
			var indexNew = activeIndex + delta;
			if (indexNew < 0) {
				indexNew = o.loop ? size - 1 : 0;
			}
			if (indexNew > size - 1) {
				indexNew = o.loop ? 0 : size - 1;
			}

			showImg(imgFrame.eq(indexNew), e, false);
		}

		var resizeTimeout = false;
		function rescale() {
			clearTimeout(resizeTimeout);
			resizeTimeout = setTimeout(function(){
				setFotoramaSize();
			}, 50);
		}

		function bindrescale() {
			fotorama.css({overflow: o.resize ? 'hidden' : ''});
			$window.bind('resize', rescale);
			if (touchFLAG) {
				window.addEventListener('orientationchange', rescale, false);
			}
		}

		bindrescale();

		// Биндим хендлеры
		fotorama.bind('showimg', function(e, index){
			if (index > size - 1 || typeof(index) != 'number') {
				index = 0
			}
			if (!o.touchStyle || !shaftMouseDownFLAG) {
				showImg(imgFrame.eq(index), e, false);
			}
		});


		fotorama.bind('rescale', function(e, width, height, resize) {
			if (width) {
				wrapWidth = width;
			}
			if (height) {
				wrapHeight = height;
			}
			wrapRatio = wrapWidth / wrapHeight * 1000;
			wrapRatioForced = wrapRatio;
			o.resize = resize;
			forcedRatioFLAG = !resize;
			setFotoramaSize();

			clearTimeout(resizeTimeout);
		});


		if (o.thumbs) {
			// Клик по тумбсам
			function onThumbClick(e) {
				e.stopPropagation();
				var thisThumb = $(this);
				if (!thisThumb.data('disabled')) {
					var i = thumb.index($(this));
					var x = e[_coo] - thumbs.offset()[_pos];
					showImg(imgFrame.eq(i), e, x);
				}
			}
			thumb.bind('click', onThumbClick);
		}

		if (o.arrows) {
			// Клик по стрелочкам, если они включены
			arrPrev.click(function(e) {
				if (!$(this).data('disabled')) {
					callShowImg(-1, e);
				}
			});
			arrNext.click(function(e) {
				if (!$(this).data('disabled')) {
					callShowImg(+1, e);
				}
			});
		}

		if (!o.touchStyle && !touchFLAG) {
			// Клик по картинке, если отключён режим таскания
			wrap.click(function(e){
				var forwardFLAG = e[_coo] - wrap.offset()[_pos] >= wrapSize/2;

				if ((!e.shiftKey && forwardFLAG && o.arrows) || (e.shiftKey && !forwardFLAG && o.arrows) || (!o.arrows && !e.shiftKey)) {
					// Если клик без шифта
					callShowImg(+1, e);
				} else {
					// Если с шифтом
					callShowImg(-1, e);
				}
			});
		}

		if (o.touchStyle || touchFLAG || (o.thumbs && o.thumbsPreview)) {
		function touch(el, mouseDown, mouseMove, mouseUp) {
			var elPos,
			coo,
			coo2,
			downPos,
			downPos2,
			downElPos,
			downTime,
			moveCoo = [],
			moveTime,
			directionLast,
			upTime,
			upTimeLast = 0;

			var movableFLAG = false;
			var checkedDirectionFLAG = false;
			var limitFLAG = false;
			function onMouseDown(e) {
				if ((touchFLAG || e.which < 2) && activeImg) {
					function act() {
						downTime = new Date().getTime();
						downPos = coo;
						downPos2 = coo2;
						moveCoo = [[downTime, coo]];

						clearBackAnimate(el);
						if (csstrFLAG) {
							el.css(getDuration(0));
						} else {
							el.stop();
						}
						elPos = el.position()[_pos];
						el.css(getTranslate(elPos, o.vertical));
						downElPos = elPos;

						mouseDown();
					}
					if (!touchFLAG) {
						coo = e[_coo];
						e.preventDefault();
						act();
						$document.mousemove(onMouseMove);
						$document.mouseup(onMouseUp);
					} else if (touchFLAG && e.targetTouches.length == 1) {
						coo = e.targetTouches[0][_coo];
						coo2 = e.targetTouches[0][_coo2];
						act();
						el[0].addEventListener('touchmove', onMouseMove, false);
						el[0].addEventListener('touchend', onMouseUp, false);
					} else if (touchFLAG && e.targetTouches.length > 1) {
						return false;
					}
				}
			}

			function onMouseMove(e) {
				function act() {
					e.preventDefault();

					moveTime = new Date().getTime();
					moveCoo.push([moveTime, coo]);

					var pos = downPos - coo;
					elPos = downElPos-pos;

					if (elPos > el.data('maxPos')) {
						elPos = Math.round(elPos + ((el.data('maxPos') - elPos)/ 1.5));
						limitFLAG = 'left';

					} else if (elPos < el.data('minPos')) {
						elPos = Math.round(elPos + ((el.data('minPos') - elPos) / 1.5));
						limitFLAG = 'right';
					} else {
						limitFLAG = false;
					}

					if (o.touchStyle) {
						el.css(getTranslate(elPos, o.vertical));
					}

					mouseMove(elPos, pos, limitFLAG);
				}
				if (!touchFLAG) {
					coo = e[_coo];
					act();
				} else if (touchFLAG && e.targetTouches.length == 1) {
					coo = e.targetTouches[0][_coo];
					coo2 = e.targetTouches[0][_coo2];

					if (!checkedDirectionFLAG) {
						if (Math.abs(coo-downPos) - Math.abs(coo2-downPos2) >= -5) {
							movableFLAG = true;
							e.preventDefault();
						}
						checkedDirectionFLAG = true;
					} else if (movableFLAG) {
						act();
					}
				}
			}

	function onMouseUp(e) {
		if (!touchFLAG || !e.targetTouches.length) {
			movableFLAG = false;
			checkedDirectionFLAG = false;

					if (!touchFLAG) {
						$document.unbind('mouseup');
						$document.unbind('mousemove');
					} else {
						el[0].removeEventListener('touchmove', onMouseMove, false);
						el[0].removeEventListener('touchend', onMouseUp, false);
					}

					upTime = new Date().getTime();
					var dirtyLeft = -elPos;

					var _backTimeIdeal = upTime - o__dragTimeout;
					var _diff, _diffMin, backTime, backCoo;
					for (i=0;i<moveCoo.length;i++) {
						_diff = Math.abs(_backTimeIdeal - moveCoo[i][0]);

						if (i == 0) {
							_diffMin = _diff;
							backTime = upTime - moveCoo[i][0];
							backCoo = moveCoo[i][1];
						}
						if (_diff <= _diffMin) {
							_diffMin = _diff;
							backTime = moveCoo[i][0];
							backCoo = moveCoo[i][1];
						}
					}

					var posDiff = backCoo - coo;
					var direction = posDiff >= 0;
					var timeDiff = upTime - backTime;
					var isSwipe = timeDiff <= o__dragTimeout;
					var timeFromLast = upTime - upTimeLast;
					var sameDirection = direction === directionLast;

					mouseUp(dirtyLeft, timeDiff, isSwipe, timeFromLast, sameDirection, posDiff, e);

					upTimeLast = upTime;
					directionLast = direction;
				}
			}

			if (!touchFLAG) {
				el.mousedown(onMouseDown);
			} else {
				el[0].addEventListener('touchstart', onMouseDown, false);
			}
		}
		}

		if (o.touchStyle || touchFLAG) {
			var clickPreventedFLAG = false;

			function shaftOnMouseDown() {
				shaftMouseDownFLAG = true;
			}
			function shaftOnMouseMove(pos, posDiff, limitFLAG) {
				clearTimeout(setShaftGrabbingFLAGTimeout);

				if (!shaftGrabbingFLAG) {
					if (o.shadows) {
						wrap.addClass(F+'__wrap_shadow');
					}
					if (!touchFLAG) {
						shaft.addClass(F+'__shaft_grabbing');
					}
					shaftGrabbingFLAG = true;
				}

				if (o.shadows) {
					if (limitFLAG) {
						var antiLimit = limitFLAG == 'left' ? 'right' : 'left';
						wrap
								.addClass(F+'__wrap_shadow_no-' + limitFLAG)
								.removeClass(F+'__wrap_shadow_no-' + antiLimit);
					} else {
						if (o.shadows) {
							wrap.removeClass(F+'__wrap_shadow_no-left '+F+'__wrap_shadow_no-right');
						}
					}
				}

				if (Math.abs(posDiff) >= 5 && !clickPreventedFLAG) {
					// Отменяем клик по ссылкам!
					clickPreventedFLAG = true;
					$('a', wrap).bind('click', preventClick);
				}

			}
			function shaftOnMouseUp(dirtyLeft, timeDiff, isSwipe, timeFromLast, sameDirection, posDiff, e) {
				shaftMouseDownFLAG = false;
				setShaftGrabbingFLAGTimeout = setTimeout(function() {
					if (!touchFLAG && o.arrows) {
						wrapLeave();
					}
					// Разрешаем клик по ссылкам!
					clickPreventedFLAG = false;
					$('a', wrap).unbind('click', preventClick);
				}, o__dragTimeout);

				if (!touchFLAG) {
					shaft.removeClass(F+'__shaft_grabbing');
				}

				if (o.shadows) {
					wrap.removeClass(F+'__wrap_shadow');
				}

				var forceLeft = false;
				var forceRight = false;

				var $target = $(e.target);
				var a = $target.filter('a');
				if (!a.length) {
					a = $target.parents('a');
				}

				if (o.touchStyle) {
					if (shaftGrabbingFLAG) {
						if (isSwipe) {
							if (posDiff <= -10) {
								forceLeft = true;
							} else if (posDiff >= 10) {
								forceRight = true;
							}
						}

						var time = o__transitionDuration;

						var index = Math.round(dirtyLeft / (wrapSize + o.margin));

						if (forceLeft || forceRight) {
								posDiff = -posDiff;
								var speed = posDiff/timeDiff;
								var virtualPos = Math.round(-dirtyLeft + speed*250);
								var newPos, maxPos, overPos;
								//animate(shaft, virtualPos, o.transitionDuration);
								var outFactor = .03;
								if (forceLeft) {
									index = Math.ceil(dirtyLeft / (wrapSize + o.margin))-1;
									newPos = -index*(wrapSize+o.margin);
									if (virtualPos > newPos) {
										overPos = Math.abs(virtualPos - newPos);
										time = Math.abs(time/((speed*250)/(Math.abs(speed*250) - overPos*(1-outFactor))));
										overPos = newPos + overPos*.03;
									}
								} else if (forceRight) {
									index = Math.floor(dirtyLeft / (wrapSize + o.margin))+1;
									newPos = -index*(wrapSize+o.margin);
									if (virtualPos < newPos) {
										overPos = Math.abs(virtualPos - newPos);
										time = Math.abs(time/((speed*250)/(Math.abs(speed*250) - overPos*(1-outFactor))));
										overPos = newPos - overPos*outFactor;
									}
								}
						}
						if (index < 0) {
							index = 0;
							overPos = false;
							time = o__transitionDuration;
						}
						if (index > size - 1) {
							index = size - 1;
							overPos = false;
							time = o__transitionDuration;
						}
						showImg(imgFrame.eq(index), e, false, false, time, overPos);
					} else if (a.length) {
						//return false;
					} else if (o.pseudoClick && !touchFLAG && timeDiff < o__dragTimeout) {
						var forwardFLAG = e[_coo] - wrap.offset()[_pos] >= wrapSize/2;
						if ((!e.shiftKey && forwardFLAG && o.arrows) || (e.shiftKey && !forwardFLAG && o.arrows) || (!o.arrows && !e.shiftKey)) {
							// Если клик без шифта
							callShowImg(+1, e);
						} else {
							// Если с шифтом
							callShowImg(-1, e);
						}
					} else {
						showImg(activeImg, e);
					}
				} else {
					if (posDiff == 0 && a.length) {
						document.location = a.attr('href');
					} else if (posDiff >= 0) {
						callShowImg(+1, e);
					} else if (posDiff < 0) {
						callShowImg(-1, e);
					}
				}

				shaftGrabbingFLAG = false;
			}

			touch(shaft, shaftOnMouseDown, shaftOnMouseMove, shaftOnMouseUp);

			if (o.touchStyle && o.thumbs && o.thumbsPreview) {
				var thumbClickUnbindedFLAG = false;

				function thumbsShaftOnMouseDown() {
					thumbsShaftMouseDownFLAG = true;
					thumbsShaftDraggedFLAG = true;
				}
				function thumbsShaftOnMouseMove(pos, posDiff) {
					if (!thumbsShaftGrabbingFLAG && Math.abs(posDiff) >= 5) {
						thumb.unbind('click', onThumbClick);
						thumbClickUnbindedFLAG = true;
						clearTimeout(setThumbsShaftGrabbingFLAGTimeout);
						thumbsShaftGrabbingFLAG = true;
					}

					setThumbsShadow(pos);
				}
				function thumbsShaftOnMouseUp(dirtyLeft, timeDiff, isSwipe, timeFromLast, sameDirection, posDiff, e) {
					thumbsShaftMouseDownFLAG = false;
					thumbsShaftGrabbingFLAG = false;
					setThumbsShaftGrabbingFLAGTimeout = setTimeout(function() {
						if (thumbClickUnbindedFLAG) {
							thumb.bind('click', onThumbClick);
							thumbClickUnbindedFLAG = false;
						}
					}, o__dragTimeout);


					dirtyLeft = -dirtyLeft;

					var newPos = dirtyLeft;
					var overPos;
					var time = o__transitionDuration*2;

					if (thumbsShaftJerkFLAG && thumbsShaftGrabbingFLAG) {
						slideThumbsShaft(0, false, false);
						thumbsShaftJerkFLAG = false;
					}

					if (dirtyLeft > thumbsShaft.data('maxPos')) {
						newPos = thumbsShaft.data('maxPos');
						time = time/2;
					} else if (dirtyLeft < thumbsShaft.data('minPos')) {
						newPos = thumbsShaft.data('minPos');
						time = time/2;
					} else {
						if (isSwipe) {
							posDiff = -posDiff;
							var speed = posDiff/timeDiff;
							newPos = Math.round(dirtyLeft + speed*250);
							var outFactor = .04;
							if (newPos > thumbsShaft.data('maxPos')) {
								overPos = Math.abs(newPos - thumbsShaft.data('maxPos'));
								time = Math.abs(time/((speed*250)/(Math.abs(speed*250) - overPos*(1-outFactor))));
								newPos = thumbsShaft.data('maxPos');
								overPos = newPos + overPos*outFactor;
							} else if (newPos < thumbsShaft.data('minPos')) {
								overPos = Math.abs(newPos - thumbsShaft.data('minPos'));
								time = Math.abs(time/((speed*250)/(Math.abs(speed*250) - overPos*(1-outFactor))));
								newPos = thumbsShaft.data('minPos');
								overPos = newPos - overPos*outFactor;
							}
						}
					}

					if (e.altKey) {
						time = time*10;
					}

					thumbsShaftPos = newPos;

					if (newPos != dirtyLeft) {
						animate(thumbsShaft, newPos, time, overPos);
						setThumbsShadow(newPos);
					}
				}

				touch(thumbsShaft, thumbsShaftOnMouseDown, thumbsShaftOnMouseMove, thumbsShaftOnMouseUp);
			}
		}
	}
})(jQuery);
