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

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

  (function($) {
 	function Module_Shows(options) {
 		var defaults = {
	       	// нужно для подгрузки видео
	       	_type: 'shows'    	        	
	    };
        this.options = $.extend(defaults, options);
        
 		// Переопределяем метод (до вызова 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].split(':');
            	if (! id[1]) {
            		return false;
            	}
            	// Прячем карусель
            	self.sliderCarousel.hideSliderCarousel();
            	// Показываем видео
            	self.sliderPanel.showVideoContent(self.options._type, id[1]);
            	// Устанавливаем id эллемента для комментирования
				self.setVideoContentId(id[1]);
				// Включаем кнопку комментрирования
				self.commentsPanel.enableCommentsButton();
				// Увеличиваем количество просмотров
				// episodes (shows просмотры изменятся, только после перезагрузки)
				var views_id = $('.views_' + id[1]);
				if (views_id.size() > 0) {
					views_id.html(parseInt(views_id.html()) + 1);
				}																
				// Если это первая загрузка, и существует хеш, то нужно подгрузить дополнительную панель
            	if (first) {
            		self.sliderCarousel.showAddithionalVideoObjectPanel(
            				self.options._type, 
            				id[1], 
            				{'episode':true},
            				function () {
            					// Рекоммендации загружаютя после полной загрузки AddithionalVideoObjectPanel
            					self.loadRecommendationPanel()
            				});
            		first = false;
            	} else {
            		// Рекоммендации
                	self.loadRecommendationPanel();
            	}
            });
		}
		
		this.construct = function() {
 			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setAutoQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.bindActions();
 			// addithional
			this.activateOpenEpisodePanel();
			this.activateShowAddEpisode();
 		}
 		
 		this.bindActions = function () {
			var self = this;
			self.bindCustomZoneActions();
			self.bindRegistrationForm();
			self.bindLoginForm();
        	self.bindSendToFriends();
        	self.bindSendBrokenVideo();
        	self.bindAddVideoForm();
			self.bindSliderActions();
        	self.bindCommentAction();
        	self.bindMyQueueAction();
        	self.bindAutoQueueAction();
        	self.bindCarouselSlider();
        	self.bindAddress();
        	self.bindSampleForm();
        	self.bindShowProfile();
        	self.bindForgotPassword();
        	// Share
            self.bindShareLink();
            // Check Episode form
            self.activateCheckEpisodeForm();
		}
 		
 		/* Recommendation */
 		
 		this.getCurrentRecommendationId = function() {
 			var self = this;
 			var currentID = false;
			
 			// Ищем Show, с помощью Episode (в открытой панели с епизодами)
 			var currentEpisode = $('#video_source_' + self.getVideoContentId() + '_episodes');
 			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                                  |
		================================================================================
		*/
		
		this.constructForNewQueue = function() {
			// this.constructForAdmin(); нельзя использовать (иначе вызовем activateOpenEpisodePanel)
			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setAutoQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.bindActions();
        	this.bindApproveAllVideo();
        	this.bindApproveVideo();
			this.bindEditVideo();
			this.bindDeleteVideo();
			this.bindOnMainVideo();
			this.bindFixedVideo();
			this.bindInTopVideo();
			this.bindInHotVideo();
			this.bindInIndexVideo();
 			// addithional
 			// TODO: url можно было вывести в Html 
			this.activateOpenEpisodePanel('/ajax/newqueue/shows/get-episode-panel-content/');
			this.activateShowAddEpisode();
			this.bindShowProfile();
        	this.bindForgotPassword();
		}
		
		/*
		================================================================================
		|                          Для страниц видео                                   |
		================================================================================
		*/
		
		// Для страниц у которых панель открыта сразу, а не подгружается ajax
		this.constructForcedOpen = function () {
			// set
			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setAutoQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.activateShowAddEpisode();
        	
        	// bind
        	var self = this;
        	self.bindCustomZoneActions();
			self.bindRegistrationForm();
			self.bindLoginForm();
        	self.bindSendToFriends();
        	self.bindSendBrokenVideo();
        	self.bindAddVideoForm();
			self.bindSliderActionsForcedOpen();
        	self.bindCommentAction();
        	self.bindMyQueueAction();
        	self.bindAutoQueueAction();
        	self.bindCarouselSlider();
        	self.bindAddressForcedOpen();
        	self.bindSampleForm();        	
        	self.bindEpisodePanel();
        	self.bindShowProfile();
        	self.bindForgotPassword();
        	// Share
            self.bindShareLink();
            // Check Episode form
            self.activateCheckEpisodeForm();
        	
        	// addithional
        	$(".show_source_for_episode:even").addClass('alt');
        	
        	// Comments
        	// Shows комментируется по episode
        	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;
			var first = true;
			$.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].split(':');
            	if (! id[1]) {
            		return false;
            	}
            	// Прячем карусель
            	self.sliderCarousel.hideSliderCarousel();
            	// Показываем видео
            	self.sliderPanel.showVideoContent(self.options._type, id[1]);
            	// Устанавливаем id эллемента для комментирования
				self.setVideoContentId(id[1]);
				// Включаем кнопку комментрирования
				self.commentsPanel.enableCommentsButton();
				// Увеличиваем количество просмотров
				// episodes (shows просмотры изменятся, только после перезагрузки)
				var views_id = $('.views_' + id[1]);
				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_Shows.prototype = {
 		activateOpenEpisodePanel: function(url) {
 			if (typeof(url) == 'undefined') {
 				url = '/ajax/shows/get-episode-panel-content/';
 			}
 			var self = this;
			var $current_source_panel = false;
			$('.show_episode_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);
								// Если нет episodes, комметировать нельзя
								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);
								$('.show_source_for_episode: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;
					}
				}
				return false;
			});
			self.bindEpisodePanel();		
			return false;
		},
		
		bindEpisodePanel: function() {
			$('.show_source_for_episode').live('click', function() {
				var $table_episode_sources = $(this).next().find('.episode_sources_wrapper');
				if ($table_episode_sources.hasClass('open')) {
					$table_episode_sources.slideUp().removeClass('open');
				} else {
					$('.episode_sources_wrapper.open').removeClass('open').hide();
					$table_episode_sources.slideDown().addClass('open');
				}
			});
			$(".show_source_for_episode").live('mouseover', function() {
				$(this).addClass("over_episode");
			}).live('mouseout', function() {
				$(this).removeClass("over_episode");
			});
			$(".video_source").live('mouseover', function() {
				$(this).addClass("over_source");
			}).live('mouseout', function() {
				$(this).removeClass("over_source");
			});
		},
		
		activateShowAddEpisode: function() {
			var self = this;
			// live - что бы контент можно было добавлять и через addithional_video_wrapper
			$('.show_add_episode').live('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				var url = $(this).attr('rel');
				// Выносим в callback (можно и так)
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_addcontent', function() {
					// снимаем обработчик, который был навешан предидущими нажатиями show_add_episode
					// это важно, так формы будут отправлятся на разные url
					$("#addShowEpisodeForm").die('submit');
					// вещаем новый
					self.activateAddVideoFormSubmit('addShowEpisodeForm', url);
				});
				return false;
			});
		},
		
		activateCheckEpisodeForm: function() {
			$('#num_of_season, #num_of_episode').live('change', function() {
				var $video_already_exists_message = $('.video_already_exists_message');
				var num_of_episode = $('#num_of_episode').val();
				var num_of_season = $('#num_of_season').val();
				if (num_of_episode.length > 0 && num_of_season.length > 0) {
					url = $('a', $video_already_exists_message).attr('href');
					$.ajax({
						url : url,
						type : "POST",
						dataType : 'json',
						timeout : 30000,
						error : function() {
							ajaxError();
						},
						success : function(json) {
							$video_already_exists_message.slideUp();
							if (json.exists) {
								$video_already_exists_message.slideDown();
							}
						},
						complete : function() {
						},
						// Parametrs
						data : {num_of_episode : num_of_episode, 
								num_of_season : num_of_season}
					});
					
				}
			});
		}
 	}
 	
 	$.extend(Module_Shows.prototype, $.Module_TV_prototype());
 	
 	$.Module_Shows = function(options) {
 		return new Module_Shows(options);
 	};
 
 })(jQuery);
