//	MINICHAT

function SendMiniChat() {
	Request('Main', 'SendMiniChat', {
		'text' : $('#minichat-input').val(),
		'nick' : $('#minichat-input-nick').val(),
		'captcha' : mccaptcha,
		'answer' : $('#minichat-input-code').val(),
		'last' : lastchat
	}, function(result) {
		if (result.success) {
			$('#minichat-error-message').fadeOut();
			$('#minichat-input').val('');
			$('#minichat-input')[0].focus();
		}
		if (result.msg) {
			ChatErrorDialog(result.msg);
		}
		mccaptcha = Math.round(Math.random() * 1000000);
		$('#minichat-input-captcha-div')[0].style.backgroundImage = "url('/Captcha/" + mccaptcha + "')";
		$('#minichat-input-code').val('');
		UpdateMiniChat(result);
	});
	return false;
}

function RefreshMiniChat() {
	Request('Main', 'RefreshMiniChat', { 'last' : lastchat }, UpdateMiniChat);
}

function ChatErrorDialog (text) {
	$('#minichat-error-message').find('li').html(text);
	$('#minichat-error-message').fadeIn();
}

function UpdateMiniChat(result) {
	
	if (result.count) {
		
		lastchat = result.last;
		
		if (!chatPage) {
			
			var mcc = $('#minichat-container');
			
			var nodes = $('#minichat-container .minichat-message');
			var cl = nodes.length;
			var rm = Math.max(cl - (10 - result.count), 0);
			for (x = 1; x <= rm; x++) {
				$(nodes[cl - x]).remove();
			}
			
			mcc.html(result.content + mcc.html());
			$('.fresh-message')
				.hide()
				.fadeIn()
				.removeClass('fresh-message');
			
			$('.minic-icons*[title]').tipsy({html: true, fade: true, gravity: 's', opacity: 0.9 })
			
		}
		
	}
	
	curTrack = result.track;
	curStream = result.stream;
	curListeners = result.listeners;
}

function PrevMiniChat() {
	Request('Main', 'LoadMiniChatPage', { page : ++chatPage }, LoadMiniChatPage);
	$('#minichat-next').removeClass('inactive');
}

function NextMiniChat() {
	if (!chatPage)
		return;
	Request('Main', 'LoadMiniChatPage', { page : --chatPage }, LoadMiniChatPage);
	if (!chatPage)
		$('#minichat-next').addClass('inactive');
}

function LoadMiniChatPage(result) {
	$('#minichat-container').html(result.content);
	$('.fresh-message').removeClass('fresh-message');
	$('.minic-icons*[title]').tipsy({html: true, fade: true, gravity: 's', opacity: 0.9 })
}

function MiniChatKeyPress(e) {
	if (e.keyCode == 13) {
		if (uid || ($('#minichat-input-code').val().length >= 6)) {
			SendMiniChat();
		}
		else {
			$('#minichat-input-code')[0].focus();
		}
		return false;
	}
	
	/*var str = $('#minichat-input').val();
	if (str.length > 79){
		$('#minichat-input').val(str.substr(0, 79));
	}*/
}

function ExpandMiniChat(id) {
	Request('Main', 'ExpandMiniChat', { id : id }, function (result) {
		if (window.mcExpanded)
			CollapseMiniChat(window.mcExpanded);
		var msg = $('#minichat-'+id);
		if (!msg[0].short)
			msg[0].short = msg.html();
		msg.html(result.text);
		msg[0].onclick = null;//function () { CollapseMiniChat(id) };
		window.mcExpanded = id;
	});
}

function CollapseMiniChat(id) {
	var msg = $('#minichat-'+id);
	msg.html(msg[0].short);
	msg[0].onclick = function () { ExpandMiniChat(id) };
}

function DeleteMiniChatMsg(id) {
	if (!confirm('Rly?'))
		return;
	Request('Admin', 'DeleteMiniChatMsg', { id : id }, function (result) {
		$('#minichat-ctr-'+id).remove();
	});
}

//	NEWS

function RateNews(id, rating) {
	Request('News', 'RateNews', {
		'news' : id,
		'rating' : rating
	}, function (result) {
		$('#news-current-rating-' + id).text(result.rating);
		$('#news-current-rating-' + id).css({ width : Math.round(17 * result.rating) + 'px' });
		$('#news-vote-count-' + id).text(result.count);
		$('#news-rating-' + id + ' li.set-rating').remove();
	});
}

//	COMMENTS

function RateComment(id, rating) {
	$('#comment-' + id + ' .comment-menu-loading').show();
	$('#comment-' + id + ' .comment-menu-rate').hide();
	Request('News', 'RateComment', {
		'comment' : id,
		'rating' : rating
	}, function (result) {
		$('#comment-' + id + ' .comment-menu-loading').hide();
		var cc = $('#comment-' + id + ' .comment-menu-count');
		cc.text(result.rating)
		if (parseInt(result.rating) < 0)
			cc.removeClass('good').addClass('bad');
		else
			cc.removeClass('bad').addClass('good');
	});
}


function UpdateCommentCaptcha() {
	cfcaptcha = Math.round(Math.random() * 1000000);
	$('#comment-post-code')[0].style.backgroundImage = "url('/Captcha/" + cfcaptcha + "')";
	$('#comment-post-code-id').val(cfcaptcha);
	$('#comment-post-code-input input').val('')[0].focus();
}

function ReturnToDefaultComment() {
	SetReplyTo(0, '');
	$('#ans-to').fadeOut();
	$('#cancel-action-button').fadeOut();
}

function SetReplyTo(id, nick) {
	if ($('#comment_action').val() != 'add') {
		$('#comment-post-message-input-textarea').val('');
		$('#ans-action').text('Вы отвечаете на пост ');
	}
	$('#comment_action').val('add');
	$('#reply_to').val(id);
	$('#ans-to-nick').text(nick);
	$('#ans-to').fadeIn();
	$('#cancel-action-button').fadeIn();
}

function EditComment(id) {
	$('#comment_action').val('edit');
	$('#ans-action').text('Вы редактируете пост ');
	$('#ans-to-nick').text('');
	$('#ans-to').fadeIn();
	$('#comment_id').val(id);
	$('#comment-post-message-input-textarea').val($('#comment-'+id).find('.comment-text-unedited').text());
	$('#cancel-action-button').fadeIn();
}

function DeleteComment(id) {
	if (!confirm('Rly?'))
		return;
	Request('Admin', 'DeleteComment', { id : id }, function (result) {
		$('#comment-'+id).remove();
	});
}

//	SLIDERS

function StartSlideTop() {
	
	$('#head-center .slide').each(function(i) {
		this.scrollIdx = i;
		this.style.left = 203 * this.scrollIdx + 'px';
	});
	
	setTimeout(DoSlideTop, 5345);
	
}

function DoSlideTop() {

	if (!doSlideTop) {
		setTimeout(DoSlideTop, 1234);
		return;
	}
	
	var SO = $('#head-center .slide');
	
	SO.each(function() {
		
		if (this.scrollIdx == -1) {
			this.scrollIdx = SO.length - 1;
		}
		else if (this.scrollIdx == 1) {
			document.cookie = 'top_slide=' + this.id.substr(1) + '; expires=Tue, 19 Jan 2038 03:14:06 UTC; path=/';
		}
		
		$(this).css({ left : 203 * this.scrollIdx + 'px' });
		this.scrollIdx--;

	});
	
	SO.animate({
		left: '-=203px'
	}, {
		easing: 'swing',
		duration: 1000
	});
	
	SO.last().queue('fx', function () {
		setTimeout(DoSlideTop, 5234);
		$(this).dequeue();
	});
	
}

function StartSlideTitles() {
	
	$('.titles2').css({ display : 'block' });
	
	$('#player-status-text .titles').each(function(i) {
		this.scrollIdx = i;
		this.style.top = 36 * this.scrollIdx + 'px';
	});
	
	setTimeout(DoSlideTitles, 4545);
	
}

function DoSlideTitles() {
	
	if (!doSlideTitles) {
		setTimeout(DoSlideTitles, 1545);
		return;
	}
	
	var SO = $('#player-status-text .titles');

	SO.each(function() {
		
		var ce;
		
		if ((ce = $('#trackName')).closest('.titles')[0].scrollIdx > 0) {
			if (curTrack.indexOf(' - ') > 0) {
				var split = $('<span>').text(curTrack).html().split(' - ', 2);
				ce.parent().addClass('title-event2');
				ce.html('<b>'+split[0]+'</b><br />'+split[1]);
			} else {
				ce.parent().removeClass('title-event2');
				ce.text(curTrack);
			}
			shownTrack = curTrack;
		}
		if ((ce = $('#streamName')).closest('.titles')[0].scrollIdx > 0) {
			ce.text(curStream);
		}
		if ((ce = $('#listenerCount')).length && ce.closest('.titles')[0].scrollIdx > 0) {
			ce.text(curListeners);
		}
		
		if (this.scrollIdx == -1) {
			this.scrollIdx = SO.length - 1;
		}

		this.style.top = 36 * this.scrollIdx + 'px';
		this.scrollIdx--;
		
		$(this).animate({ top: 36 * this.scrollIdx + 'px'}, { duration: 600 });

	});
	
	SO.last().queue('fx', function () {
		setTimeout(DoSlideTitles, 3976);
		$(this).dequeue();
	});
	
}

// RATE TRACK

function RateTrack(rating) {
	Request('Main', 'RateTrack', {
		'track' : shownTrack,
		'rating' : rating
	}, function (result) {
		
		if (result.message) {
		
			$('#titles-message').html(result.message).fadeIn();
			
			setTimeout(function () {
				$('#titles-message').fadeOut();
			}, 2000);
			
		}
		
	});
	return false;
}

// SET BITRATE

function SetBitrate(bitrate) {
	var types = ["pls", "wax", "xspf", "ram"];
	
	for (i = 0; i < 4; i++) {
		var type = types[i];
		$('#link_'+type)[0].href = '/listen/' + bitrate + '/radio.' + type;
	}
	
	document.cookie = 'bitrate=' + bitrate + '; expires=Tue, 19 Jan 2038 03:14:06 UTC; path=/';
	
	$('.player-freq').removeClass('selected');
	$('#player-freq-' + bitrate).addClass('selected');
}

function OpenPlayer(url) {
	return !window.open('/Player', "cr_player", "width=320,height=140,left=500,top=300,menubar=no,toolbar=no,location=yes,directories=yes,status=no,resizable=no,scrollbars=no")
}

function RefreshTrack() {
	Request('Main', 'RefreshTrack', { }, function (result) {
		curTrack = result.track;
		curStream = result.stream;
		curListeners = result.listeners;
	});
}

// LOGIN

function AuthPopup(url) {
	pop = window.open('/Auth', "authpopup", "width=600,height=500,status=0,toolbar=0,menubar=0,directories=0")
	
	off = $('#main').offset();
	pop.moveTo(off.left + 100, off.top + 100);
	
	pop.focus();
	
	pop.location = url;
	
	return false;
}

function LoginFB(action) {
	return AuthPopup('https://www.facebook.com/dialog/oauth?client_id=111797605560995&scope=email,user_birthday&redirect_uri=http://' + document.domain +'/Auth/fb/' + action + '&display=popup');
}

function LoginVK(action) {
	VK.Auth.login(function (response) {
		if (response.session) {
			Request('Auth', 'VK', {
				session : response.session,
				action : action
			}, function () {
				window.location.reload();
			});
		}
	});
	return false;
}

function LoginDR(action) {
	return AuthPopup('/Auth/DR/' + action);
}

function RemoveContact(type) {
	if (!confirm('Вы уверены?'))
		return;
	Request('Auth', 'Remove', { type : type });
}

// REGISTER

function UpdateRegisterCaptcha() {
	cfcaptcha = Math.round(Math.random() * 1000000);
	$('#reg-code-input-text')[0].style.backgroundImage = "url('/Captcha/" + cfcaptcha + "')";
	$('#reg-captcha-id').val(cfcaptcha);
	$('#reg-captcha-answer').val('')[0].focus();
}

// SMILEYS

jQuery.fn.extend({
	insertAtCaret: function(myValue){
		return this.each(function(i) {
			if (document.selection) {
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}
			else if (this.selectionStart || this.selectionStart == '0') {
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
				this.focus();
				this.selectionStart = startPos + myValue.length;
				this.selectionEnd = startPos + myValue.length;
				this.scrollTop = scrollTop;
			} else {
				this.value += myValue;
				this.focus();
			}
		})
	}
});

function InsertSmiley(tag) {
	$('#comment-post-message-input-textarea').insertAtCaret(" "+tag+" ");
}
function InsertSmileyMini(tag) {
	$('#minichat-input').insertAtCaret(" "+tag+" ");
}
function easy_post(e, form)
{
	if (((e.keyCode == 13) || (e.keyCode == 10)) && (e.ctrlKey == true)) form.submit();
}

// FORM

function OpenForm(id) {
	$('#darkness').css({
		'width': $(document).width(),
		'height':$(document).height()
	}).fadeIn();
	
	var cf = $('#' + id);
	cf.css({
		'margin-top' : parseInt($(window).height()/2 - cf.height()/2) + 'px',
		'margin-left' : parseInt($(window).width()/2 - cf.width()/2) + 'px'
	}).fadeIn();
	cf.keyup(function(e, form) {
		if (e.keyCode == 27)
			CloseForm(id);
	});
}

function CloseForm(id) {
	$('#'+  id + ',#darkness').fadeOut(500);
	$('#contact-text').text('');
}

// CONTACT

function ContactOpen(to) {
	contactTo = to;
	OpenForm('contact-form');
	$('#contact-name,#contact-mail,#contact-text')[0].focus();
}

function ContactSend() {
	Request('Main', 'ContactSend', {
		to: contactTo,
		name : $('#contact-name').val(),
		mail : $('#contact-mail').val(),
		text : $('#contact-text').val()
	}, CloseForm('contact-form'));
}

// INVITE

function InviteOpen() {
	OpenForm('invite-form');
	$('#invite_link')[0].focus();
}

// PROFILE PHOTO UP

function PhotoUploadStart() {
	$('#panel-photo-selected').html('<img class="wait-loading" src="/img/news/loading.gif">');
}

function PhotoUploadDone(url) {
	$('#panel-photo-selected').html('<img src="' + url + '" /><input type="hidden" name="photo_change" value="1" />');
}

// NOTICES

function CloseNotice(id) {
	Request('Main', 'CloseNotice', { id : id });
	$('#notice-'+id).slideUp({duration : 200});
}

