	
	$(function() {
		
		// Day topics
		
		var dayTopicImg = $('#js-dayTopicImg');
		var dayTopicLink = $('#js-dayTopicLink');
		var dayTopList = $('.b-mpBlock_dayTopics__topicsList');

		var topicItems = dayTopList.find('li');
		
	
		$('.b-mpBlock_dayTopics__topicsList li').live('click', function() {
																		
				var dayTopListTop = dayTopList.offset().top;
				
				var _this = $(this);
				
				if (!_this.hasClass('active')) {
					
					var container = _this;
				

					var firstItem = dayTopList.find('li:first');
					//console.log(firstItem);
					topicItems.removeClass('active');
					_this.addClass('active');
					
					dayTopicImg.fadeOut(500, function()
					{
												
						$(this).attr("src", _this.attr("url"));
						dayTopicLink.attr("href", _this.attr("rel"));
												
						$(this).load(function()
						{
							$(this).fadeIn(500);
						});
						
					});
					
					
					
					var newTop = container.offset().top-dayTopListTop;
					container.animate({top: -newTop + "px"}, 200, function()
					{
						firstItem.stop().remove().css({top: 0});
						firstItem.insertAfter(container).ready(function()
						{										
							container.css({top: 0}).remove();
							$('.b-mpBlock_dayTopics__topicsList').prepend(container);
						});
						
					});
					firstItem.animate({top: newTop + "px"}, 200, function()
					{
						$(this).css({top: 0});
					});
					
				}
				
				return false;
		});
		
		$('[rel="popup-player"]').click(function() {
      var rev = $(this).attr("rev"),
        width = 553,
        height = 630;
        url = $(this).attr("href");
      if (navigator.userAgent.indexOf('Chrome/') > 0) {
      if (window.videoPopup) {
          window.videoPopup.close();
          window.videoPopup = null;
        }
      }
      window.videoPopup = window.open(url, 'videoPopup', 'width=' + width + ',height=' + height + ',resizable,location,status,scrollbars');
      if (window.videoPopup.outerWidth) {
        window.videoPopup.outerWidth = width;
        window.videoPopup.outerHeight = height;
      }
      else if (w.resizeTo) {
        window.videoPopup.resizeTo(width,height);
      }
      window.videoPopup.focus();
			return false;
		
		});
		
		// Login, password recovery
		
		$('.b-auth-form').bind('keydown', 'tab', function() {
					var curfocus = $(this).data("currentfocus");
					var active = $('[tabindex="'+(curfocus+1)+'"]');
					if (active.length > 0) {
						active.focus();
						$(this).data("currentfocus", (curfocus+1) );
					} else {
						$('[tabindex="1"]').focus();
						$(this).data("currentfocus", 1 );
					}

					return false;

				}).data("currentfocus", 1);
				
				if (!$('#js-popup').hasClass('hidden')) {
							$('#js-popup input#email').focus();
						};
								
		$('#js-login').click(function() {
			$('#js-popup, .b-overlay').removeClass('hidden');
			$('#js-popup input#email').focus();
			return false;
		});			
		
		$('#js-forgotPass').click(function() {
			$('#js-recoveryForm').removeClass('hidden');
			$('#js-popup').addClass('hidden');
			return false;
		});
		
		$('#js-iRemember').click(function() {
			$('#js-recoveryForm').addClass('hidden');
			$('#js-popup').removeClass('hidden');
			return false;
		});
		
		
		$('.popup .close, .popup .l-close').click(function() {
			$('.popup, .b-overlay').addClass('hidden');
			return false;
		});
		
		$('.b-channelGroup__cap__num').click(function() {
			$(this).closest('.b-channelGroup').toggleClass('expd');
		});
		
		function check_buttons(obj) {
			if (obj.prev().attr('class') == null) {
				$('#js-prevPhoto').addClass('hidden');
			} else {
				$('#js-prevPhoto').removeClass('hidden');
			}
				
			if (obj.next().attr('class') == null) {
				$('#js-nextPhoto').addClass('hidden');
			} else {
				$('#js-nextPhoto').removeClass('hidden');
			}
		}
		
		$('.b-photo-gallery a').click(function() {
			$('.b-photo-gallery a').removeClass('active');
			$(this).addClass('active');
			$('#js-photo-detail').attr("src", $(this).attr('href')).load(function() {$('#js-gallery').css({marginTop: -$(this).height()/2-30 + "px", marginLeft: -$(this).width()/2-160 + "px"});});
			check_buttons($(this));
			$('#js-gallery, .b-overlay').removeClass('hidden');
			return false;	
		});
		
		
		$('#js-prevPhoto, #js-nextPhoto').click(function() {
			var cur = $('.b-photo-gallery a.active');
			cur.removeClass('active');
			if ($(this).attr('id') == 'js-prevPhoto') {
				var selected = cur.prev();
				
			} else {
				var selected = cur.next();
				
			}
			
			check_buttons(selected);
			
			selected.addClass('active');
			$('#js-photo-detail').attr("src", selected.attr('href')).load(function() {$('#js-gallery').css({marginTop: -$(this).height()/2-30 + "px", marginLeft: -$(this).width()/2-160 + "px"});});
		});
		
		
		// Stats
		
		$('.b-mpBlock_weekStat__menu a').click(function() {
			$(this).closest('.b-mpBlock_weekStat__menu').find('a').removeClass('selected');
			$(this).addClass('selected');
			$('.b-personStats-list').css({display: "none"});
			$('.'+$(this).attr('rel')).css({display: "block"});
			return false;
		});
		
		$('.go').click(function() {
			$.ajax({
				type: 'GET',
				url: 'promo/episodes/show',
				success: function(data) {
		            $(".b-header__news__item").replaceWith(data);
		          }
			});
			return false;
		});
		
		$('.js-lookStat').click(function() {
			var me = $(this);
		
			$.ajax({
				type: 'POST',
				url: '/promo/admin/top_units/show_stat',
				data: "authenticity_token="+$.URLEncode(AUTH_TOKEN) + "&name=" +me.attr('name'),
				success: function(data) {
			       me.next('.stat').html(data);
	     		},
				error: function() {
					me.next('.stat').html('error');
				}    
			});
			
			
			return false;
		});
		
		$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
		  while(x<c.length){var m=r.exec(c.substr(x));
		    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
		    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
		    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
		URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
		  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
		  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
		});
		
		
		$('#js-popup form').submit(function() {
			$.ajax({
				type: 'POST',
				dataType: "json",
				url: '/session.json',
				data: $(this).serialize(),
				success: function(data) {
			      document.location.href = data["return_to"] || "/";
	     		},
				error: function() {
					$('.informer').removeClass('hidden');
				}    
			});
			return false;
		});
		
		var table = $('#js-choise-main-pic');
		$(function() {
			$('#js-choise-main-pic input.radio').click(function() {

				if ($(this).attr('checked')) {
					$('tr', table).removeClass('selected');
					$(this).closest('tr').addClass('selected');
				}

			});
		});
		
		var minDate = $('.datepickerDateTo').datepicker({
							dateFormat: 'dd.mm.yy',
							maxDate: new Date(),
							onSelect: function (dateText, inst) { 
							   maxDate.datepicker( "option" , "minDate", new Date(inst.currentYear, inst.currentMonth, inst.currentDay) )
						      }
							});		

				var maxDate = $('.datepickerDateBy').datepicker({
							dateFormat: 'dd.mm.yy',
							maxDate: new Date(),
							minDate: new Date()
							});			

				$('input.js-focus').focus();

	});
