/*
 * jQuery tv module v1.0.0 - http://www.onlinetvcast.com/
 *
 */

// FIXME: глобальный рефакторинг

  (function($) {
 	function Module_Movies(options) {
 		var defaults = {
 			// нужно для подгрузки видео
	       	_type: 'movies'
	    };
        this.options = $.extend(defaults, options);
        
        /* Add content form */
		
		this.bindAddVideoForm = function() {
			var self = this;
			var url = $('.add_content').attr('rel');
			$('.add_content').bind('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_addcontent', function() {
					activateCalendar();
				});
				return false;
			});		
			self.activateAddVideoFormSubmit('addContentForm', url);
		}
				
		this.activateAddVideoFormSubmit = function(formID, url) {
			var self = this;
			var $form = $('#' + formID);
			$form.live('submit', function() {
				$('input[type=submit]', this).attr('disabled', 'disabled');
				$('.submit_addContentForm').addClass('disabled');
				// is $(this), rather than $("#registrationForm"), otherwise will not work after Ajax update
				$('.loading', this).show();
				$(this).ajaxSubmit({    					
					url: url,
					success: function(html) {
						window.scrollTo(0, 0);
						self.customzone.setCustomzoneContent(html);
						// after ajax
	  					activateCalendar();
						return false;
					},
					data: {
						// ajaxSubmit - does'n include the name of the submit 
						'form_submit' : true
					}
				});
				return false;
			});
		},
		
		// Переопределяем метод (до вызова construct)
 		this.bindAddress = function() {
			var self = this;
			var first = true;
			$.address.init(function(event) {
                // $('a.show_video_content.ajax_link').address();
            }).change(function(event) {
            	// Cуществует правильный хеш
            	if (event.value.length <= 1 || typeof event.pathNames[2] == 'undefined') {
            		first = false;
            		return false;
            	}
            	var id = event.pathNames[2];
            	if (! id) {
            		return false;
            	}
            	// Прячем карусель
            	self.sliderCarousel.hideSliderCarousel();
            	// Показываем видео
            	self.sliderPanel.showVideoContent(self.options._type, id);
            	// Устанавливаем id эллемента для комментирования
				self.setVideoContentId(id);
				// Включаем кнопку комментрирования
				self.commentsPanel.enableCommentsButton();
				// Увеличиваем количество просмотров
				// sources (movies просмотры изменятся, только после перезагрузки)
				var views_id = $('.views_' + id);
				if (views_id.size() > 0) {
					views_id.html(parseInt(views_id.html()) + 1);
				}				
				// Если это первая загрузка, и существует хеш, то нужно подгрузить дополнительную панель
            	if (first) {
            		self.sliderCarousel.showAddithionalVideoObjectPanel(
            				self.options._type, 
            				id, 
            				{'source':true},
            				function () {
            					// Рекоммендации загружаютя после полной загрузки AddithionalVideoObjectPanel
            					self.loadRecommendationPanel()
            				});
            		first = false;
            	} else {
            		// Рекоммендации
                	self.loadRecommendationPanel();
            	}
            });
		}
		
 		this.construct = function() {
 			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.bindActions();
 			// addithional
			this.activateOpenSourcePanel();
			this.activateMovieAddSource();
 		}
 		
 		/* Recommendation */
 		
 		this.getCurrentRecommendationId = function() {
 			var self = this;
 			var currentID = false;
			
 			// Ищем Show, с помощью Episode (в открытой панели с епизодами)
 			var currentEpisode = $('#video_source_' + self.getVideoContentId() + '_sources');
 			if (currentEpisode.size() > 0) {
 				currentID = currentEpisode.parents('.video_content_object').attr('id').split('_');
 				currentID = currentID[2];
 			}
 			
 			// Ищем Show в sliderCarousel(дополнительная панель)
 			if (! currentID) {
 				var currentShow = $('#addithional_videot_content .video_content_object');
 				if (currentShow.size() > 0) {
 					currentID = currentShow.attr('id').split('_');
 	 				currentID = currentID[2];
 	 			}
 			}
 			
			// Если просмотр происходит в пределах одного объекта (напр. смотрим епизоды одного шоу)
			if (self.lastRecommendationId == currentID) {
				return false;
			}
			return currentID;
 		},
		
		/*
		================================================================================
		|                        Для страниц newQueue                                  |
		================================================================================
		*/
		
		// для страниц myQueue
		this.constructForNewQueue = function() {
			// this.constructForAdmin(); нельзя использовать (иначе вызовем activateOpenSourcePanel)
			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.bindActions();
        	this.bindApproveVideo();
			this.bindEditVideo();
			this.bindDeleteVideo();
			this.bindOnMainVideo();
			this.bindFixedVideo();
			this.bindInTopVideo();
			this.bindInHotVideo();
			this.bindInIndexVideo();
 			// addithional
 			// TODO: url можно было вывести в Html 
			this.activateOpenSourcePanel('/ajax/newqueue/movies/get-episode-panel-content/');
			this.activateMovieAddSource();
		}
		
		/*
		================================================================================
		|                          Для страниц видео                                   |
		================================================================================
		*/
		
		// Для страниц у которых панель открыта сразу, а не подгружается ajax
		this.constructForcedOpen = function () {
			// set
			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.activateMovieAddSource();
        	
        	// bind
        	var self = this;
        	self.bindCustomZoneActions();
			self.bindRegistrationForm();
			self.bindLoginForm();
        	self.bindSendToFriends();
        	self.bindSendBrokenVideo();
        	self.bindAddVideoForm();
			self.bindSliderActionsForcedOpen();
        	self.bindCommentAction();
        	self.bindMyQueueAction();
        	self.bindCarouselSlider();
        	self.bindAddressForcedOpen();
        	self.bindSampleForm();        	
        	self.bindSourcePanel();
        	self.bindShowProfile();
        	self.bindForgotPassword();
        	// Share
            self.bindShareLink();
        	        	
        	// addithional
        	$('.video_source:even').addClass('alt');
        	
        	// Comments
        	// Movie комментируется по source
        	var video_source = $('.source_panel .video_source:first');
        	if (video_source.size()) {
        		var id = video_source.attr('id').split('_');						
    			// Устанавливаем id эллемента для комментирования
    			self.setVideoContentId(id[2]);
    			// Включаем кнопку комментрирования
    			self.commentsPanel.enableCommentsButton();
        	}
		}
				
		this.bindAddressForcedOpen = function () {
			var self = this;
			$.address.init(function(event) {
                // Мученно, намученно, перекрученно
                // Нужно изменения хеша, но  $('a.show_video_content').address() не подходит, так как у нас линк уже с хешем (у episode(source) нет отдельной страницы)
                $('a.show_video_content').bind('click', function() {
                	window.location.hash = $(this).attr('href').split('#')[1];
                 	return false;
                });
            }).change(function(event) {
            	// Cуществует правильный хеш
            	if (event.value.length <= 1 || typeof event.pathNames[2] == 'undefined') {
            		first = false;
            		return false;
            	}
            	var id = event.pathNames[2];
            	if (! id) {
            		return false;
            	}
            	// Прячем карусель
            	self.sliderCarousel.hideSliderCarousel();
            	// Показываем видео
            	self.sliderPanel.showVideoContent(self.options._type, id);
            	// Устанавливаем id эллемента для комментирования
				self.setVideoContentId(id);
				// Включаем кнопку комментрирования
				self.commentsPanel.enableCommentsButton();
				// Увеличиваем количество просмотров
				// sources (movies просмотры изменятся, только после перезагрузки)				
				var views_id = $('.views_' + id);
				if (views_id.size() > 0) {
					views_id.html(parseInt(views_id.html()) + 1);
				}
            });
		}
				
		this.bindSliderActionsForcedOpen = function() {
			var self = this;
			$('.show_video_content').live('click', function() {
				// Если это не ссылка, то ищем ее в этом элементе
				if (! $(this).is('a')) {
					$(this).find('a').click();
					return;
				}
			});
			// смотри также стр.161 (Module_TV)
			$('.video_player_close').live('click', function() {
				self.sliderPanel.hideVideoContent();
				// Очищаем хеш
				window.location.hash = '';
				// Показываем карусель (возможно реализовать задержку, но тогда функцию вынести в sliderPanel)
				self.sliderCarousel.showSliderCarousel();
			});
		}
 	}
 	
 	// TODO: привести в нормальный вид
 	Module_Movies.prototype = {
 		activateOpenSourcePanel: function (url) {
 			if (typeof(url) == 'undefined') {
 				url = '/ajax/movies/get-source-panel-content/';
 			}
 			var self = this;
			var $current_source_panel = false;
			$('.show_source_panel').live('click', function(){
				var $video_content_object = $(this).parents('.video_content_object');
				var $source_panel = $('.source_panel', $video_content_object);
				var $source_panel_loading = $('.source_panel_loading', $video_content_object);
				
				if ($source_panel.hasClass('open')) {
					$source_panel.slideUp().removeClass('open');
				} else {
					
					// Close open panel
					if ($current_source_panel)
						$current_source_panel.slideUp().removeClass('open');
					
					$source_panel_loading.show();
					if (! $source_panel.hasClass('loaded')) {
						var id = $video_content_object.attr('id').split('_');
						$.ajax({
							url : url + id[2],
							type : "POST",
							dataType : 'html',
							timeout : 30000,
							error : function() {
								ajaxError();
							},
							success : function(html) {
								var $video_source = $('.video_source:first', html);
								// Если нет sources, комметировать нельзя
								if ($video_source.size()) {
									var id = $video_source.attr('id').split('_');								
									// Устанавливаем id эллемента для комментирования
									self.setVideoContentId(id[2]);
									// Включаем кнопку комментрирования
									self.commentsPanel.enableCommentsButton();
								}
																
								$source_panel_loading.hide();
								$('.source_panel_content', $source_panel).html(html);
								$('.video_source:even', $source_panel).addClass('alt');
								$source_panel.slideDown().addClass('open').addClass('loaded');
								$current_source_panel = $source_panel;
								// следование экрана за раскрытым списком
								$("html").animate({ scrollTop: $('.source_panel_content', $source_panel).offset().top - 350}, 1100);
							}
						});
					} else {
						$source_panel_loading.hide();
						$source_panel.slideDown().addClass('open');
						$current_source_panel = $source_panel;
					}
				}
				self.bindSourcePanel();
				return false;
			});
		},
		
		bindSourcePanel: function() {
			$(".video_source").live('mouseover', function() {
				$(this).addClass("over_episode")
			}).live('mouseout', function() {
				$(this).removeClass("over_episode")
			});
		},
				
		activateMovieAddSource: function () {
			var self = this;
			// live - что бы контент можно было добавлять и через addithional_video_wrapper
			$('.movies_add_source').live('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				var url = $(this).attr('rel');
				// Выносим в callback (можно и так)
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_addcontent', function() {
					// снимаем обработчик, который был навешан предидущими нажатиями movies_add_source
					// это важно, так формы будут отправлятся на разные url
					$("#addMovieSourceForm").die('submit');
					// вещаем новый
					self.activateAddVideoFormSubmit('addMovieSourceForm', url);
				});
				return false;
			});
		}
 	}
 	 	
 	$.extend(Module_Movies.prototype, $.Module_TV_prototype());
 	
 	$.Module_Movies = function(options) {
 		return new Module_Movies(options);
 	};
 
 })(jQuery);
