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

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

 (function($) {
 	function Module_TV(options) {
 		var defaults = {
 			// нужно для подгрузки видео
	       	_type: 'tv'     	        	
	    };
        this.options = $.extend(defaults, options);
        this.videoContentId = false;
        this.lastRecommendationId = false; 
 	}
 	 	 	 	
 	Module_TV.prototype = {
 		construct: function() {
 			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	this.bindActions();
 		},
 				
		bindActions: function () {
			var self = this;
			self.bindCustomZoneActions();
			self.bindRegistrationForm();
			self.bindLoginForm();
        	self.bindSendToFriends();
        	self.bindSendBrokenVideo();
        	self.bindAddVideoForm();
			self.bindSliderActions();
        	self.bindCommentAction();
        	self.bindMyQueueAction();
        	self.bindCarouselSlider();
        	self.bindAddress();
        	self.bindSampleForm();
        	self.bindShowProfile();
        	self.bindForgotPassword();
            self.bindShareLink();
            self.bindFeedbackForm();
		},
		
		/* Address plugin */
		
		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[1] == 'undefined') {
            		first = false;
            		return false;
            	}
            	var id = event.pathNames[1].split(':');
            	if (! id[1]) {
            		return false;
            	}
            	// Прячем карусель
            	self.sliderCarousel.hideSliderCarousel();
            	// Показываем видео
            	self.sliderPanel.showVideoContent(self.options._type, id[1], id[0]);
            	// Устанавливаем дополнительные функции для видео
            	self.activateAddithionalVideoFunctions();
            	// Устанавливаем id эллемента для комментирования
				self.setVideoContentId(id[1]);
				// Включаем кнопку комментрирования
				self.commentsPanel.enableCommentsButton();
				// Увеличиваем количество просмотров
				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], 
            				null,
            				function () {
            					// Рекоммендации загружаютя после полной загрузки AddithionalVideoObjectPanel
            					self.loadRecommendationPanel();
            				});
            		first = false;
            	} else {
            		// Рекоммендации
                	self.loadRecommendationPanel();
            	}
            });
		},
		
		bindShareLink: function() {
			$('.shared_it').bind('click', function(){
				var title_for_shared = $('#title_for_shared');
				var title_for_shared = title_for_shared.size() > 0 ? title_for_shared.text() : $('title').text();
				$(this).attr('href', 'http://www.addtoany.com/share_save?linkurl=' + window.location.href + '&title=' + title_for_shared);
			});
		},
		
		activateAddithionalVideoFunctions: function() {
			/*var self = this;
			
			// mediaplayer-viral (swfobject)
			// Функция обратного вызова			
			playerReady = function(obj) {
				try {
					var player = $j("#"+obj['id']);				
					self.player = player[0];
					
					// Нужно для закрытия видое потока
					// self.sliderPanel.setPlayer(player);
					
					// fullscreen
					$('.video_player_fullscreen').bind/* not live *//*('click', function() {
						// Проблема:
						// http://www.longtailvideo.com/support/forums/jw-player/javascript-interaction/12050/fullscreen-by-clicking-on-text-link-doesnt-work
					});
					// close
					// смотри также стр.161
					$('.video_player_close').bind/* not live *//*('click', function() {
						// Останавливаем плейер
						self.player.sendEvent("STOP");
					});
					// Автостарт
					self.player.sendEvent("PLAY", true);
				} catch (err){
				}				
			}
			
			// wmvplayer
			/*if (typeof(window['ply'] != 'undefined')) {
				ply.sendEvent('PLAY', true);
			}*/
		},
		
		/* Customzone */
		
		setCustomZone: function() {
			var self = this;
			self.customzone = $.Module_Customzone();
		},
		
		bindCustomZoneActions: function() {
			var self = this;
			$('.customzone_close, .customzone_close_link').live('click', function() {
				self.customzone.close();
				// Показываем карусель
				if (self.sliderCarousel) {
	            	self.sliderCarousel.showSliderCarousel();
				}
			});
		},
		
		/* Slider panel */
		
		setSliderPanel: function() {
			var self = this;
			self.sliderPanel = $.Module_SliderPanel();
		},
		
		bindSliderActions: function() {
			var self = this;
			$('.show_video_content').live('click', function() {
				// Если это не ссылка, то ищем ее в этом элементе
				if (! $(this).is('a')) {
					// сработает bindAddress
					$(this).find('a.show_video_content:first').click();
					return;
				}
				// БЕЗ return false;
			});
			// смотри также стр.108
			$('.video_player_close').live('click', function() {
				// Прячем видео
				self.sliderPanel.hideVideoContent();
				// Выключаем кнопку комментирования
				// TODO: на отдельных страницах не нужно выключать
				self.setVideoContentId(false);
				self.commentsPanel.disableCommentsButton();
				// Очищаем хеш
				window.location.hash = '';
				// Показываем карусель (возможно реализовать задержку, но тогда функцию вынести в sliderPanel)
				if (self.sliderCarousel) {
	            	self.sliderCarousel.showSliderCarousel();
				}
			});
		},
										
		/* Comments panel */
		
		setCommentsPanel: function() {
			var self = this;
			self.commentsPanel = $.Module_CommentsPanel();
		},
		
		bindCommentAction: function() {
			var self = this;
			$('.add_comments').bind('click', function() {
				videoContentId = self.getVideoContentId();
				// Видео для комментрировнаия не было установленно
				if (! videoContentId) {
					return false;
				}
				self.commentsPanel.showCommentsPanel($(this).attr('href'), videoContentId);
				return false;
			});
								
			$('#comment_wrapper .close').bind('click', function() {
				self.commentsPanel.hideCommentsPanel();
				return false;
			});
		},
		
		getVideoContentId: function() {
			var self = this;
			return self.videoContentId;
		},
		
		setVideoContentId: function(videoContentId) {
			var self = this;
			self.videoContentId = videoContentId;
		},
		
		/* MyQueue */
		
		setMyQueue: function() {
			var self = this;
			self.myQueue = $.Module_MyQueue();
		},
		
		bindMyQueueAction: function() {
			var self = this;
			$('.addMyQueue').live('click', function() {
				$(this).parents('.MyQueue_show');
				self.myQueue.addInMyQueue($(this));
			});
						
			$('.removeFromMyQueue').live('click', function() {
				self.myQueue.removeFromMyQueue($(this));
			});
		},
		
		/* AutoQueue */
		
		setAutoQueue: function() {
			var self = this;
			self.autoQueue = $.Module_AutoQueue();
		},
		
		bindAutoQueueAction: function() {
			var self = this;
			$('.addAutoQueue').live('click', function() {
				$(this).parents('.MyQueue_show');
				self.autoQueue.addInAutoQueue($(this));
			});
									
			$('.removeFromAutoQueue').live('click', function() {
				self.autoQueue.removeFromAutoQueue($(this));
			});
		},
		
		/* Source panel */
		
		activateDecorateSourcePanel: function() {
			$('.table_video_info').hover(function() {
				$(this).addClass('hover');
			}, function(){
				$(this).removeClass('hover');
			});
			$('.td_video_logo').hover(function(){ 
				$(this).parents('table:first').find('.table_video_info').addClass('hover'); 
			}, function(){ 
				$(this).parents('table:first').find('.table_video_info').removeClass('hover');
			});
			// tooltip
			/*$('.table_video_info').tooltip({
				bodyHandler: function() {
					return $('.description_wrapper a', this).html();
				},
				showURL: false
			});*/
		},
		
		/* Slider Carousel */
		
		setSliderCarousel: function() {
			var self = this;
			self.sliderCarousel = $.Module_SliderCarousel();
		},
		
		bindCarouselSlider: function() {
			var self = this;
			$('.show_video_object_from_slider_carousel').bind('click', function() {
				var id = $(this).attr('id').split('_');
				self.sliderCarousel.showAddithionalVideoObjectPanel(self.options._type, id[2]);
			});
				
			$('#addithional_video_wrapper .close').bind('click', function() {
				self.sliderCarousel.hideAddithionalVideoObjectPanel();
				return false;
			});
		},
		
		/* Forgot Password */
		
		bindForgotPassword: function() {
			var self = this;
			// Именно так, у на с еще не загружено forgot_password_link
			$('.forgot_password_link').live('click', function() {
				var url = $(this).attr('href');
				// Change background of CUSTOMZONE on Login
				// Уже было измененно при загрузке логин формы			
				// $('.c-round').addClass('c-round-login');
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_login', function(){
					self.bindActivateForgetForm(url);													
				});
				return false;
			});
		},
		
		bindActivateForgetForm: function(url) {
			var self = this;
			var forgotForm = $('#forgotForm');
			forgotForm.bind('submit', function() {
				$('input[type=submit]', this).attr('disabled', 'disabled');
				$('.submit_forgotForm').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);
						self.bindActivateForgetForm(url);
						return false;
					},
					data: {
						// ajaxSubmit - does'n include the name of the submit 
						'form_submit' : true
					}
				});
				return false;
			});
		},
		
		/* Sent friend */
		
		bindSendToFriends: function() {
			var self = this;
			var send_to_friends = $('.send_to_friends');
			send_to_friends.bind('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				self.customzone.setContentByRequestInCustomzone(send_to_friends.attr('href'), 'customzone_addcontent', function() {
					$("#inviteForm #link").val(window.location);
					$("#inviteForm #linkShow").val(window.location);
				});
				return false;
			});
			
			var inviteForm = $("#inviteForm");			
			inviteForm.live('submit', function() {
				$('input[type=submit]', this).attr('disabled', 'disabled');
				$('.submit_inviteForm').addClass('disabled');
				// is $(this), rather than $("#registrationForm"), otherwise will not work after Ajax update
				$('.loading', this).show();
				$(this).ajaxSubmit({    					
					url: send_to_friends.attr('href'),
					success: function(html) {
						window.scrollTo(0, 0);
						self.customzone.setCustomzoneContent(html);
						return false;
					},
					data: {
						// ajaxSubmit - does'n include the name of the submit 
						'form_submit' : true
					}
				});
				return false;
			});
		},
				
		/* Broken link */
		
		bindSendBrokenVideo: function() {
			var self = this;
			var sent_broken_video = $('.sent_broken_video');
			sent_broken_video.bind('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				self.customzone.setContentByRequestInCustomzone(sent_broken_video.attr('href'), 'customzone_addcontent', function() {
					var message = $("#brokenvideoForm #brokenLink");
					message.val(window.location);
				});
				return false;
			});
						
			var brokenvideoForm = $("#brokenvideoForm");			
			brokenvideoForm.live('submit', function() {
				$('input[type=submit]', this).attr('disabled', 'disabled');
				$('.submit_brokenvideoForm').addClass('disabled');
				// is $(this), rather than $("#registrationForm"), otherwise will not work after Ajax update
				$('.loading', this).show();
				$(this).ajaxSubmit({    					
					url: sent_broken_video.attr('href'),
					success: function(html) {
						window.scrollTo(0, 0);
						self.customzone.setCustomzoneContent(html);
						return false;
					},
					data: {
						// ajaxSubmit - does'n include the name of the submit 
						'form_submit' : true
					}
				});
				return false;
			});
		},
		
		/* Sample Form */
		
		bindSampleForm: function() {
			var self = this;
			var sampleContentForm = $('#sampleContentForm');
			$('select', sampleContentForm).bind('change', function() {
				self.customzone.blockPage();
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				sampleContentForm.submit();
			});
		},
		
		/* Show Profile */ 
		
		bindShowProfile: function() {
			var self = this;
			$('.show_user_profile').live('click', function() {
				var url = $(this).attr('rel');
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_registration', function() {
					activateCheckboxes();
				});
				return false;
			});
			
			$('.blockedProfile').live('click', function() {
				var id = $j(this).attr("id").split("_");
				// Значения ставим наоборот, так как используется click, а не change ( т.е. сначала происходит событие click, а потом уже change)
				var value = ($j(this).attr('checked') == true) ? 0 : 1;
				$j.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
					},
					data : {'id' : id[1], 'value' : value}
				});
			});
		},
		
		/* Feedback form */
		
		bindFeedbackForm: function() {
			// Captcha Reload
			$('#feedbackForm #recaptcha_reload').live('click', function(){
				$('#feedbackForm .td_captcha_image #captcha_image').empty()
				$('#feedbackForm .td_captcha_image .loading_captcha').show();
				$.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
						$('#feedbackForm .td_captcha_image .loading_captcha').hide();
						$('#feedbackForm #captcha_image').empty().html(json.image);
						$('#feedbackForm #captcha-id').val(json.id);
					}
				});
			});
		},
						
		/* Registration form */
		
		bindRegistrationForm: function() {
			var self = this;
			var users_registration_registration = $('.users_registration_registration');
			var url = users_registration_registration.attr('rel'); //('href');
			users_registration_registration.bind('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_registration', function() {
					activateCalendar();
				});
				return false;
			});			
			self.activateRegistrationFormSubmit(url);
			
			// Captcha Reload
			$('#registrationForm #recaptcha_reload').live('click', function(){
				$('#registrationForm .td_captcha_image #captcha_image').empty()
				$('#registrationForm .td_captcha_image .loading_captcha').show();
				$.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
						$('#registrationForm .td_captcha_image .loading_captcha').hide();
						$('#registrationForm #captcha_image').empty().html(json.image);
						$('#registrationForm #captcha-id').val(json.id);
					}
				});
			});
		},
				
		activateRegistrationFormSubmit: function(url) {
			var self = this;
			var $form = $("#registrationForm");
	  		$form.live('submit', function() {		            
				$('input[type=submit]', this).attr('disabled', 'disabled');
				$('.submit_registration_form').addClass('disabled');
			    $('.loading', this).show();		            
			    // is $(this), rather than $("#registrationForm"), otherwise will not work after Ajax update
	    		$(this).ajaxSubmit({    					
			  		url: url,
			  		success: function(html) {
			  			// replace the entire content
			  			self.customzone.setCustomzoneContent(html);
	  					// after ajax
	  					activateCalendar();				        
			        	return false;
			        },
			        data: {
			        	// ajaxSubmit - does'n include the name of the submit 
			        	'form_submit' : true,
			        	'last_visited_page' : window.location.pathname
			        }
				});
	    		return false;
	  		});
		},
		
		/* Login Form */
		
		bindLoginForm: function() {
			var self = this;
			var users_login_login = $('.users_login_login');
			var url = users_login_login.attr('rel'); //('href');
			users_login_login.bind('click', function(){
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				// Change background of CUSTOMZONE on Login			
				$('.c-round').addClass('c-round-login');
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_login');
				return false;
			});
			// Change background of CUSTOMZONE on default
			$('.customzone_close').live('click', function(){
				$('.c-round').removeClass('c-round-login');
			});
			self.activateLoginFormSubmit(url);
		},
		
		activateLoginFormSubmit: function(url) {
			var self = this;
			var $form = $("#loginForm");		
	  		$form.live('submit', function() {
				$('input[type=submit]', this).attr('disabled', 'disabled');
				$('.submit_login_form').addClass('disabled');
			    $('.loading', this).show();
			    // is $(this), rather than $("#loginForm"), otherwise will not work after Ajax update
	    		$(this).ajaxSubmit({    					
					url: url,
					type : "POST",
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success: function(html) {
						self.customzone.setCustomzoneContent(html);
					   	return false;
					},
					data: {
					   	// ajaxSubmit - does'n include the name of the submit 
					   	'form_submit' : true
					}
			  	});
	    		return false;
	  		});
		},
		
		/* Add content form */
		
		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');
				// нужно снимать обработчик ($("#addContentForm").die('submit');), который был навешан предидущими нажатиями add_content
				// но это не критично, так формы будут отправлятся на один и тот же url
				return false;
			});	
			self.activateAddVideoFormSubmit('addContentForm', url);
		},
		
		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);
						return false;
					},
					data: {
						// ajaxSubmit - does'n include the name of the submit 
						'form_submit' : true
					}
				});
				return false;
			});
		},
		
		closeVideoPanel: function() {
			var self = this;
			// Прячем видео
			if (self.sliderPanel) {
				self.sliderPanel.forcedClose();
			}
			// Прячем карусель
			if (self.sliderCarousel) {
            	self.sliderCarousel.hideSliderCarousel();
			}
		},
		
		/* Recommendation */
		
		// TODO: вынести в плагин
		loadRecommendationPanel: function() {
			var self = this;
			var currentID = self.getCurrentRecommendationId();
			if (! currentID) {
				return;
			}
			var recommendation_panel = $('#recommendation_panel');
			var loading = $('.loading', recommendation_panel);
			var recommendation = $('#recommendation_content', recommendation_panel);
			// Обнуляем рекоммендации
			recommendation.html('');
			// Показуем индикатор загрузки
			loading.show();
			$.ajax({
				url : '/ajax/' + self.options._type + '/load-recommendation/' + currentID,
				type : "POST",
				dataType : 'html',
				timeout : 30000,
				error : function() {
					ajaxError();
				},
				success : function(html) {
					// Прячем индикатор загрузки
					loading.hide();
					// Показываем рекоммендации
					recommendation.html(html).show();
					self.lastRecommendationId = currentID;
				}
			});
 		},
 		
 		getCurrentRecommendationId: function() {
 			var self = this;
 			var currentID = self.getVideoContentId();
			return currentID;
 		},
		
		/*
		================================================================================
		|                          Для администратора                                  |
		================================================================================
		*/
		
		constructForAdmin: function() {
			this.construct();
			this.bindApproveVideo();
			this.bindRefuseVideo();
			this.bindEditVideo();
			this.bindDeleteVideo();
			this.bindOnMainVideo();
			this.bindFixedVideo();
			this.bindInTopVideo();
			this.bindInHotVideo();
			this.bindInIndexVideo();
		},
		
		bindApproveAllVideo: function() {
			$('.video_action_buttons .approveAllNewQueue').live('click', function() {
 				if (! you_are_sure()) {
					return false;
				}
				var $this = $(this);
				// :first нужен если это episode или source (ведь у родителя тоже есть свой video_source:first)
				var $video_source = $this.parents('.video_source:first');
				$.ajax({
					url : $this.attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
						if (json.error) {
							alert(json.error);
							return;
						}
						$this.parents('.source_panel_content').fadeTo("fast", '0.3');
					}
				});
				return false;
			});
		},
		
		bindApproveVideo: function() {
			$('.video_action_buttons .approveNewQueue').live('click', function() {
 				if (! you_are_sure()) {
					return false;
				}
				var $this = $(this);
				// :first нужен если это episode или source (ведь у родителя тоже есть свой video_source:first)
				var $video_source = $this.parents('.video_source:first');
				$.ajax({
					url : $this.attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
						if (json.error) {
							alert(json.error);
							return;
						}
						$video_source.fadeTo("fast", '0.3');
					}
				});
				return false;
			});
		},
		
		bindRefuseVideo: function() {
			$('.video_action_buttons .refuseNewQueue').live('click', function() {
				if (! you_are_sure()) {
					return false;
				}
				var $this = $(this);
				// :first нужен если это episode или source (ведь у родителя тоже есть свой video_source:first)
				var $video_source = $this.parents('.video_source:first');
				$.ajax({
					url : $this.attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
					ajaxError();
				},
				success : function(json) {
					if (json.error) {
						alert(json.error);
						return;
					}
					$video_source.fadeTo("fast", '0.3');
				}
				});
				return false;
			});
		},
		
		bindEditVideo: function() {
			var self = this;
			$('.video_action_buttons .editNewQueue').live('click', function() {
				// Закрываем видео панель (видео+карусель)
				self.closeVideoPanel();
				window.scrollTo(0, 0);
				var url = $(this).attr('rel');
				self.customzone.setContentByRequestInCustomzone(url, 'customzone_addcontent', function() {
					// снимаем обработчик, который был навешан предидущими нажатиями editNewQueue
					$("#editContentForm").die('submit');
					// вещаем новый
					self.activateAddVideoFormSubmit('editContentForm', url);
				});
				return false;
			});
		},
		
		bindDeleteVideo: function() {
			var self = this;
			$('.video_action_buttons .deleteNewQueue').live('click', function() {
	        	if (! you_are_sure()) {
					return false;
				}
				var $this = $(this);
				// :first нужен если это episode или source (ведь у родителя тоже есть свой video_source:first)
				var $video_source = $this.parents('.video_source:first');
				$.ajax({
					url : $this.attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
						if (json.error) {
							alert(json.error);
							return;
						}
						$video_source.slideUp();
					}
				});
				return false;
			});
		},
		
		bindOnMainVideo: function() {
			var self = this;
			// activateCheckboxes();
			$('.showOnMain').live('change', function() {
				var id = $j(this).attr("id").split("_");
				var value = ($j(this).attr('checked') == true) ? 1 : 0;
				// Значения ставим наоборот, так как используется click, а не change ( т.е. сначала происходит событие click, а потом уже change)
				// var value = ($j(this).attr('checked') == true) ? 0 : 1;
				$j.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
					},
					data : {'id' : id[1], 'value' : value}
				});
			});
		},
		
		bindFixedVideo: function() {
			var self = this;
			$('.fixed').live('change', function() {
				var id = $j(this).attr("id").split("_");
				var value = ($j(this).attr('checked') == true) ? 1 : 0;
				$j.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
					},
					data : {'id' : id[1], 'value' : value}
				});
			});
		},
		
		bindInTopVideo: function() {
			var self = this;
			$('.intop').live('change', function() {
				var id = $j(this).attr("id").split("_");
				var value = ($j(this).attr('checked') == true) ? 1 : 0;
				$j.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
					},
					data : {'id' : id[1], 'value' : value}
				});
			});
		},
		
		bindInHotVideo: function() {
			var self = this;
			$('.inhot').live('change', function() {
				var id = $j(this).attr("id").split("_");
				var value = ($j(this).attr('checked') == true) ? 1 : 0;
				$j.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
					},
					data : {'id' : id[1], 'value' : value}
				});
			});
		},
		
		bindInIndexVideo: function() {
			var self = this;
			$('.inindex').live('change', function() {
				var id = $j(this).attr("id").split("_");
				var value = ($j(this).attr('checked') == true) ? 1 : 0;
				$j.ajax({
					url : $(this).attr('rel'),
					type : "POST",
					dataType : 'json',
					timeout : 30000,
					error : function() {
						ajaxError();
					},
					success : function(json) {
					},
					data : {'id' : id[1], 'value' : value}
				});
			});
		},
		
		/*
		================================================================================
		|                          Для страниц видео                                   |
		================================================================================
		*/
		
		constructForcedOpen: function() {
			// set
			this.setCustomZone();
 			this.setSliderPanel();
        	this.setCommentsPanel();
        	this.setMyQueue();
        	this.setSliderCarousel();
        	this.activateDecorateSourcePanel();
        	
        	// 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.bindShowProfile();
        	self.bindForgotPassword();
        	// Share
            self.bindShareLink();
        	
        	// addithional
			var id = $('.video_source:first').attr('id').split('_');							
			// Устанавливаем id эллемента для комментирования
			self.setVideoContentId(id[2]);
			// Включаем кнопку комментрирования
			self.commentsPanel.enableCommentsButton();
		},
		
		bindSliderActionsForcedOpen: function() {
			var self = this;
			$('.show_video_content').live('click', function() {
				self.bindAddressForcedOpen();
				return false;
			});;
			
			$('.video_player_close').live('click', function() {
				self.sliderPanel.hideVideoContent();
				// Показываем карусель (возможно реализовать задержку, но тогда функцию вынести в sliderPanel)
				self.sliderCarousel.showSliderCarousel();
			});
		},
				
		bindAddressForcedOpen: function () {
			var self = this;
			// Запускаем видео
			var id = window.location.pathname.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();
			// Увеличиваем количество просмотров
			var views_id = $('.views_' + id[1]);
			if (views_id.size() > 0) {
				views_id.html(parseInt(views_id.html()) + 1);
			}
		},
		
		/*
		================================================================================
		|                     Для администратора (страницы с видео)                    |
		================================================================================
		*/
		
		constructForcedOpenForAdmin: function() {
			this.constructForcedOpen();
			this.bindApproveVideo();
			this.bindRefuseVideo();
			this.bindEditVideo();
			this.bindDeleteVideo();
			this.bindOnMainVideo();
			this.bindFixedVideo();
			this.bindInTopVideo();
			this.bindInHotVideo();
			this.bindInIndexVideo();			
		}
 	}
 	 	
 	$.Module_TV = function(options) {
 		return new Module_TV(options);
 	};
 	
 	$.Module_TV_prototype = function() {
 		return Module_TV.prototype;
 	};
 
 })(jQuery);
