/**
* кнопка играть
*/
var Playbutton = {

    add_queue_selector : ".add-queue",
    buy_item_selector : ".buy-item",
    add_to_playlist : ".add-playlist",
    playlist_list : ".list-menu-playlist",
    add_to_playlist_selector : ".list-menu-playlist li",
    gift_selector : ".gift-friend",
    video_stream_selector : ".video-stream",
	playlistTableTrSelector : ".playlist-table tr",
    changeRingtone: ".change-ringtone",
    recommend_selector: ".recommend",
    
        //функция заполняет плейбаттон рекомендованными треками 
    setRecommend: function(content_id, popup){
        if ($(popup).find('.recommend li').length == 0) {
            $.ajax({
                type: "POST",
                url: '/recommend/get/',
                //dataType : "json",                            
                data: "content_id=" + content_id,
                success: function(msg) { 
                    $(popup).find('.recommend').html($(popup).find('.recommend').html() + msg);     
                }
            });  
        
            return true;
        }
        return false;
    },

	// смена кнопок
	init: function(show, button, popup){
		var play = button + " .play";
		var list = button + " .list";
		var insertPlace = $(popup).children().children();

		// принаведении на таблицу
		$(Playbutton.playlistTableTrSelector).hover(function ()
        {
			var tr = $(this);
			var current = $(this).find(button);
			current.addClass("active");
		}, function() {
			var current = $(this).find(button);
			if (!current.children().hasClass("active")) {
				current.removeClass("active");
			}
		});

		//показывать или скрывать кнопку
		show.live('mouseover', function ()
        {
			var current = $(this).children(button);
			current.addClass("active");

			// клик по кнопке play…
			current.children(play).bind("click", function()
            {
            	$(popup).removeClass("active"); // удаляем попап

				$(Playbutton.playlistTableTrSelector).removeClass("active");

                var content_id = $(this).find('.content-id').text();
                var content_type = $(this).find('.content-type').text();

                if (content_type == 'tracks' || content_type == "audiobook")
                {
                	var guid = $(this).find('.guid').text();
                    var from_playlist = $(this).find('.from-playlist').text();
                    var playlist_type = $(this).find('.playlist-type').text();
                    var playlist_id = $(".buttons .playlist_id").first().text();
                }

				// если play сейчас уже включена, то при клике по ней…
				if ($(this).hasClass("active"))
				{

					$(this).parents(Playbutton.playlistTableTrSelector).removeClass("active");

					$(button).removeClass("active"); // скрываем все кнопоки на странице
					$(button).children().removeClass("active"); // переводим всех потомков кнопок (play, list и т.д.) в состояние по умолчанию (выключено)

                    if (content_type == 'tracks' && guid == window.top.Pleer.getCurrentTrack())
                    {
                        window.top.Pleer.Pause(true);
                    }
				}
                else
                {
					$(this).parents(Playbutton.playlistTableTrSelector).addClass("active");
					$(button).removeClass("active"); // скрываем все кнопоки на странице
					$(button).children().removeClass("active"); // переводим всех потомков кнопок (play, list и т.д.) в состояние по умолчанию (выключено)
					current.addClass("active"); // вся кнопка остается на странице
					$(this).addClass("active");	// нажимаем play (становится как pause)

                    if (content_type == 'tracks' || content_type == "audiobook")
                    {
                        TConsole.log ('guid='+guid);
                        TConsole.log ('from_playlist='+from_playlist);
                        TConsole.log ('playlist_type='+playlist_type);
                        TConsole.log ('pl_id='+playlist_id);

                        if (!playlist_id)
                        {
                            window.top.Pleer.Play(guid, false);
                        }
                        else
                        {
                            window.top.Playlist.loadPlaylist(playlist_id, playlist_type, false, true, guid);
                        }
                    }
                    else if (content_type == "albums")
                    {
                        window.top.Playlist.loadPlaylist(content_id, content_type, false, true);
                    }
                    else if (content_type == "clips" || content_type == "films")
                    {
                        iframeAdapter.goTo("/video/view/id/" + content_id);
                    }
				}
                return false;
			});
			// клик по кнопке list…
			current.children(list).bind("click", function()
            {                
                // если list сейчас уже включена, то при клике по ней…
				if ($(this).hasClass("active"))
				{
					$(popup).removeClass("active"); // удаляем попап
					$(button).children(list).removeClass("active"); // отжимаем все list
				}
                else
                {
                    current.children(list).parent().find(Playbutton.add_queue_selector + " b").html('В новый плейлист').parent().find('.to').text('new');

                    // показывать выпадающий список
					var offset = $(this).offset(); // координаты кнопки
					// хак :-(
					if ($(this).width()==28){var widthPopup = offset.left-$(this).width()+7;}
					else {var widthPopup = offset.left-($(this).width()/2)-17;}

					// показывать список с учетом края экрана
					var popupOffset = $(popup).offset();
					var popupOffsetLeft = 165+widthPopup;
					// если список выходит за пределы экрана
					if (popupOffsetLeft>=$(window).width())
					{
						var diffrence = popupOffsetLeft-$(window).width();
						$(popup).addClass("active").css({"top":offset.top+($(this).height()-5)+"px", "left":widthPopup-diffrence+"px"}); //показать окошко относительно координат нажатия
					} else {
						$(popup).addClass("active").css({"top":offset.top+($(this).height()-5)+"px", "left":widthPopup+"px"}); //показать окошко относительно координат нажатия
					}                                       
			                //Playbutton.setRecommend($(button).find('.recommend .content-id').text(), popup);     
					
					 // если подменю вылазит за экран
				     $(".add-playlist").live("hover", function(){
				      	var sndmenuOffsetLeftWidth = $(this).children(".list-menu-playlist").offset().left + $(this).children(".list-menu-playlist").width();
				      	if (sndmenuOffsetLeftWidth>=$(window).width()){
				       	$(this).children(".list-menu-playlist").css("left", "-152px");
				      }
				     });
					
					insertPlace.empty(); // отчистить место, куда помещаем меню
					$(this).next().clone().prependTo(insertPlace).show(); // скопировать и показать меню.

					$(button).children(list).removeClass("active"); // отжимаем все list
					$(button).removeClass("active"); // скрываем все кнопки на странице

					// проверяем, включена ли у какой-либо кнопки play
					$(button).children(play).each(function ()
					{
						// если включена, то…
						if ($(this).hasClass("active"))
						{
							$(this).parent(button).addClass("active"); // то показываем кнопку родителя
						}
					});
					current.addClass("active"); // вся кнопка остается на странице
					$(this).addClass("active"); // кнопка list зажимается
				}
				
				/*
				* грязный хак к кнопке
				*/
				
				if($(popup).hasClass("active"))
				{
					var clickCounter = 0;
					window.top.$(document).bind("click", function(e){
						if (clickCounter==1)
						{
						
								if($(e.target).hasClass("list"))
								{
									clickCounter = 1;
								} else {
								
									if ($(e.target).parents().filter(popup).length != 1)
									{									
										clickCounter = 0;
										$(popup).removeClass("active").fadeOut("fast");
										$(button).children(list).removeClass("active"); // отжимаем все list
									//	$(document).unbind("click");
										
									} else {
										clickCounter = 1;
										return;
									}
									
								}

						} else {
							clickCounter=1;
						}
					});	
				}
					 

			});
        });
		show.live('mouseout', function() {
			var current = $(this).children(button);
			if (!current.children().hasClass("active")) {
				current.removeClass("active");
			}
			current.unbind("click");
			current.children().unbind("click");
		});
                $(Playbutton.add_to_playlist).die('click');
		// выставление списка плейлистов слева или справа
		$(Playbutton.add_to_playlist).live("hover", function()
		{
			var playlistListOffset = $(Playbutton.playlist_list).offset();
			var playlistListOffsetLeft = 152+playlistListOffset.left;

			if (playlistListOffsetLeft>=$(window).width())
			{
				$(this).children(Playbutton.playlist_list).css("left","-152px");
			}
		});



        $(Playbutton.add_queue_selector).die('click');
        //добавление в плейлист
        $(Playbutton.add_queue_selector).live ('click', function ()
        {
            var add_to = $(this).find('.to').text();
            if (window.top.Pleer.currentPlaylistType == 'default' || window.top.currentPlaylistId == 7202)
            {
                add_to = "new";
            }
            var content_type = $(this).find('.content-type').text();
            var content_id = $(this).find('.content-id').text();

            Playbutton.hideAllList();
            if (add_to == "new")
            {
                window.top.Playlist.newPlaylist(content_type, content_id);
            }
            else
            {
                if (window.top.Playlist.addToPlaylist(content_type, content_id, window.top.Pleer.currentPlaylistId) == false)
                {
                    alert('Произошла ошибка');
                }
            }

            return false;
        });
        $(Playbutton.buy_item_selector).die('click');
        //покупка контента
        $(Playbutton.buy_item_selector).live('click', function ()
        {
            var content_type = $(this).find('.content-type').text();
            var content_id = $(this).find('.content-id').text();

            window.top.Fastbuy.fastorder(content_type, content_id);
            Playbutton.hideAllList();

            return false;
        });
        
        $(Playbutton.add_to_playlist_selector).die('click');
        //добавить в выбранный плейлист
        $(Playbutton.add_to_playlist_selector).live('click', function()
        {
            var to_playlist = $(this).attr('class');
            var content_id = $(this).parent().parent().parent().parent().parent().find(".content-id").text();
            var content_type = $(this).parent().parent().parent().parent().parent().find(".content-type").text();

            //alert('добавить ' + content_type + ' c id=' + content_id + ' в плейлист с id = ' + to_playlist);

            if (window.top.Playlist.addToPlaylist(content_type, content_id, to_playlist) == false)
            {
                alert('Произошла ошибка');
            }
            Playbutton.hideAllList();
            return false;
        });
        $(Playbutton.gift_selector).die('click');
        $(Playbutton.gift_selector).live('click', function(){
            var content_id = $(this).find('.content-id').text();
            var content_type = $(this).find('.content-type').text();
            window.top.Fastbuy.gift(content_type, content_id);
            Playbutton.hideAllList();
            return false;
            //alert('Подарить другу контент ' + content_type + ' с id=' + content_id);
        });
        $(Playbutton.recommend_selector).die('click');
        $(Playbutton.recommend_selector).live('click', function(){
            var content_id = $(this).find('.content-id').text();
            var playlist_title = $(this).find('.content-title').text();
                    window.top.$.fancybox({
                href:'/recommend/popup/content_id/' + content_id + '/format/ajax',
                overlayColor:"black", 
                overlayOpacity:0.65,
                onComplete:function(){
                    
                    //играть все песни
                    window.top.iframeAdapter.getElement("#popup-content .buttons .play").click(function()
                    {
                        /*var artist_id = $(this).parent().find('.artist_id').text();
                        window.top.Playlist.loadPlaylist(artist_id, 'artist', false, true);

                        return false;*/
                        var playlist_content_ids = new Array();
                        var playlist_content = window.top.iframeAdapter.getElement("#popup-content .playbutton .play .content-id");
                        $.each(playlist_content, function() {
                            playlist_content_ids.push($(this).text());
                        }); 
                        window.top.Playlist.createPlaylistFromTracksAndPlay('Рекомендации для ' + playlist_title, playlist_content_ids, true, true);
                        
                        return false;
                    });

                    //все песни в плейлист
                    window.top.iframeAdapter.getElement("#popup-content .buttons .new").click( function()
                    {
                        var playlist_content_ids = new Array();
                        var playlist_content = window.top.iframeAdapter.getElement("#popup-content .playbutton .play .content-id");
                        $.each(playlist_content, function() {
                            playlist_content_ids.push($(this).text());
                        }); 
                        window.top.Playlist.createPlaylistFromTracksAndPlay('Рекомендации для ' + playlist_title, playlist_content_ids, false, false);
                        
                        return false;
                    });
                    
                    window.top.iframeAdapter.getElement("#popup-content td.approve .btn-service-bg").click (function()
                    {
                        var content_id = $(this).parent().find(".content_id").text();
                        var btn = $(this);
                        $.ajax({
                            type: "GET",
                            dataType: 'json',
                            url: "/recommend/approve/content_id/" + content_id + "/format/ajax/",
                            success: function(msg){
                               if (msg.status == 'ok') {
                                   btn.remove();
                               } else {
                                   alert('Извините, сейчас сервис принятия мнений находится на тех. обслуживании. Попробуйте через 5 минут.');
                               }
                            }
                        });
                        return false;
                    });
                    
                    var show = window.top.iframeAdapter.getElement(".overlay .showplaybutton");
                    var button = ".playbutton";
                    var popup = ".overlay .list-popup";
                    Playbutton.init(show, button, popup);
                }
            });
            
            Playbutton.hideAllList();
            return false;
        });
        $(Playbutton.changeRingtone).die('click');
        // Замени гудок - баннер с подтверждением
        $(Playbutton.changeRingtone).live('click', function(){
            var export_id = $(this).find('.export-id').text();
            var login = $(this).find('.login').text();
            var price = $(this).find('.price').text();
            //TConsole.log('changeRingtone');
            window.top.Fastbuy.changeRingtone(export_id, login, price);
            Playbutton.hideAllList();
            
            //alert('Замени гудок на ' + export_id + ' для login ' + login);
            return false;
        });

        // Одноразовый стримминг видео
        $(Playbutton.video_stream_selector).live('click', function(){
            var content_id = $(this).find('.content-id').text();
            //var content_type = $(this).find('.content-type').text();
            var content_type = 'clipstream';
            window.top.Fastbuy.fastorder(content_type, content_id);
            Playbutton.hideAllList();
            //alert('Одноразовый стримминг видео ' + content_type + ' с id=' + content_id);
            return false;
        });
        
	},

    hideAllList : function ()
    {
        $(".showplaybutton .list.active").removeClass('active');
        $(".list-popup").removeClass("active");
        $(".playbutton").removeClass("active");
        $("body").unbind("click");
        return false;
    }
}
