/**
*/
var multiUploadifyExtraSelector = '',
singleUploadifyExtraSelector  = ':not(#f_photoForThumb)';

/* Fast Show Photos */
//console.log('prephoto');
if(current_structure_id == 113)
{
	var img = new Image();
	img.src = '/img/loadinfo.net.gif';
//console.log('photo');
}

var radioWindow = undefined;

function UpdateOverallPanelLinksPadding()
{
	var totalWidth = 0;
	$("#overallPanel a").each(function(){
		totalWidth += $(this).width();
	});
	//console.log($("#overallPanel").innerWidth());
	//console.log($("#overallPanel").css('width'));
	$("#overallPanel a:not(:first)").css('padding-left', ( (910 - totalWidth)/$("#overallPanel a").size() ) + 'px');
}

function ImgAreaSelectInitialize()
{
	var thumb_height = 70,
	thumb_width = 70;

	$('#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 wrap_img()
{
	$("#content img[class!=default]").each( function()
	{
		$(this).wrap('<div class="img_frame" />').wrap('<div class="if_middle_right" />').wrap('<div class="if_middle_left" />');
		$(this).parent().parent().before('<div class="if_top"><div class="if_top_left"></div><div class="if_top_right"></div><div class="if_top_middle"></div><div class="clearfix"></div></div>');
		$(this).parent().parent().after('<div class="if_bottom"><div class="if_bottom_left"></div><div class="if_bottom_right"></div><div class="if_bottom_middle">'+$(this).attr('alt')+'</div><div class="clearfix"></div></div>');
	});
}

var ticking;

function move_digit(id)
{
	var top = $(id+" .digits_img").css('top');
	top = top.split('px');
	if(top[0]*1+77 <= 0)
		$(id+" .digits_img").css('top', (top[0]*1+77)+'px');
}

function tic(max, id)
{
	if
	(
		$("#days_digit").attr('rel') == '0' &&
		$("#hours_digit_0").attr('rel') == '0' &&
		$("#hours_digit_1").attr('rel') == '0' &&
		$("#minuts_digit_0").attr('rel') == '0' &&
		$("#minuts_digit_1").attr('rel') == '0' &&
		$("#seconds_digit_0").attr('rel') == '0' &&
		$("#seconds_digit_1").attr('rel') == '0'
		)
		{
		clearInterval(ticking);
		return;
	}

	var digit = $(id).attr('rel');
	var overflow = false;
	if(digit-- == 0)
	{
		digit = max;
		new_top = max*462;
		$(id+" .digits_img").css('top','-'+new_top+'px');
		overflow = true;

		//Тикаем следующей фигней
		var next_id = '', next_max = 9;

		switch(id)
		{
			case '#seconds_digit_1':
				next_id = '#seconds_digit_0';
				next_max = 5;
				break;
			case '#seconds_digit_0':
				next_id = '#minuts_digit_1';
				break;
			case '#minuts_digit_1':
				next_id = '#minuts_digit_0';
				next_max = 5;
				break;
			case '#minuts_digit_0':
				next_id = '#hours_digit_1';
				if($("#hours_digit_0").attr('rel') == 0)
					next_max = 3;
				break;
			case '#hours_digit_1':
				next_id = '#hours_digit_0';
				next_max = 2;
				break;
			case '#hours_digit_0':
				next_id = '#days_digit';
				next_max = 9;
				break;
		}

		tic(next_max, next_id);
	}
	$(id).attr('rel', digit);

	var frame_time = 60;
	if(!overflow)
	{
		setTimeout(move_digit, frame_time, id);
		setTimeout(move_digit, frame_time*2, id);
		setTimeout(move_digit, frame_time*3, id);
		setTimeout(move_digit, frame_time*4, id);
		setTimeout(move_digit, frame_time*5, id);
		setTimeout(move_digit, frame_time*6, id);
	}


}

$(document).ready( function()
{
	//tic();
	//$("#seconds_digit_1 .digits_img").css('top','-'+($("#seconds_digit_1").attr('rel')*462)+'px');
	if(current_structure_id == 1)
	{
		$(".digits_img").each(function(){
			$(this).css('top','-'+($(this).parent().attr('rel')*462)+'px');
		})
		ticking = setInterval(tic, 1000, 9, '#seconds_digit_1');
	}

	$("#top_menu .submenu .submenu_item:last-child, #top_menu .submenu .submenu_item:last").css('border','0');
	$("#top_menu .menu_item:last").css('background-image', 'none').find('a').css('padding-right','0');
	//var Image1 = new Image(); Image1.src = '/img/arrow_left_hover.gif';

	/*if(!($.browser.msie && ($.browser.version.charAt(0) == '6' || $.browser.version.charAt(0) == '7')))
    {
    wrap_img();
    }
    */

	/********************/
	if(false && current_structure_id == 1)
	{
		$(".menu_item").unbind('mouseenter');
		$(".menu_item, div.submenu_item").unbind('mouseleave');

		$(".menu_item").mouseenter(function(){
			$(this).addClass('hover_menu_item');
			$(this).children('.submenu').slideDown('slow');

			var l = 0, t = 0;
			if($(this).hasClass("menu_item"))
			{
				t += $(this).outerHeight();
				l = -$(this).position().left;
			}

			$("#"+$(this).attr("rel")).css("left",l+"px");
			$("#"+$(this).attr("rel")).css("top",t+"px");
		})

		$(".menu_item").mouseleave(function(){
			$(this).removeClass('hover_menu_item');
			$(this).children('.submenu').hide();
		})
	}
	else
	{
		$("div.menu_item, div.submenu_item").unbind('mouseenter');
		//Поведение меню
		$("div.menu_item, div.submenu_item").mouseenter(function() {
			//var elem = document.getElementById($(this).attr("id"));
			var l = 0;
			var t = 0;

			/*while (elem)
            {
            l += elem.offsetLeft;
            t += elem.offsetTop;
            elem = elem.offsetParent;
            }*/

			if($(this).hasClass("menu_item"))
			{
				t += $(this).outerHeight();
			}

			if(!$(this).hasClass("menu_item"))
			{
				l = $(this).outerWidth();
				t = $(this).position().top;
			}

			$("#"+$(this).attr("rel")).css("left",l+"px");
			$("#"+$(this).attr("rel")).css("top",t+"px");
			$("#"+$(this).attr("rel")).slideDown('slow');;
		});

	/*$("div.menu_item, div.submenu_item").mouseleave(function() {
        if($(this).hasClass("submenu"))
        $(this).hide();
        $("#"+$(this).attr("rel")).hide();

        });*/
	}
	/**********************/

	$(".calendar_active").mouseenter(function(){
		$(this).children(".calendar_event").slideDown('slow');
	})
	$(".calendar_active").mouseleave(function(){
		$(this).children(".calendar_event").hide();
	})



	$("#content table[class!=default] tr th:last-child, #content table[class!=default] tr td:last-child").css('border-right-color','#787878');
	$("#left_line_wrapper").css('min-height',$("#main_wrapper").height()+'px')


	swfobject.embedSWF("/swf/play2.swf", "audio_player_block", 600, 25, "9.0.0.0", "/swf/expressInstall.swf",
	{
		wmode: "transparent",
		theme: 1,
		/*ID: 2,*/
		xml_link: "/swf/playlist.xml"
	},
	{
		wmode: "transparent",
		allowScriptAccess: "always",
		movie: "/swf/play2.swf"
	}
	);
	//Баннер организация
	swfobject.embedSWF("/swf/banner.swf", "banner", 940, 80, "9.0.0.0", "/swf/expressInstall.swf",
	{
		wmode: "transparent"
	},
	{
		wmode: "transparent",
		allowScriptAccess: "always",
		movie: "/swf/banner.swf"
	}
	);

	$(".music_link[rel]").click(function(){
		swfobject.embedSWF("/swf/play2.swf", "audio_player_block", 600, 25, "9.0.0.0", "/swf/expressInstall.swf",
		{
			wmode: "transparent",
			theme: 1,
			ID: $(this).attr('rel'),
			xml_link: "/swf/playlist.xml",
			autoplay: 1
		},
		{
			wmode: "transparent",
			allowScriptAccess: "always",
			movie: "/swf/play2.swf"
		}
		);
	})

	swfobject.embedSWF("/swf/top.swf", "logo_movie_clip", 280, 170, "9.0.0.0", "/swf/expressInstall.swf",
	{
		wmode: "transparent",
		sound: "/swf/sound.mp3",
		video_: "/swf/silent_video_flat.swf"
	},
	{
		wmode: "transparent",
		allowScriptAccess: "always",
		movie: "/swf/top.swf"
	}
	);

	$("#content table tr:even td").addClass('even');
	$("#content table tr:odd td").addClass('odd');

	$("#change_bg_block").click(function(){
		if($("body").hasClass('light'))
		{
			$("body").removeClass('light');
			$.cookie('the_light', '0', {
				expires:  0,
				path: '/'
			});
			$("#search_submit").attr('src' ,'/img/header/search_submit.png');
			$("#audio_player_block img").attr('src', '/img/temp/player.png');
		}
		else
		{
			$("body").addClass('light');
			$.cookie('the_light', '1', {
				expires: 31,
				path: '/'
			});
			$("#search_submit").attr('src' ,'/img/light/header/search_submit.png');
			$("#audio_player_block img").attr('src', '/img/light/temp/player.png');
		}
	})


	$("#like_it_block").click(function(){
		var new_height = $(this).hasClass('visible') ? 47 : 155;
		if($(this).hasClass('visible')) $(this).removeClass('visible'); else $(this).addClass('visible');
		$(this).animate({
			height: new_height
		}, 1000);
	})

	$(".music_link").click(function(){
		return false;
	})

	$(".calendar_month").click(function(){
		$(".calendar_month").removeClass('active_month')
		.end().find($(this)).addClass('active_month');

		$("#calendar_month_days_wrapper div").removeClass('calendar_selected_month_days')
		.end().find('#' + $('.active_month').attr('rel') + '-' + $('#selected_year').attr('rel')).addClass('calendar_selected_month_days');
	})

	$("#selected_year").click(function(){
		$("#years_list").fadeToggle('fast');
	})

	$("#years_list a").click(function(){
		if(!$(this).hasClass('underlined'))
		{
			$("#selected_year").html($(this).attr('rel')).attr('rel', $(this).attr('rel'));

			$("#years_list")
			.find('a.underlined').removeClass('underlined').addClass('not_underlined')
			.end()
			.find($(this)).removeClass('not_underlined').addClass('underlined');

			$("#calendar_month_days_wrapper div").removeClass('calendar_selected_month_days')
			.end().find('#' + $('.active_month').attr('rel') + '-' + $('#selected_year').attr('rel')).addClass('calendar_selected_month_days');
		}

		$("#years_list").hide();
		return false;
	})


	$("#bottom_photos_center").scrollable(
	{
		speed: 1000
	}
	);

	$("#clock").mouseenter(function(){
		$("#mainAnnounce").animate(
		{
			top: 0
		}
		, 1000
		);
	})

	$("#clock").mouseleave(function(){
		$("#mainAnnounce").animate(
		{
			top: 170
		}
		, 1000, function(){
			$("#mainAnnounce").css('top', '-170px');
		}
		);
	})

	$(".timeDivision").click(function(){
		$(".timeDivision").removeClass('active').end().find($(this)).addClass('active');
		if($(this).hasClass('past'))
			$.cookie('pastEvents', '1', {
				expires:  1,
				path: '/'
			});
		else
			$.cookie('pastEvents', '', {
				expires:  0,
				path: '/'
			});
		location.href = '/novosti/anonsy/';
	})

	$('.share_buttons').each(function(){
		if($(this).attr('id') !== undefined && $(this).attr('id').length > 0)
			new Ya.share({
				element: $(this).attr('id'),
				elementStyle: {
					'type': 'none',
					'border': true,
					'quickServices': ['vkontakte', 'facebook', 'twitter', 'odnoklassniki']
				},
				description: $(this).attr('data-description'),
				image: $(this).attr('data-image')
			/*,link: 'http://www.yandex.com/',
            title: 'Yandex — the best search engine in the universe!',
            popupStyle: {
                blocks: {
                    'Поделись-ка!': ['yaru', 'twitter', '', 'vkontakte'],
                    'Поделись-ка по-другому!': ['yaru', 'twitter', 'vkontakte']
                },
                copyPasteField: true
            },
            serviceSpecific: {
                twitter: {
                    title: '#Yandex — the best search engine in the universe!'
                }
            }*/
			});
	});

	$("#closeTwitterWidget").click(function(event){
		$("#twitterWidget").fadeOut('slow');
		$.cookie("showTwitterWidget", "false",{
			expires: 1,
			path: "/"
		});
		$("#openTwitterWidget").fadeIn('slow');
		return false;
	});
	$("#openTwitterWidget").click(function(){
		$("#twitterWidget").fadeIn('slow');
		$.cookie("showTwitterWidget", "",{
			expires: 0,
			path: "/"
		});
		$("#openTwitterWidget").fadeOut('slow');
		return false;
	});

	/* Fast Show Photos */
	$(".fastPrev").click(function(event){

		$('.gallery_details_img').append('<div class="loadinfo"></div>');

		var item = $("#fastShowItems div.active").removeClass('active').prev(), img = '';
		if(item.size() == 1)
			img = item.addClass('active').attr('data-img');
		else
			img = $("#fastShowItems div:last").addClass('active').attr('data-img');

		//console.log(img);

		$('#itemBigImg').attr('src', img);

		event.preventDefault();
	})

	$(".fastNext").click(function(event){
		$('.gallery_details_img').append('<div class="loadinfo"></div>');

		var item = $("#fastShowItems div.active").removeClass('active').next(), img = '';
		if(item.size() == 1)
			img = item.addClass('active').attr('data-img');
		else
			img = $("#fastShowItems div:first").addClass('active').attr('data-img');

		//console.log(img);
		$('#itemBigImg').attr('src', img);

		event.preventDefault();
	})

	$('#itemBigImg').load(function(){
		$('.gallery_details_img .loadinfo').remove();
	});

	$(".bottom_photo").bind({
		mouseenter:function()
		{
			$(this).css('height', '113px').css('top', '-10px');
		},
		mouseleave: function()
		{
			$(this).css('height', '93px').css('top', '0px');
		}
	});


	$("#calendar_months_prev").click(function(){
		if($(".calendar_month:last").hasClass('active_month'))
		{
			if($("#years_list a:first").attr('rel') != $("#selected_year").attr('rel'))
			{
				$("#years_list a[rel="+$("#selected_year").attr('rel')+"]").parent().prev().children('a').click();
				$(".calendar_month:first").click();
			}
		}
		else
			$(".calendar_month.active_month").next().click();

	})

	$("#calendar_months_next").click(function(){
		if($(".calendar_month:first").hasClass('active_month'))
		{
			if($("#years_list a:last").attr('rel') != $("#selected_year").attr('rel'))
			{
				$("#years_list a[rel="+$("#selected_year").attr('rel')+"]").parent().next().children('a').click();
				$(".calendar_month:last").click();
			}
		}
		else
			$(".calendar_month.active_month").prev().click();
	})


	$("#listenRadioBlock").click(function(){
		//var myUrl = "http://wdstudio.al.ru/exewin.htm";
		//if(radioWindow === undefined)
		radioWindow = window.open("/radio/", "Ibiza Radio", "width=250,height=125,resizable=no,scrollbars=no,menubar=no,directories=no,location=no,status=no,toolbar=no");
	});

	$(".imageShowCount").each(function(){
		$(this).css('left', ($(this).parent().width() - $(this).outerWidth())/2);
	})


	UpdateOverallPanelLinksPadding();
	ThumbnailInitialize();
});


