/* nbcarchives playlist js library
 * $Revision: 4715 $
 * $Id: playlist.js 4715 2010-04-22 21:09:46Z rcrathore $ 
 */
var playlist ={};
playlist.item = function(order,name,id){
	this.order=order;
	this.name= name;
	this.id=id;
}
playlist.util = {
		userCycledPlaylist:false,
		oldTitle:"",
		personUUID:"",
		items: [],
		
		setItem:function(order,name,id){
			this.items[this.items.length]= new playlist.item(order,name,id);
		},
		
		playlistInit: function() {
			$('#absnav ul li').removeClass('brow'); $('#tab2').addClass('brow');
			$('.show_tooltip').tooltip({
				track: false,
				delay: 0,
				showURL: false,
				fade: 250,
				top: -117,
				left: -313
			});
			this.bindBehavior();
			$("#add_new_playlist a").click(function(){
				playlist.util.addNewPlaylistPopup("Add a new playlist",'<label for="new_playlist_item">New Playlist:</label><input type="text" id="new_playlist_item" />','popup_small')
			});
			$('#playlist_save').click(function(){
				var playlist_ids_array = [];
				var playlist_names_array = [];

				var playlist_item_name_new = '';
				var playlist_item_name_old = '';
				$('#playlist_list input').each(function(){
					playlist_ids_array.push($(this).attr('id'));
					playlist_item_name_new = $.trim($(this).val());

					if (playlist_item_name_new == null || playlist_item_name_new.length == 0) {
						playlist_item_name_new = playlist_item_name_old; 
					} else {
						playlist_item_name_old= $(this).siblings('.playlist_item').text();
					}

					playlist_names_array.push(playlist_item_name_new + "$$DLIM1$$" + playlist_item_name_old);
					
				});

				var delimited_playlistnames = playlist_names_array.join("$$DLIM2$$");
				var comma_separated_playlistids = playlist_ids_array.join();
				if (null != comma_separated_playlistids && comma_separated_playlistids.length > 0) {
					playlist.util.orderCategory(delimited_playlistnames, comma_separated_playlistids);
				}
			});
			$('#playlist_view_link').click(function(){
				$('.playlist').addClass('playlist_view');
				$('#playlist_list').sortable('destroy');
				$('#playlist_list').children('.selected').removeClass('selected');
				$('#playlist_list_view').children('.selected').removeClass('selected');
				$('#playlist_list li input').hide();
				$('.edit_playlist_item').show();
				$('.save_playlist_item').hide();
				$('#playlist_list').attr('id','playlist_list_view');
				$('.playlist_item').show();
				$('.inactive_link').removeClass('inactive_link');
				$('#playlist_view_link').addClass('inactive_link');
				/* show all */
				playlist.util.cyclePlaylist(playlist.util.personUUID);
				$('#playlist_show_all').addClass('selected');
			})
			$('#playlist_edit_view_link').click(function(){
				$('.playlist').removeClass('playlist_view');
				$('#playlist_list_view').attr('id','playlist_list');
				$('.inactive_link').removeClass('inactive_link');
				$('#playlist_edit_view_link').addClass('inactive_link');
				$('#playlist_list').sortable();
			})
			$('.playlist_edit_view').addClass('playlist_view');
			$('#playlist_list li input').hide();
			$('.edit_playlist_item').show();
			$('.save_playlist_item').hide();
			$('#playlist_list').attr('id','playlist_list_view');
			$('.playlist_item').show();
			$('.inactive_link').removeClass('inactive_link');
			$('#playlist_view_link').addClass('inactive_link');

			
		},
		
		loadPlaylists:function() {
			$('#playlist_show_all,#playlist_edit_view_link').hide();
			if (null == this.personUUID || $.trim(this.personUUID).length == 0 ) {
				/* User is not logged in */
				search_resultCount = 0;
				nodelist_buffer_type = 'error';
				message_title = 'Welcome to My Playlists.';
				message_body='<p>Please sign in to see your playlists.</p>';
				var content = '<div id="empty_playlist"><h4>';
				content+=message_title;
				content+='</h4>';
				content+=message_body;
				content+='</div>' ;
				$('div#page_center > div#page_setup > h3').html('&nbsp;');
				$('div#page_center > div#page_setup > div.content').html('').html(content);
				/* dont go further*/
				return ;
			}
			
			if (playlist.util.items.length ==0) {
				/* There is no playlist */
				search_resultCount = 0;
				nodelist_buffer_type = 'error';
				message_title = 'Welcome to My Playlists.';
				message_body = '<p>To create your own playlists, click the "Edit" tab on the tool to the left.  You can create as many playlists as you like and title them (or re-title them) whenever you want.  You can also drag and drop them in the list so they\'re in the order you prefer!</p>';
				message_body += '<p>To save videos, documents, and other resources to your playlists, click the "Save" button on the bottom of any Cue Card. </p>';
				
				var content = '<div id="empty_playlist"><h4>';
				content+=message_title;
				content+='</h4>';
				content+=message_body;
				content+='</div>' ;
				$('div#page_center > div#page_setup > h3').html('&nbsp;');
				$('div#page_center > div#page_setup > div.content').html('').html(content);
				/* dont go further*/
				return ;
			} 
			$.each(playlist.util.items, function(n,item){
				/* Add hidden li's */
				var content = '<li style="display:none">';
				content +='<a class="playlist_item" href="#" onclick="playlist.util.cyclePlaylist(\'' + item.id + '\'); return false;">' +  item.name + '</a>';
				content +='<input type="text" value="' + item.name + '" id="' + item.id + '"/>';
				content +='<a href="Javascript:;" class="edit_playlist_item">edit playlist item</a>';
				content +='<a href="Javascript:;" class="save_playlist_item">save playlist item</a>';
				content +='<a href="Javascript:;" class="delete_playlist_item">delete playlist item</a>';
				content +='</li>';
		
				$(content).appendTo('ul#playlist_list_view');
			 });
			
			
			
			$.each(playlist.util.items, function(n,item){
				
				playlist.util.viewPlaylist(item.id, item.name);
				
			 });
//		
//			var content = '<div id="empty_playlist"><h4>';
//			content+='Welcome to My Playlists.';
//			content+='</h4>';
//			content+='<p>Click on playlist name on left to see videos.</p>';
//			content+='</div>' ;
//			$('div#page_center > div#page_setup > h3').html('&nbsp;');
//			$('div#page_center > div#page_setup > div.content').html('').html(content);
		},
		
		viewPlaylist: function (listId, listName) {
			
			$.get("/nbcarchive/viewplaylist/?uuid=" +  this.personUUID + "&listId=" + listId + "&listName=" + listName, function(data) {
				var $data = $(data);
				if ($data.find("error > code").size() == 0 ) {
					/* no error code */
					
						if (typeof nodelist_buffer == 'object' && $(nodelist_buffer).find('course').size() > 0) {
							
							var newChapterNode = null ;
							
							if (nodelist_buffer.importNode) {
							     newChapterNode = nodelist_buffer.importNode($data.find('chapter').get(0),true);
							} else {
							     newChapterNode = $data.find('chapter').get(0);
							}
							
							try {
							
								$(newChapterNode).appendTo($(nodelist_buffer).find('course'));
									
							} catch (e) {
								if (e.code == DOMException.WRONG_DOCUMENT_ERR) {
									//display the error message
									alert("DOMException.WRONG_DOCUMENT_ERR:" + e.code);
								}
								else {
									alert("unexpected exception. code: " + e.code); 
								}
							}	
						} else {
							nodelist_buffer = data ;
						}
				}


				message_title		 = 'This playlist is empty!';
				message_body		 = 'Choose any resource from the archive and click the "Save" button to save it to your playlist.';
				isSearchActive = false;
				isPlaylistActive = true;
				search_resultCount = 1;
				nodelist_buffer_type = 'playlist_results';
				
				position_id = playlist.util.personUUID;
				shared_playlist_uid=playlist.util.personUUID;
				/* display appropriate li when callback is called. */
				$("#playlist_list_view > li").has("input#" +listId).show();
				
				/* post processing after all playlists loaded through ajax */
				if ( $('ul#playlist_list_view').find('li:visible').size() == playlist.util.items.length) {
					/* total li's equals total playlists. that means all ajax calls finished */
					playlist.util.afterPlaylistsLoaded();
				}

			});
	},
	afterPlaylistsLoaded: function() {
			/* remove all li's except the first one (show all) */
			$('#playlist_show_all,#playlist_edit_view_link').show();
			if (!this.userCycledPlaylist) {
				/*process all nodes and display*/
				playlist.util.cyclePlaylist(playlist.util.personUUID);
				$('#playlist_show_all').addClass('selected');
			}
			
	},
	createContentCategory: function (categoryName,order) {
	
		var snasUrl =  "/nbcarchive/nbcarchive_manage_playlists_as_groups.jsp?operation=addplaylist&personUUID=" + this.personUUID + "&categoryName="+categoryName+"&order="+order;
		  
			$.ajax({
			    url: snasUrl,
			    type: 'GET',
			    dataType: 'text',
			    timeout: 60000,
			    error: function(){
			        alert('AjaX Error! while saving new playlist. Please try after some time.');
			        return false;
			    },
			    success: function(xml){
			       	if(xml.indexOf("error") != -1) {
			       		alert('We are unable to store the new playlist. Please try after some time. ');
			       		return false;
					} else {
						
						if(xml.indexOf("<success>") > -1)
					    {
							var new_item_id = xml.substring(xml.indexOf("<ID>")+4,xml.indexOf("</ID>"));
						    
							$('#playlist_list').append('<li><a class="playlist_item" onclick="playlist.util.cyclePlaylist(\''+new_item_id+'\'); return false;">'+categoryName+'</a><input id="'+new_item_id+'" type="text" value="'+categoryName+'" /><a href="Javascript:;" title="edit playlist item" class="edit_playlist_item">edit playlist item</a><a href="Javascript:;" title="save playlist item" class="save_playlist_item">save playlist item</a><a href="Javascript:;" title="delete playlist item" class="delete_playlist_item">delete playlist item</a></li>');
							playlist.util.bindBehavior();
							return true;
					    } else {
						    alert('We are unable to store the new playlist. Please try after some time.');
						    return false;
					    }
					}
			    }
			});
	}, 
	
	editContentCategory: function (categoryName,id) {
	
		var snasUrl =  "/nbcarchive/nbcarchive_manage_playlists_as_groups.jsp?operation=editplaylist&personUUID=" + this.personUUID + "&categoryName="+categoryName+"&oldCategoryName="+playlist.util.oldTitle+"&id="+id;
		  
		$.ajax({
		    url: snasUrl,
		    type: 'GET',
		    dataType: 'text',
		    timeout: 60000,
		    error: function(){
		        alert('AjaX Error! while editing new playlist. Please try after some time.');
		        return false;
		    },
		    success: function(xml){
			    var returnValue = false;
		       	if(xml.indexOf("error") != -1) {
		       		//alert('response is incorrect, re setting the playlist title to old title');
					$("#"+id).siblings('.playlist_item').html(playlist.util.oldTitle);
					document.getElementById(id).value = playlist.util.oldTitle;   
				    alert('We are unable to edit the title of playlist. Please try after some time.');
				} else {
					
					if(xml.indexOf("<success>") > -1)
				    {
						$("#"+id).siblings('.playlist_item').html(categoryName);
						returnValue = true;

				    } else {
				    	alert('response is incorrect,'+xml +' re setting the playlist title to old title');
						$("#"+id).siblings('.playlist_item').html(playlist.util.oldTitle);
						document.getElementById(id).value = playlist.util.oldTitle; //$("#"+id).attr('value') = playlist.util.oldTitle;
					    alert('We are unable to edit the title of playlist. Please try after some time.'+xml);
				    }
					
				}
		       	playlist.util.oldTitle = "";
				$("#"+id).hide();
				$("#"+id).siblings('.edit_playlist_item').show();
				$("#"+id).siblings('.playlist_item').show();
				$("#"+id).siblings('.save_playlist_item').hide();
				return returnValue;
		    }
		});
	},

	deleteContentCategory: function (title, categoryId) {
	
		var snasUrl =  "/nbcarchive/nbcarchive_manage_playlists_as_groups.jsp?operation=deleteplaylist&personUUID=" + this.personUUID + "&id="+categoryId+"&categoryName="+title;
	  
		  
		$.ajax({
		    url: snasUrl,
		    type: 'GET',
		    dataType: 'text',
		    timeout: 60000,
		    error: function(){
		        alert('AjaX Error! while deleting playlists. Please try after some time.');
		        return false;
		    },
		    success: function(xml){
		       	if(xml.indexOf("error") != -1) {
		       		alert('unable to delete playlists. Please try after some time. ');
		       		return false;
				} else {
					
					if(xml.indexOf("<success>") > -1)
				    {
						$('.deleting_playlist').remove();

						// remove from front end
						$(nodelist_buffer).find('#'+categoryId).each(function(){
							$(this).remove();
						});
						
						position_id= playlist.util.personUUID;

						// reprocess nodes and display
						processNodelistBuffer();
						return true;
				    } else {
					    alert('Please remove all Cue Cards from this playlist (by clicking the red X to the right) before deleting the playlist itself.');
					    return false;
				    }
				}
		    }
		});
	},
	
	orderCategory: function (categoryNameList,categoryIdList) {
		
	 var snasUrl = "/nbcarchive/nbcarchive_manage_playlists_as_groups.jsp";
	 var uuid= this.personUUID;
		$.ajax({
		    url: snasUrl,
		    type: 'POST',
		    data: {operation:'editorder', personUUID:uuid, namelist:categoryNameList},
		    dataType: 'text',
		    timeout: 60000,
		    error: function(){
		        alert('AjaX Error! while ordering playlists. Please try after some time.');
		        return false;
		    },
		    success: function(xml){
		       	if(xml.indexOf("error") != -1) {
		       		alert('unable to order playlists. Please try after some time. ');
		       		return false;
				} else {
					
					if(xml.indexOf("<success>") > -1)
				    {
						$('#playlist_list input').each(function(){
							var playlist_item_name_new = $.trim($(this).val());
							if (null != playlist_item_name_new && playlist_item_name_new.length > 0) {
								$(this).siblings('.playlist_item').text(playlist_item_name_new);
							}
						});
						$('.playlist_item').show();
						$('#playlist_list input').hide();
						$('.save_playlist_item').hide();
						$('.edit_playlist_item').show();
						$('.delete_playlist_item').show();
						alert('Playlists are reordered and saved.');
						return true;
				    } else {
					    alert('We are unable to order the playlists. Please try after some time.');
					    return false;
				    }
				}
		    }
		});
	}, 
	deletePlaylistPopup : function (title,msg,playlist_id,dialogClass){
		$(".dialog_popup").dialog( 'destroy' );
		$(".dialog_popup").remove();
		$('<div class="dialog_popup">'+msg+'<div class="button_div_line"></div></div>').insertAfter('#absout');
		$(".dialog_popup").dialog({
			buttons: {
				"ok": function() {
					$(this).dialog("close");
					$(".dialog_popup").dialog().remove();
					playlist.util.deleteContentCategory(title, playlist_id);
					}, 
				"Cancel": function() {
					$('.deleting_playlist').removeClass('deleting_playlist');
					$(this).dialog("close");
					$(".dialog_popup").dialog().remove();
				}
			},
			modal: true,
			title: 'Delete playlist: '+title+'?',
			dialogClass: dialogClass
		});
	}, 
	addNewPlaylistPopup: function (title,msg,dialogClass){
		$('<div class="dialog_popup">'+msg+'<div class="button_div_line"></div></div>').insertAfter('#absout');
		var new_playlist_item = '';
		$(".dialog_popup").dialog({
			buttons: {
				"save": function() {
					var new_playlist_item = $('#new_playlist_item').attr('value');
					if(!new_playlist_item){
						alert("You must type a new playlist name or hit 'Cancel'.");
					}else{
						$(this).dialog("close");
						$(this).dialog().remove();
						//alert("backend/db add new playlist function goes here");
						
						var playlist_ids_array = [];
						var playlist_names_array = [];
						var playlist_array = {};
						var playlist_item_id = '';
						var playlist_item_name = '';
						$('#playlist_list input').each(function(){
							playlist_item_id = $(this).attr('id');
							playlist_item_name = $(this).val();
							playlist_ids_array.push(playlist_item_id);
							playlist_names_array.push(playlist_item_name);
							playlist_array[playlist_item_id]=playlist_item_name;
						});
						var proceedToSave = true;
						//alert(playlist_names_array);
						for(i=0; i<playlist_names_array.length; i++) {
							if (playlist_names_array[i].toLowerCase() == new_playlist_item.toLowerCase()) {
								alert('A playlist with this name already exists in your list, please type a unique name');
								proceedToSave =  false; 
							}
						}
						//alert(proceedToSave);
						if (proceedToSave) {
							playlist.util.createContentCategory(new_playlist_item,playlist_names_array.length);
						}
					}
				}, "Cancel": function() {
					$(this).dialog("close");
					$(this).dialog().remove();
				}
			},
			modal: true,
			title: 'Add playlist?',
			dialogClass: dialogClass
		});
	},
	bindBehavior: function (){
		$("#playlist_list").sortable();
		$(".edit_playlist_item").click(function(){
			playlist.util.oldTitle = $(this).siblings('input').attr('value');
			$(this).siblings('input').show();
			$(this).siblings('.save_playlist_item').show();
			$(this).siblings('.playlist_item').hide();
			$(this).hide();
		});
		$(".save_playlist_item").click(function(){
			var new_playlist_title = $(this).siblings('input').attr('value');
			var new_playlist_id = $(this).siblings('input').attr('id');
			playlist.util.editContentCategory(new_playlist_title, new_playlist_id);
		});
		$(".delete_playlist_item").click(function(){
			var delete_playlist_title = $(this).siblings('input').attr('value');
			var delete_playlist_id = $(this).siblings('input').attr('id');
			$('.deleting_playlist').removeClass('deleting_playlist');
			$(this).parent('li').addClass('deleting_playlist');
			playlist.util.deletePlaylistPopup(delete_playlist_title,'Clicking "OK" below will permanently delete the playlist and all its associated cards : "'+delete_playlist_title+'".',delete_playlist_id,'popup_small');
		});
		$("#playlist_list_view .playlist_item").click(function(){
			$('#playlist_list').children('.selected').removeClass('selected');
			$('#playlist_list_view').children('.selected').removeClass('selected');
			$(this).parent('li').addClass('selected');
		});
	},
	
	cyclePlaylist: function (id) {
		this.userCycledPlaylist = true;
		if (search_resultCount > 0) {
			position_id = id;
			nodelist_buffer_type='filter';
			processNodelistBuffer();
		}
		$('#playlist_list').children('.selected').removeClass('selected');
		$('#playlist_list_view').children('.selected').removeClass('selected');
		$("#playlist_list_view").find("#"+id).each(function() {
			$(this).parent('li').addClass('selected');
		});
		addThisSharePlaylist();
	},
	
	deleteCardPopup: function (cardid){

		if (position_id == this.personUUID) {
			alert('The card cannot be deleted from the "Show all" playlist. Please choose a playlist to delete the card from the specific playlist.');
			return; 
		}
	
		$('<div class="dialog_popup">Clicking "OK" will remove this Cue Card from your playlist and any personal data saved in the NOTES drawer will be permanently deleted.<div class="button_div_line"></div></div>').insertAfter('#absout');
		$(".dialog_popup").dialog({
			buttons: {
				"ok": function() {
					$(this).dialog("close");
					playlist.util.deleteCardFromPlaylist(cardid);
					
				}, "Cancel": function() {
					$(this).dialog("close");
				}
			},
			modal: true,
			title: 'Delete card?',
			dialogClass: 'popup_small'
		});
	},
	
	deleteCardFromPlaylist: function (cardid) {

	
		var playlist_name = null;
		$('#playlist_list_view input').each(function(){
			if (position_id == $(this).attr('id')) {
				playlist_name = $(this).val();
			}
		});
		
		// delete node from backend
		var snasUrl = "/nbcarchive/nbcarchive_manage_playlists_as_groups.jsp?operation=deleteCard&personUUID=" + this.personUUID + "&cardid="+cardid+"&categoryName="+playlist_name+"&categoryId="+position_id;
			  
			$.ajax({
			    url: snasUrl,
			    type: 'GET',
			    dataType: 'text',
			    timeout: 60000,
			    error: function(){
			        alert('AjaX Error! while deleting card from my playlist. Please try after some time.');
			        return false;
			    },
			    success: function(xml){
			       	if(xml.indexOf("error") != -1) {
			       		alert('unable to delete card from my playlist. Please try after some time.');
			       		return false;
					} else {
						
						if(xml.indexOf("<success>") > -1)
					    {
							// remove from front end
							$(nodelist_buffer).find('#'+position_id).find('#'+cardid).each(function(){
								$(this).attr("id2", "TBD");
							});
	
							// reprocess nodes and display
							processNodelistBuffer();
																    
							return true;
					    } else {
						    alert('We are unable to delete the card from the playlist. Please try after some time.');
						    return false;
					    }
					}
			    }
			});
	
	},

	moveItemInPlaylist: function (cardid, contentID, playlistname) {

//		alert("Flash called with cardid " + cardid + " ,contentID: " + contentID + " and list name: " + playlistname);
		var snasUrl =  "/nbcarchive/snas/api/getContentGroup?contentID=" + contentID + "&siteName=aod.icue.nbcuni.com&siteDomainName=aod.icue.nbcuni.com&fromRow=0&toRow=2000&timestamp=" + (new Date().getTime());
	
	
		$.ajax({
		    url: snasUrl,
		    type: 'GET',
		    dataType: 'text',
		    timeout: 25000,
		    error: function(){
		        alert('AjaX Error!');
		    },
		    success: function(xml){
		       	if(xml.indexOf("<error>") != -1){
			    	alert('Error: No playlist found for this video clip.');
				} else {
					var contentGroupXml = "<?xml version=\"1.0\"?><chapters>";
					// process all the groups and create the xml with two attributes (id, name).
					$(parseXML(xml)).find('content').each(function() {
						contentGroupXml += "<chapter id='" + $(this).find('groupID').text() + "' name='" + $(this).find('GroupName').text()+ "' ></chapter>"
					});
					contentGroupXml += "</chapters>" ;
					// alert(contentGroupXml);
					var groupInfoForContent = parseXML(contentGroupXml);
	
					// find the current playlists for this card in the nodelist_buffer 
					var groupIdArray = new Array();
	
					$(nodelist_buffer).find('#'+cardid).parents('chapter').each(function() {
						//alert("content group in node list buffer: " + $(this).attr('id'));
						groupIdArray.push($(this).attr('id'));
					});
	
	
					$.each(groupIdArray, function(n, $groupID)  {
						if ($(groupInfoForContent).find('#'+ $groupID ).size() == 0) {
						   if ($(nodelist_buffer).find('#'+ $groupID + ' > #'+ cardid ).size() > 0) {
						      $(nodelist_buffer).find('#'+ $groupID + ' > #'+ cardid ).get(0).setAttribute('id2','TBD');
						   }
						} 
					});
	
					// after the above removal process, the groupInfoForContent contains 
					// only the groups that are new for this card on this page
					// for each group left in the list 
					$(groupInfoForContent).find('chapter').each(function() {
						var $playlistID = $(this).attr('id');
						var $playlistName = $(this).attr('name'); 
						if ($(nodelist_buffer).find('#'+ $playlistID + ' > #'+ cardid ).size() == 0) {
						    // alert("adding card " + cardid + " to playlist " + $playlistID) ;
							playlist.util.addNodeToChapter(cardid, $playlistID, $playlistName);
						}
						if ($(nodelist_buffer).find('#'+ $playlistID + ' > #'+ cardid ).size() > 0) {
						 try{
						  $(nodelist_buffer).find('#'+ $playlistID + ' > #'+ cardid ).get(0).removeAttribute('id2');
						 } catch (e) {
							alert("ERROR id2" + e.code);
						 }
						}
					});
	
					processNodelistBuffer();
					if($("#playlist_list_view > li.selected > input").size() > 0) {
						playlist.util.cyclePlaylist($("#playlist_list_view > li.selected > input:first").attr('id'));
					}
				}
				
		    }
		});

},

addNodeToChapter: function (cardid, playlistid, playlistname) {

	var cuecardnode = $(nodelist_buffer).find('#'+cardid).filter(":first");

	var newNodeXML= "<?xml version=\"1.0\"?><node id='"+cuecardnode.attr('id')+"' thumb='"+cuecardnode.attr('thumb')+
		"' publish='"+cuecardnode.attr('publish')+"' eventlabel='"+cuecardnode.attr('eventlabel')+
		"' eventstart='"+cuecardnode.attr('eventstart')+"' airlabel='"+cuecardnode.attr('airlabel')+
		"' airdate='"+cuecardnode.attr('airdate')+"' length='"+cuecardnode.attr('length')+
		"' number='"+cuecardnode.attr('number')+"' type='"+cuecardnode.attr('type')+
		"' ><title>"+cuecardnode.find('title').text()+ "</title><description>"+cuecardnode.find('description').text()+"</description></node>";
		
		var newNode = null ;
		/* Please see http://www.alistapart.com/articles/crossbrowserscripting/ */
		if (nodelist_buffer.importNode) {
		  newNode = nodelist_buffer.importNode($(parseXML(newNodeXML)).find('node').get(0),true);	
		} else {
	          newNode = $(parseXML(newNodeXML)).find('node').get(0);	
		}

		if($(nodelist_buffer).find('#'+playlistid).size() > 0)  {
			// alert("existing playlist " + playlistid);
			try{
			$(newNode).appendTo($(nodelist_buffer).find('#' + playlistid).get(0)); 

			} catch (e) {
				if (e.code == DOMException.WRONG_DOCUMENT_ERR) {
					//display the error message
					alert("DOMException.WRONG_DOCUMENT_ERR:" + e.code);
				}
				else {
					alert("unexpected exception. code: " + e.code); 
				}
			}	

		} else {
			// this category is newly created. 
			// alert("new playlist " + playlistid);
			var chapterNode = parseXML("<?xml version=\"1.0\"?><chapter id='"+playlistid+"' nodelist='none'></chapter>");
			var newChapterNode = null ;
			if (nodelist_buffer.importNode) {
			     newChapterNode = nodelist_buffer.importNode($(chapterNode).find('chapter').get(0),true);
			} else {
			     newChapterNode = $(chapterNode).find('chapter').get(0);
			}

			try {
				// insert new chapter(playlist) after the last chapter
				$(newChapterNode).appendTo($(nodelist_buffer).find('course'));

				$(newNode).appendTo($(nodelist_buffer).find('#' + playlistid).get(0)); 

			} catch (e) {
				if (e.code == DOMException.WRONG_DOCUMENT_ERR) {
					//display the error message
					alert("DOMException.WRONG_DOCUMENT_ERR:" + e.code);
				}
				else {
					alert("unexpected exception. code: " + e.code); 
				}
			}	

			if ($('#playlist_list_view').find('#'+playlistid).size() ==0) {
					// Add the playlist 
					$('#playlist_list_view').attr('id','playlist_list');
					$('#playlist_list').append('<li><a class="playlist_item" onclick="playlist.util.cyclePlaylist(\''+playlistid+'\'); return false;">'+playlistname+'</a><input id="'+playlistid+'" type="text" value="'+playlistname+'" /><a href="Javascript:;" title="edit playlist item" class="edit_playlist_item">edit playlist item</a><a href="Javascript:;" title="save playlist item" class="save_playlist_item">save playlist item</a><a href="Javascript:;" title="delete playlist item" class="delete_playlist_item">delete playlist item</a></li>');
					playlist.util.bindBehavior();
					$('#playlist_list').attr('id','playlist_list_view');
				}
				position_id = playlistid;
		}
	}
}
/* End of file
 * $Revision: 4715 $
 * $Id: playlist.js 4715 2010-04-22 21:09:46Z rcrathore $ 
 */
