var tracklist_ids  = [];
var playlist_ids   = [];
var rating_dom_ids = {};

var page_actions = {
	'home_index': function()
	{
		$('#teaser_albums').cycle({ 
		  fx:       'scrollLeft' 
		, speed:    'fast' 
	    , timeout:  0 
	    , next:     '#frontpage_teaser_next'
	    , pager:    '#frontpage_teaser_pager'
	    , easing:   'easeInOutSine'
	    , speed:    600
	    , timeout:  6000
	    , delay:    1000
	    , pause:    true
	    , cleartypeNoBg: true
       });
	},
	'playlist_edit': function()
	{
		$("#sortable").sortable({
			placeholder: 'ui-state-highlight',
			update:      function(event, ui)
			{
				current = ui.item 
				track_id = ui.item[0].id.split("_")[1];
				
				tmp = $('#sortable').sortable('serialize').split("&");
				ordering = {};
				i = 0;
				for(t in tmp)
				{
					ordering[tmp[t].split("=")[1]] = ++i;
				}
				
				$.ajax({
					url: url_editprefix+"/"+track_id+"/"+ ordering[track_id] + suffix
				  , cache: false
				});
				
			}
		});

		$("#sortable").disableSelection();

		$('#btn_playlist_rename').click(function(event)
		{
			event.preventDefault();			
			$('#div_playlist_title').toggle();
			$('#div_playlist_title_rename').toggle();	
		});
	},

    'playlist_publish': function()
    {
      $('#btn_playlist_publish').click(function(event)
      {
        event.preventDefault();
        $("#playlist_is_published").attr("value", 1);
        $("#publish_form").submit();
      });

      $('#btn_playlist_unpublish').click(function(event)
      {
        event.preventDefault();
        $("#playlist_is_published").attr("value", 0);
        $("#publish_form").submit();
      });
    }
};

this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 15;
		yOffset = 5;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$(".tooltip").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		
		tt = $("#tooltip");
		w = tt.width();
		tt.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.css("width", w > 300 ? 300 : w )
			.fadeIn("fast");
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });	
	$(".tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px");
	});			
};


function prepareRating()
{
	// retrieve track ids from rating widget
	// fill local tracklist_id array
	$(".rating").each(function(){
		tracklist_ids.push($(this).attr("id").split("_")[1]);
	});
	
	// PLAYLIST RATING
	$(".rating_playlist").each(function(){
		playlist_ids.push($(this).attr("id").split("_")[1]);
	});
}



function updateRating()
{

	data = tracks_ratings;
	if(!data.success)
	{
		$('.rating .auto-submit-star').rating({
			blur: function()
			{
				$('.rating .star-rating-on').removeClass("star-rating-on");  
			},
			callback: function(a,b)
			{
        		$.ajax({
        		  url: lang_prefix+'/login'+suffix
               ,  cache: true
               ,  success: function(msg){
                 $.blockUI({ message: msg});
                 $('.blockOverlay').attr('title','Click to unblock').click($.unblockUI); 
               }
        		});
        		
    		  }
        });

		$('.rating input.auto-submit-star').click(function(event){
			event.preventDefault();
		});
		
		
	}
	else
	{ // data.success === true

		for(r in data.result)
		{
			$("input[name='trackrate_"+r+"']")[data.result[r]-1].checked = true;
		}
	
		$('.rating .auto-submit-star').rating({
			cancelValue: 0
		  , callback: function(value, link)
		    {
				id = ($(this).attr("id").split("_"))[1];
				track_dom = "#track_"+id;
				$(track_dom).fadeOut();
	
				$.ajax({
					url: '/rate/track/'+id+'/'+value+suffix
	              , success: function()
	                {
	                  $(track_dom).fadeIn();
	                }
	            }); 
		    }
		});
	}
	
	// PLAYLISTS RATINGS UPDATE
	data = playlists_ratings;
	if(!data.success)
	{
		$('.rating_playlist .auto-submit-star').rating({
			blur: function()
			{
			$('.rating_playlist .star-rating-on').removeClass("star-rating-on");  
			},
			callback: function(a,b)
			{
				$.ajax({
					url: '/user/loginForm'  + suffix
						,  cache: true
						,  success: function(msg){
					$.blockUI({ message: msg});
					$('.blockOverlay').attr('title','Click to unblock').click($.unblockUI); 
				}
				});
				
			}
		});
		
		$('.rating_playlist input.auto-submit-star').click(function(event){
			event.preventDefault();
		});
		
		return true;
	}
	
	for(r in data.result)
	{
		$("input[name='playlistrate_"+r+"']")[data.result[r]-1].checked = true;
	}
	
	$('.rating_playlist .auto-submit-star').rating({
		cancelValue: 0
		, callback: function(value, link)
		{
		id = ($(this).attr("id").split("_"))[1];
		playlist_dom = "#playlist_"+id;
		$(playlist_dom).fadeOut();
		
		$.ajax({
			url: '/rate/playlist/'+id+'/'+value+suffix
			, success: function()
			{
			$(playlist_dom).fadeIn();
			}
		}); 
		}
	}); 
}


$(document).ready(function(){
	// things to hide on dom ready	
	$('#language_list').hide();
	$('.auto-submit-star').hide();
	
	tl = $('#top_listen');
	if(tl)
	{
		// TRACK RATING
		prepareRating();

		$.ajax({
			  url: lang_prefix+'/getDynamics'+suffix
			, cache: false
			, data: "t[]="+tracklist_ids.join("&t[]=")+"&pl[]="+playlist_ids.join("&pl[]=")
			, success: function(data)
			{
				$("body").append(data);
				$("#user_menu").append($('#copy_usermenu'));

				$("#my_playlists .indicator").hide();
				$("#my_playlists .content").append($('#copy_myplaylists'));

				
				$("#top_listen .indicator").hide();
				$("#top_listen .content").append($('#copy_toprecordings'));
				$('#top_recordings_list a.play.track').click(function(event){
				    event.preventDefault();
				    jQuery('#head_audio_player_holder')[0].loadTracklist({'type':'track','id': $(this).attr('rel')});
				});
				
				$("#top_playlists .indicator").hide();
				$("#top_playlists .content").append($('#copy_topplaylists'));

				
				updateRating();
			}
		});
	}

    // REGISTER: PRIVACY POLICY
	$(".privacy_policy").click(function(event){
		event.preventDefault();
		
		$.ajax({
			url: $(this).attr("href")
		  , cache: true
		  ,  success: function(msg){
				$.blockUI({ message: msg});
				$('.blockOverlay').attr('title','Click to unblock').click($.unblockUI); 
		  }
		});
    });
	
    // VIDEOS: TERMS & CONDITIONS
	$(".terms").click(function(event){
		event.preventDefault();
		
		$.ajax({
			url: $(this).attr("href")
			, cache: true
			,  success: function(msg){
			$.blockUI({ message: msg});
			$('.blockOverlay').attr('title','Click to unblock').click($.unblockUI); 
		}
		});
	});

	$(".delete_playlist").click(function(event){
		return confirm("Confirm delete");
	});

	$(".delete_playlist_track").click(function(event){
		return confirm("Confirm delete");
	});

	// PLAY TRACK
	$('a.button.play.track').click(function(event){
		event.preventDefault();
		$('#head_audio_player_holder')[0].loadTracklist({'type':'track','id': $(this).attr('rel')});
	});
	
	// PLAY PLAYLIST
	$('a.button.play.playlist').click(function(event){
		event.preventDefault();
		var slugs = $(this).attr('rel').split(":");
		jQuery('#head_audio_player_holder')[0].loadTracklist({'type':'playlist','user_slug': slugs[0],'slug': slugs[1]});
	});

	// PLAY CELEBRITY PLAYLIST
	$('a.button.play.celebrity_playlist').click(function(event){
		event.preventDefault();
		jQuery('#head_audio_player_holder')[0].loadTracklist({'type':'celebrity_playlist','slug': $(this).attr('rel')});
	});
	
	// PLAY TEASER CDS
	$('a.play_teaser.cd').click(function(event){
		event.preventDefault();
		jQuery('#head_audio_player_holder')[0].loadTracklist({'type':'album','id': $(this).attr('rel')});
	});

	// PLAY CDS
	$('a.button.play.cd').click(function(event){
		event.preventDefault();
		jQuery('#head_audio_player_holder')[0].loadTracklist({'type':'album','id': $(this).attr('rel')});
	});
	
	// PLAY ALBUMS
	$('a.button.play.album').click(function(event){
		event.preventDefault();
		jQuery('#head_audio_player_holder')[0].loadTracklist({'type':'album','id': $(this).attr('rel')});
	});

	// ADD TO PLAYLIST
	$(".add_to_playlist").click(function(event){
		event.preventDefault();
		
		$.ajax({
			url: $(this).attr("href")
		  , cache: true
		  ,  success: function(msg){
				$.blockUI({ message: msg});
				$('.blockOverlay').attr('title','Click to unblock').click($.unblockUI); 
		  }
		});
	});


	body_id = document.body.id;
	if(page_actions[body_id])
	{
		page_actions[body_id]();
	}

	tooltip();
	
	$('.cd_choice select').change(function(){
		  document.location.href = $(this)[0].value;
	});

	sf = $('#search_field');

	sf.focus(function(){
		if($(this).attr('rel') == this.value)
		{
			this.value = '';
		}
	});

	sf.blur(function(){
		if(this.value.trim() == '')
		{
			this.value = $(this).attr('rel');
		}
	});
	
	sf[0].form.onsubmit = function(){
		if(sf.attr('rel') == sf[0].value)
		{
			sf[0].value = '';
		}
		
		return true;
	};

	
    var flashvars = {
    		remoteURL:'/player/playlist'+suffix
    		, remoteURL2:'/odstreaming/audio/get/isrc/:upc/:isrc'+suffix
    };
    var params = {
    	  menu:'false'
    	, wmode:'transparent'
    };
    var attributes = {};
//  swfobject.embedSWF("/flash/chopin-audio-player.swf", "head_audio_player_holder", "100%", "100%", "9.0.0", null, flashvars, params, attributes);
    swfobject.embedSWF("/flash/streaming-player.swf", "head_audio_player_holder", "100%", "100%", "9.0.0", null, flashvars, params, attributes);
});

