﻿
(function($) {
	if (!$.yamayka) {
		$.yamayka = new Object();
	};

	$.yamayka.fslider = function(el, options) {
		var base                    = $(el);
		this.base                   = base;

		base.defaultOptions = {
			"timeAnimation"			: 800,
			"easing"				: "linear",
			"queue"					: false,
			"loader"				: "#fslider_loader",
			"navContainer"			: "#fslider_nav",
			"nextControl"			: "#fslider_next",
			"prevControl"			: "#fslider_prev",
			"currentCounter"		: "#fslider_current",
			"totalCounter"			: "#fslider_total",
			"imgTitle"				: "#fslider_img_title",
			"pager"					: "#slider_pager",
			"resetImgSrc"			: false,
			"centering"				: true,
			"swipe"					: false,
			"keyNavigation"			: true,
			"continuous"			: false,
			"autoplay"				: 1500,				// time in ms to autoplay slider; if false  - autoplay off
			"start"					: false,				// стартовать ли слайдер после инициализации
			"check_height"			: false,
			"centerImg"				: false,
			"coef"					: 0
		};

		base.init = function() {
			base.options                = $.extend({}, base.defaultOptions, options || {});

			base.active                 = false;		// активен ли слайдер - т.е. отображается ли он на странице
			base.loader$                = $(base.options.loader);
			base.li$             	    = $('li', base);
			base.ul$					= $('ul', base);
			base.img$					= $('img', base.li$);
			base.liCount  	            = base.li$.length;
			base.totalCounter$			= $(base.options.totalCounter);
			base.currentCounter$		= $(base.options.currentCounter);
			base.imgTitle$				= $(base.options.imgTitle);
			base.images					= [];
			base.ready                  = false;
			base.timeoutID              = null;
			
			if (base.options.start) {
				base.ready = base.setCurrent(0);
				if (base.ready) {
					base.preloadImages(base.img$, function(){
						base.ul$.fadeIn('normal', function(){
							base.startInit();
							base.ul$.css('visibility','visible');
						});
						
					});
				}
			}
		};
		base.startInit = function() {
			if (base.options.check_height) base.css('height', $(base.li$[base.curr]).data("i_h")+'px');
			if (base.options.centering) $(window).trigger('resize');
			if (base.liCount > 1) base.li$.eq((base.curr+1)).css({'left': '1044px'});
			if (base.imgTitle$.length) base.imgTitle$.html($('img', base.li$[base.curr])[0].title);
			if (base.totalCounter$.length) base.totalCounter$.text(base.liCount);
			if (base.currentCounter$.length) base.currentCounter$.text(base.curr + 1);
			if (base.liCount > 1) base.setNavigation();
			$('.video').each(function(i){
				$(this).data({i_h:$(">iframe", this).height(), i_w:$(">iframe", this).width(), title:$(">a", this).attr('title')});
			});
			if (base.options.centerImg){
				var center = $('<div></div>').css({display: "table-cell", verticalAlign: "middle", textAlign: "center"});
				$('>img, >iframe',base.li$).wrap(center);
			}
		};
		
		base.setNavigation = function() {
			base.nextControlhandler();
			base.prevControlhandler();
			if (base.options.pager) base.pagerInit();
			if (base.options.keyNavigation) base.keyNavigation();
			if (base.options.swipe) base.swipe();
			if (base.options.autoplay) base.autoplay(base.options.autoplay);
		};
		
		base.setCurrent = function(i) {
			if (base.liCount < 0) {return false;}
			base.curr =((i >= 0) && (i < base.liCount))?i:0;
			return true;
		};
		base.preloadImages = function(image, callback, pointer) {
			base.ul$.css('visibility','hidden');
			if (pointer === undefined) pointer = 0;
			if (image.length > pointer) {
				var img = $('<img>');
				img.bind("load error", $.proxy(function (event) {
					base.images[pointer] = img;
					$(base.li$[pointer]).data({i_w:$(image[pointer]).width(),i_h:$(image[pointer]).height(),title:$(image[pointer]).attr('title')});
					base.preloadImages(image, callback, pointer + 1);
				},this)).attr("src", $(image[pointer]).attr("src"));
				
			} else {
				callback();
			}
		};
		base.pagerInit = function() {
			var counteiner = $(base.options.pager);
			if (!counteiner.length) return;
			counteiner.append('<ul></ul>');
			$(base.li$).each(function(i){
				var page_button = $('<li></li>');
				if (i == base.curr) page_button.addClass('select_page');
				page_button.appendTo(base.options.pager+">ul");
			});
			base.pageNavigation();
		};
		base.pageNavigation = function() {
			$("ul>li", base.options.pager).click( function(e){
				e.stopPropagation;
				var need = $(this).index();
				base.animation_new(need, true);
			});
		};
		base.animation_new = function(need, clicked) {
			if (!base.ready || need == base.curr) return;
			if (clicked == undefined) clicked = false;
			base.ready = false;
			var mod = $(base.li$).outerWidth(true);
			var i_mod = base.options.coef;
			var k = 1;
			if ($(base.li$[need]).hasClass('video')) {
				$(base.options.nextControl).css('zIndex','-1');
				$(base.options.prevControl).css('zIndex','-1');
			} else {
				$(base.options.nextControl).css('zIndex','5');
				$(base.options.prevControl).css('zIndex','5');
			}
			if (base.options.check_height) {
				if ($(base.li$[need]).data("i_h") != $(base.li$[base.curr]).data("i_h")){
					$(base.options.imgTitle).hide();
					$(base.options.pager).hide();}
				if ($(base.li$[need]).data("i_h") > $(base.li$[base.curr]).data("i_h"))
					base.css("height",$(base.li$[need]).data("i_h")+'px');
			}
			if (need > base.curr){
				var h = -1;
				for (i=(base.curr+1); i<=(need+1); i++){
					var v_l = (mod*k)+i_mod;
					$(base.li$[i]).css({'left': v_l+'px'});
					k++;
				}
			} else {
				var h = 1;
				for (i=(base.curr-1); i>=(need-1); i--){
					var v_l = (mod*k)-i_mod;
					$(base.li$[i]).css({'left': (v_l*-1)+'px'});
					k++;
				}
			}
			$(base.ul$).stop(true, true).animate({
				left: ((v_l-(mod-(i_mod*h)))*h) + 'px'
				},{
					duration: base.options.timeAnimation,
					complete: function() {
						base.curr = need;
						$(base.ul$).css('left','0px');
						$(base.li$).css('left','-20000px');
						if (base.options.check_height) {
							base.css('height', $(base.li$[base.curr]).data("i_h")+'px');
							$(base.options.imgTitle).fadeIn(100);
							$(base.options.pager).fadeIn(100);
						}
						if (base.currentCounter$.length) base.currentCounter$.text(base.curr+1);
						if (base.imgTitle$.length) base.imgTitle$.html($(base.li$[base.curr]).data("title"));
						if ($(base.options.pager).length) $('li', base.options.pager).removeClass().eq(base.curr).addClass('select_page');						
						$(base.li$[base.curr]).css('left',i_mod + 'px');
						$(base.li$[base.curr - 1]).css('left',((mod)*-1)+i_mod + 'px');
						$(base.li$[base.curr + 1]).css('left',(i_mod + mod)+'px');
						base.ready = true;
					}
			});
			if (clicked) {
				clearTimeout(base.timeoutID);
				base.timeoutID = null;
			}
			if (base.options.autoplay && !clicked) {
				base.autoplay(base.options.autoplay + base.options.timeAnimation);
			}
		
		}
		base.swipe = function(){
			if (base.options.swipe){
	            new FingerSwipe(base.ul$, {
	                'onSwipeRight': $.proxy(function() {
	            		if ( !(!base.options.continuous && (base.curr == 0))) {
		            			base.animation_new(base.curr-1);
		            		}
	                     setTimeout(function() {
	                         //$('#ajax_loader').hide();
	                        }, 200);
	                }, this),
	                'onSwipeLeft': $.proxy(function() {
	    				if ( !(!base.options.continuous && (base.curr == (base.liCount-1))) ) {
	    						base.animation_new(base.curr+1);
	    				}
	                     setTimeout(function() {
	                         //$('#ajax_loader').hide();
	                        }, 200);
	                }, this)
	            });
			}
			
		};

		base.nextControlhandler = function() {
			$(base.options.nextControl).click(function(e) {
				e.preventDefault();
				if ( !(!base.options.continuous && (base.curr == (base.liCount-1))) ) {
						base.animation_new(base.curr+1, true);
				}
			});
		};

		base.prevControlhandler = function() {
			$(base.options.prevControl).click(function(e) {
				e.preventDefault();
				if ( !(!base.options.continuous && (base.curr == 0)) ) {
					base.animation_new(base.curr-1, true);
				}
			});
		};

        base.keyNavigation = function(){
            $(document).keydown(function(e) {
            	e.preventDefault();
					if(e.keyCode == 37) { // left
						if ( !(!base.options.continuous && (base.curr == 0))) {
							base.animation_new(base.curr-1, true);
						} 
					}
					else if(e.keyCode == 39) { // right
						if (!(!base.options.continuous && (base.curr == (base.liCount-1)))) {
							base.animation_new(base.curr+1, true);
						}
					}
            });
       };
		base.centering = function() {
			if (base.options.centering) {
				$(window).bind('resize', function(e) {
					base.li$.each(function(index) {
						var img_h = $('img', this).height();
						var base_h = base.height();
						if (img_h > base_h) {
							$(this).css('top', ((base_h - img_h)/2) + 'px');
						} else {
							$(this).css('top', '0px');
						}
					});
				});
			}
		};
		base.autoplay = function(time) {
			if (time) {
				base.timeoutID = setTimeout(function() {
					if ( !(!base.options.continuous && (base.curr == (base.liCount-1))) ) {
						base.animation_new(base.curr+1);
					} else {
						clearTimeout(base.timeoutID);
						base.timeoutID = null;
					}
				}, time);
			}
		};

		// Make it go!
		base.init();
	};

	$.yamayka.fslider.prototype.getcurrent = function() {
		return this.base.curr;
	};

	$.yamayka.fslider.prototype.startfrom = function(i) {
		var base = this.base;
		if (!base.active) {
			var curr = parseInt(i);
			base.loader$.show();
			base.options.start = true;
			base.setCurrent(curr);
		}
	};

	$.yamayka.fslider.prototype.stop = function() {
		var base = this.base;
		if (base.active) {
			base.ready = false;
			base.active = false;
			clearTimeout(base.timeoutID);
			base.timeoutID = null;
			base.fadeOut(500, function() {
			});
		}
	};

	// jQuery plugin
	$.fn.fslider = function(options) {
		return this.each(function() {
			new $.yamayka.fslider(this, options);
		});
	};

})(jQuery);

