// To open the playlist drawer in screenshot/vid page
function open_playlist_drawer() {
	$("#playlist_add_drawer").hide();
	$("#playlist_success_msg").hide();
	$("#playlist_form").show();
	$("#flag_content").hide();
	$("#flagcontent_block").hide();
	$("#play_list_block").slideDown(300);
}

// To close the playlist drawer in screenshot/vid page
function close_playlist_drawer() {
	$("#play_list_block").slideUp(300,function(){$("#playlist_add_drawer").show();$("#flag_content").show();});
}

// Change event of playlist name drop down
$("select#select_playlist_name").change(function(ele) {
	var value =$("select#select_playlist_name option:selected").val();
	if(value == '0') {
		$("#new_playlist").show();
		$("#txt_playlist_name").val('');
		$("#txt_playlist_name").focus();
		$("#playlist_msg").text('');
	} else {
		if(is_in_playlist_array(value+'*')){
			$("#playlist_msg").text('Already present in playlist!');
		} else {
			$("#playlist_msg").text('');
		}
		$("#new_playlist").hide();
	}
});

//Playlist Add Button's click event 
$("button#playlist_add").click(function(ele) {
	this.blur();							
	var value =$("select#select_playlist_name option:selected").val();					
	if(value == '0') {
		title = $("#txt_playlist_name").val();
		if(jQuery.trim(title) == ''){
			alert('Enter Playlist title');
			$("#txt_playlist_name").val('');
			$("#txt_playlist_name").focus();
			return;
		} else {
			$("#playlist_add").after("<span class='ajax-spinner'><img src='/static/images/ajax-loader.gif' alt='' style='vertical-align: middle;' /></span>");
			$("#playlist_add").attr("disabled","disabled");
			$.post("/playlists/create/", {object_type:obj_type, object_id:obj_id, playlist_title:title}, playlist_return, "json");
		}
	} else {
		var value =$("select#select_playlist_name option:selected").val();
		if(is_in_playlist_array(value+'*')){
			$("#playlist_msg").text('Already present in playlist!');
		} else {
			//add spinner image to show some processing
			$("#playlist_add").after("<span class='ajax-spinner'><img src='/static/images/ajax-loader.gif' alt='' style='vertical-align: middle;' /></span>");
			$("#playlist_add").attr("disabled","disabled");
			$.post("/playlists/add/", {object_type:obj_type, object_id:obj_id, playlist_id:value}, playlist_return, "json");
		}
	}
	
});

// Callback function on Add playlist button's click event
function playlist_return(data){
	$("#playlist_add").next("span.ajax-spinner").remove();
	$("#playlist_add").removeAttr("disabled");
	if(data['error'] == 0) {
		$("select#select_playlist_name").html(data['dropdown']);
		add_to_present_in_playlist_array(data['newid'] + '*');
		$("#new_playlist").hide();
		$("#playlist_form").hide();
		$("#playlist_success_msg em").html('Successfully added to <a href="/users/'+ loggedin_username +'/playlists/?playlist='+ data['newid'] +'">playlist</a>');
		$("#playlist_success_msg").show();
	} else {
		$("#playlist_msg").text(data['status']).show();
	}
}



// To scroll to correct position of the playlist pod when any item of the playlist is seen in ss/vid
function scroll_to_playlist(index) {
	$('#playlist_pod').addClass("playlist_scroll");
	$('#playlist_pod').attr('scrollTop', $("#playlist_object_"+index).attr('offsetTop')-90);
}

// To see previous item of playlist
$("a#prev").click(function(ele) {
	if($("input#chk_random").attr('checked')){
		var idx = Math.floor(Math.random()*total_obj) + 1;
		if(idx == selected_index) 
			idx = Math.floor(Math.random()*total_obj) + 1;
		if(idx == selected_index) 
			idx = Math.floor(Math.random()*total_obj) + 1;
	}else{
		var idx = selected_index - 1;
	}
	//if next index  is different
	if(idx != selected_index) {
		if($("input#chk_random").attr('checked'))
			var url = obj_array[idx]+ '&shuffle=1';
		else
			var url = obj_array[idx]; 
		//load the url now 
		window.location = url
	}
});

// To see next item of playlist
$("a#next").click(function(ele) {
						   
	if($("input#chk_random").attr('checked')) {
		var idx = Math.floor(Math.random()*total_obj)+1;
		if(idx == selected_index) 
			idx = Math.floor(Math.random()*total_obj) + 1;
		if(idx == selected_index) 
			idx = Math.floor(Math.random()*total_obj) + 1;
	} else {
		var idx = selected_index+1;
	}
	//if next index  is different
	if(idx != selected_index) {
		if($("input#chk_random").attr('checked'))
			var url = obj_array[idx]+ '&shuffle=1';
		else
			var url = obj_array[idx]; 
		//load the url now 
		window.location = url
	}
});





// Js events and functions used in profile playlist
//'sort playlist' button's click event
$("#sort_list").click(function(ele){
	if($(this).attr("disabled") == 'disabled') return false;
	$("#playlist_controls").after("<span class='ajax-spinner'><img src='/static/images/ajax-loader.gif' alt='' style='vertical-align: middle;' /></span>");
	disable_playlist_controls();
	disable_remove_items();
	$.post("/playlists/show_sortable_items/", {playlist_id:playlist_id}, show_sortable_item);
});

//Callback function of 'sort playlist' button's click() event
function show_sortable_item(data){
	$("#playlist_controls").next("span.ajax-spinner").remove();
	 if(data != '') {
	 	 $('#reorder_playlist_list').html(data)
		 show_only('sort_playlist');	
		 dragsort.makeListSortable(document.getElementById("reorder_playlist_list"),verticalOnly, saveOrder);
		 $('#but_order').removeAttr("disabled");
		 $('#but_cancel').removeAttr("disabled");
	}
}

//When 'Save Reordering' button is clicked  
$("#but_order").click(function(ele){
	if($(this).attr("disabled") == 'disabled') return false;							   
	var sortstr = junkdrawer.inspectListOrder('reorder_playlist_list');
	$('#but_order').attr("disabled","disabled");
	$('#but_cancel').attr("disabled","disabled");
	$("#playlist_controls").after("<span class='ajax-spinner'><img src='/static/images/ajax-loader.gif' alt='' style='vertical-align: middle;' /></span>");
	$.post("/playlists/sorting/", {ordered_list:sortstr,playlist_id:playlist_id}, sorting_return);

});	

//Callback function of 'Save Reordering' button's click event
function sorting_return(data){
	 $("#playlist_controls").next("span.ajax-spinner").remove();
	 if(data != '') {
	 	//alert(data)
		$("#normal_playlist").html(data);
	}
	show_only('normal_playlist');		
	enable_playlist_controls();
	enable_remove_items();
}

//If 'Cancel reorder' is clicked
$("#but_cancel").click(function(ele){
	 if($(this).attr("disabled") == 'disabled') return false;			
	 show_only('normal_playlist');								
	 enable_playlist_controls();
	 enable_remove_items();
});	

//'Edit Playlist' click event
$("#edit_title").click(function(ele){
	if($(this).attr("disabled") == 'disabled') return false;
	show_only('edit_playlist');									
	 disable_playlist_controls();
});	

// Edit Playlist 'Cancel' button's click event
$("#but_title_cancel").click(function(ele){
	if($(this).attr("disabled") == 'disabled') return false;
	show_only('normal_playlist');
	enable_playlist_controls();
});	

// Edit Playlist 'Save' button's click event
$("#but_title_save").click(function(ele){
	if($(this).attr("disabled") == 'disabled') return false;								
	var title = $("#txt_title").val();
	var desc = jQuery.trim($("#txt_desc").val());
	if(jQuery.trim(title) == ''){
		$("#txt_title").val('')
		$("#txt_title").focus()
		alert("This shouldn't be blank")
		return;
	}
	$('#but_title_save').attr("disabled","disabled");
	$('#but_title_cancel').attr("disabled","disabled");
	$("#playlist_controls").after("<span class='ajax-spinner'><img src='/static/images/ajax-loader.gif' alt='' style='vertical-align: middle;' /></span>");
	$.post("/playlists/save_title/", {playlist_id:playlist_id, playlist_title:title, playlist_desc:desc}, save_title_return, "json");
});	

// Callback function of Playlist 'Save' button's click event
function save_title_return(data){
	$("#playlist_controls").next("span.ajax-spinner").remove();
	if(data['error'] == 0){
		$("#playlist_title").html(data['title']);
		if(data['desc'] == "")
		$("#playlist_desc").html("No description");
		else
		$("#playlist_desc").html(data['desc']);
		$("#playlist_title_nav_"+playlist_id).html(data['title']);
		//commented as not sure where to show the message
		//$("#playlist_msg").text('Edited successfully').stop().css("opacity", 1).fadeIn(30);
	} else {
		//$("#playlist_msg").text('Error occured').stop().css("opacity", 1).fadeIn(30);
	}
	$('#but_title_save').removeAttr("disabled");
	$('#but_title_cancel').removeAttr("disabled");
	show_only('normal_playlist');
	enable_playlist_controls();
}	

//This is called when remove Link is clicked to delete one item from playlist
function delete_item(id){
	if($("#del_pl_item_"+id).attr("disabled") == 'disabled') return false;
	var ans = confirm("Are you sure you want to delete the playlist?");
	
	if(ans){
		$("#del_pl_item_"+id).after("<span class='ajax-spinner'><img src='/static/images/ajax-loader.gif' alt='' style='vertical-align: middle;' /></span>");
		$("#del_pl_item_"+id).attr("disabled","disabled");
		disable_playlist_controls();
		$.post("/playlists/delete_item/", {playlist_object_id:id}, delete_item_return, "json");
	}
}

//Callback function of 'Remove' link's click event
function delete_item_return(data){
	 $("#del_pl_item_"+data['itemid']).next("span.ajax-spinner").remove();
	 $("#del_pl_item_"+data['itemid']).removeAttr("disabled");
	if(data['error'] == 0) {
		$("#po_"+data['itemid']).fadeOut(1000,function(){
			$("#nav_item_count_"+playlist_id).html('('+ data['count'] + ' items)');
		});
		if(data['count'] == 1) {
			$('#sort_list').fadeOut(1000);
		}
		if(data['count'] == 0) {
			$('#play_all').fadeOut(1000);
		}		
	}
	enable_playlist_controls();
}

// 'Delete playlist' button's click event
$("#delete_playlist").click(function(ele){
	if($(this).attr("disabled") == 'disabled') return false;									 
	var ans = confirm("Are you sure you want to delete the playlist?");
	if(ans){
		$("#form_remove_playlist").submit();
	}
});	

// Disable all playlist controls 
function disable_playlist_controls(){
	$("#edit_title").attr("disabled","disabled");
	$("#sort_list").attr("disabled","disabled");
	$("#delete_playlist").attr("disabled","disabled");
}

// Enable all playlist controls
function enable_playlist_controls(){
	$("#edit_title").removeAttr("disabled");
	$("#sort_list").removeAttr("disabled");
	$("#delete_playlist").removeAttr("disabled");
}

//disable all remove Item links
function disable_remove_items(){
	for(var i=0; i< item_array.length;i++)
		$("#del_pl_item_"+item_array[i]).attr("disabled","disabled");
}

//enable all remove Item links
function enable_remove_items(){
	for(var i=0; i< item_array.length;i++)
		$("#del_pl_item_"+item_array[i]).removeAttr("disabled");
}

// Show only one playlist POD at a time in profile
function show_only(id){
	//playlist edit area
	if(id == 'edit_playlist') 
		$("#edit_playlist").show();
	else
		$("#edit_playlist").hide();
	//Sortable list
	if(id == 'sort_playlist')
		$("#sort_playlist").show(); 
	else
		$("#sort_playlist").hide(); 
	//Normal display list
	if(id == 'normal_playlist')
		$("#normal_playlist").show(); 
	else
		$("#normal_playlist").hide(); 
}

//for add new playlist
$("input[id^='new_pl']").focus(function(){ 
	if($(this).val() =='Create a new list')
	$(this).val('');
});

//for add new playlist
$("input[id^='new_pl']").blur(function(){ 
	if($(this).val() =='')
	$(this).val('Create a new list');
});

//this function is called when a playlist is clicked to add item in it 
function add_to_pl(pl_id,obj_id,but_no,serial_no){
if($("#li_"+obj_id+"_"+serial_no).attr("disabled") == 'disabled') return false;
$("#li_"+obj_id+"_"+serial_no).attr("disabled","disabled");
pl_list[but_no][serial_no].actioned=1;
$("#li_"+obj_id+"_"+serial_no).addClass("processing");
$.post("/playlists/add/", {object_type:obj_type, object_id:obj_id, playlist_id:pl_id}, pl_item_add_return, "json");
}

//call back function for item add in playlist
function pl_item_add_return(data){
	if(data['error'] == 0) {
		pl=$("#new_pl"+data['itemid']).parent().attr('id');
		for(jj=0;jj< pl_list[pl].length;jj++){ // search in the playlist array and for right playlist mark is selected
			if((pl_list[pl][jj]).id == data['newid']){
			(pl_list[pl][jj]).selected=1;
			(pl_list[pl][jj]).actioned=0;
			}
		}
	}else{
		alert("Could not add to playlist");
	}
	$("#apl_"+data['itemid']).click(); // click the button twice to refresh the list.
	$("#apl_"+data['itemid']).click();
}

//this function is called when a playlist is clicked to remove item in it 
function remove_from_pl(pl_id,obj_id,but_no,serial_no){
if($("#li_"+obj_id+"_"+serial_no).attr("disabled") == 'disabled') return false;
$("#li_"+obj_id+"_"+serial_no).attr("disabled","disabled");
pl_list[but_no][serial_no].actioned=1;
$("#li_"+obj_id+"_"+serial_no).removeClass("selected");
$("#li_"+obj_id+"_"+serial_no).addClass("processing");
$.post("/playlists/delete_item_from_playlist/", {playlist_id:pl_id, object_type:obj_type, object_id:obj_id}, my_pl_item_delete_return, "json");
}

//call back function for item remove in playlist
function my_pl_item_delete_return(data){
	if(data['error'] == 0) {
		pl=$("#new_pl"+data['itemid']).parent().attr('id');
		for(jj=0;jj< pl_list[pl].length;jj++){ // search in the playlist array and for right playlist mark is selected
			if((pl_list[pl][jj]).id == data['playlistid']){
			(pl_list[pl][jj]).selected=0;
			(pl_list[pl][jj]).actioned=0;
			}
		}
	}else{
		alert("Could not remove from playlist");
	}
	$("#apl_"+data['itemid']).click(); // click the button twice to refresh the list.
	$("#apl_"+data['itemid']).click();
}

//for add new playlist input box
$("input[id^='new_pl']").keypress(function(key){
obj_id=($(this).attr("id")).substring(6);			   
if(key.which==13){ // sence enter
	if($(this).val()==''){ // nothing entered
	alert("Set a new playlist name and then enter");
	}else{
		title=$(this).val();
		$(this).val('Creating new playlist....');
		$(this).attr("disabled","disabled");
		$(this).blur();
		$.post("/playlists/create/", {object_type:obj_type, object_id:obj_id, playlist_title:title}, pl_add_return, "json");
	}
}
});


// callback function for new playlist create 
function pl_add_return(data){
	pl=$("#new_pl"+data['itemid']).parent().attr('id');
	$("#new_pl"+data['itemid']).val('Create a new list');
	if(data['error'] == 0) {
		for(jj=0;jj< pl_list.length;jj++){ //update playlist list for all screenshots
			nple = new play_list_element(data['newid'],data['newtitle']);
			pl_list[jj].push(nple);
		}
		pl_list[pl][pl_list[pl].length - 1].selected = 1;
		$("#new_pl"+data['itemid']).val('Create a new list');
		$("#pl_count").text(pl_list[pl].length);
		$("#apl_"+data['itemid']).click(); // refresh the list show
		$("#apl_"+data['itemid']).click();
	} else { // error in creating new playlist
		alert(data['status']);
		$("#new_pl"+data['itemid']).val('Create a new list');
	}
	$("#new_pl"+data['itemid']).removeAttr("disabled");
}

//generate button name for add playlist
function button_name(i){
	count=0;
	for(jj=0;jj<pl_list[i].length;jj++){
		if((pl_list[i][jj]).selected == 1)
		count++;
	}
	
	if(count==0){
		$("#add_button"+i).text("Add to Playlist");
	}else{
		if(count==1)
		$("#add_button"+i).text("1 List");
		else
		$("#add_button"+i).text(count+" Lists");
	}
}

// shows dropdown list of playlists
function show_list(i,obj_id) {	
	$('#pl_list'+i).toggle();
	if($('#pl_list'+i).css('display') == "block"){ // when showing list update the last open list reference
	$("#apl_"+obj_id).removeClass('addtopl_btn');
	$("#apl_"+obj_id).addClass('addtopl_btn_selected');
		if(open_list > 0 && open_list != obj_id )
			$("#apl_"+open_list).click(); // close the other list which is already open

	  open_list = obj_id;
	}
	if($('#pl_list'+i).css('display') == "none"){
	$("#apl_"+obj_id).removeClass('addtopl_btn_selected');
	$("#apl_"+obj_id).addClass('addtopl_btn');
	  open_list = -1;
	}
	button_name(i);
	// short the list
	pl_list[i].sort(function(a,b){if((a.title).toLowerCase() > (b.title).toLowerCase()) return 1; else return -1;});
	
	jj=0;
	list_html="";
	for(jj=0;jj< pl_list[i].length;jj++){
		list_html+="<li id='li_";
		list_html+=obj_id+"_"+jj+"'";
		if(pl_list[i][jj].selected==1){
			list_html+=" onClick='javascript:remove_from_pl( "+pl_list[i][jj].id+","+obj_id+","+i+","+jj+")'";
			if(pl_list[i][jj].actioned==0)
			list_html+=' class="selected"';
		}else{ 
			list_html+=" onClick='javascript:add_to_pl( "+pl_list[i][jj].id+","+obj_id+","+i+","+jj+")'";
		}
		if(pl_list[i][jj].actioned==1){
			list_html+=' class="processing"';
			list_html+=" disabled = 'disabled' ";
		}
		list_html+="><span>";
		list_html+=pl_list[i][jj].title;
		list_html+=	"</span></li>";
	}
	$('#item_list'+i).html(list_html);	
}
