var mainPane = 1;
tinyMCE
		.init( {
			mode : "textareas",
			theme : "advanced",
			plugins : "safari,pagebreak,style,table,advimage,advlink,nonbreaking",
			editor_selector : "withMCE",
			editor_deselector : "withoutMCE",

			indentation : '10pt',
			entity_encoding : "raw",

			// just learn to use Shift+Enter instead of using these 3 lines
			// force_br_newlines : true,
			// force_p_newlines : false,
			// forced_root_block : '',

			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "tablecontrols,|,cut,copy,paste,|,search,replace,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,forecolor,backcolor",
			theme_advanced_buttons3 : "link,unlink,insertfile,image,|,sub,sup,nonbreaking,|,code,styleprops,|,charmap,|,flyoutbreak",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			content_css : "../css/tinymce_content.css",
			file_browser_callback : "ajaxfilemanager",
			
			setup : function(ed) {
		        // Add a custom button
		        ed.addButton('flyoutbreak', {
		            title : 'Set flyout breakpoint',
		            image : '/images/design/icons/flyout_break.gif',
		            onclick : function() {
		                ed.focus();
		                ed.selection.setContent('<hr class="flyout_breakpoint" />');
		            }
		        });
		    },


			// Theme options
			// Drop lists for link/image/media/template dialogs
			// template_external_list_url : "/js/for_mce/template_list.js",
			// external_link_list_url : "/js/for_mce/link_list.js"
			// external_image_list_url : "/js/for_mce/image_list.js",
			// media_external_list_url : "/js/for_mce/media_list.js"

			external_link_list_url : "/getStaticPageLinks.php"
		});
// simplified version (no file upload)
tinyMCE
	.init( {
		mode : "textareas",
		theme : "advanced",
		plugins : "safari,pagebreak,style,table,advlink,nonbreaking",
		editor_selector : "withSimpleMCE",
		editor_deselector : "withoutMCE",
	
		indentation : '10pt',
		entity_encoding : "raw",
	
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "tablecontrols,|,cut,copy,paste,|,search,replace,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,forecolor,backcolor",
		theme_advanced_buttons3 : "link,unlink,|,sub,sup,nonbreaking,|,code,styleprops,|,charmap",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		content_css : "../css/tinymce_content.css"
});

function ajaxfilemanager(field_name, url, type, win) {
	var ajaxfilemanagerurl = "/js/tinymce/jscripts/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php";
	switch (type) {
	case "image":
		break;
	case "media":
		break;
	case "flash":
		break;
	case "file":
		break;
	default:
		return false;
	}
	tinyMCE.activeEditor.windowManager
			.open(
					{
						url : "/js/tinymce/jscripts/tiny_mce/plugins/ajaxfilemanager/ajaxfilemanager.php",
						width : 782,
						height : 440,
						inline : "yes",
						close_previous : "no"
					}, {
						window : win,
						input : field_name
					});
}
/**
 * @desc stretch empty content pane to fill the screen
 */
function adjustContentHeight() {
	$('.adjustingWidth').width(500);

	var el = $('.content-block');
	el.css('height', '');
	var navh = $('.staticnav').height() + 40;
	if (((el.height() + 600) < $(window).height()) || (el.height() < navh)) {
		el.height($(window).height() - 600);
		if (el.height() < navh + 30) {
			el.height(navh + 30);
		}
	}
	var news = $('.content-news');
	if (news.height() < 300) {
		news.height(300);
	}

	return true;
}
/**
 * @desc some minor layout adjustments
 */
function adjustLayout() {
	var color = $("#wrapper").css("background-color");
	$('.staticnav a').css('color', color);
	$('.activelink').children('ul>li').css('margin-left', '5px').css(
			'margin-top', '-3px').show();
	$('.currentlink > a').css('text-decoration', 'none');
	$('.staticnav li:not(:has(ul))').css('background',
			'url(../images/menu/noexpand.gif) 0px 5px no-repeat');
	$('.hiddenpagelink').css('color', '#9d9d9d');
}
/**
 * @desc frame resize utility from
 *       http://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content/362564#362564
 */
function resizeIframe(height) {
	// "+60" is a general rule of thumb to allow for differences in
	// IE & and FF height reporting, can be adjusted as required..
	document.getElementById('forumiframe').height = parseInt(height) + 100;
	adjustContentHeight();
}

$(document)
		.ready(
				function() {
					$(window).resize(function(e) {
						return adjustContentHeight();
					});
					bindHandlers();
					reportErrors();
					// design init
					$(".footer-center ul li:first").addClass("border-none");
					if (privacyMode == '1') {
						if (friends == '1') {
							var modules = {
								'3' : '1',
								'2' : '2',
								'8' : '3',
								'1' : '4',
								'4' : '5',
								'7' : '6'
							};
						} else {
							var modules = {
								'3' : '1',
								'2' : '2',
								'1' : '3',
								'4' : '4',
								'7' : '5'
							};
						}
					} else {
						if (friends == '1') {
							var modules = {
								'3' : '1',
								'2' : '2',
								'8' : '3',
								'1' : '4',
								'5' : '5',
								'6' : '6',
								'4' : '7',
								'7' : '8'
							};
						} else {
							var modules = {
								'3' : '1',
								'2' : '2',
								'1' : '3',
								'5' : '4',
								'6' : '5',
								'4' : '6',
								'7' : '7'
							};
						}
					}
					if (friends == '1') {
						var m = 4;
					} else {
						var m = 3;
					}
					if (location.search.length > 0) {
						var querystring = location.search.replace('?', '')
								.split('&');
						var query = {};
						for ( var i = 0; i < querystring.length; i++) {
							var name = querystring[i].split('=')[0];
							var value = querystring[i].split('=')[1];
							query[name] = value;
						}
						if (query['m'] && modules[query['m']]) {
							m = modules[query['m']];
						}
					}
					if (privacyMode == '1') {
						if (friends == '1') {
							$(".slide").hrzAccordion( {
								eventTrigger : "click",
								openOnLoad : m,
								handlePositionArray : "left,left,left,left,left,right",
								containerClass : "container",
								handleClass : "handle",
								handleClassOver : "handleOver",
								handleClassSelected : "handleSelected"
	
							});
						} else {
							$(".slide").hrzAccordion( {
								eventTrigger : "click",
								openOnLoad : m,
								handlePositionArray : "left,left,left,left,right",
								containerClass : "container",
								handleClass : "handle",
								handleClassOver : "handleOver",
								handleClassSelected : "handleSelected"
	
							});
						}
					} else {
						if (friends == '1') {
							$(".slide")
								.hrzAccordion(
									{
										eventTrigger : "click",
										openOnLoad : m,
										handlePositionArray : "left,left,left,left,left,left,left,right",
										containerClass : "container",
										handleClass : "handle",
										handleClassOver : "handleOver",
										handleClassSelected : "handleSelected"
	
									});
						} else {
							$(".slide")
							.hrzAccordion(
								{
									eventTrigger : "click",
									openOnLoad : m,
									handlePositionArray : "left,left,left,left,left,left,right",
									containerClass : "container",
									handleClass : "handle",
									handleClassOver : "handleOver",
									handleClassSelected : "handleSelected"

								});
						}
					}

					$(
							".forum-category thead .forum-title, .forum-stat thead .forum-title")
							.corner("top 15px");
					// END OF design init

					var color = $("#wrapper").css("background-color");
					$('.staticnav a').css('color', color).css(
							'text-decoration', 'underline').hover(function() {
						$(this).css('text-decoration', 'none');
					}, function() {
						if (!$(this).parent().hasClass('currentlink')) {
							$(this).css('text-decoration', 'underline');
						}
					});

					$('body').ajaxSuccess(function() {
						adjustLayout();
					});
					
					$('#search_input input').unbind().bind('click', function() {
						var content = $(this).val();
						if (content == 'поиск...') {
							$(this).val('');
						}
					}).bind('blur', function() {
						var content = $(this).val();
						if (content == '') {
							$(this).val('поиск...');
						}
					});

					adjustLayout();
					adjustContentHeight();
					playMenuJDock();
					playMenuShift();
					footerSliderShift();
					handlePlaceTabSelection();
					startBannerRotation();
					mcSubmitPersons(false);
					bindVodAgreementControls();
					checkVodAgreement();
					
					// function to handle the data coming back from the history
					// upon forward/back hit
// $.history.callback = function ( reinstate, cursor ) {
// // $('body').css('cursor','wait');
// var path = '/index.php?m=1&ajax=1';
// if (typeof(reinstate) !== 'undefined') {
// path = reinstate.path || path;
// }
// $.ajax({
// url : path,
// success : function(data) {
// var contblock = $('.content-block');
// contblock.empty();
// contblock.html(data);
// adjustContentHeight();
// bindHandlers();
// triggerAkkordion(path);
// $.history._locked = false;
// // $('body').css('cursor','default');
// return true;
// },
// error: function () {
// // $('body').css('cursor','default');
// $.history._locked = false;
// return false;
// }
// });
// };
					// $.history.init();
					
				}).keyup(function(e) {
					if (e.keyCode == 27) { // esc
						$('#close_authorization').click();
					}
				});

// Hook into State Changes
// var History = window.History;
History.Adapter.bind(window, 'statechange', function() {
	if ( !History.enabled ) {
		return false;
	}
	var	State = History.getState(),
	rootUrl = History.getRootUrl(),
	url = State.url,
	relativeUrl = url.replace(rootUrl,'');
	if (relativeUrl == '') {
		relativeUrl = 'index.php?m=1&a=178&ajax=1';
	}
	if (relativeUrl.indexOf('ajax=1') >= 0) {
		var method = 'GET';
		var data = '';
		if (typeof State.data != 'undefined' && !$.isEmptyObject(State.data)) {
			method = 'POST';
			var data_arr  = new Array();;
			for (var n in State.data) {
				data_arr.push(n + '=' + State.data[n]);
			}
			data = data_arr.join('&');
			// alert(data);
		}
		showAjaxWaitAnimation();
		$.ajax({
		url: relativeUrl,
		type : method,
		data: data,
		success: function(data, textStatus, jqXHR){
			hideAjaxWaitAnimation();
			$.fn.colorbox.close();
			var contblock = $('.content-block');
			contblock.empty();
			contblock.html(data);
			adjustContentHeight();
			bindHandlers();
			triggerAkkordion(relativeUrl);
			$(window).scrollTop(0);
			// $('html,body').scrollTo();
			return true;
		},
		error: function(jqXHR, textStatus, errorThrown){
			hideAjaxWaitAnimation();
			$.fn.colorbox.close();
			$(window).scrollTop(0);
			document.location.href = relativeUrl;
			return false;
		}
		}); // end ajax
	} else {
		window.location = url;
	}
});
// $(window).bind('statechange', function() {
// alert('here');
// var State = History.getState(),
// rootUrl = History.getRootUrl(),
// url = State.url,
// relativeUrl = url.replace(rootUrl,'');
// // alert(rootUrl);
// // alert(relativeUrl);
// // if (relativeUrl.indexOf('ajax=1') > 0) {
// if (relativeUrl != '') {
// $.ajax({
// url: relativeUrl,
// success: function(data, textStatus, jqXHR){
// // alert('success');
// var contblock = $('.content-block');
// contblock.empty();
// contblock.html(data);
// adjustContentHeight();
// bindHandlers();
// triggerAkkordion(relativeUrl);
// return true;
// },
// error: function(jqXHR, textStatus, errorThrown){
// document.location.href = relativeUrl;
// return false;
// }
// }); // end ajax
// } else {
// window.location = url;
// }
// }); // end onStateChange

function test(totest) {
	if (totest)
		alert(totest);
	else
		alert('test!');
}

function checkVodAgreement() {
	if (typeof vod_agreed != 'undefined' && vod_agreed == '0') {
		$('.agree_overlay').show();
		$('.agreepage').first().show();
		return false;
	} else {
		return true;
	}
}

function bindVodAgreementControls() {
	$('.agree_bottom_no_button, .agree_close_link').die().live('click', function(){
		$.cookie("vod_agreed", "0");
		var href = '/';
		window.location.replace(href);
		$('.agreepage').first().hide();
		// $('.agree_overlay').first().hide();
	});
	$('.agree_bottom_ok_button').die().live('click', function(){
		$.cookie("vod_agreed", "1");
		$('.agreepage').first().hide();
		$('.agree_overlay').first().hide();
	});
}

function bindColorboxes() {
	$('a.fullimagelink').colorbox( {
		opacity : 0,
		overlayClose : false,
		scrolling : false,
		href : function() {
			var position = location.href.indexOf("index.php");
			var host = location.href.substring(0, position);
			var image = $(this).find('img').attr('src');
			var image_parts = image.split('/');
			image = image_parts[image_parts.length - 1];
			image = host + 'images/newsitems/full/' + image;
			return image;
		}
	});
	$('a.establfullimagelink').colorbox( {
		opacity : 0,
		overlayClose : false,
		scrolling : false,
		href : function() {
			var position = location.href.indexOf("index.php");
			var host = location.href.substring(0, position);
			var image = $(this).find('img').attr('src');
			return host + image;
		}
	});
	$('a.eventfullimagelink').colorbox( {
		opacity : 0,
		overlayClose : false,
		scrolling : false,
		href : function() {
			var position = location.href.indexOf("index.php");
			var host = location.href.substring(0, position);
			var image = $(this).find('img').attr('src');
			return host + image;
		}
	});
	
	$('.forColorbox').colorbox( {
		opacity : 0,
		overlayClose : false,
		scrolling : false
	});
	
	$('.mc_m_p_img, .mc_movie_screenshot, .vod_screen4colorbox').colorbox( {
		opacity : 0,
		overlayClose : false,
		scrolling : false,
		href : function() {
			var position = location.href.indexOf("index.php");
			var host = location.href.substring(0, position);
			var image = $(this).find('img').attr('src');
			return host + image;
		}
	});
}

function bindHandlers() {

	adjustLinks();
	
	bindColorboxes();

	$('.dateinput').calendricalDate( {
		usa : true
	});
	$('.timeinput').calendricalTime();

	// $(":submit").keydown(function(e) {
	// if (e.keyCode == 13) {
	// $this.parents('form').submit();
	// return false;
	// }
	// });

	$("form").die().live('submit', function() {
		$(":submit", this).click(function() {
			$(this).attr("disabled", "disabled");
			return false;
		});
	});

	ctrls4Categories();
	ctrls4news();
	ctrls4newsitem();
	ctrls4static();
	ctrls4messages();
	ctrls4announces();
	ctrls4confirmations();
	ctrls4banners();
	handleAkkordionNavigation();
	votingHandler();
	bindActionConfirmations();
	ctrls4rules();
	ajaxCrossing();
	bindManualCtrls();
	pageCrossing();
	bindMcInputHandlers();
	bindMcHandlers();
	showTagCloud();
	bindVodHandlers();

	$('.childrenlink').die().live('mouseenter', function() {
		$(this).parent().find('.childrenmenu').fadeIn(100);
	});

	$('.childrenmenu').die().live('mouseleave', function() {
		$(this).fadeOut(100);
	});

	$('.staticpagechildren').die().live('mouseleave', function() {
		$(this).find('.childrenmenu').fadeOut(100);
	});

	$('.announcementlink').die().live('mouseenter', function() {
		$(this).find('.announcementcontent').slideDown(200);
	}).live('mouseleave', function() {
		$(this).find('.announcementcontent').slideUp(100);
	});

	$('.staticpagemodules select').change(function() {
		var val = $(this).val();
		$('.staticpageslinks').hide();
		$('#formodule' + val).show();
	});

	$('#confirm_button').die().live('click', function() {
		$(this).parents('form').submit();
		$.fn.colorbox.close();
	});
	$('confirm_no_button').die().live(
			'hover',
			function() {
				$(this).css('background-image',
						'url(../images/msg/no_button_hover.png)');
			});
	$('confirm_yes_button').die().live(
			'hover',
			function() {
				$(this).css('background-image',
						'url(../images/msg/yes_button_hover.png)');
			});
	
	$('#confirmEditing, #request_discount_card, #save_component').unbind().bind('click', function() {
		var form = $(this).parents('form').first();
		if (checkInputNotEmpty(form)) {
			adjustRulesOrder();
			form.submit();
		}
		return false;
	});
	
	$('#request_discount_card, #requestStatistics').die().live('click', function() {
		var form = $(this).parents('form').first();
		if (checkInputNotEmpty(form)) {
			form.submit();
		}
		return false;
	});
	
//	$('#confirm_movie_order').die().live('click', function() {
//		alert('op!');
//		var form = $(this).parents('form').first();
//		form.submit();
//		return false;
//	});
	
	$('#mc_mo_s_b_1, #mc_mo_s_b_2').die().live('click', function() {
		var form = $(this).parents('form').first();
		if (checkInputNotEmpty(form)) {
			ajaxSubmitForm(form);
			// form.submit();
		}
		return false;
	});
	
	$('#confirm_movie_order').die().live('click', function() {
		var form = $(this).parents('form').first();
		// ajaxSubmitForm(form);
		form.submit();
		return false;
	});
	
	$('.sort_order').die().live('click', function() {
		var form = $(this).parents('form').first();
		var id = $(this).attr('href');
		form.find("input[name='sort']").attr('value', id);
		form.submit();
		return false;
	});
	
	$('#confirmEditorComment').unbind().bind('click', function() {
		$(this).parents('.overflow_pane').hide();
		$('.confirm_overlay').hide();
		$(this).parents('form').first().submit();
		return false;
	});
	
	$('#cancelEditorComment').unbind().bind('click', function() {
		$('.confirm_overlay').hide();
		$(this).parents('.overflow_pane').hide();
	});
	
	$('.add_editorcomments').unbind().bind('click', function() {
		$('.confirm_overlay').show();
		$('.overflow_pane').show();
	});
	
	$('.establ_table tr:odd').css('background', '#e2e2e2');
	
	$('#searchEstablishments').unbind().bind('click', function() {
		var sef = $('#searchEstablForm').first();
		var visible = sef.is(':visible');
		if (visible) {
			sef.hide();
			$(this).find('.button_message').html('Поиск');
			adjustContentHeight();
		} else {
			sef.show();
			$(this).find('.button_message').html('Отмена');
			adjustContentHeight();
		}
		return false;
	});
	
	$('#findEstablishments').unbind().bind('click', function(event) {
		var form = $(this).parents('form').first();
		var path = $(form).attr('action');
		path = addArgAjax(path);
		var formdata = $(form).serialize();
		if ( History.enabled ) {
			History.pushState(null, null, path);
			event.preventDefault();
			return false;
		} else {
			$.ajax( {
				type : 'POST',
				url : path,
				data: formdata,
				success : function(data) {
					var contblock = $('.content-block');
					contblock.empty();
					contblock.html(data);
					adjustContentHeight();
					bindHandlers();
	// $.history( {'path':path + '&' + formdata } );
					return false;
				}
			});
			return false;
		}
	});
	
	$('#request_discount_button').die().live('click', function() {
		$('#discount_description').hide();
		$('#discount_card_order').show();
		return false;
	});
	
	$('#cancelOrder').die().live('click', function() {
		$('#discount_card_order').hide();
		$('#discount_description').show();
		return false;
	});
	
	$('#blog_tab_2 .blog:first, #blog_tab_3 .blog:first').css('border', 'none');
	
	$('.show_component_content').die().live('click', function() {
		var content = $(this).siblings('.hidden_component_content').first().html();
		$.colorbox({html:content, width:'900px', height:'600px', top:'30px'});
	});
	
	$('#show_discount_rules').die().live('click', function() {
		var content = $(this).parent().siblings('.hidden_component_content#hidden_rules').first().html();
		$.colorbox({html:content, width:'900px', height:'600px', top:'30px'});
	});

	$('#all_partners').die().live('click', function() {
		var current = $('#hidden_partners');
		if (!current.is(':visible')) {
			current.show(0);
			$(this).find('.table_button_message').html('Скрыть');
		} else {
			current.hide(0);
			$(this).find('.table_button_message').html('Все партнеры');
		}
		return false;
	});
	
	$('.loginlink').unbind().bind('click', function() {
		$('.confirm_overlay').show();
		$('#authorization_wrapper').show();
	});
	
	$('#close_authorization, #login_button').die().live('click', function() {
		$('#authorization_wrapper').hide();
		$('.confirm_overlay').hide();
	});
	
}

function checkInputNotEmpty(form) {
	var smthMissed = false;
	var empty = '';
	$(form).find('.notEmpty').each(function(){
		var tmp = $(this).val();
		tmp = $.trim(tmp);
		if (tmp.length == 0) {
			smthMissed = true;
			empty = $(this).attr('title');
		}
	});
	if (smthMissed) {
		alert('Поле "' + empty + '" обязательно для заполнения.');
		return false;
	} else {
		return true;
	}
	return false;
}

function ctrls4staticNavigation() {
	$('.navmenulink').die().live('mouseenter', function() {
		$(this).parent().find('.navmenu').fadeIn(100);
	});

	$('.navmenu').die().live('mouseleave', function() {
		$(this).fadeOut(100);
	});

	$('.staticnavmenu').die().live('mouseleave', function() {
		$(this).find('.navmenu').fadeOut(100);
	});
}

function ajaxCrossing() {
	$('.ajaxCrossing').die().live('click', function(event) {
		var path = $(this).attr('href');
		path = addArgAjax(path);
		if (isRelativeUrl(path)) {
			// alert(path);
			// $('body').css('cursor','wait');
			stopAndUnloadJWPlayer();
			// showAjaxWaitAnimation();
			if ( History.enabled ) {
				History.pushState(null, null, path);
				event.preventDefault();
				// checkVodAgreement();
				return false;
			} else {
				$.ajax({
					url : path,
					success : function(data) {
						hideAjaxWaitAnimation();
						var contblock = $('.content-block');
						contblock.empty();
						contblock.html(data);
						adjustContentHeight();
						bindHandlers();
						triggerAkkordion(path);
						// checkVodAgreement();
	// $.history( {'path':path } );
						return false;
					},
					error: function () {
						hideAjaxWaitAnimation();
						return false;
					}
				});
				return false;
			}
		} else {
			return true;
		}
	});
}

function pageCrossing() {
	$('.pageCrossing').die().live('click', function(event) {
		var form = $(this).parents('form').first();
		var path = $(form).attr('action');
		path = addArgAjax(path);
		var formdata = $(form).serialize();
		// showAjaxWaitAnimation();
//		alert(formdata);
		var data = formdata.split('&');
		var obj = {};
		for (var item in data) {
//			alert(data[item]);
			var d = data[item].split('=');
			var prop_name = d[0];
			obj[prop_name] = d[1]; // [prop_name] = d[1];
		}
		// alert(obj);
		if ( History.enabled ) {
			History.pushState(obj, null, path);
			event.preventDefault();
			return false;
		} else {
			$.ajax( {
				type : 'POST',
				url : path,
				data: formdata,
				success : function(data) {
					hideAjaxWaitAnimation();
					var contblock = $('.content-block');
					contblock.empty();
					contblock.html(data);
					adjustContentHeight();
					bindHandlers();
	// $.history( {'path':path + '&' + formdata } );
					return false;
				},
				error : function() {
					hideAjaxWaitAnimation();
					return false;
				}
			});
			return false;
		}
	});
}

function triggerAkkordion(path) {
	var p = path.indexOf("?m=");
	var n = path.substring(p + 3, p + 4);
	if (privacyMode == '1') {
		if (friends == '1') {
			var modules = {'3' : '1','2' : '2','8' : '3','1' : '4',	'4' : '5','7' : '6'};
		} else {
			var modules = {'3' : '1','2' : '2','1' : '3','4' : '4','7' : '5'};
		}
	} else {
		if (friends == '1') {
			var modules = {'3' : '1','2' : '2','8' : '3','1' : '4','5' : '5',
					'6' : '6','4' : '7','7' : '8'};
		} else {
			var modules = {'3' : '1','2' : '2','1' : '3','5' : '4',
					'6' : '5','4' : '6','7' : '7'};
		}
	}
	m = modules[n] - 1;
	$('#slideHandle' + m).click();
}

function isRelativeUrl(url) {
	if (url && url.indexOf("/") == 0) {
		return true;
	}
	return false;
}

function playMenuJDock() {
	var jqDockOpts = {
		align : 'bottom',
		size : 90,
		distance : 130
	};
	$('.for_jDock').jqDock(jqDockOpts);
}

function playMenuShift() {
// $('.play_right').hover(function() {
// startPlayMenuRightShift();
// }, function() {
// stopPlayMenuRightShift();
// });
//
// $('.play_left').hover(function() {
// startPlayMenuLeftShift();
// }, function() {
// stopPlayMenuLeftShift();
// });
	$('.play_right').unbind().bind('click', function() {
		playMenuRightShiftOneStep();
	});
	$('.play_left').unbind().bind('click', function() {
		playMenuLeftShiftOneStep();
	});
}

function playMenuRightShiftOneStep() {
	var links = new Array();
	var icons = new Array();
	$('.playmenulink').each(function() {
		links.push($(this).attr('href'));
	});
	$('.playmenuicon').each(function() {
		icons.push($(this).attr('src'));
	});

	var lastlink = links.shift();
	var lasticon = icons.shift();
	links.push(lastlink);
	icons.push(lasticon);
	var i = 0;
	$('.playmenulink').each(function() {
		$(this).attr('href', links[i]);
		i++;
	});
	i = 0;
	$('.playmenuicon').each(function() {
		$(this).attr('src', icons[i]);
		i++;
	});
}

function playMenuLeftShiftOneStep() {
	var links = new Array();
	var icons = new Array();
	$('.playmenulink').each(function() {
		links.push($(this).attr('href'));
	});
	$('.playmenuicon').each(function() {
		icons.push($(this).attr('src'));
	});
	var lastlink = links.pop();
	var lasticon = icons.pop();
	links.unshift(lastlink);
	icons.unshift(lasticon);
	var i = 0;
	$('.playmenulink').each(function() {
		$(this).attr('href', links[i]);
		i++;
	});
	i = 0;
	$('.playmenuicon').each(function() {
		$(this).attr('src', icons[i]);
		i++;
	});
}

// function startPlayMenuRightShift() {
// var links = new Array();
// var icons = new Array();
// $('.playmenulink').each(function() {
// links.push($(this).attr('href'));
// });
// $('.playmenuicon').each(function() {
// icons.push($(this).attr('src'));
// });
//
// shiftingPlayMenuRight = window.setInterval(function() {
// var lastlink = links.shift();
// var lasticon = icons.shift();
// links.push(lastlink);
// icons.push(lasticon);
// var i = 0;
// $('.playmenulink').each(function() {
// $(this).attr('href', links[i]);
// i++;
// });
// i = 0;
// $('.playmenuicon').each(function() {
// $(this).attr('src', icons[i]);
// i++;
// });
// }, 300);
// }

// function stopPlayMenuRightShift() {
// clearInterval(shiftingPlayMenuRight);
// // alert('stopped');
// }
//
// function startPlayMenuLeftShift() {
// var links = new Array();
// var icons = new Array();
// $('.playmenulink').each(function() {
// links.push($(this).attr('href'));
// });
// $('.playmenuicon').each(function() {
// icons.push($(this).attr('src'));
// });
//
// shiftingPlayMenuLeft = window.setInterval(function() {
// var lastlink = links.pop();
// var lasticon = icons.pop();
// links.unshift(lastlink);
// icons.unshift(lasticon);
// var i = 0;
// $('.playmenulink').each(function() {
// $(this).attr('href', links[i]);
// i++;
// });
// i = 0;
// $('.playmenuicon').each(function() {
// $(this).attr('src', icons[i]);
// i++;
// });
// }, 300);
// }
//
// function stopPlayMenuLeftShift() {
// clearInterval(shiftingPlayMenuLeft);
// }

function handleAkkordionNavigation() {
	$('.handle').die().live(
			'click',
			function(e) {
				if (e.pageX) {
					var id = $(this).attr('id');
					var length = id.length;
					var n = id.substring(length - 1, length);
					if (privacyMode == '1') {
						if (friends == '1') {
							var arr = new Array('3', '2', '8', '1', '4',
									'7');
						} else {
							var arr = new Array('3', '2', '1', '4', '7');
						}
					} else {
						if (friends == '1') {
							var arr = new Array('3', '2', '8', '1', '5',
									'6', '4', '7');
						} else {
							var arr = new Array('3', '2', '1', '5',
									'6', '4', '7');
						}
					}
					var m = arr[n];
					var act = '178';
					var path = window.location.pathname;
					path += '?m=' + m + '&a=' + act + '&ajax=1';
					if (m == '4') {
						path += '&cache=2'
					}
					if ( History.enabled ) {
						History.pushState(null, null, path);
						e.preventDefault();
						return false;
					} else {
						$.ajax( {
							url : path,
							success : function(data) {
								$('.content-block').html(data);
								adjustContentHeight();
	// $.history( {'path':path } );
								return true;
							}
						});
					}
				}
				return true;
			});
}

function ctrls4newsitem() {
	$('.itemcontrols').hover(function(event) {
		$(this).width(391);
		var current = $(this).find('.newsmenucontainer');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}, function(event) {
		$(this).width(164);
		var current = $(this).find('.newsmenucontainer');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});
}

function ctrls4news() {
	$('.adminmenu').die().live('mouseenter', function(event) {
		var current = $(this).find('.adminmenu_content');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}).live('mouseleave', function(event) {
		var current = $(this).find('.adminmenu_content');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});
}

function ctrls4messages() {
	$('.messagemenu').die().live('mouseenter', function(event) {
		var current = $(this).find('.messagemenucontainer');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}).live('mouseleave', function(event) {
		var current = $(this).find('.messagemenucontainer');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});
}

function ctrls4rules() {
	
	$('.rulesubclauses').siblings('.rulecontent').addClass('withsubclauses');
	
	$('.withsubclauses').die().live('click', function(event) {
		var current = $(this).siblings('.rulesubclauses');
		if (current.length !== 0) {
			if (current.is(':visible')) {
				current.hide(0);
			} else if (!current.is(':visible')) {
				current.show(0);
			}
		}
	});

	$('.fold_all_rules img').die().live('click', function() {
		$('.rulesubclauses').hide(0);
	});

	$('.unfold_all_rules img').die().live('click', function() {
		$('.rulesubclauses').show(0);
	});
	
	// for rules editing
	$('.remove_rule img').die().live('click', function() {
		alert('Удаляем правило');
		var li = $(this).parents('li').first();
		if (li.hasClass('immutablerule') || li.find('.immutablerule').length > 0) {
			alert('Нельзя удалить правило, на основании которого совершали администраторские действия');
		} else {
			li.remove();
			adjustRulesOrder();
			adjustRulesHierarchyIds();
		}
	});
		
	 $('.add_rule img').die().live('click', function() {
		 alert('Добавляем правило в конце раздела');
		 var last = $("input[name='last_rule_id']");
		 var lastid = last.val();
		 lastid++;
		 last.attr('value', lastid);
		 var controls = $(this).parents('.edit_rules_controls').first();
		 var controlsid = controls.attr('id');
		 var parentid = controlsid.split('_')[1];
		 if (!parentid) {
			 parentid = 0;
		 }
		 controls.siblings('ul').first().append('<li id="rule-' + lastid + '"><input type="hidden" class="rule_order" name="rule-' + lastid + '" value="0" /><span class="hierarchy_holder"> </span><textarea name="rule-' + lastid + '_parent-' + parentid + '" rows="4" cols="60" class="notEmpty" title="Правило"> </textarea><div class="edit_rules_controls" id="forrule_' + lastid + '"><span class="remove_rule"><img src="/images/menu/remove_rule.png"><span> Удалить подпункт</span></span><span class="add_rule"><img src="/images/menu/add_rule.png"><span> Добавить подпункт</span></span></div><ul> </ul></li>');
		 adjustRulesOrder();
		 adjustRulesHierarchyIds();
	 });
	 
}

function adjustRulesHierarchyIds() {
	$('.hierarchy_holder').each(function() {
		var n = '';
		$(this).parents('li').each(function() {
			n = $(this).find('.rule_order').first().attr('value') + '.' + n;
		});
		n = n.substring(0, n.length - 1);
		$(this).html(n);
	});
}

function adjustRulesOrder() {
	$('#edit_rules ul').each(function() {
		var n = 1;
		$(this).children('li').each(function() {
			$(this).children('.rule_order').attr('value', n);
			n++;
		}); 
	});
}

function ctrls4Categories() {
	$('.ctrlsmenutrigger .triggeringcntrls').hover(
			function(event) {
				var current = $(this).parents('.ctrlspane').find(
						'.dockContainer');
				var visible = current.is(':visible');
				$('.dockContainer').fadeOut(500);
				$('.ctrlsmenutrigger').css('background-image',
						'url(/images/ctrls/ctrls_background.png)');
				$('.ctrlsmenutrigger img').attr('src',
						'/images/ctrls/arrows.png');
				if (!visible) {
					current.prev('.ctrlsmenutrigger').css("background-image",
							"url(/images/ctrls/ctrls_background_flipped.png)");
					current.prev('.ctrlsmenutrigger').find('img').attr('src',
							'/images/ctrls/arrows_flipped.png');
					current.fadeIn(400);
				}
			}, function(event) {
				return true;
			});
	$('.ctrlspane').hover(
			function(event) {
				return true;
			},
			function(event) {
				$('.dockContainer').fadeOut(500);
				$('.ctrlsmenutrigger').css('background-image',
						'url(/images/ctrls/ctrls_background.png)');
				$('.ctrlsmenutrigger img').attr('src',
						'/images/ctrls/arrows.png');
			});

	var jqDockOpts = {
		align : 'right',
		duration : 200,
		labels : 'tc',
		size : 50,
		distance : 45
	};
	$('.jqDock').jqDock(jqDockOpts);
}

function ctrls4static() {
	$('.staticpagecontrols').die().live('mouseenter', function(event) {
		$(this).width(289);
		var current = $(this).find('.newsmenucontainer');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}).live('mouseleave', function(event) {
		$(this).width(120);
		var current = $(this).find('.newsmenucontainer');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});

}
function bindManualCtrls() {
	$('.manuallink').unbind().bind('click', function(event) {
		// $('.confirm_overlay').show();
		$('.manualcontent').show();
	});
	$('.manual_close_link').unbind().bind('click', function(event) {
		$('.manualcontent').hide();
		// $('.confirm_overlay').hide();
	});
	$('.manual_question').unbind().bind('click', function() {
		$(this).next('.manual_answer').toggle();
	});
}

/*
 * from:
 * http://stackoverflow.com/questions/210717/what-is-the-best-way-to-center-a-div-on-the-screen-using-jquery
 */
jQuery.fn.center = function() {
	this.css("position", "absolute");
	this.css("top", ($(window).height() - this.height()) / 2
			+ $(window).scrollTop() + "px");
	this.css("left", ($(window).width() - this.width()) / 2
			+ $(window).scrollLeft() + "px");
	return this;
}

function reportErrors() {
	var err = $('.errormsg_back');
	var t = err.text();
	if ($.trim(t) !== '') {
		$('.errors').center().fadeIn('slow'); // .delay(3000).fadeOut('0');
		$('.confirm_overlay').show();
		$('.confirm_overlay').unbind().bind('click', function() {
			$('.errors').fadeOut(0);
			$(this).hide();
		});
	}
}

function showAjaxWaitAnimation() {
// $('#ajax_wait_animation').center().show().unbind().bind('click', function() {
// $(this).hide();
// });
	$('#ajax_wait_animation').show().unbind().bind('click', function() {
		$(this).hide();
	});
}

function hideAjaxWaitAnimation() {
	$('#ajax_wait_animation').hide();
}

function addArgAjax(original) {
	var out = original;
	if (original && original.indexOf("ajax") < 0) {
		if (original.indexOf("?") >= 0) {
			out = original + '&ajax=1';
		} else {
			out = original + '?ajax=1';
		}
	}
	return out;
}

function adjustLinks() {
	var orig = $('a.fullimagelink').attr('href');
	var modified = addArgAjax(orig);
	$('a.fullimagelink').attr('href', modified);
	orig = $('.loginlink a').attr('href');
	modified = addArgAjax(orig);
	$('.loginlink a').attr('href', modified);
	orig = $('#confirmation_flyout').attr('href');
	modified = addArgAjax(orig);
	$('#confirmation_flyout').attr('href', modified);
}
/**
 * @desc limit input text length from:
 *       http://www.rgagnon.com/jsdetails/js-0091.html
 */
function limitText(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
		alert("Максимальная длина текста анонса составляет " + limitNum
				+ " символов.");
	}
}

function ctrls4announces() {
	$('.announcementcontrols').die().live('mouseenter', function(event) {
		$(this).width(200);
		var current = $(this).find('.announcementcontrolscont');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}).live('mouseleave', function(event) {
		$(this).width(100);
		var current = $(this).find('.announcementcontrolscont');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});
}

function ctrls4confirmations() {
	$('.confirmationcontrols').die().live('mouseenter', function(event) {
		$(this).width(280);
		var current = $(this).find('.confirmationcontrolscont');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}).live('mouseleave', function(event) {
		$(this).width(100);
		var current = $(this).find('.confirmationcontrolscont');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});
}

function ctrls4banners() {
	$('.bannercontrols').die().live('mouseenter', function(event) {
		$(this).width(200);
		var current = $(this).find('.bannercontrolscont');
		if (!current.is(':visible')) {
			current.show(0);
		}
	}).live('mouseleave', function(event) {
		$(this).width(100);
		var current = $(this).find('.bannercontrolscont');
		if (current.is(':visible')) {
			current.hide(0);
		}
	});
}

function votingHandler() {
	lastvoted = 0;
	$('.voting').die().live(
			'mouseenter',
			function(event) {
				$(this).siblings().find('img').attr('src',
						'/images/stars/star_to_vote_empty.png');
				$(this).find('img').attr('src',
						'/images/stars/star_to_vote_filled.png').end()
						.prevAll().find('img').attr('src',
								'/images/stars/star_to_vote_filled.png');
			}).live('click', function() {
		var id = $(this).attr('id');
		var val = id.split('_')[1];
		$('#voting_result').attr('value', val);
		lastvoted = val;
	});

	$('.votescontainer').die().live(
			'mouseleave',
			function() {
				$(this).find('.voting img').attr('src',
						'/images/stars/star_to_vote_empty.png');
				$(this).find('.voting:lt(' + lastvoted + ') img').attr('src',
						'/images/stars/star_to_vote_filled.png');
			});
}

function bindActionConfirmations() {
 	 actions = new Array();
	 actions['action_156'] = 'Вы уверены, что хотите запретить комментарии?';
	 actions['action_155'] = 'Вы уверены, что хотите разрешить комментарии?';
	 actions['action_158'] = 'Вы уверены, что хотите запретить голосование?';
	 actions['action_157'] = 'Вы уверены, что хотите разрешить голосование?';
	 actions['action_128'] = 'Вы уверены, что хотите заблокировать новость?';
	 actions['action_129'] = 'Вы уверены, что хотите разблокировать новость?';
	 actions['action_142'] = 'Вы уверены, что хотите удалить комментарий?';
	 actions['action_143'] = 'Вы уверены, что хотите восстановить комментарий?';
	 actions['action_207'] = 'Вы уверены, что хотите скрыть мероприятие от просмотра?';
	 actions['action_208'] = 'Вы уверены, что хотите открыть мероприятие для просмотра?';
	 actions['action_199'] = 'Вы уверены, что хотите скрыть организацию от просмотра?';
	 actions['action_200'] = 'Вы уверены, что хотите открыть организацию для просмотра?';
	 actions['action_195'] = 'Вы уверены, что хотите выйти из режима администрирования?';
	 actions['action_194'] = 'Вы уверены, что хотите войти в режим администрирования?';
	 actions['action_189'] = 'Вы уверены, что хотите скрыть анонс?';
	 actions['action_192'] = 'Вы уверены, что хотите открыть анонс для просмотра?';
	 actions['action_215'] = 'Вы уверены, что хотите изъять баннер из баннерооборота?';
	 actions['action_216'] = 'Вы уверены, что хотите добавить баннер в баннерооборот?';
	 actions['action_162'] = 'Вы уверены, что хотите безвозвратно удалить категорию?';
	 actions['action_173'] = 'Вы уверены, что хотите скрыть страницу от просмотра?';
	 actions['action_174'] = 'Вы уверены, что хотите открыть страницу для просмотра?';
	 actions['action_172'] = 'Вы уверены, что хотите безвозвратно удалить эту страницу?';
	 actions['action_154'] = 'Вы уверены, что хотите выйти?';
	 actions['action_224'] = 'Вы уверены, что хотите удалить регистрацию пользователя на мероприятие?';
	 actions['action_225'] = 'Вы уверены, что хотите отказать пользователю в регистрации на мероприятие?';
	 actions['action_228'] = 'Вы уверены, что хотите скрыть новость от просмотра?';
	 actions['action_229'] = 'Вы уверены, что хотите открыть новость для просмотра?';
	 actions['action_183'] = 'Вы уверены, что хотите удалить объявление?';
	 actions['action_234'] = 'Вы уверены, что хотите отправить заведение на утверждение администратором?';
	 actions['action_239'] = 'Вы уверены, что хотите утвердить заведение и добавить его в общий список?';
	 actions['action_240'] = 'Вы уверены, что хотите вернуть заведение на доработку? Рекомендуется предварительно добавить комментарий для редактора.';
	 actions['action_244'] = 'Вы уверены, что хотите заблокировать блог заведения?';
	 actions['action_253'] = 'Вы уверены, что хотите заблокировать комментарии к странице блога?';
	 actions['action_254'] = 'Вы уверены, что хотите разрешить комментарии к странице блога?';
	 actions['action_255'] = 'Вы уверены, что хотите заблокировать комментарии к блогу?';
	 actions['action_256'] = 'Вы уверены, что хотите разрешить комментарии к блогу?';
	 actions['action_261'] = 'Вы уверены, что хотите удалить запись блога?';
	 actions['action_266'] = 'Вы уверены, что хотите удалить информацию о дисконтной карте?';
	 actions['action_274'] = 'Вы уверены, что хотите заблокировать комментарий?';
	 actions['action_295'] = 'Вы уверены, что хотите запретить появление комментария на главной странице?';
	 actions['action_296'] = 'Вы уверены, что хотите запретить появление фильма на главной странице?';
	 actions['action_305'] = 'Вы уверены, что хотите удалить новость?';
	 actions['action_315'] = 'Вы уверены, что хотите удалить единицу контента киноклуба?';
	
	 for (var link in actions) {
		$('a#' + link).die().live('click',
		function() {
			var id = $(this).attr('id');
			var text = '';
			if (actions[id]) {
				text = actions[id];
			}
			showConfirmationMessage(
				text,
				function(refer) {
					redirectToHref(refer);
				}, this);
			return false;
		});
	 }
}

function showConfirmationMessage(msg, callback, ref) {
	$('.confirm_message .message_bg #message_text').html(msg);
	$('.confirm_overlay').show();
	$('.confirm_message').center().show();
	$('.confirm_yes_button').unbind().bind('click', function() {
		$('.confirm_message').hide();
		$('.confirm_overlay').hide();
		$('.confirm_message .message_bg #message_text').html(' ');
		callback(ref);
	});
	$('.confirm_no_button').unbind().bind('click', function() {
		$('.confirm_message').hide();
		$('.confirm_overlay').hide();
		$('.confirm_message .message_bg #message_text').html(' ');
	});
	return false;
}

function redirectToHref(refer) {
	var href = $(refer).attr('href');
	window.location.replace(href);
}

function footerSliderShift() {
	$('.footer-slider_right').hover(function() {
		startFooterSliderRightShift();
	}, function() {
		stopFooterSliderRightShift();
	});

	$('.footer-slider_left').hover(function() {
		startFooterSliderLeftShift();
	}, function() {
		stopFooterSliderLeftShift();
	});
}

function startFooterSliderRightShift() {
	var links = new Array();
	var icons = new Array();
	$('.footer-slider_item a').each(function() {
		links.push($(this).attr('href'));
	});
	$('.footer-slider_item').each(function() {
		icons.push($(this).css('background-image'));
	});

	shiftingFooterSliderRight = window.setInterval(function() {
		var lastlink = links.shift();
		var lasticon = icons.shift();
		links.push(lastlink);
		icons.push(lasticon);
		var i = 0;
		$('.footer-slider_item a').each(function() {
			$(this).attr('href', links[i]);
			i++;
		});
		i = 0;
		$('.footer-slider_item').each(function() {
			$(this).css('background-image', icons[i]);
			i++;
		});
	}, 200);
}

function stopFooterSliderRightShift() {
	clearInterval(shiftingFooterSliderRight);
}

function startFooterSliderLeftShift() {
	var links = new Array();
	var icons = new Array();
	$('.footer-slider_item a').each(function() {
		links.push($(this).attr('href'));
	});
	$('.footer-slider_item').each(function() {
		icons.push($(this).css('background-image'));
	});

	shiftingFooterSliderLeft = window.setInterval(function() {
		var lastlink = links.pop();
		var lasticon = icons.pop();
		links.unshift(lastlink);
		icons.unshift(lasticon);
		var i = 0;
		$('.footer-slider_item a').each(function() {
			$(this).attr('href', links[i]);
			i++;
		});
		i = 0;
		$('.footer-slider_item').each(function() {
			$(this).css('background-image', icons[i]);
			i++;
		});
	}, 200);
}

function stopFooterSliderLeftShift() {
	clearInterval(shiftingFooterSliderLeft);
}
// a better way for easier tabs: http://dimox.name/universal-jquery-tabs-script/
function handlePlaceTabSelection() {
	$('.place_tabs a').die().live(
			'click',
			function() {
				var tab = $(this).attr('href');
				$('.place_tabs').css("background-image",
						"url(../images/menu/" + tab + ".png)");
				$('.place-items-blocks').hide();
				$('#' + tab).fadeIn();
				return false;
			});
	$('.blog_tab_cont a').die().live(
			'click',
			function() {
				$('.blog_tab_cont').css('z-index', 10);
				$('.tab_bg').removeClass('activetabitem');
				$(this).parents('.tab_bg').addClass('activetabitem');
				var tab = $(this).attr('href');
				$(this).parents('.blog_tab_cont').css('z-index', 50);
				$('.blog_tab').hide();
				$('#' + tab).fadeIn();
				adjustContentHeight();
				return false;
			});
}

function startBannerRotation() {
	getNextBanner();
	// setInterval(getNextBanner,10000); // time in milliseconds
}

function getNextBanner() {
	var n = $('.hidden_banner').length;
	var cur_id = -1;
	var current = $('.hidden_banner.activebanner');
	if (current.length > 0) {
		cur_id = current.attr('id');
		cur_id = cur_id.split('_');
		cur_id = cur_id[cur_id.length - 1];
	}
	var r = Math.floor(Math.random() * n) + 1;
	if (n > 1) {
		while (r == cur_id) {
			r = Math.floor(Math.random() * n) + 1;
		}
	}
	var newbanner = $('#hiddenbanner_' + r);
	$('.hidden_banner').removeClass('activebanner');
	newbanner.addClass('activebanner');
	var src = newbanner.find('.banner_image').html();
	src = $.trim(src);
	var link = newbanner.find('.banner_link').html();
	link = $.trim(link);
	var type = newbanner.find('.banner_type').html();
	type = $.trim(type);
	if (type == '1') { // swf
		$('#banner_pane').flash({swf:src,height:90,width:500});
	} else {
		$('#banner_pane').flash().remove();
		$('#banner_pane').html('<a href="' + link + '"><img src="'
			+ src + '" alt="" width="500" height="90" /></a>');
	}

}

function getScrollOffsetTop() {
	var scrollTop = $(window).scrollTop();
	return scrollTop;
}

function bindMcInputHandlers() {
	// awards
	$('.award_4_movie').die().live('change', function() {
		var selected = $(this).val();
		if (selected > 0) {
			var nominations = $('.mc_input_hidden').find('#nominations4_' + selected + ' select').first().clone();
			var award = $(this).attr('name');
			award = award.split('_')[1];
			$(nominations).attr('name', 'nomination4_' + award);
			$(this).parent().siblings('.awardcol2').html(nominations);
			var years = $('.mc_input_hidden').find('#years_2_add select').first().clone();
			$(years).attr('name', 'year4_' + award);
			$(this).parent().siblings('.awardcol4').html(years);
			var winner = $('.mc_input_hidden').find('#winner_2_add input').first().clone();
			$(winner).attr('name', 'winner4_' + award);
			$(this).parent().siblings('.awardcol5').html(winner);
		} else {
			$(this).parent().siblings('.awardcol2').empty();
			$(this).parent().siblings('.awardcol3').empty();
			$(this).parent().siblings('.awardcol4').empty();
			$(this).parent().siblings('.awardcol5').empty();
		}
	});
	$('.nomination_4_award').die().live('change', function() {
		var selected = $(this).val();
		var award = $(this).parent().siblings('.awardcol1').find('select').attr('name');
		award = award.split('_')[1];
		if (selected > 0 && (typeof mc_personal_nominations != 'undefined') && ($.inArray(selected, mc_personal_nominations) > -1)) {
			// var persons = $('.mc_input_hidden').find('#receivers_2_add
			// select').first().clone();
			var persons = $('#mc_possible_receivers select').first().clone();
			$(persons).attr('name', 'receivers4_' + award + '[]');
			$(this).parent().siblings('.awardcol3').html(persons);
		} else {
			$(this).parent().siblings('.awardcol3').empty();
		}
	});
	$('.mc_add_award').die().live('click', function() {
		var awards_n_input = $(this).siblings("input[name='awards_n']");
		var awards_n = $(awards_n_input).attr('value');
		var awards = $('.mc_input_hidden').find('#awards_2_add select').first().clone();
		var next = parseInt(awards_n) + 1;
		$(awards).attr('name', 'award_' + next);
		var row = $('<div class="awardcols"><span class="awardcol2"></span><span class="awardcol3">'
				+ '</span><span class="awardcol4"></span><span class="awardcol5"></span>'
				+ '<span class="mc_remove_award"><img src="/images/menu/remove_rule.png" /></span></div>');
		var span_1 = $('<span class="awardcol1"></span>');
		$(span_1).html(awards);
		$(row).prepend(span_1);
		$(this).before(row);
		$(awards_n_input).attr('value', next);
	});
	$('.mc_remove_award').die().live('click', function() {
		$(this).parents('.awardcols').first().remove();
		var awards_n_input = $('input#mc_awards_n');
		var awards_n = $(awards_n_input).attr('value');
		var next = parseInt(awards_n) - 1;
		$(awards_n_input).attr('value', next);
	});
	$('.mc_add_person_award').die().live('click', function() {
		var awards_n_input = $(this).siblings("input[name='awards_n']");
		var awards_n = $(awards_n_input).attr('value');
		var awards = $('.mc_input_hidden').find('#awards_2_add select').first().clone();
		var movies = $('.mc_input_hidden').find('#movies_2_add select').first().clone();
		var years = $('.mc_input_hidden').find('#years_2_add select').first().clone();
		var winner = $('.mc_input_hidden').find('#winner_2_add input').first().clone();
		var next = parseInt(awards_n) + 1;
		$(awards).attr('name', 'award_' + next);
		$(movies).attr('name', 'movie4_' + next);
		$(years).attr('name', 'year4_' + next);
		$(winner).attr('name', 'winner4_' + next);
		var row = $('<div class="awardcols"><span class="mc_remove_award"><img src="/images/menu/remove_rule.png" /></span></div>');
		var span_1 = $('<span class="awardcol1"></span>');
		var span_2 = $('<span class="awardcol2"></span>');
		var span_3 = $('<span class="awardcol3"></span>');
		var span_4 = $('<span class="awardcol4"></span>');
		var span_5 = $('<span class="awardcol5"></span>');
		$(span_1).html(awards);
		$(span_3).html(movies);
		$(span_4).html(years);
		$(span_5).html(winner);
		$(row).prepend(span_5);
		$(row).prepend(span_4);
		$(row).prepend(span_3);
		$(row).prepend(span_2);
		$(row).prepend(span_1);
		$(this).before(row);
		$(awards_n_input).attr('value', next);
	});
	$('.mc_add_person_job').die().live('click', function() {
		var jobs_n_input = $(this).siblings("input[name='mc_moviejobs_n']");
		var jobs_n = $(jobs_n_input).attr('value');
		var movies = $('.mc_input_hidden').find('#movies4jobs_2_add select').first().clone();
		var jobs = $('.mc_input_hidden').find('#occupations_2_add select').first().clone();
		var next = parseInt(jobs_n) + 1;
		$(movies).attr('name', 'movie4job_' + next);
		$(jobs).attr('name', 'job4movie_' + next);
		var row = $('<div class="jobcols"><span class="mc_remove_moviejob"><img src="/images/menu/remove_rule.png" /></span></div>');
		var span_1 = $('<span></span>');
		var span_2 = $('<span></span>');
		$(span_1).html(movies);
		$(span_2).html(jobs);
		$(row).prepend(span_2);
		$(row).prepend(span_1);
		$(this).before(row);
		$(jobs_n_input).attr('value', next);
	});
	$('.mc_remove_moviejob').die().live('click', function() {
		$(this).parents('.jobcols').first().remove();
		var jobs_n_input = $('input#mc_moviejobs_n');
		var jobs_n = $(jobs_n_input).attr('value');
		var next = parseInt(jobs_n) - 1;
		$(jobs_n_input).attr('value', next);
	});
	$('.award_4_person').die().live('change', function() {
		var selected = $(this).val();
		if (selected > 0) {
			var nominations = $('.mc_input_hidden').find('#nominations4_' + selected + ' select').first().clone();
			var award = $(this).attr('name');
			award = award.split('_')[1];
			$(nominations).attr('name', 'nomination4_' + award);
			$(this).parent().siblings('.awardcol2').html(nominations);
		} else {
			$(this).parent().siblings('.awardcol2').empty();
		}
	});
	// persons
	$('#mc_save_item_parse').die().live('click', function() {
		mcSubmitPersons(true);
		return false;
	});
	// movie
	$('#mc_s_i_submit_action').die().live('click', function() {
		var form = $(this).parents('form').first();
		// alert($(form).attr('action'));
		var msg = '';
		var stars = $(form).find('#mcinparticipants_1').attr('value');
		if (!stars || stars.length == 0) {msg += 'Актеры не указаны.<br/>'};
		var directors = $(form).find('#mcinparticipants_2').attr('value');
		if (!directors || directors.length == 0) {msg += 'Режиссер не указан.<br/>'};
		var writers = $(form).find('#mcinparticipants_3').attr('value');
		if (!writers || writers.length == 0) {msg += 'Сценарист не указан.<br/>'};
		var composers = $(form).find('#mcinparticipants_4').attr('value');
		if (!composers || composers.length == 0) {msg += 'Композитор не указан.<br/>'};
		var title_ru = $(form).find('#mc_in_title_ru').attr('value');
		if (!title_ru || title_ru.length == 0) {msg += 'Не указано русское название.<br/>'};
		var genres = $(form).find('#mc_in_genres').attr('value');
		if (!genres || genres.length == 0) {msg += 'Не указан жанр фильма.<br/>'};
		if (msg.length > 0) {
			msg += 'Вы уверены, что хотите сохранить без этих данных?<br/>';
			showConfirmationMessage(
				msg,
				function(refer) {
					mcSubmitForm(refer);
				}, form);
		} else {
			mcSubmitForm(form);
		}
		return false;
	});
	
	$('#mc_s_p_submit_action').die().live('click', function() {
		var form = $(this).parents('form').first();
		var msg = '';
		var name = $(form).find('#mc_in_name').attr('value');
		if (!name || $.trim(name).length == 0) {
			msg += 'Ошибка: не указано имя.'
		};
		if (msg.length > 0) {
			alert(msg);
			return false;
		}
		mcSubmitForm(form);
		return false;
	});

	$('#mc_s_ni_submit_action').die().live('click', function() {
		var form = $(this).parents('form').first();
// var msg = '';
// var name = $(form).find('#mc_in_name').attr('value');
// if (!name || $.trim(name).length == 0) {
// msg += 'Ошибка: не указано имя.'
// };
// if (msg.length > 0) {
// alert(msg);
// return false;
// }
		mcSubmitForm(form);
		return false;
	});
	
	$('#mc_c_e_submit_action').die().live('click', function() {
		var form = $(this).parents('form').first();
		mcSubmitForm(form);
		return false;
	});
	
	$('.mc_remove_link').die().live('click', function() {
		$(this).parents('.mc_link').first().remove();
		var links_n_input = $('input#mc_links_n');
		var links_n = $(links_n_input).attr('value');
		var next = parseInt(links_n) - 1;
		$(links_n_input).attr('value', next);
	});
	
	$('.mc_add_link').die().live('click', function() {
		var links_n_input = $(this).siblings("input[name='links_n']");
		var links_n = $(links_n_input).attr('value');
		var next = parseInt(links_n) + 1;
		var row = $('<div class="mc_link"><span><input type="text" name="link_files[]" value="" size="20" />'
			+'</span><span class="some_from_left"><input type="text" name="link_names[]" value="" size="20" />'
			+ '</span><span class="some_from_left"><input type="text" name="link_descriptions[]" value="" size="20" />'
			+ '</span><span class="mc_remove_link"><img src="/images/menu/remove_rule.png" /></span></div>');
		$(this).before(row);
		$(links_n_input).attr('value', next);
	});
	
	$('.mc_remove_award_nomination').die().live('click', function() {
		var parent = $(this).parents('.awardnomcols').first(); // .remove();
		var id2del = $(parent).find('input.mc_award_nom_input').first().attr('name');
		id2del = id2del.split('_')[1];
		var ids_input = $('input#mc_nomination_ids');
		var ids = $(ids_input).attr('value');
		var ids = ids.split(',');
		var idx = ids.indexOf(id2del);
		if(idx != -1) ids.splice(idx, 1); // Remove if found
		ids = ids.join(',');
		$(ids_input).attr('value', ids);
		$(parent).remove();
	});
	$('.mc_add_award_nomination').die().live('click', function() {
		var ids_input = $('input#mc_nomination_ids');
		var ids = $(ids_input).attr('value');
		var ids = ids.split(',');
		var max_id = $('input#mc_max_id').attr('value');
		next_id = parseInt(max_id) + 1;
		$('input#mc_max_id').attr('value', next_id);
		var row = $('<div class="awardnomcols"><span><input type="text" class="mc_award_nom_input" value="" name="nomination_'
				+ next_id + '" size="40"></span><span class="mc_award_personal_input"><input type="checkbox" name="personal_'
				+ next_id + '" value="1" /></span><span class="mc_remove_award_nomination">'
				+ '<img src="/images/menu/remove_rule.png"></span></div>');
		$(this).before(row);
		ids.push(next_id);
		ids = ids.join(',');
		$(ids_input).attr('value', ids);
	});

}

function bindMcHandlers() {
	$('#mcsearchtab_1').die().live('click', function() {
		$('#mcsearchtab_2').css('z-index', '50');
		$(this).css('z-index', '150');
		$('#mcsearchtabcontent_2').hide();
		$('#mcsearchtabcontent_1').show();
	});
	$('#mcsearchtab_2').die().live('click', function() {
		$('#mcsearchtab_1').css('z-index', '50');
		$(this).css('z-index', '150');
		$('#mcsearchtabcontent_1').hide();
		$('#mcsearchtabcontent_2').show();
	});
	
	$('#mcmovieordertab_1').die().live('click', function() {
		$('#mcmovieordertab_2').css('z-index', '50');
		$(this).css('z-index', '150');
	});
	$('#mcmovieordertab_2').die().live('click', function() {
		$('#mcmovieordertab_1').css('z-index', '50');
		$(this).css('z-index', '150');
	});
	
	$('#mcmainmovieordertab_1').die().live('click', function() {
		$('#mcmainmovieordertab_2').css('z-index', '50');
		$('#mcmainmovieordertab_2').css('top', '0px');
		$(this).css('z-index', '150');
		$(this).css('top', '1px');
	});
	$('#mcmainmovieordertab_2').die().live('click', function() {
		$('#mcmainmovieordertab_1').css('z-index', '50');
		$('#mcmainmovieordertab_1').css('top', '0px');
		$(this).css('z-index', '150');
		$(this).css('top', '1px');
	});
	
	$('.mc_comments_input_wrapper textarea').die().live('click', function() {
		var content = $(this).val();
		if ($.trim(content) == 'Ваш комментарий...') {
			$(this).val('');
		}
	}).live('blur', function() {
		var content = $(this).val();
		if ($.trim(content) == '') {
			$(this).val('Ваш комментарий...');
		}
	});
	
	$('.mc_comments_input_submit input').die().live('click', function() {
		var form = $(this).parents('form').first();
		mcSubmitComment(form);
	});
	
	$('#mcmoviemediatab_1').die().live('click', function() {
		$('#mcmoviemediatab_2').css('z-index', '50');
		$('#mcmoviemediatab_2').css('top', '0px');
		$(this).css('z-index', '150');
		$(this).css('top', '2px');
		$('.mc_movie_teasers').hide();
		$('.mc_movie_screenshots').show();
	});
	$('#mcmoviemediatab_2').die().live('click', function() {
		$('#mcmoviemediatab_1').css('z-index', '50');
		$('#mcmoviemediatab_1').css('top', '0px');
		$(this).css('z-index', '150');
		$(this).css('top', '2px');
		$('.mc_movie_screenshots').hide();
		$('.mc_movie_teasers').show();
	});
	
	$('.mc_m_p_preview_item').die().live('click', function() {
		var source = $(this).find('img');
		var path_1 = source.attr('src');
		var destination = $('.mc_m_p_img img');
		var path_2 = destination.attr('src');
		destination.attr('src', path_1);
		source.attr('src', path_2);
	});
	
	function carouselItemLoadCallback5(carousel, state) {
		carousel.size(parseInt($('#mc_main_movies_m_d_1_hidden_items>div').length));
		$('#mc_main_movies_m_d_1_hidden_items .mc_m_d_movie_wrapper').each(function() {
			carousel.add($(this).index(), $(this).html());
		});
	}
	
	$('#mc_main_movies_m_d_1').jcarousel({
		itemLoadCallback: carouselItemLoadCallback5,
    });
	
// $('.mc_editable_rating .mc_rating_value_item').die().live('mouseenter',
// function() {
// $(this).removeClass('mc_rating_item_grey
// mc_rating_item_selected').addClass('mc_active_rating_item');
// $(this).prevAll().removeClass('mc_rating_item_grey
// mc_rating_item_selected').addClass('mc_active_rating_item');
// }).live('mouseleave', function() {
// var current_rating = $(this).parent().attr('id').split('_')[1];
// $(this).parent().find('.mc_active_rating_item').removeClass('mc_active_rating_item');
// $(this).parent().find('.mc_rating_value_item:lt(' + current_rating +
// ')').addClass('mc_rating_item_selected');
// $(this).parent().find('.mc_rating_value_item:gt(' + current_rating + '),
// .mc_rating_value_item:eq(' + current_rating +
// ')').addClass('mc_rating_item_grey');
// }).live('click', function() {
// var ind = $(this).index();
// var current_id = $(this).parent().attr('id');
// $(this).parent().attr('id', current_id[0] + '_' + ind);
// $(this).parent().removeClass('mc_editable_rating');
// var path = $(this).siblings('#mcirel').attr('value');
// updateItemRating(ind, path, $(this).parent());
// });
	
	$('.mc_editable_rating .mc_rating_value_item').die().live('mouseenter', function() {
		$(this).find('img').attr('src', '/images/design/mc/mc_rating_star_active_17x17.png');
		$(this).prevAll().find('img').attr('src', '/images/design/mc/mc_rating_star_active_17x17.png');
		// $(this).removeClass('mc_rating_item_grey
		// mc_rating_item_selected').addClass('mc_active_rating_item');
		// $(this).prevAll().removeClass('mc_rating_item_grey
		// mc_rating_item_selected').addClass('mc_active_rating_item');
	}).live('mouseleave', function() {
		var current_rating = $(this).parents('.mc_mo_r_value').attr('id').split('_')[1];
		// $(this).parent().find('.mc_active_rating_item').removeClass('mc_active_rating_item');
		$(this).parents('.mc_mo_r_value').find('.mc_rating_value_item:lt(' + current_rating + ') img').attr('src', '/images/design/mc/mc_rating_star_selected_17x17.png');
		$(this).parents('.mc_mo_r_value').find('.mc_rating_value_item:gt(' + current_rating + ') img, .mc_rating_value_item:eq(' + current_rating + ') img').attr('src', '/images/design/mc/mc_rating_star_empty_17x17.png');
	}).live('click', function() {
		var ind = $(this).index() + 1;
		var current_id = $(this).parents('.mc_mo_r_value').attr('id');
		$(this).parents('.mc_mo_r_value').attr('id', current_id[0] + '_' + ind);
		$(this).parents('.mc_mo_r_value').removeClass('mc_editable_rating');
		var path = $(this).parents('.mc_mo_r_value').find('#mcirel').attr('value');
		updateItemRating(ind, path, $(this).parents('.mc_mo_r_value').first());
	});
	
	function updateItemRating(rating, path, rNode) {
		path = addArgAjax(path);
		var item = $('#mcirdata').attr('value');
		item = item.split('_');
		var item_type = item[1];
		var item_id = item[2];
		// alert('item_id:' + item_id + ' item_type:' + item_type + ' rating:' +
		// rating + ' path:' + path);
		var data = 'id=' + item_id + '&type=' + item_type + '&rating=' + rating;
		$.ajax( {
			type: "POST",
			url : path,
			data: data,
			success : function(data) {
				// alert(data);
				var resp = $('.mc_rating_response_message', data);
				var msg = $(resp).text();
				var r_new = $(resp).attr('id');
				r_new = r_new.split('_')[1];
				var current_r = $(rNode).attr('id').split('_')[0];
				$(rNode).attr('id', current_r + '_' + r_new);
				$('.errormsg_back .errormsg').text(msg);
				r_new--;
				$(rNode).find('.mc_rating_value_item:gt(' + r_new + ') img').attr('src', '/images/design/mc/mc_rating_star_empty_17x17.png');
				$(rNode).find('.mc_rating_value_item:lt(' + r_new + ') img, .mc_rating_value_item:eq(' + r_new + ') img').attr('src', '/images/design/mc/mc_rating_star_selected_17x17.png');
				reportErrors();
				return true;
			},
			error: function () {
				return false;
			}
		});
	}
	
	$('.mc_comment_page_link').die().live('click', function() {
// var p = $(this).attr('href');
// p = p.split('p=')[1];
// p = p.split('&')[0];
		var p = $(this).attr('id');
		p = p.split('_')[1];
		$('.mc_comments_block').hide();
		$('#mc_comments_block_' + p).show();
		$('.mc_comment_page_link').removeClass('mc_c_p_l_active');
		$('#mccplactive_' + p).addClass('mc_c_p_l_active');
		$(window).scrollTop($('#mc_comments_top_anchor').offset().top);
		// alert(p);
		return false;
	});
	
}

function mcSubmitPersons(removeCols) {
	var form = $('#mc_persons_form').first();
	var path = $(form).attr('action');
	path = addArgAjax(path);
	var formdata = $(form).serialize();
	$.ajax( {
		type : 'POST',
		url : path,
		data: formdata,
		success : function(data) {
			var hiddenblock = $('#hide_resp');
			hiddenblock.html(data);
			mcParsedNamesToLists(removeCols);
		}
	});
	return false;
}

function mcSubmitForm(form) {
	// alert('submiting');
	form.submit();
}

function mcSubmitComment(form) {
	var path = $(form).attr('action');
	path = addArgAjax(path);
	var formdata = $(form).serialize();
	$.ajax( {
		type : 'POST',
		url : path,
		data: formdata,
		success : function(data) {
			var contblock = $('.content-block');
			contblock.empty();
			contblock.html(data);
			adjustContentHeight();
			bindHandlers();
		}
	});
	return false;
}

function ajaxSubmitForm(form) {
	var path = $(form).attr('action');
	path = addArgAjax(path);
	var formdata = $(form).serialize();
	$.ajax( {
		type : 'POST',
		url : path,
		data: formdata,
		success : function(data) {
			var contblock = $('.content-block');
			contblock.empty();
			contblock.html(data);
			adjustContentHeight();
			bindHandlers();
		}
	});
	return false;
}

function mcParsedNamesToLists(removeCols) {
	// alert('parsing');
	var lists = $(".parse_response", $('#hide_resp'));
	// alert($(lists).html());
	$('.parsed_names', lists).each(function () {
		var id = $(this).attr('id');
		id = id.split('_')[1];
		var list = $(this).html();
		// alert(list);
		$('#mc_in_names_list_' + id).html(list);
	});
	$('.parsed_names_field', lists).each(function () {
		var id = $(this).attr('id');
		id = id.split('_')[1];
		var val = $(this).html();
		// alert(val);
		$('#mcinparticipants_' + id).attr('value', val);
	});
	if (removeCols) {
		$('.awardcols').remove();
	}
// $('.parsed_name', lists).each(function() {
// var name = $(this).text();
// var id = $(this).attr('id').split('_')[1];
// });
}

function updateLoginState() {
	window.location="/index.php?m=6&a=290";
}

function showTagCloud() {
	if ($('#mc_main_tagcloud_1').length > 0) {
		var tagsurlencoded = $('#tagsurlencoded_1').attr('value');
		var rnumber = Math.floor(Math.random() * 9999999);
		var so = new SWFObject("/js/tag_cloud/tagcloud.swf?r=" + rnumber,
				"tagcloudflash", "350", "350", "9");
		so.addParam("wmode", "transparent");
		so.addParam("allowScriptAccess", "always");
		so.addParam("bgcolor", "#FF0000");
		so.addVariable("tspeed", "150");
		so.addVariable("distr", "true");
		so.addVariable("mode", "tags");
		so.addVariable("tcolor", "0x542F57");
		so.addVariable("tcolor2", "0x009CFF");
		so.addVariable("hicolor", "0x009CCF");
		so.addVariable("tagcloud", tagsurlencoded);
		so.write("mc_main_tagcloud_1");	
	}
}

function bindVodHandlers() {
	$('.vod_video_request').die().live('click', function() {
		// alert('Здесь мы будем взимать плату через биллинг...\nА пока просто выдаем доступ на 1 минуту для тестирования.');
		return true;
	});
	
	if ($('div#videodiv').length > 0) {
		var video = $('#videodiv .videolink').first().attr('value');
		if (video != undefined) {
			// jwplayer("videodiv").remove();
			var params = video.split('::');
			// loadJWPlayer();
			changeJWPlayerSource(params[0], params[1], params[2], params[3]);
		}
		return false;
	}
	
	function loadJWPlayer() {
	    jwplayer("videodiv").setup({
	        flashplayer : "/js/jwplayer/player.swf",
	        height : 270,
	        width : 480
	    });
	}
	
	function changeJWPlayerSource(host, port, videofile, hash) {
		// alert('here we are');
		var rndNum = Math.round(1000 * Math.random());
		var file = videofile.split('.');
		var ext = file.pop();
		file = file.join('.'); // in case there is another dot in the file name
		// jwplayer("videodiv").remove();
		// provider : 'rtmp',
		// alert(host + port);
	    jwplayer("videodiv").setup({
	        flashplayer : "js/jwplayer/player.swf?" + rndNum,
	        file : 'mp4:' + videofile,
	        streamer: 'rtmpe://' + host + ':' + port + '/vod?' + hash + '&' + file + '&' + ext,
	        height : 270,
	        allowfullscreen:'true',
	        allowscriptaccess:'always',
	        autostart: true,
	        width : 480
	    });
	}
}

function stopAndUnloadJWPlayer() {
	if ($('object#videodiv').length > 0) {
		jwplayer().stop();
		jwplayer("videodiv").remove();
	}
}

function setRequestStatus(dh) {
	// alert('dh: ' + dh);
	var path = '/index.php?m=7&a=314';
	var formdata = 'dh=' + dh;
	$.ajax( {
		type : 'POST',
		url : path,
		data: formdata,
		success : function(data) {
			// alert(data);
			return true;
		}
	});
}
