/* Для специального JS-кода конкретных пректов */

var multiUploadifyExtraSelector = '',
singleUploadifyExtraSelector  = ':not(#f_sendVideoFile):not(#f_photoForThumb)';

var mainpage_video_moving;

var datepickerWasInitialized = false;

if(current_structure_id == 1)
{
	mainpage_video_moving = setInterval(MoveMainpageVideo, 5000);
}

jQuery( function($)
{
	$.datepicker.regional['ru'] = {
		closeText: 'Закрыть',
		prevText: '&#x3c;Пред',
		nextText: 'След&#x3e;',
		currentText: 'Сегодня',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
		'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
		dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
		dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		weekHeader: 'Не',
		dateFormat: 'dd.mm.yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
	};
	$.datepicker.setDefaults($.datepicker.regional['ru']);
});

function MoveMainpageVideo()
{
	if($(".active_video_switcher_control").next().size() != 0)
	{
		$(".active_video_switcher_control").removeClass('active_video_switcher_control').next().addClass('active_video_switcher_control');
		$(".active_video_switcher_movie").removeClass('active_video_switcher_movie').next().addClass('active_video_switcher_movie');
	}
	else
	{
		$(".active_video_switcher_control").removeClass('active_video_switcher_control');
		$(".active_video_switcher_movie").removeClass('active_video_switcher_movie');
		$(".video_switcher_control:first").addClass('active_video_switcher_control');
		$(".video_switcher_movie:first").addClass('active_video_switcher_movie');
	}
}

function replace_checkboxes()
{
	$("input[type=checkbox]").each( function()
	{
		$(this).wrap('<span class="checkbox_replacer_wrapper replacer_wrapper"/>').parent().append('<img alt="" src="/img/forms/checkbox_'+($(this).attr('checked')!=='checked'?'in':'')+'active.gif" rel="#'+$(this).attr("id")+'"/>');

		$(this).parent().children('img').click( function()
		{
			var new_value = $($(this).attr('rel')).attr('checked')!=='checked'?'checked':'';
			$($(this).attr('rel')).attr('checked', new_value).change();
		})
		$(this).change( function()
		{
			$(this).parent().children('img').attr('src', "/img/forms/checkbox_"+($(this).attr('checked')!=='checked'?'in':'')+"active.gif");
		})
	});
}

function replace_radios()
{
	$("input[type=radio]").each( function()
	{
		$(this).wrap('<span class="radio_replacer_wrapper replacer_wrapper"/>').parent().append('<img alt="" src="/img/forms/radio_'+($(this).attr('checked')!=='checked'?'in':'')+'active.gif" rel="#'+$(this).attr("id")+'"/>');

		$(this).parent().children('img').click( function()
		{
			var new_value = 'checked';//$($(this).attr('rel')).attr('checked')===false?'checked':'';
			$($(this).attr('rel')).attr('checked', new_value).change();
		})
		$(this).change( function()
		{
			$('input[type=radio][name='+$(this).attr('name')+']').each( function()
			{
				$(this).parent().children('img').attr('src', "/img/forms/radio_"+($(this).attr('checked')!=='checked'?'in':'')+"active.gif");
			})
		})
	});
}

function UpdateRelation(link)
{
	var m_action = link.hasClass('add_event_relation_link')?'1':'0';
	var data_row = 'script=relation_update&m_event_id='+encodeURIComponent(link.attr('rel'))+'&m_action='+encodeURIComponent(m_action);

	jQuery.ajax({
		type: "post",
		dataType: "json",
		data: data_row,
		url: "/ajax/",
		success: function(data, textStatus)
		{
			if(m_action == '1')
			{
				link.removeClass('add_event_relation_link');
				link.addClass('delete_event_relation_link');
				link.text('- Я передумал!');
				$("#event_users_count_div").text($("#event_users_count_div").text()*1+1);
			}
			else
			{
				$("#event_users_count_div").text($("#event_users_count_div").text()*1-1);
				link.addClass('add_event_relation_link');
				link.removeClass('delete_event_relation_link');
				if(link.hasClass('video'))
					link.text('+ Мне нравится');
				else
					link.text('+ Собираюсь посетить');
			}
		},
		error: function()
		{
			alert('Извините, произошла ошибка. Свяжитесь с администратором или попробуйте повторить дейсвтие позже.');
		}
	});

}

function ToggleCityInput()
{
	if($("#user_country").val() == '626')
		$("#user_city_div").show();
	else
		$("#user_city_div").hide();
}

function FilterLocationReload()
{
	var link = location.href.split('/');
	location.href = '/'+link[3]+'/';
}

function FilterInitialize()
{
	/***************** filter *************************/
	$(".filter_control").click( function()
	{
		$('.filter_control_form').hide();
		$(this).children('.filter_control_form').show();
	})

	$(".close_filter a").live('click', function(){
		$(this).parent().parent().hide();
		return false;
	})

	$(".item_place_filter").click(function(){
		$.cookie('place_filter', $(this).attr('rel'), {
			expires:  31,
			path: '/',
			domain: ".luckytv.ru"
		});
		$.cookie('part_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$(".item_part_filter").click(function(){
		$.cookie('part_filter', $(this).attr('rel'), {
			expires:  31,
			path: '/',
			domain: ".luckytv.ru"
		});
		$.cookie('place_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$(".item_date_filter").click(function(){
		$.cookie('date_filter', $(this).attr('rel'), {
			expires:  31,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$(".filter_link").live('click', function(){
		var cookie_value = '';
		if($(this).hasClass('place_link'))
		{
			cookie_value = $(this).attr('rel');
			$.cookie('place_filter', cookie_value, {
				expires:  31,
				path: '/',
				domain: ".luckytv.ru"
			});
			$.cookie('part_filter', '', {
				expires:  0,
				path: '/',
				domain: ".luckytv.ru"
			});
		}
		else if($(this).hasClass('part_link'))
		{
			cookie_value = $(this).attr('rel');
			$.cookie('part_filter', cookie_value, {
				expires:  31,
				path: '/',
				domain: ".luckytv.ru"
			});
			$.cookie('place_filter', '', {
				expires:  0,
				path: '/',
				domain: ".luckytv.ru"
			});
		}

		FilterLocationReload();
		return false;
	})

	$("#submenu_90 a").click(function(){
		var cookie_value = $(this).attr('href').substr(1);
		var link = $("#menu_item_90 > div.menu_text a").attr('href');

		$.cookie('part_filter', cookie_value, {
			expires:  31,
			path: '/',
			domain: ".luckytv.ru"
		});
		$.cookie('submenu_part_filter', '1', {
			expires:  31,
			path: '/',
			domain: ".luckytv.ru"
		});
		$.cookie('place_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		location.href = link;
		return false;
	})

	$("#place_filter_cancel").live('click',function(){
		$.cookie('place_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$("#part_filter_cancel").live('click',function(){
		$.cookie('part_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$("#date_filter_cancel").live('click',function(){
		$.cookie('date_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$("#datepicker").datepicker(
	{
		showOtherMonths:true,
		showWeek: true,
		beforeShowDay: function(date)
		{
			return [true, '', ''];
		},
		onSelect: function(dateText)
		{
			if(datepickerWasInitialized)
			{
				$.cookie('date_filter', dateText, {
					expires:  31,
					path: '/',
					domain: ".luckytv.ru"
				});
				FilterLocationReload();
			}
			else
				datepickerWasInitialized = true;
			return false;
		}
	});

	$("#date_all a").click(function(){
		$.cookie('date_filter', '', {
			expires:  0,
			path: '/',
			domain: ".luckytv.ru"
		});
		FilterLocationReload();
		return false;
	})

	$("#datepicker table tr td a").live('mouseenter', function()
	{
		$(this).parent().parent().addClass('active_week');
		$(this).css('color','red');
	})
	$("#datepicker table tr td a").live('mouseleave', function()
	{
		$(this).parent().parent().removeClass('active_week');
		$(this).css('color','#434343');
	})

	/************* end-filter *********************/

	$(".toolkit_form .field_date input").datepicker("destroy");
	$(".toolkit_form .field_date input").datepicker(
	{
		showOtherMonths:true,
		selectOtherMonths: true,
		changeMonth: true,
		changeYear: true,
		yearRange: 'c-100:c',
		onSelect: function(dateText, inst)
		{
			$($(this).attr('rel')).text(dateText);
			return false;
		}
	});
}

function ImgAreaSelectInitialize()
{
	var thumb_height = 110,
	thumb_width = 110;

	$('#thumbnailBig').imgAreaSelect({
		aspectRatio: '1:' + (thumb_height / thumb_width) + '',
		handles: true,
		onSelectEnd: function(img, selection) {
			var scaleX = thumb_width / selection.width;
			var scaleY = thumb_height / selection.height;

			var current_large_image_width = $('#thumbnailBig').width(),
			current_large_image_height = $('#thumbnailBig').height();

			$('#thumbnailSmall').css({
				width: Math.round(scaleX * current_large_image_width) + 'px',
				height: Math.round(scaleY * current_large_image_height) + 'px',
				marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
				marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
			});

			$('#f_photoX1').val(selection.x1);
			$('#f_photoY1').val(selection.y1);
			$('#f_photoX2').val(selection.x2);
			$('#f_photoY2').val(selection.y2);
			$('#f_photoWidth').val(selection.width);
			$('#f_photoHeight').val(selection.height);
		}
	})
}

function ThumbnailInitialize()
{

	ImgAreaSelectInitialize();

	$("#f_photoForThumb").uploadify({
		'uploader'  : '/uploadify/uploadify.swf',
		'script'    : '/uploadify/uploadifyPhoto.php',
		'cancelImg' : '/img/uploadify/cancel.png',
		'folder'    : '/upload/tmp',
		'fileExt'     : '*.jpg;*.gif;*.png;',
		'fileDesc'    : 'Image Files',
		'auto'      : true,
		'multi'     : false,
		'removeCompleted'   :   false,
		'onComplete' : function(event, queueID, fileObj, response, data)
		{
			var json = jQuery.parseJSON(response);

			if(json.error == 1)
			{
				$('#' + event.target.id + queueID).find('.percentage').remove()
				.end().removeClass('completed').addClass('wrongFile')
				.append('<span class="error"> - ' + json.text + "</span>");
			}
			else
			{
				$(event.target).parents('form').append('<input type="hidden" id="'+event.target.id+'_value_'+queueID+'" name="'+event.target.id+'_values[]" value="'+json.file+'"/>');

				$("#thumbnailWrapper").show();
				$("#thumbnailBig").attr('src', '/upload/tmp/' + json.file);
				$("#thumbnailSmall").attr('src', '/upload/tmp/' + json.file);
				$("#f_photoImg").val('/upload/tmp/' + json.file);
				ImgAreaSelectInitialize();
			}
		},
		onCancel: function(event, ID, fileObj, data)
		{
			//console.info('Из аплэудифая мульти: удален '+ID);
			var filename = $('#' + event.target.id+'_value_'+ID).val();
			jQuery.ajax({
				type:   "post",
				dataType: "json",
				url:    "/uploadify/delete.php",
				data:   "file="+filename,
				success:function(jsonData){
					/*console.log(jsonData);
					console.info('Код выполнения удаления: ' + jsonData.state);*/
					//$("#thumbnailWrapper").hide();
					$("#f_photoImg").val('');
				},
				error:  function(){
					//console.error('Запрос на удаление файла не выполнен.')
				}

			})
			$('#' + event.target.id+'_value_'+ID).remove();
		},
		onInit: function()
		{
		/*$('#'+this.id).parent().append('<a href="" rel="#'+this.id+'" class="doUpload">Загрузить выбранные файлы</a>');
			$('a.doUpload').click(function(){
				$($(this).attr('rel')).uploadifyUpload();
				return false;
			})*/
		}
	});
}

function PrivateRoomInitialize()
{
	var url = location.href.split('#');
	if(url.length == 2)
	{
		$(".private_room_content_block").hide();
		switch(url[1])
		{
			case 'messages':
				$("#private_room_content_messages").show();
				break;
			default:
				$("#private_room_content_info").show();
				break;
		}
	}

	$("a.private_room_toggle_link").live('click',function(){
		var target = $(this).attr('rel').split('.');
		$("."+target[0]+"_block").hide().end().find("#"+target[0]+"_"+target[1]).show();

		if(target[1] == 'edit')
		$('div[class|="imgareaselect"]').show();
		else
		$('div[class|="imgareaselect"]').hide();
	})

	//Private room menu
	$("#private_room_menu .menu_item").click( function()
	{
		if(!$(this).hasClass('active_menu_item'))
		{
			$("#private_room_menu .active_menu_item").removeClass('active_menu_item');
			$(this).addClass('active_menu_item');
			$(this).children('.menu_text').children('a').click();
		}
	})

	//Pager
	$(".event_pager_page a").click(function(){
		$(".event_pager_page").removeClass('active_page');
		$(this).parent().addClass('active_page');

		$(".event_page").hide().end()
		.find("#event_page_"+$(this).attr('rel')).show();
		return false;
	})

	$(".video_pager_page a").click(function(){
		$(".video_pager_page").removeClass('active_page');
		$(this).parent().addClass('active_page');

		$(".video_page").hide().end()
		.find("#video_page_"+$(this).attr('rel')).show();
		return false;
	})

	$(".users_pager_page a").click(function(){
		$(".users_pager_page").removeClass('active_page');
		$(this).parent().addClass('active_page');

		$(".users_page").hide().end()
		.find("#users_page_"+$(this).attr('rel')).show();
		return false;
	})

	//Uploadify
	$("#f_sendVideoFile").uploadify({
		'uploader'  : '/uploadify/uploadify.swf',
		'script'    : '/uploadify/uploadify.php',
		'cancelImg' : '/img/uploadify/cancel.png',
		'folder'    : '/upload/tmp',
		'fileExt'     : '*.avi;*.mp4;*.mpeg;*.flv;*.mpg',
		'fileDesc'    : 'Video Files',
		'auto'      : false,
		'multi'     : false,
		'removeCompleted'   :   false,
		'onComplete' : function(event, queueID, fileObj, response, data)
		{
			console.info('Из аплэудифая мульти: добавлен '+queueID);

			var json = jQuery.parseJSON(response);

			if(json.error == 1)
			{
				$('#' + event.target.id + queueID).find('.percentage').remove()
				.end().removeClass('completed').addClass('wrongFile')
				.append('<span class="error"> - ' + json.text + "</span>");
			}
			else
			{
				$(event.target).parents('form').append('<input type="hidden" id="'+event.target.id+'_value_'+queueID+'" name="'+event.target.id+'_values[]" value="'+json.file+'"/>');
			}
		},
		onCancel: function(event, ID, fileObj, data)
		{
			console.info('Из аплэудифая мульти: удален '+ID);
			var filename = $('#' + event.target.id+'_value_'+ID).val();
			jQuery.ajax({
				type:   "post",
				dataType: "json",
				url:    "/uploadify/delete.php",
				data:   "file="+filename,
				success:function(jsonData){
					console.log(jsonData);
					console.info('Код выполнения удаления: ' + jsonData.state);
				},
				error:  function(){
					console.error('Запрос на удаление файла не выполнен.')
				}

			})
			$('#' + event.target.id+'_value_'+ID).remove();
		},
		onInit: function()
		{
			$('#'+this.id).parent().append('<a href="" rel="#'+this.id+'" class="doUpload">Загрузить выбранные файлы</a>');
			$('a.doUpload').click(function(){
				$($(this).attr('rel')).uploadifyUpload();
				return false;
			})
		}
	});


	$("#private_room_content_messages a").click(function(event){
		var suffix = '/?q#messages', link = $(this).attr('href');
		if(link.charAt(link.length-1) == '/') suffix = '?q#messages';
		location.href = $(this).attr('href') + suffix;
		event.preventDefault();
	})
}

function SendVideoFromSubmitHandler(step, success)
{
	var info_id = '#sendVideoResult';
	var form_id = '#sendVideoForm';

	var data_row = 'script=sendVideo';
	if(step === undefined) step = 1;
	if(success === undefined) success = false;
	if(step == 1)
	{
		data_row += get_all_form_data(form_id);
		ajax_query(info_id, form_id, data_row);
	}
	else if(step == 2)
	{
		if(success)
			$(form_id).find("input[type='text'], input[type='password'], textarea").val('');
	}
}


function SendVideoInitialize()
{
	$("#sendVideoForm").submit(function(event){
		SendVideoFromSubmitHandler();
		event.preventDefault();
	}).find('#sendVideoSubmit').click(function(event){
		SendVideoFromSubmitHandler();
		event.preventDefault();
	});
}

$(document).ready( function()
{
	FilterInitialize();

	if(current_structure_id == 116)
	{
		var anc = location.href.split('#');
		if(anc.length > 1 && anc[1] == 'results')
		{
			show_results();
		}
	}

	$("#user_edit_form input").unbind('focus').unbind('blur');

	/* Понравилось и Собираюсь пойти ссылки */
	$('.event_relation_link').click(function(){
		UpdateRelation($(this));
		return false;
	})

	ToggleCityInput();
	$("#user_country").change(function(){
		ToggleCityInput();
	})

	ThumbnailInitialize();
	PrivateRoomInitialize();

	$(".lucky_video_player_div").each( function (i)
	{
		var id = $(this).attr("id");
		var file = $(this).attr("data-filename");
		var preview = $(this).attr("data-preview");
		var v_comment = $(this).attr("data-comment");
		var hd = $(this).attr("data-hdfile");
		var player_path = "/players/";

		var width = 700;
		var height = 424;
		if($(this).hasClass('mainpage_lucky_video'))
		{
			width = 539;
			height = 237;
		}

		if(hd.length > 0)
		{
			swfobject.embedSWF(player_path + "ass_player.swf", id, width, height, "9.0.115.0", player_path + "expressInstall.swf",
			{
				allowFullScreen: "true",
				media1Type: "video",
				media2Type: "video",
				MediaLink: file,
				MediaLink2: hd,
				defaultMedia: "1",
				image: preview,
				/*logo: player_path + "logo.swf",
				logoLink: "http://www.as-flash.com",
				logoTarget: "_blank",*/
				playOnStart: "false",
				share: "false",
				fullVideoScale: "true",
				imageScaleType: "0"
			},
			{
				wmode: "transparent",
				allowFullScreen: "true",
				allowScriptAccess: "always",
				movie: player_path + "ass_player.swf"
			}
			);
		}
		else
		{
			swfobject.embedSWF(player_path + "ass_player.swf", id, width, height, "9.0.115.0", player_path + "expressInstall.swf",
			{
				media1Type: "video",
				allowFullScreen: "true",
				MediaLink: file,
				image: preview,
				/*logo: player_path + "logo.swf",
				logoLink: "http://www.as-flash.com",
				logoTarget: "_blank",*/
				playOnStart: "false",
				share: "false",
				fullVideoScale: "true",
				imageScaleType: "0"
			},
			{
				wmode: "transparent",
				allowFullScreen: "true",
				allowScriptAccess: "always",
				movie: player_path + "ass_player.swf"
			}
			);
		}
	});

	$("#header_menu .menu_item .menu_text:last").css('background-image','none');
	$(".bottom_tags div.tag_item:last").css('border','0');

	$("#content[class=static]").wrapInner('<div class="content_padding" />').prepend('<h1>'+$("#content h1:first").text()+'</h1>');
	$(".content_padding h1").remove();

	replace_checkboxes();
	replace_radios();

	$(".video_switcher_control").click( function()
	{
		clearInterval(mainpage_video_moving);
		if(!$(this).hasClass('active_video_switcher_control'))
		{
			$(".active_video_switcher_control").removeClass('active_video_switcher_control');
			$(this).addClass('active_video_switcher_control');
			$(".active_video_switcher_movie").removeClass('active_video_switcher_movie');
			$($(this).attr('rel')).addClass('active_video_switcher_movie');
		}
	})
	$(".event_item:even").css('margin-right','22px');


	//pager scroll
	$('.pager_wrapper').jScrollPane();

	var active_page = $('.active_page').attr('rel')>=5?$('.active_page').attr('rel')-5:$('.active_page').attr('rel');

	var active_page_pos = active_page*30;

	if(active_page_pos > $(".pager").width()-$(".jspContainer").width())
		$('.jspPane').css('left', '-'+($(".pager").width()-$(".jspContainer").width())+'px');
	else
		$('.jspPane').css('left', '-'+active_page_pos+'px');

	var active_page_pos = active_page*$('.jspDrag').width()/11;
	if(active_page_pos + $('.jspDrag').width() < $('.jspTrack').width())
		$('.jspDrag').css('left', active_page_pos+'px');
	else
		$('.jspDrag').css('left', ($('.jspTrack').width() - $('.jspDrag').width())+'px');

	SendVideoInitialize();
})

