/**☆_☆~'~`'"Teletyperrrsz!*/

$(function(){

	window.Gallery = (function() {

		var $g, $items, $g_doc,
			nItems,
			t_left,
			nCurrentItem = 1,
			nCurrentW,
			is_process = false;

		// Options
		var options = {
			rW: 0.4,
			rH: 335,
			offsetL: 300
		}

		function _init() {
			$g = $('#gallery');
			if( !$g.size() ){
				return;
			}

			// preload
			$g.hide();

			$items = $g.find('.item');
			nItems = $items.size();

			var currentImgSrc = $items.eq(nCurrentItem).find('img').attr('src'),
				currentImg = new Image();

			currentImg.onload = function(){

				nCurrentW = this.width;

				$g.show();
				_initDOM();

			};

			currentImg.src = currentImgSrc;
		}

		function _initDOM() {
			$g_doc = $('#layout');

			$items.each(function(){
				var $t = $(this);
				_setItem( $t );
			});

			_resetItem( nCurrentItem );
			_scrollTo( $items.eq( nCurrentItem ) );

			/*
			 * Events
			 */

			// Mouse
			$items
				.bind('click', function(){
					_setCurrent( $(this) );
				})
				.hover(
					function(){
						$(this).addClass('hover');
					},
					function(){
						$(this).removeClass('hover');
					}
				);

			$items.find('.next').click(function(){
				_next();
			});
			$items.find('.prev').click(function(){
				_prev();
			});

			//$g.mousemove(function(e){ _mouseNavigator(e) });


			// Keyboard
			if( navigator.userAgent.indexOf('Opera') > -1 ) {
				// Не работает в Chrome
				$(window).bind('keypress', function(e){ _keyNavigator(e) });
			} else {
				// Не работает в Opera [keypress для arrow-keys не работает в Safari (Chrome?)]
				//$(document).bind('keypress', function(e){ _keyNavigator(e); });
				$(document).bind('keydown', function(e){ _keyNavigator(e); });
			}
		}

		function _setItem( item ){
			var img = item.find('img'),
				imgW = 150; //img.attr('width');

			item
				.width(imgW + 'px')
				.height(options.rH + 'px');
		}

		function _resetItem( n ){
			$items
				.eq( n )
				.css({
					'width': nCurrentW + 'px',
					'height': '480px'
				})
				.addClass('active');

			t_left = $items.eq( n ).parent('li').offset().left;
		}

		function _setCurrent( item ){
			if( !is_process && !$(item).hasClass('active') ) {
				is_process = true;

				var $t = $(item),
					last_active = $items.filter('.active'),
					last_act_w = parseInt(last_active.find('img').width()),
					last_act_thumb_w = 150, //last_act_w * options.rW,
					to_width = _get_realWidth( $t );

				last_active
					.animate({
						width: last_act_thumb_w + 'px',
						height: options.rH + 'px',
						top: '0'
					}, 'slow')
					.removeClass('active');

				$t.animate({
					width: to_width + 'px',
					height: '480px',
					top: '-85px'
				}, 'slow', function(){

					$t.addClass('active');
					is_process = false;

					nCurrentItem = $items.index( $t );

				});

				t_left = $t.parent('li').offset().left;
				if( t_left > $g_doc.width() / 2 ) {
					t_left -= last_act_w - last_act_thumb_w;
				}
				_scrollTo( $t );

				//console.log( $g_doc.width() / 2 );

			}
		}

		function _prev(){
			(nCurrentItem > 0) && _setCurrent( $items.eq(nCurrentItem-1) );
		}

		function _next(){
			(nCurrentItem < nItems-1) && _setCurrent( $items.eq(nCurrentItem+1) );
		}

		function _get_realWidth( item ){
			var $t = $(item),
				//wrap = $t.children('span'),
				item_image = $t.find('img'),
				to_width = item_image.css({'position': 'absolute', 'width': 'auto', 'height': 'auto'}).width();

			//wrap.css({'position': 'relative'});
			item_image.css({'position': 'relative', 'width': '100%', 'height': '100%'});

			return to_width;
		}

		function _scrollTo( item ){
			var $t = $(item),
				//t_left = $t.offset().left,
				g_doc_width = $g_doc.width() / 2,
				act_left = Math.abs(g_doc_width - t_left),
				new_left = (g_doc_width > t_left ? ($g.position().left + act_left) : ($g.position().left - act_left))

			$g.animate({
				left: new_left - options.offsetL + 'px'
			}, 'slow');
		}

		function _mouseNavigator( e ) {
			var layout_width = $g_doc.width(),
				g_right = $g.position().left + $g.width(),
				_X = e.clientX,
				_leftX = parseInt( layout_width * 0.1 ),
				_rightX = layout_width - _leftX;

			if( !is_process ) {
				if( _X <= _leftX && $g.position().left < 0 ) {
					$g.stop();
					is_process = true;
					$g.animate({'left': '0'}, 'slow', 'linear', function(){
						is_process = false;
					});
				} else if( _X >= _rightX &&  g_right > layout_width ) {
					$g.stop();
					is_process = true;
					$g.animate({'left': (layout_width - $g.width())}, 'slow', 'linear', function(){
						is_process = false;
					});
				}
			}
		}

		function _keyNavigator( e ) {
			//e = $(e).get(0);

			if( is_process ) {
				//e.preventDefault();
				e.stopPropagation();

				return true;
			}

			var keyCode = e.keyCode;

			if( e.ctrlKey ){
				// Move
				if( keyCode == 37 || keyCode == 39 ) {
					e.preventDefault();
					e.stopPropagation();

					var next = nCurrentItem;
					//console.log( nCurrentItem );

					if( keyCode == 37 && nCurrentItem > 0 ) {
						next = nCurrentItem - 1;
					} else if( keyCode == 39 && nCurrentItem < nItems-1) {
						next = nCurrentItem + 1;
					}

					(nCurrentItem !== next) && _setCurrent( $items.eq(next) );
				}
			}

			return true;
		};


		return {
			init: _init()
		}

	})();


	/**
	 * KeyNavigator
	 */
	var KeyNavigator = (function() {
		var aLinks = [
			{
				sRel     : 'next',
				iKeyCode : 0x27,
				sHref    : ''
			},
			{
				sRel     : 'prev',
				iKeyCode : 0x25,
				sHref    : ''
			},
		];


		function _processKey(e) {
			var keyCode = e.keyCode;

			if( e.ctrlKey ){

				for( var i = 0, nLinks = aLinks.length; i < nLinks; i++ ) {
					if( aLinks[i].iKeyCode == keyCode && aLinks[i].sHref !== '' ) {

						document.location = aLinks[i].sHref;

					}
				}

			}
		}

		return {
			init: function() {
				var aLinkElements = $('link');

				for(var i = 0, sRel, nLen = aLinkElements.length; i < nLen; i++) {
					sRel = aLinkElements[i].rel;

					for( var j = 0; j < aLinks.length; j++ ) {
						if( aLinks[j] && aLinks[j].sRel === sRel && aLinks[j].href !== '' ) {

							aLinks[j].sHref = aLinkElements[i].href;
							break;
						}
					}
				}

				//console.log( aLinks );

				// Keyboard
				if( navigator.userAgent.indexOf('Opera') > -1 ) {
					// Не работает в Chrome
					$(window).bind('keypress', function(e){ _processKey(e) });
				} else {
					// Не работает в Opera
					$(document).bind('keydown', function(e){ _processKey(e) });
				}

			}
		}
	})();

	KeyNavigator.init();

});

