(function($){
	$(function(){
		if($('.mini-ages').length){
			new MiniAges();
		}
		if($('ul.ages-menu').length){
			new AddMiniLooks();
		}
		
		if($('.winners .winner').length){
			$('.winners .winner').hover(function(){
				$(this).addClass('hover');
			}, function(){
				$(this).removeClass('hover');
			});
		}
		
		if($('body.minilook-winners').length){
			$('.g-page').prepend('<div class="mini-bg mini-winners"></div>')
		}
		
		$(window).load(function(){
			$('.mini-arrows').each(function(){
				new MiniArrows($(this));
			});
			var flash_notice = $('#flash-notice');
			if (flash_notice.length) {
				bubble.preload({success: true, message:flash_notice.text()});
				setTimeout(function(){
					bubble.close({});
				}, 3000)
			}
		});
		
		if($('.mini-looks-wrap').length){
			new MiniLooksScroll();
		}
		
		MiniLookUpload.init_uploaders();
		trackButtons();

		
	});
	
	
	function  MiniLooksScroll(){
		this.init();
	}
	
	MiniLooksScroll.prototype = {
		init:function(){
			var _my = this;
			this.staticBlock = $('.mini-looks-wrap');
			this.movedBlock = this.staticBlock.find('.mini-looks-moved');
			this.looks = this.movedBlock.find('.look');
			this.movedBlock.width(this.looks.length*(this.looks.eq(0).width()+47));
			this.leftArrows = this.staticBlock.find('.arr-left');
			this.rightArrows = this.staticBlock.find('.arr-right');
			this.centerOfLook = this.looks.eq(0).width()/2;
			this.i = 0;
			this.lamp = $('.mini-auto .lamp');
			this.wheels = $('.wheels i');
			this.leftArrows.click(function(){
				_my.leftArrows.addClass('click');
				_my.scrollLook(-1);
				setTimeout(function(){
					_my.leftArrows.removeClass('click');
				}, 150);
			});
			this.rightArrows.click(function(){
				_my.rightArrows.addClass('click');
				_my.scrollLook(1);
				setTimeout(function(){
					_my.rightArrows.removeClass('click');
				}, 150);
			});
			this.checkSize();
			var id = window.location.hash;
			if(id.match(/\/\d+/)){
				for (var i=0; i < this.looks.length; i++) {
					if(this.looks.eq(i).attr('id') == id){
						this.i = i-1;
						this.scrollLook(1);
						break
					}
				};
			} else {
				this.scrollLook(0);
			}
			$(window).resize(function(){
				_my.checkSize();
			});
			this.vote();
			this.codeForBlock();
		},
		codeForBlock:function(){
			var _my = this;
			this.codeButtons = this.staticBlock.find('.look-info span.code');
			this.codeWindow = this.staticBlock.find('.mini-code');
			this.codeWindow.find('span').click(function(){
				_my.codeWindow.fadeOut('fast', function(){
					$(this).find('textarea').empty();
				});
			});
			this.codeButtons.click(function(){
				_my.codeWindow.fadeIn('fast', function(){
					$(this).find('textarea').focus();
				});
				_my.codeWindow.find('textarea').text($(this).parents('.look').find('textarea').text());
			})
		},
		vote:function(){
			var _my = this;
			this.voteLeft = $('.vote-rule .point-left span');
			$(".look .rating span").click(function(){
				var obj = $(this);
				if(!obj.is('.checked')){
					$.post("/specials/mini/"+obj.parents("div.look").attr('id').replace(/\D+/, "") + "/vote", {_method: 'put', authenticity_token: window._token}, function(data){
						var data = eval('('+data+')');
						obj.parent().find('p').html(data['rating']);
						obj.addClass('checked');
						_my.voteLeft.html(data['votes_left']);
					});
				}
			});
		},
		scrollLook:function(dir){
			if(this.i+dir < this.looks.length && this.i+dir >=0){
				var _my = this;
				this.i = this.i + dir;
				var next = this.looks.eq(this.i);
				this.looks.addClass('side');
				this.startRide(dir);
				this.movedBlock.stop().animate({left:this.cons + this.movedBlock.offset().left - next.offset().left}, 'fast', 'linear', function(){
					next.removeClass('side');
					if(!$.browser.msie){
						window.location.hash = '/'+next.attr('id');
					}
					_my.stopRide();
				});
			}
		},
		checkSize:function(){
			this.center = this.staticBlock.width()/2;
			this.cons = this.center - this.centerOfLook;
		},
		startRide:function(dir){
			var _my = this;
			var step = 33;
			this.lamp.css({display:'none'});
			clearInterval(this.interval);
			if(dir == 1 || dir == 0){
				this.interval = setInterval(function(){
					var top = parseInt(_my.wheels.css('top'));
					if(top > -111){
						_my.wheels.css({top:top-step});
					} else {
						_my.wheels.css({top:0});
					}
				}, 25);
			} else {
				this.interval = setInterval(function(){
					var top = parseInt(_my.wheels.css('top'));
					if(top < 0){
						_my.wheels.css({top:top+step});
					} else {
						_my.wheels.css({top:-132});
					}
				}, 25);
			}
		},
		stopRide:function(){
			this.lamp.css({display:'block'});
			clearInterval(this.interval);
		}
	}
	
	
	
	
	
	
	// включает или выключает кнопки отправки мини-лука в зависимости от наличия фото
	function trackButtons(){
		if ($(".add-look-blocks .visible .img-wrap img").length) {
			$('.apply-filter').addClass('apply-filter-visible');
			$('.send').addClass('send-visible');
		} else {
			$('.apply-filter').removeClass('apply-filter-visible');
			$('.send').removeClass('send-visible');
		}
	}
	
	// преобразовывает src в зависимости от секции и фильтра
	function miniLookSource(src){
		src = src.replace(/\/([^\/]*)\./, "/mini_look-image.")
		
		var section = $("#mini_look_section").val();
		
		if (section == "mini-club") {
			src = src.replace(/(\.)/, "-mini.");
		} else {
			src = src.replace(/(\.)/, "-preview.");
			if ($("#mini_look_filter_applied").val() == "1") {
				src = src.replace(/(\.)/, "_" + $("#mini_look_section").val() + ".");
			}
		}
		
		return src;
	}
	
	function changeMiniLook() {
		var img = $(".add-look-blocks .visible .img-wrap img");
		if (img.length) {
			img.attr('src', miniLookSource(img.attr('src')));
		}
	}
	
	var MiniLookUpload = {
	  init_uploaders: function(){
	    jQuery(".mini-look-upload").each(function(){
        var new_up = new SWFUpload(MiniLookUpload.uploader_options(jQuery(this).attr('id')));
	    });
	  },
	  uploader_options: function(id){
	    var default_options = {
				file_post_name: "mini_look[image]",
        upload_url: "/specials/mini/?lam_flash_session_id=" + encodeURIComponent(get_cookie('lam')),
        flash_url: "/flash/swfupload.swf",
        file_types: "*.jpe; *.jpg; *.jpeg; *.tiff; *.tif; *.png; *.bmp",
        begin_upload_on_queue: true,
        use_server_data_event: true,
				
				// debug: true,
		
        button_placeholder_id: id,
        button_width: "340",
        button_height: "519",
        button_text: "",
        button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
        button_cursor: SWFUpload.CURSOR.HAND,

        file_dialog_complete_handler: MiniLookUpload.imageSelected,
        upload_success_handler: MiniLookUpload.uploaded,

        upload_complete_handler: MiniLookUpload.imageUploaded
        // upload_success_handler: BGSWFUpload.imageAdded,
        // upload_error_handler: BGSWFUpload.imageNotAdded
	    }
	
			// опции, которые надо наложить
			var options = {
				"years": {
				},
				"mini-club": {
	        button_width: "519",
	        button_height: "340"
				}
			}
			
			return Object.extend(default_options, options[id]);
	  },
	  imageSelected: function(selected, queued) {
	    if (selected > 0) {
	      this.startUpload();
	    }
	  },
	  imageUploaded: function() {
	  },
	  // imageAdded: function(file, server_data) {
	  //   this.uploadingImagesCount--;
	  //   var _up = this;
	  //   var _html = eval(server_data);
	  //   setTimeout(function() {
	  //     _up.gallery.find(".bb-photo-loading:first").replaceWith(_html);
	  //     GLOBAL.reInit();
	  //     if(_up.uploadingImagesCount == 0) {
	  //       _up.gallery.sortable('refresh');
	  //       _up.gallery.sortable('enable');
	  // 
	  //     }
	  //   }, 100);
	  // },
	  // imageNotAdded: function() {
	  //   this.uploadingImagesCount--;
	  //   setTimeout(function() {
	  //     jQuery(".gallery-photos .uploading:first").removeClass('uploading').
	  //       html('Файл не загрузился');
	  //   }, 100);
	  // }
		uploaded: function(file, data) {
			var data = eval("("+data+")");
			$("#mini-look-form").attr('action', data['url']);
			$('.add-look .img-wrap').empty();
			$(".add-look-blocks .visible .img-wrap").html("<img src=\""+miniLookSource(data['src'])+"\">");
			trackButtons();
		}
	}
	
	function get_cookie(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	}
	
	function MiniArrows(arrows){
		this.init(arrows);
	}
	
	MiniArrows.prototype = {
		init:function(arrows){
			var _my = this;
			this.arrows = arrows;
			this.leftArrow = this.arrows.find('.arr-left');
			this.rightArrow = this.arrows.find('.arr-right');
			this.imgsWrap = this.arrows.parent().find('.mini-control');
			this.imgs = this.imgsWrap.find('img');
			this.step = this.imgs.eq(0).width();
			this.imgs.eq(0).addClass('now');
			for(var i=1; i<this.imgs.length; i++){
				this.imgs.eq(i).css({left:this.step});
			}
			this.flag = true;
			
			this.leftArrow.click(function(){
				if(_my.flag == true){
					_my.flag = false;
					_my.leftArrow.addClass('click');
					setTimeout(function(){
						_my.leftArrow.removeClass('click');
					}, 150);
					_my.switchImg(-1);
				}
			});
			this.rightArrow.click(function(){
				if(_my.flag == true){
					_my.flag = false;
					_my.switchImg(1);
					_my.rightArrow.addClass('click');
					setTimeout(function(){
						_my.rightArrow.removeClass('click');
					}, 150);
				}
			});
		},
		switchImg:function(dir){
			var _my = this;
			var now = this.imgs.parent().find('.now');
			var index = this.imgs.index(now);
			var next = index+dir;
			if(next <= this.imgs.length-1 && next >= 0){
				now.animate({left:this.step}, 'fast', function(){
					_my.flag = true;
				}).removeClass('now');
				this.imgs.eq(next).animate({left:0}, 'fast').addClass('now');
			} else if(next < 0){
				now.animate({left:this.step}, 'fast', function(){
					_my.flag = true;
				}).removeClass('now');
				this.imgs.eq(this.imgs.length-1).animate({left:0}, 'fast').addClass('now');
			} else if(next >= this.imgs.length){
				now.animate({left:this.step}, 'fast', function(){
					_my.flag = true;
				}).removeClass('now');
				this.imgs.eq(0).animate({left:0}, 'fast').addClass('now');
			}
		}
	}
	
	function AddMiniLooks(){
		this.init();
	}
	
	AddMiniLooks.prototype = {
		init:function(){
			var _my = this;
			this.agesWrap = $('ul.ages-menu');
			this.ages = this.agesWrap.find('li');
			this.lookBlocks = $('.add-look-blocks');
			this.ages.click(function(){
				if(!$(this).is('.selected')){
					_my.switchAge($(this));
				}
			});
			
			$('.apply-filter').click(function(){
				$(this).toggleClass('checked');
				// инвертируем флаг в форме
				var previous_val = $('#mini_look_filter_applied').val();
				$("#mini_look_filter_applied").val(previous_val == "1" ? "0" : "1");
				changeMiniLook();
			});
		},
		switchAge:function(li){
			this.ages.removeClass('selected');
			li.addClass('selected');
			$("#mini_look_section").val(li.attr('id').replace(/^a-/, ""));
			
			if(li.is('.a-last')){
				this.lookBlocks.find('.add-look:first').removeClass('visible');
				this.lookBlocks.find('.l-last').addClass('visible');
			} else {
				this.lookBlocks.find('.add-look:last').removeClass('visible');
				this.lookBlocks.find('.add-look:first').addClass('visible');
			}
			changeMiniLook();
			trackButtons();
		}
	}
	
	function MiniAges(){
		this.init();
	}
	
	MiniAges.prototype = {
		init:function(){
			var _my = this;
			$('.g-page').prepend('<div class="ages-preload"><div class="mini-bgs mini-bg1"></div><div class="mini-bgs mini-bg2"></div><div class="mini-bgs mini-bg3"></div><div class="mini-bgs mini-bg4"></div><div class="mini-bgs mini-bg5"></div><div class="a-60s"></div><div class="a-70s"></div><div class="a-80s"></div><div class="a-90s"></div><div class="a-mini"></div></div><div class="mini-bg mini-bg1"></div><div class="mini-bg mini-bg2"></div><div class="mini-bg mini-bg3"></div><div class="mini-bg mini-bg4"></div><div class="mini-bg mini-bg5"></div>');
			$('.mini-bg').height($('.g-page .l-page').eq(0).height());
			this.agesWrap = $('.mini-ages');
			this.ages = this.agesWrap.find('.m-age');
			this.flag = true;
			this.ages.hover(function(){
				if(!$(this).is('.selected') && _my.flag == true){
					_my.flag = false;
					_my.switchAge($(this), _my.ages.index(this));
				} else if($(this).is('.selected')){
					$('.mini-bg').eq(_my.ages.index(this)).fadeIn(500);
				}
			}, function(){
				$('.mini-bg').fadeOut(500);
			});
		},
		switchAge:function(age, index){
			var _my = this;
			var prev = this.agesWrap.find('.open:visible').parents('li');
			this.prevAge = {
				block:prev,
				close:prev.find('.close'),
				open:prev.find('.open')
			}
			this.selectedAge = {
				block:age,
				close:age.find('.close'),
				open:age.find('.open')
			}
			this.nextAge = this.agesWrap.find('li.m-l0');
			this.prevAge.block.animate({borderLeftColor:'#898989', borderRightColor:'#898989', borderTopColor:'#898989', borderBottomColor:'#898989'}, 100 , 'linear');
			this.selectedAge.close.fadeOut(100);
			$('.mini-bg').stop().fadeOut(350);
			this.prevAge.open.fadeOut(100, function(){
				new classAnimate(function(now, prev){
					_my.prevAge.block.width(800-(800-36)*(now));
					_my.selectedAge.block.width(36+(800-36)*now);
				}, 250, 'easeOutQuad', function(){
					_my.agesWrap.find('.selected').removeClass('selected');
					_my.nextAge.removeClass('m-l0');
					$('.mini-bg').eq(index).fadeIn(500);
					_my.ages.eq(index+1).addClass('m-l0');
					_my.selectedAge.block.css({borderRight:'8px solid #898989'}).animate({borderLeftColor:'#00aef0', borderRightColor:'#00aef0', borderTopColor:'#00aef0', borderBottomColor:'#00aef0'}, 100, 'linear', function(){
						_my.prevAge.close.fadeIn(500);
						_my.selectedAge.open.fadeIn(100, function(){
							_my.selectedAge.block.removeAttr('style').addClass('selected');
							_my.flag = true;
						});
					});
				});
			});
		}
	}

})(jQuery);