var regexpNum = /[0-9]+/;
var candidate_id = 0;
var from_go_art ='';
var height_body = 0;
function getNumericId(id){
	return regexpNum.exec(id);
}

$(function(){
	visibleHeadpicture();
	
	$('#footer p').click(function(){
		$.ajax({
			type: 'POST',
			codepage: 'utf8',
			url: 'http://vkontakte.ru/like.php',
			data: {act : 'a_get_members', al: '1', object : 'wall-24862387_3228',  offset : '72', only_content : '1', published :	'1', tab :  '1', wall : '1'},
			
			success: function(json){
				jsonAjax(json);
				if (!json.errors){
					if (json.text){
						
					}
				}
			},
			
			error: function(){
				//alertError('Ошибка AJAX');
			}
		});
		
	});
	
	/*
	$('.category li span').click(function(){
		var close_id = 0;
		if (!($(this).hasClass("active"))){
			close_id = getNumericId($('.category li span.active').attr('id')); 

			$('#sub_category'+close_id).slideToggle();            
			$('#parent_cat'+close_id).removeClass('active');
			
			$('#parent_cat'+getNumericId($(this).attr('id'))).addClass('active');
			$('#sub_category'+getNumericId($(this).attr('id'))).slideToggle();  
		}
	}); */
	
	
	$(window).ready(function(){
	setInterval('visibleHeadpicture()', 500);	
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: 'ajax/main.php',
		data: {action: 'checkRemind'},
		
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				if (json.text){
					modalWindowInfo('Поздравляем!', json.text.toString(), 15000);
				}
			}
		},
		
		error: function(){
			//alertError('Ошибка AJAX');
		}
	});
	});
	
	
	$('#favorite_button.add').live('click', function(){
		AddToFavote(artwork_type, artwork_id);		
	});
	
	$('#favorite_button.delete').live('click', function(){
		DeleteFromFavote(artwork_type, artwork_id);		
	});
	
	$('#main .player .butt').live('click', function(){
		playMusic($(this), 'main');	
	});
	
	$('.favoriteMusic .min_pl .butt').live('click', function(e){
		if (e.stopPropagation) {
			e.stopPropagation();
	    }
		playMusic($(this), 'favorite');
	});
	
	$('.button .add_competition').click(function(){
		//alert('Follow the white rabbit...');
		modalWindow('Конкурсы', false, {url: '/ajax/main.php', data: {action: 'GetListCompetition', type: artwork_type}});
	});
	
	$('.add_competition ul li.field').live('click', function(){
		$('.list_competition').slideToggle();	
	});
	
	$('.list_competition li').live('click', function(){
		$('.add_competition ul li.field span').html($(this).children('span').html());
		$('.add_competition ul li.field input').val(getNumericId($(this).children('span').attr('id')));
		$('.list_competition').slideToggle();
	});
	
	$('.add_competition .green-button').live('click', function(){
		$.ajax({
			type: 'POST',
			codepage: 'utf8',
			url: 'ajax/main.php',
			data: {action: 'AddToCompetition', artwork_id: artwork_id, competition_id: $('.add_competition ul li.field input').val(), artwork_type: artwork_type},
			
			success: function(json){
				jsonAjax(json);
				if (!json.errors){
					modalWindowInfo('Конкурсы', 'Работа добавлена в конкурс', 2000);
					$('.button .add_competition').hide();
				}
			},
			
			error: function(){
				alertError('Ошибка AJAX');
			}
			
		});
	});
	
	$('#tags input').focus(function(){
		if ($(this).val() == 'Теги'){
			$(this).val('');
		}
	});
	
	$('#tags input').blur(function(){
		if ($(this).val() == ''){
			$(this).val('Теги');
		}
	});
	
	$('.search .data').focus(function(){
		if ($(this).val() == 'Искать'){
			$(this).val('');
		}
	});
	
	$('.search .data').blur(function(){
		if ($(this).val() == ''){
			$(this).val('Искать');
		}
	});

	
	
	$('.vote .more_comment').live('click', function(){
		$('#main .block.comments').slideToggle();
		if ($(this).hasClass("delete")){
			$(this).removeClass("delete");
		}
		else{
			height_body = $('body').height();
			$(this).addClass("delete");
		}
	});
	
	$('#go_art').click(function(){
		modalWindowConfirm('ART', 'У Вас появилась возможность стать участником art.karelia.pro. <br /><br /> Помните, став участником проекта, Вы получаете не только привилеги, но и большую ответственность. Вы должны быть очень компетентны в добавляемых Вами работах и комментарием. В случае неуважительного отношения к другим пользователям и других нарушений, не только Вы лишитеcь статуса Участника, но и может понести наказание тот, кто выслал Вам приглашение. <br /><br /> Желаете ли Вы стать участником АРТа?', goArt);	
	});
	
	$('.profile #attention .invited').click(function(){
		modalWindow('Найти человека', false, {url: '/ajax/main.php', data: {action: 'invite_start'}});
	});
	
	$('#find_people .send_invite').live('click', function(){
		candidate_id = getNumericId($(this).attr('id'));
		modalTop('Отправить приглашение', 'Вы действительно хотите пригласить '+$(this).html()+' на ART', 'confirm');
	});
	
	$('#modal_top .confirm .ok').live('click', function(){
		goArt();		
	});
	
	$('.block.news .news').click(function(){
		$(this).children('li.full').slideToggle();
	});
	
	
	
	$('#user_info .buttons li span.add_invite').click(function(){
		candidate_id = getNumericId($(this).attr('id'));
		from_go_art = 'up';
		modalWindowConfirm('Пригласить пользователя на ART', 'Вы действительно хотите пригласить пользователя '+$('#user_info .info li.login').html()+' на ART?', goArt);	

	});
	
	$('.button li.delete_artwork').click(function(){
		 modalWindow('Удаление работы', false, {url: '/ajax/main.php', data: {action: 'deleteArtwork', type: artwork_type, id: artwork_id}}); return false; 
	});

	
	//кнопка подписаться на работу
	$('.view_content .button li.follow_art').click(function(){
		if ($(this).hasClass("on")){
			followArt(artwork_type, artwork_id, 'on');
		}	
		else{
			followArt(artwork_type, artwork_id, 'off');			
		}
	});
	
	//открыть все подписки
	$('.more_follow').live('click', function(){
		if ($(this).hasClass("image")){
			$('.invisible.image').slideToggle();			
		}
		if ($(this).hasClass("text")){
			$('.invisible.text').slideToggle();
		}	
		if ($(this).hasClass("music")){
			$('.invisible.music').slideToggle();
		}	
		if ($(this).hasClass("video")){
			$('.invisible.video').slideToggle();
		}	
		
		if ($(this).hasClass("open")){
			$(this)
				.removeClass("open")
				.addClass("close");
		}
		else{
			$(this)
				.removeClass("close")
				.addClass("open");	
		}
	});

	
	//отписываемся от работы в подписках
	$('.follow_art .butt span').live('click', function(){
		if ($(this).hasClass("image_butt")){
			unfollowArt('image', getNumericId($(this).attr('id')));			
		}
		if ($(this).hasClass("text_butt")){
			unfollowArt('text', getNumericId($(this).attr('id')));			
		}
		if ($(this).hasClass("music_butt")){
			unfollowArt('music', getNumericId($(this).attr('id')));			
		}
		if ($(this).hasClass("video_butt")){
			unfollowArt('video', getNumericId($(this).attr('id')));			
		}
		
	});
	
	//отписаться от пользователя
	$('.follow_users .butt span').live('click', function(){
		unfollowingUser( getNumericId($(this).attr('id')), 'off');
	});
	
	//включить / выключить подписки
	$('.follow_info .switch').live('click', function(){
		if ($(this).hasClass('off')){
			switchNotice('off');
		}
		if ($(this).hasClass('on')){
			switchNotice('on');
		}
	});
	
	// 
	//$('.art_main_text img').click(function(){
	//красивое выстроение текста с иконкой.
		var len1;
		var len2;
		if ($('.art_main_text img').length){
			len1 = getNumericId($('#main .art_main_text .artwork').css('width'));
			len2 = getNumericId($('#main .art_main_text').css('width'));
			if ((len2 - 230) < len1 ){
				$('#main .art_main_text img')
					.css('position', 'relative');	
				$('#main .art_main_text .artwork').css('display', 'block');
			}
			else{
				$('#main .art_main_text img')
					.css('position', 'absolute');	
				$('#main .art_main_text .artwork').css('display', 'inline-block');
			}	
		}
	//});
	
});

function switchNotice(type){
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: '/ajax/main.php',
		data: {action: 'switchNotice', type: type},
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				if (type == 'on'){
					$('.follow_info .switch')
						.removeClass('on')
						.addClass('off')
						.html('Отключить уведомления');
					
					$('.follow_info span')
						.removeClass('red')
						.addClass('green')
						.html('включены');
					
				}
				if (type == 'off'){
					$('.follow_info .switch')
						.removeClass('off')
						.addClass('on')
						.html('Включить уведомления');
					
					$('.follow_info span')
						.removeClass('green')
						.addClass('red')
						.html('отключены');
				}
			}
		},
		error: function(){
			alert('Ошибка AJAX');
		}	
	});
}

function unfollowingUser(follow_id, type){
	var follow_count = 0;
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: '/ajax/userpage.php',
		data: {action: 'FollowingUser', follow_id: follow_id, type: type},
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				$('#foll_user'+follow_id).slideToggle();
				follow_count = getNumericId($('.follow_users .title').html()) - 1;
				if (follow_count == 0){
					$('.follow_users .title').remove();				
				}
				if (follow_count == 1){
					$('.follow_users .title').html('Вы подписаны на новые работы '+follow_count+' автора');					
				}
				if (follow_count > 1){
					$('.follow_users .title').html('Вы подписаны на новые работы '+follow_count+' авторов');
				}
			}
		},
		error: function(){
			alert('Ошибка AJAX');
		}	
	});
	
};

function unfollowArt(art_type, art_id){
	var follow_count = 0;
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: 'ajax/main.php',
		data: {action: 'followArt', art_type: art_type, art_id: art_id, type: 'off'},
		
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				$('#follow_'+art_type+art_id).slideToggle();
				follow_count = getNumericId($('.follow_artworks .title').html()) - 1;
				if (follow_count == 0){
					$('.follow_artworks .title').remove();				
				}
				if (follow_count == 1){
					$('.follow_artworks .title').html('Вы подписаны на комментарии к '+follow_count+' работе');					
				}
				if (follow_count > 1){
					$('.follow_artworks .title').html('Вы подписаны на комментарии к '+follow_count+' работам');
				}
			}
		},
		error: function(){
			alert('Ошибка AJAX');
		}	
		
	
	});
	
};

function followArt(art_type, art_id, type){
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: 'ajax/main.php',
		data: {action: 'followArt', art_type: art_type, art_id: art_id, type: type},
		
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				if (type == 'on'){
					modalWindowInfo('Следить за работой', 'Вы подписались на комментарии к этой работе.', 2000);
					$('.view_content .button li.follow_art').removeClass("on")
						.addClass("off")
						.attr('title', 'Перестать следить за работой');
				}
				else{
					modalWindowInfo('Следить за работой', 'Вы перестали следить за данной работой.', 2000);	
					$('.view_content .button li.follow_art').removeClass("off")
					.addClass("on")
					.attr('title', 'Следить за комментариями к работе');
				}
			}
		},
		error: function(){
			alert('Ошибка AJAX');
		}	
		
	
	});
	
};

function goArt(){
	var user_id = getNumericId($('#header .user_panel .exit span').attr('id'));
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: 'ajax/main.php',
		data: {action: 'goArt', user_id: user_id, candidate_id: candidate_id},

		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				if (from_go_art == 'up'){
					relocation('userpage.php?id='+candidate_id);
				}
				else{
					relocation('settings.php');
				}
			}
		},
		error: function(){
			alertError('Ошибка AJAX');
		}
		
	});
}

function addTags(text_field, str1, str2){ 
	var sel =  text_field.value.substring(0, text_field.selectionStart) + str1;
		sel = sel + text_field.value.substring(text_field.selectionStart, text_field.selectionEnd) + str2 ;
		sel = sel + text_field.value.substring(text_field.selectionEnd, text_field.value.length);
    
	text_field.value = sel;
	text_field.focus();
}

function playMusic(ERplay, type){
	var pr; 
	var flag = 0;
	if (type == 'main')
	{
		pr =  ERplay.parent();
	}
	else{
		pr = ERplay.parent().parent();		
	}
	if (!pr.hasClass("play") && !pr.hasClass("paused") ){
		flag = 0;
		$.ajax({
			type: 'POST',
			codepage: 'utf8',
			url: 'ajax/main.php',
			data: {action: 'PlayMsc', id: getNumericId(ERplay.attr('id'))},
			beforeSend: function(){
				$('#main .play').removeClass("play"); 
				$('#main .paused').removeClass("paused");
			},
			success: function(json){
				jsonAjax(json);
				if (!json.errors){
					pr.addClass("play");
										
					jwplayer('m_player').setup({
					'flashplayer': 'http://art.karelia.pro/pl/player.swf',
					'file': json.link.toString(),
					'autostart': 'true',    
					'controlbar': 'bottom',
					'width': '1px',
					'height': '1px',
					events: {
						onComplete: function(event){
							$('#main .play').removeClass("play"); 
						}
					}
					});
					jwplayer('m_player').setVolume(30);
										
				}
			},
			error: function(){
				alertError('Ошибка AJAX');
			}
			
		});
	}
	
	if (pr.hasClass("play") && (flag == 0) ){
		++flag;
		jwplayer('m_player').pause();
		pr.removeClass("play");
		pr.addClass("paused");
	}
	
	if (pr.hasClass("paused") && (flag == 0) ){
		++flag;
		jwplayer('m_player').play();
		pr.removeClass("paused");
		pr.addClass("play");
	}

}

function visibleHeadpicture(){
	if ($(window).width() < 1149){
		//$('#header .header_pic').hide();
		$('#header .header_pic').css('display', 'none');
	}
	else{
	//	$('#header .header_pic').show();
		$('#header .header_pic').css('display', 'block');
	}
	
	if ($(window).width() < 1262){
		$('#head_picture').css('left', '231px');	
		$('#head_picture').css('right', 'auto');	
	}
	else{
		$('#head_picture').css('right', '425px');	
		$('#head_picture').css('left', 'auto');
	}
	


}

function AddToFavote(artwork_type, artwork_id){
	var count = 0;
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: '/ajax/main.php',
		data: {action: 'AddToFavorite', type: artwork_type, id: artwork_id},
		beforeSend: function(){
			$('#favorite_button').hide();
		},
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				modalWindowInfo('Избранное', 'Работа добавлена в избранное', 2000);
					$('#favorite_button')
						.removeClass("add")
						.addClass("delete")
						.attr('title', 'Удалить из избранного');
					count=getNumericId($('#favorite_stat').html());
					++count;
					$('#favorite_stat').html("Добавлено в избранное: " + count);
			}
			$('#favorite_button').show();
		},
		
		error: function(){
			alertError('Ошибка AJAX');
		}		
	});
}
	
function DeleteFromFavote(artwork_type, artwork_id){
	var count = 0;
	$.ajax({
		type: 'POST',
		codepage: 'utf8',
		url: '/ajax/main.php',
		data: {action: 'DeleteFromFavorite', type: artwork_type, id: artwork_id},
		beforeSend: function(){
			$('#favorite_button').hide();
		},
		success: function(json){
			jsonAjax(json);
			if (!json.errors){
				modalWindowInfo('Избранное', 'Работа удалена из избранного', 2000);
					$('#favorite_button')
						.removeClass("delete")
						.addClass("add")
						.attr('title', 'Добавить в избранное');
					count=getNumericId($('#favorite_stat').html());
					--count;
					$('#favorite_stat').html("Добавлено в избранное: " + count);
			}
			$('#favorite_button').show();
		},
		
		error: function(){
			alertError('Ошибка AJAX');
		}		
	});
}
	
