
var initGalleryMoving = function(){

	/**
	 * @param {Object} number number of picture to slide to
	 * @param {Boolean} toTheEnd Indicates if it is needed to slide to the end of picture (if false - to the begining)
	 */
	var slideToFrame = function(frame,toTheEnd){
		if (typeof toTheEnd == "undefined") {
			toTheEnd = false;
		}
		var $frame = $(frame);
		active = frame;
		slideTo = $frame.position().left;
		if(toTheEnd){			
			var width = $frame.width();
			if(width >= containerWidth){
				slideTo += width - containerWidth;
			}			
		}
		
		var current = $('#wide').position().left;
		
		var ratio = Math.abs(slideTo + current)/882; 
		
		if(ratio < 3){
			ratio = Math.sqrt(ratio);
		}else{
			ratio = 1;
		}
		
		var slideNum = parseInt($frame.attr('slideNum'),10);
		$('#wide').animate({
			'left': -slideTo
		},400 * ratio,'swing');
		$('#imgmenu a').removeClass('active');
		$('#imgmenu a:eq('+(slideNum)+')').addClass('active');
		if(slideNum === 0){
			$('#bigimage').hide();
			document.location = loc + '#mainmenu';
		}else{
			$('#bigimage').show();
			document.location = loc + '#image' + slideNum;
		}	
	};

	var previous = function(ui, offset){
		var found = false;
		var num = 0;
		var i;
		var left = ui.position.left; // Left position of #wide div
		//Find first element that is visible on the right
		var element = null;
		
		if(left > 0){
			//Reached begining
			return $('#wide .element:first').get(0);
		}
		$('#wide .element').each(function(){
			if(!found){
				elLeft = $(this).position().left;
				var right = $(this).position().left;
				right += parseInt($(this).css('margin-left').replace('px',''),10);
				right += parseInt($(this).css('margin-right').replace('px',''),10);
				right += $(this).width();
				if(right > - left + 300){
					found = true;					
					element = this;
				}
			}
		});
		var elLeft = $(element).position().left;
		var right = $(element).position().left;		 
		right += parseInt($(element).css('margin-left').replace('px',''),10);
		right += $(element).width();
		//var slideNum = $(element).attr('slideNum');
		if(element === active && elLeft < - left){
			return null;
		/*}else if(right > -left + containerWidth && element === active){
			return element;*/
		}else{
			return element;
		}
	};	

	var next = function(ui, offset){
		var found = false;
		var num = 0;
		var i;
		var left = ui.position.left;
		
		if( - left + $('#wide .element:last').width() > wideWidth){
			return $('#wide .element:last').get(0);
		}
		
		//Find first picture with left position < half of #container			
		var element = null;
		$('#wide .element').each(function(){
			if(!found){
				var elLeft = $(this).position().left;
				if(elLeft > -left + containerWidth - 300){
					found = true;
				}else{
					element = this;
				}
			}
		});
		
		
		var elLeft = $(element).position().left;
		var right = $(element).position().left;		 
		right += parseInt($(element).css('margin-left').replace('px',''),10);
		right += $(element).width();
		//var slideNum = $(element).attr('slideNum');
		if(element === active && right > -left + containerWidth ){
			return null;
		/*}else if(elLeft < - left && element === active ){
			return element;*/
		}else{
			return element;
		}
	};

	var slide = function(ui, offset){
		var left = ui.position.left;
		var toTheEnd = false;
		var num;
		/**
		 * Sliding to the right 
		 */
		if(offset > 0){
			//Find previous frame to show
			num = previous(ui, offset);
			//If frame found
			if(num){
				toTheEnd = true;
				//If this is active frame slide to the begining of it
				if(num == active){
					toTheEnd = false;
				}
				slideToFrame(num,toTheEnd);
			}
		/**
		 * Sliding to the left
		 */
		}else if(offset < 0){
			//Find next frame to show
			num = next(ui, offset);
			if(num){
				//If this is active frame slide to the end of it
				if(num == active){
					toTheEnd = true;
				}
				slideToFrame(num,toTheEnd);
			}
		}
	};

	/**
	 * Start position (x,y) of cursor.
	 */
	var startX = 0;
	var startY = 0;
	/**
	 * Cursor move offset
	 */
	var offset = 0;
	/**
	 * Width of the container frame
	 */
	var containerWidth = $('#container').width();
	/**
	 * width of the #wide div
	 */
	var wideWidth = 0;
	/**
	 * Number of active image
	 */
	var active ;
	/**
	 * Number of image to process
	 */
	var count = 0;
	/**
	 * Location of the page.
	 */
	var loc = document.location.href.split('#')[0];
	
	
	$('.langmenu').html('<a id="bigimage">на весь екран</a>');
	$('#bigimage').click(function(){
		$(active).find('img').dblclick();
	});
	
	/**
	 * Add container for numbers menu before #container div
	 */
	$('#container').before('<div id="imgmenu"></div>');
	/**
	 * Iterate all images
	 *  - add margins to small images
	 *  - calculate width of #wide div
	 *  - add numbered links to the #imgmenu
	 *  - calculate number of frames in gallery
	 */
	$('#wide .element').each(function(){
		var margin_left;
		var margin_right;
		
		if($(this).width() < containerWidth-10){
			margin_left = (containerWidth - $(this).width())/2;
			margin_right = margin_left;
			wideWidth += containerWidth - $(this).width();
		}else{
			margin_left = 10;
			margin_right = margin_left;
			wideWidth += 20;
		}
		// No margin on the left to first element
		if(count === 0){
			margin_left = 0;
		}		
		$(this).css({
			'margin-left': margin_left,
			'margin-right': margin_right
		});

		wideWidth += $(this).width();
		
		/**
		 * Add links to menu, for each element 
		 */ 
		var zero = ''; //Add zero to the begining if numner is less then 10 (for one digit numbers)
		if(count < 10){
			zero = '0';
		}
		if(count === 0){
			$('#imgmenu').append('<a href="'+loc+'#mainmenu">МЕНЮ</a>');
		}else{
			$('#imgmenu').append('<a href="'+loc+'#image'+ count+'">' + zero + count + '</a>');
		}
		//this.slideNum = count;
		$(this).attr('slideNum', count);
		count++;
	});	
	/**
	 * Add frame with menu to the end
	 */
	$('#wide .element:first').clone(true).appendTo('#wide');
	wideWidth += $('#wide .element:first').width(); 
	
	//Set active image
	active = document.location.href.split('#');
	if(active[1] && active[1] == 'mainmenu' ){
		active = 0;
	}else if(active[1]){
		active = parseInt(active[1].replace('image',''),10);
	}else{
		active = 0;
	}
	active = $('#wide .element').get(active);
	

	/**
	 * Set width of #wide div
	 */
	$('#wide').css('width', wideWidth);
		
	//Set active frame
	slideToFrame(active);

	$('#imgmenu a').click(function(){
		var href = $(this).attr('href').split('#')[1];
		if(href == 'mainmenu'){
			slideToFrame($('#wide .element').get(0));
		}else{
			slideToFrame($('#wide .element').get(parseInt(href.replace('image',''),10)));
		}
		$(this).blur();		
	});
	
	
	// UI has some bug with overlayed links...
	$('#menu a').click(function(){
		window.location.href = $(this).attr('href');
	});


	/**
	 * Use jQuery UI draggable function to make #wide div draggable
	 */
	$('#wide').draggable({
		'axis':'x',
		'start':function(e){
			startX = e.originalEvent.pageX;
			startY = e.originalEvent.pageY;
		},
		'stop':function(e,ui){
			offset = e.originalEvent.pageX - startX;
			slide(ui, offset);			
		},
		cancel: '#menu a'
	});
	
};


$(function(){
	
	//prevent load of images
	$("div.tx-rhmgallery-pi1 img[src*='uploads/tx_rhmgallery']").each(function(){ $(this).before('<span style="display:none;">'+ $(this).attr('src') +'</span>') }).attr('src','clear.gif');
	
	// initialize moving engine
	initGalleryMoving();

	// Load images (as postProcess)
	var curPage = document.location.href.split("/")[3].split("#")[0];	
	$.getJSON(
		"/" + curPage + "/",
		{
			"type" : "244"
		},
		function(json){
			var imgList = '';
			var imgSrcArr = [];
			
			// Make load queue of images (firstly active, then left and right and rest)
			active = document.location.href.split('#');
			if(active[1] && active[1] != 'mainmenu'){
				active = parseInt(active[1].replace('image',''),10);
				imgSrcArr.push(json.imgArr[active-1].src);
				if(json.imgArr[active]) {imgSrcArr.push(json.imgArr[active].src);}
				if(active < json.imgArr.length) {imgSrcArr.push(json.imgArr[active].src);}
			}
			
			for (var item in json.imgArr) {
				if(json.imgArr[item]) {
					imgList += json.imgArr[item].wholeItem;
					if (json.imgArr[item].src) {imgSrcArr.push(json.imgArr[item].src);}
				}
			}

			$.preload(
				imgSrcArr,
				{
					onComplete:function(data){
						// Fill target image sources
						//console.debug("div.tx-rhmgallery-pi1 span:contains('"+ data.original+"')");
						$("div.tx-rhmgallery-pi1 span:contains('"+ data.original+"')").next().attr('src',data.original);
					}
				}
			);
		}
	);
	
});