/*
| -------------------------------------------------------------------------
| Common functions
| -------------------------------------------------------------------------
*/
/* Strip domain from url (without http://)
*****************************************/
function fnGetDomain(url) {
   return url.match(/:\/\/(.[^/]+)/)[1];
}
/* PHP-функция: htmlspecialchars
***********************************/
function htmlspecialchars(text)
{
	var chars = Array("&", "<", ">", '"', "'");
	var replacements = Array("&amp;", "&lt;", "&gt;", "&quot;", "'");
	for (var i=0; i<chars.length; i++)
	{
		var re = new RegExp(chars[i], "gi");
		if(re.test(text))
		{
			text = text.replace(re, replacements[i]);
		}
	}
	return text;
}
/* PHP-функция: implode
************************/
function implode(delimiter, pieces) {
	return ( (pieces instanceof Array) ? pieces.join ( delimiter ) : pieces );
}
/* PHP-функция: explode
*************************/
function explode(delimiter, string) {
	var emptyArray = { 0: '' };
	if ( arguments.length != 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined' )
	{
		return null;
	}
	if ( delimiter === '' || delimiter === false || delimiter === null )
	{
		return false;
	}
	if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object' )
	{
		return emptyArray;
	}
	if ( delimiter === true ) {
		delimiter = '1';
	}
	return string.toString().split ( delimiter.toString() );
}
/* PHP-функция: in_array
*************************/
function in_array(needle, haystack, strict)
{
	var found = false, key, strict = !!strict;
	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}
	return found;
}
/* PHP-функция: count
*************************/
function count( mixed_var, mode ) {
	var key, cnt = 0;
	if( mode == 'COUNT_RECURSIVE' ) mode = 1;
	if( mode != 1 ) mode = 0;
	for (key in mixed_var) {
		cnt++;
		if( mode==1 && mixed_var[key] && (mixed_var[key].constructor === Array || mixed_var[key].constructor === Object) ) {
			cnt += count(mixed_var[key], 1);
		}
	}
	return cnt;
}


/*
| -------------------------------------------------------------------------
| Radio
| -------------------------------------------------------------------------
*/
/*-- Play --*/
function playRadio(stream, radio_title, player_type)
{
//	var randomnumber = '?no-cache=' + Math.floor(Math.random()*111) + '-' + Math.floor(Math.random()*999);
	$('#current_radio_title').text(radio_title);
	var flashvars = {way:stream, swf:"/s/swf/player.swf?"+playerVersion, w:"300", h:"50", color:"619AE9", autoplay:"1", volume:"75", playerType:player_type};
	var params = {bgcolor:"#FFFFFF", allowFullScreen:"false", menu:"false", wmode:"opaque"};
	var attributes = {id:"player_swf",name:"player_swf"};
	swfobject.embedSWF("/s/swf/player.swf?"+playerVersion, "player_swf", "300", "50", "10.2.153", "/s/swf/expressInstall.swf", flashvars, params, attributes);
	$.cookies.set('RP_current_stream', stream, {hoursToLive: 24});
	$.cookies.set('RP_current_title', radio_title, {hoursToLive: 24});
	$.cookies.set('RP_autoplay', '1', {hoursToLive: 24});
	$.cookies.set('RP_player_type', player_type, {hoursToLive: 24});
	return false;
}
/*-- Stop --*/
function stopRadio(stream)
{
	var flashvars = {way:stream, swf:"/s/swf/player.swf?"+playerVersion, w:"300", h:"40", color:"619AE9", autoplay:"0", volume:"75"};
	var params = {bgcolor:"#FFFFFF", allowFullScreen:"false", menu:"false", wmode:"opaque"};
	var attributes = {id:"player_swf",name:"player_swf"};
	swfobject.embedSWF("/s/swf/player.swf?"+playerVersion, "player_swf", "300", "40", "10.2.153", "/s/swf/expressInstall.swf", flashvars, params, attributes);
//	$.cookies.set('current_stream', null, {hoursToLive: 24});
	$.cookies.set('RP_autoplay', '0', {hoursToLive: 24});
}


/*
| -------------------------------------------------------------------------
| Video
| -------------------------------------------------------------------------
*/
/*-- Play --*/
function playVideo(videoid)
{
	var params = { allowScriptAccess: "always", bgcolor:"#FFFFFF", allowFullScreen:"true", menu:"false", wmode:"opaque" };
	var attributes = {};
	attributes.id = "youtubePlayer";
	swfobject.embedSWF('http://www.youtube.com/v/'+videoid+"?hl=ru&fs=1&rel=0&enablejsapi=1&playerapiid=ytplayer&showinfo=0&iv_load_policy=3&cc_load_policy=0&showsearch=0&fs=1&autoplay=1", "youtubePlayer", "560px", "340px", "8", null, null, params, attributes);
//	$('#youtubePlayer').html('<iframe class="youtube-player" type="text/html" width="560" height="340" src="http://www.youtube.com/embed/'+videoid+'?hl=ru&fs=1&rel=0&enablejsapi=1&playerapiid=ytplayer&showinfo=0&iv_load_policy=3&cc_load_policy=0&showsearch=0&fs=1&autoplay=1" frameborder="0"></iframe>');
}

function onYouTubePlayerReady(playerId) {
//	youtubePlayer.playVideo();
	ytplayer = document.getElementById("youtubePlayer");
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}
function onytplayerStateChange(newState) {
	if (newState == 0)
	{
		if ($('.play-video').hasClass('active-video') == true)
		{
			$('.play-video.active-video').parents('li').next().find('a.play-video').click();
		};
	};
}
var timerId = null;
var n = 1;
var obj, videoid;
function rotateVideoImg() {
	n++;
	if (n > 3) n = 1;
	obj.attr('src', 'http://img.youtube.com/vi/'+videoid+'/'+n+'.jpg');
}

/*
| -------------------------------------------------------------------------
| $(document).ready()
| -------------------------------------------------------------------------
*/
$(document).ready(function(){
/*
| -------------------------------------------------------------------------
| Play from cookie
| -------------------------------------------------------------------------
*/
	var RP_autoplay = jQuery.cookies.get('RP_autoplay');
	if (RP_autoplay == 1)
	{
		var RP_current_stream = $.cookies.get('RP_current_stream');
		if (RP_current_stream != null)
		{
			var RP_current_title = $.cookies.get('RP_current_title');
			if (RP_current_title == null) {RP_current_title = '';};
			playRadio(RP_current_stream, RP_current_title, $.cookies.get('RP_player_type'));
		};
	};
	if (RP_autoplay == 0)
	{
		var RP_current_title = $.cookies.get('RP_current_title');
		if (RP_current_title == null) {RP_current_title = '';};
		$('#current_radio_title').text(RP_current_title);
	};

/*
| -------------------------------------------------------------------------
| Radio lnk
| -------------------------------------------------------------------------
*/
	$('.play-radio').click(function(){
		var stream = $(this).attr('data-stream');
		var radio_title = $(this).attr('data-title');
		var player_type = $(this).attr('data-player_type');
		playRadio(stream, radio_title, player_type);
		$('.play-radio').removeClass('active-radio');
		$(this).addClass('active-radio');
	});
/*
| -------------------------------------------------------------------------
| Radio btn
| -------------------------------------------------------------------------
*/
	$('.play-radio-btn').click(function(){
		var stream = $(this).attr('data-stream');
		var radio_title = $(this).attr('data-title');
		var player_type = $(this).attr('data-player_type');
		if ($(this).hasClass('play-radio-btn-stop') == false) {
		// play
			playRadio(stream, radio_title, player_type);
			$('.play-radio').removeClass('active-radio');
			$('.play-radio-btn-stop img').attr('src', '/s/i/player/play.png');
			$('.play-radio-btn-stop').removeClass('play-radio-btn-stop');
			$(this).addClass('play-radio-btn-stop');
			$('.play-radio-btn-stop img').attr('src', '/s/i/player/stop.png');
		} else {
		// stop
			stopRadio(stream);
			$('.play-radio-btn-stop img').attr('src', '/s/i/player/play.png');
			$(this).removeClass('play-radio-btn-stop');
		};
	});

/*
| -------------------------------------------------------------------------
| Account
| -------------------------------------------------------------------------
*/
	$('#checkLogin').click(function(){
		JsHttpRequest.query('/account/ajax_check_login', 
			{
				'user_login': $('#user_login').val()
			},
			function(result, errors)
			{
				if (result["error"] != "") {
					alert(result["error"]);
				} else {
					alert(result["content"]);
				};
			}, true
		); // JsHttpRequest
		return false;
	});
/* ------ */
	$('#saveSettings').click(function(){
		JsHttpRequest.query('/account/ajax_edit_personal', 
			{
				'uid': $('#uid').val(),
				'user_login': $('#user_login').val(),
				'user_name': $('#user_name').val(),
				'user_email': $('#user_email').val()
			},
			function(result, errors)
			{
				if (result["error"] != "") {
					alert(result["error"]);
				} else {
					alert(result["content"]);
				};
			}, true
		); // JsHttpRequest
		return false;
	});


/*
| -------------------------------------------------------------------------
| Play Video
| -------------------------------------------------------------------------
*/
	$('.play-video').live('click', function(){
		var videoid = $(this).attr('id');
		$('.play-video').removeClass('active-video');
		$(this).addClass('active-video');
		playVideo(videoid);
		$('#youtubePlayerTitle').text($(this).text());
		document.title = $(this).text();
		return false;
	});
/*
| -------------------------------------------------------------------------
| Get Video List
| -------------------------------------------------------------------------
*/
	$('.get-video-list').click(function(){
		$('.video-nav li').removeClass('active');
		$(this).parents('li').addClass('active');
		$('#videoList').html('<div style="padding:10px 0 0 160px"><img src="/s/i/ajax-loader-video.gif" alt="" /></div>');
		var order = $(this).attr('data-order');
		JsHttpRequest.query('/video/ajax/'+order, '',
			function(result, errors)
			{
				if (result["error"] != "") {
					alert(result["error"]);
				} else {
					$('#videoList').html(result["content"]);
					document.getElementById('videoList').scrollTop = 0;
				};
			}, false
		); // JsHttpRequest
		return false;
	});
/*
| -------------------------------------------------------------------------
| Video Hover Img Preview
| -------------------------------------------------------------------------
*/
	$('.video-list-item').live('mouseenter', function(){
		videoid = $(this).find('.play-video').attr('id');
		obj = $(this).find('.video-img img');
		timerId = setInterval(rotateVideoImg, 700);
	});
	$('.video-list-item').live('mouseleave', function(){
		clearInterval(timerId);
		n = 1;
		videoid = $(this).find('.play-video').attr('id');
		$(this).find('.video-img img').attr('src', 'http://img.youtube.com/vi/'+videoid+'/1.jpg');
	});



/*
| -------------------------------------------------------------------------
| HIT Video
| -------------------------------------------------------------------------
*/
	$('.video-hit-item').live('mouseenter', function(){
		videoid = $(this).find('.play-hit-video').attr('id');
		obj = $(this).find('.video-img img');
		timerId = setInterval(rotateVideoImg, 700);
	});
	$('.video-hit-item').live('mouseleave', function(){
		clearInterval(timerId);
		n = 1;
		videoid = $(this).find('.play-hit-video').attr('id');
		$(this).find('.video-img img').attr('src', 'http://img.youtube.com/vi/'+videoid+'/1.jpg');
	});
//-----
	$('.play-hit-video').live('click', function(){
		var videoid = $(this).attr('id');
		var title = $(this).text();
		$('.play-hit-video').removeClass('active-video');
		$(this).addClass('active-video');
		playHitVideo(videoid, title);
		return false;
	});
//-----
	$('#hitVideoPlayerClose').live('click', function(){
		$('#youtubeHitPlayer').html('');
		disablePopup();
//		$('#hitVideoPlayer').hide('fast');
		return false;
	});

}); // END $(document).ready()

/*-- Play HIT 40 --*/
function playHitVideo(videoid, title)
{
	$('#hitVideoPlayerTitle').text(title);
	centerPopup();
	loadPopup();
//	$('#hitVideoPlayer').show('fast');
	var params = { allowScriptAccess: "always", bgcolor:"#FFFFFF", allowFullScreen:"true", menu:"false", wmode:"opaque" };
	var attributes = {};
	attributes.id = "youtubeHitPlayer";
//	swfobject.embedSWF('http://www.youtube.com/v/'+videoid+"?hl=ru&fs=1&rel=0&enablejsapi=1&playerapiid=ytplayer&showinfo=0&iv_load_policy=3&cc_load_policy=0&showsearch=0&fs=1&autoplay=1", "youtubeHitPlayer", "560px", "340px", "8", null, null, params, attributes);
	$('#youtubeHitPlayer').html('<iframe class="youtube-player" type="text/html" width="560" height="340" src="http://www.youtube.com/embed/'+videoid+'?hl=ru&fs=1&rel=0&enablejsapi=1&playerapiid=ytplayer&showinfo=0&iv_load_policy=3&cc_load_policy=0&showsearch=0&fs=1&autoplay=1" frameborder="0"></iframe>');
}
//0 means disabled; 1 means enabled;
var popupStatus = 0;
//loading popup with jQuery magic!
function loadPopup(){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("fast");
		$("#hitVideoPlayer").fadeIn("slow");
		popupStatus = 1;
	}
}
//disabling popup with jQuery magic!
function disablePopup(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("fast");
		$("#hitVideoPlayer").fadeOut("slow");
		popupStatus = 0;
	}
}
//centering popup
function centerPopup(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $("#hitVideoPlayer").height();
	var popupWidth = $("#hitVideoPlayer").width();
	//centering
	$("#hitVideoPlayer").css({
//		"position": "absolute",
		"top": windowHeight/2-popupHeight/2,
		"left": windowWidth/2-popupWidth/2+50
	});
	//only need force for IE6
//	$("#hitVideoPlayer").css({
//		"height": windowHeight
//	});
}


/*
| -------------------------------------------------------------------------
| Notifications
| -------------------------------------------------------------------------
*/
var notificationsTimeout;
$("#closeNotification").live('click', function () {
	$('#notificationsWrapper').slideUp('slow');
});
function showNotifications(hideOnTime) {
	$('#notificationsWrapper').slideDown('slow', function callback() {
		if (hideOnTime) notificationsTimeout = setTimeout("$('#notificationsWrapper').slideUp('slow')", 3000);
	});
}
function processingMessage() {
	$("#notifications").html('<div class="processing">Пожалуйста подождите...</div><img src="/s/i/icons/close_16.png" id="closeNotification" alt="" width="" height="" />');
	showNotifications(false);
}
function notificationMessage(type, text) {
	clearTimeout(notificationsTimeout);
	$('#notificationsWrapper').hide();
	$("#notifications").html('<div class="'+type+'">'+text+'</div>');
	showNotifications(true);
}


/*
| -------------------------------------------------------------------------
| Flash Player Set Cookie
| -------------------------------------------------------------------------
*/
function flashSetCookie(name, value)
{
  document.cookie = name+"="+value;
}
