//to store title of the notecard
var notecardTitle = "";

var editor;

//global variable used for ajax request
var ajaxReq;

var win;

var newNoteWin;

Ext.WindowMgr.zseed=9999;
YAHOO.namespace("example.container");

var pileStore = "";

/*
 * function to show overlay for the creation of new notecard
 */
function showOverlay()
{
	hidePopupOnDrag();
	prepareMaskNote();
	if(!newNoteWin){
		createNewNoteWin();
	}else{
		Ext.getCmp('mypileid').setValue("0");
		pileStore.reload();
		newNoteWin.show();
	}
	
}

/*
 * function to show alert overlay
 */
function showAlertBox(message, src)
{	
	function handleOk() {
		if(src == "Notecard")
		{
			//document.getElementById("txt_"+noteInEditMode).value = "Title";
			document.getElementById("txt_"+noteInEditMode).select();
		}
		if(src == "Outline")
		{
			//document.getElementById("txt_"+itemInEditMode.substr(4)).value = "Topic Title";
			
			document.getElementById("txt_"+itemInEditMode.substr(4)).select();
		}
		if(src == "LiNotecard")
		{
			var noteid = getNotecardId(liNoteInEditMode);
			var txt_field = "txt_li_"+noteid;
			//document.getElementById(txt_field).value = "Title";
			document.getElementById(txt_field).select();
		}
		if(src == "Pile")
		{
			//document.getElementById("txt_"+pileInEditMode).value = "Title";
			document.getElementById("txt_"+pileInEditMode).select();
		}
		if(src == "Project")
		{
			openChoseProjectDg();
		}	
	};
	Ext.MessageBox.show({
		title: 'Error',
		msg: message ,
		buttons: Ext.MessageBox.OK,
		fn: handleOk,
		icon: Ext.MessageBox.ERROR
	});
}
/*
 * function to show overlay for the pile
 */
function showPileOverlay()
{
	// Instantiate the Dialog
	Ext.MessageBox.prompt('New Pile', 'Pile Title:', handlePileSubmit);
	function handlePileSubmit(btn, val){
		text = val.toString();
		text = Trim(text);
		if (btn == "ok") {
			if (Trim(text) == "") {
				Ext.MessageBox.show({
					title: 'Error',
					msg: 'Please enter a title for this pile.',
					buttons: Ext.MessageBox.OK,
					fn: showPileOverlay,
					icon: Ext.MessageBox.ERROR
				});
			}
			else {
				if(alphaNumPile(text)){
					if (!CheckPileTitle(Trim(text), "")) {
						document.getElementById(overElement).style.display = "none";
						for (i = 0; i < notecardID.length; i++) {
							if (notecardID[i][0] == overElement) {
								notecardID[i][6] = "none";
							}
						}
						document.getElementById(underElement).style.display = "none";
						for (i = 0; i < notecardID.length; i++) {
							if (notecardID[i][0] == underElement) {
								notecardID[i][6] = "none";
							}
						}
						document.getElementById("thumb_" + overElement).style.display = "none";
						document.getElementById("thumb_" + underElement).style.display = "none";
						createPile(posXY, Trim(text));
					}
					else {
						Ext.MessageBox.show({
							title: 'Error',
							msg: 'A pile with this title already exists.',
							buttons: Ext.MessageBox.OK,
							fn: showPileOverlay,
							icon: Ext.MessageBox.ERROR
						});
					}
				}else{
					Ext.MessageBox.show({
							title: 'Error',
							msg: 'Please use only letters and/or numbers in the pile title.',
							buttons: Ext.MessageBox.OK,
							fn: showPileOverlay,
							icon: Ext.MessageBox.ERROR
					});
				}
			}
		}else{
			YAHOO.util.Dom.setX(overElement, YAHOO.util.Dom.getX(overElement)+100);
			for (i = 0; i < notecardID.length; i++) {
				if (notecardID[i][0] == overElement) {
					notecardID[i][1] = YAHOO.util.Dom.getX(overElement)+100;
				}
			}
			setLeftTopInBirdsEyeView(overElement, getLeftTopInTabletop(overElement));
		}
	}
}

/*
 * function to edit the notecard content
 */
function editNotecard()
{
	hideMe();
	hidePopupOnDrag();
	openNoteEditView();
}

/*
 * function to show pile details
 */
function pileDetails(pileid)
{	
	var maskWin;
	//retrieve the current projectID
	var projectID = document.getElementById("projectID").value;	
	//hide summary popup
	hidePopupOnDrag();
	var success = function(o)
	{
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
				
		maskWin.close();
		var data;
		try
		{
			data = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch(e)
		{
			alert(e);
		}
		var pileTitle = data[0];		
		var pileDet = data[1];			
		if(pileDet!=null)
		{	
			var html = "";
			for(i=0;i<pileDet.length;i++)
			{
				var ntitle = pileDet[i][0];
				if(pileDet[i][1] == "&nbsp")
				{
					var source = pileDet[i][1];
				}
				else
				{
					var source = Ext.util.Format.htmlEncode(pileDet[i][1]);
				}
				if(pileDet[i][2] == "")
				{
					var url = "&nbsp";
				}
				else
				{
					var url = "<a target='_blank' href="+pileDet[i][2]+">"+pileDet[i][2]+"</a>";
				}
				
				var pages = pileDet[i][3];
				var quote = pileDet[i][4];
				var para = pileDet[i][5];
				var ideas = pileDet[i][6];
				var cdate = pileDet[i][7];
				var mdate = pileDet[i][8];
				var tags = pileDet[i][9];
				var ptitle = pileDet[i][10];
				var visual_cues = pileDet[i][12];
								
				//button for the comments section
				if(isTeacher == "1"){
					var btnComment = "<a href=# class=smalltext>Add Comment</a> <a href=# onclick=showAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>-</a> | <a href=# class=smalltext>View Comments <a href=# onclick=showComments('comm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideComments('comm_"+pileDet[i][10]+"') class=smalltext>-</a></a></td></tr></table>";
				}else{
					var btnComment = "";
				}
				//button for the notecard section
				if(isTeacher == "1"){
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a></td></tr></tbody></table></th></tr>";
				}else{
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit')><img alt=Edit notecard src=../notecards/_images/edit.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit') class=smalltext>Edit</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete')><img alt=Delete Notecard src=../notecards/_images/cancel.png></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete') class=smalltext>Delete</a></td></tr></tbody></table></th></tr>";
				}
				//button for the notecard section
				if(isTeacher == "1")
				{
					var commBody = "";
					commBody = commBody + "<table style=\"border: none; width: 100%;\"><tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td><td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4><ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];
					for(j=0;j<comm.length;j++){
						commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px; padding-top:5px; margin-bottom:5px'><span width='100%' alt='click to edit' style='display:block;cursor:pointer;' class='commBodyOut' onmouseover=mouseOverCommBody('comm_text_"+comm[j][5]+"') onmouseout=mouseOutCommBody('comm_text_"+comm[j][5]+"') onclick=editCommentText('"+comm[j][5]+"') id='comm_text_"+comm[j][5]+"'>"+comm[j][1]+"</span><span width='100%' style='display:none;' id='txt_comm_body_"+comm[j][5]+"'><textarea id='tb_comm_"+comm[j][5]+"' cols=100 rows=5 style='border:1px solid #7F9DB9'></textarea><br><input type='button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Submit' onclick=endEditCommentText()>&nbsp;<input type = 'button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Cancel' onclick=cancelEditCommentText()></span>";
						if(comm[j][3] != "" && comm[j][3] != null){
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) </i></font>";
						}else{
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) (comment not yet viewed by the author of the list)</i></font>";
						}
						if(comm[j][4] != "" && comm[j][4] != null){
							commBody = commBody + " <font color=#808080><i>(deleted by recipient on "+comm[j][4]+" PST)</i></font>";
						}						
						commBody = commBody + "<br><span align='right'><a id='editComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=editCommentText('"+comm[j][5]+"')>Edit Comment</a> | <a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></span></li>";						
					}
					commBody = commBody + "</ol></td></table>";					
				}
				else
				{
					var commBody = "";
					commBody = commBody + "<table style=\"border: none; width: 100%;\"><tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td><td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4><ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];					
					for(j=0;j<comm.length;j++)
					{
						if(comm[j][4] != "" && comm[j][4] != null)
						{							
						}
						else
						{
							commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px;padding-top:5px;margin-bottom:5px'>"							
							if(comm[j][3] != "" && comm[j][3] != null && comm[j][3] != 1)
							{
								commBody = commBody + "<img width='28' height='11' border='0' src='./images2/new.gif'/>&nbsp;<span id='comm_text_"+comm[j][5]+"'>";
							}
							commBody = commBody + comm[j][1]+"</span><br><font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST)</i></font><br><a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></li>";
						}
					}
					commBody = commBody + "</ol></td></table>";
				}
				html = html + "<div id ='det_Notecard_"+ptitle+"'><table id=notecardtb class=notecardtb cellspacing=0><tbody><tr><th colspan=2><table class=notecardhead border=0><tbody><tr><td width=50% class=noborder><span class=notetitle>"+ntitle+"</span>"+btnNotes+"<tr><td class=subhead>Source:</td><td class=noteitem><span>"+source+"</span></td></tr><tr><td class=subhead>URL:</td><td class=noteitem><span>"+url+"</span></td></tr><tr><td class=subhead>Pages:</td><td class=noteitem><span>"+pages+"</span></td></tr><tr><td class=subhead>Tags:</td><td class=noteitem><span>"+tags+"</span></td></tr><tr><td class=subhead>Visual Cues:</td><td class=noteitem><span>"+visual_cues+"</span></td></tr><tr><td class=subhead>Quotation:</td><td class=noteitem><span class=quoteclass>"+quote+"</span></td></tr><tr><td class=subhead>Paraphrase:</td><td class=noteitem><span class=paraclass>"+para+"</span></td></tr><tr><td class=subhead>My Ideas:</td><td class=noteitem><span class=ideasclass>"+ideas+"</span></td></tr><tr><td class=subhead>History:</td><td class=noteitem><span>Notecard Created: "+cdate+"  |  Updated: "+mdate+"</span></td></tr></td></tr>";
				if(isTeacher == "1")
				{
					html = html + "<tr><td class=subhead>Comment:</td><td class=noteitem><table><tr><td><textarea id='ta_"+pileDet[i][10]+"' rows=5 cols=100></textarea></td><td>&nbsp;&nbsp;&nbsp;<input type=button class=btn value=Submit onclick=addComment('"+pileDet[i][10]+"')></td></tr></table></td></tr>";
					html = html + "<tr><td></td><td class=noteitem><span id='prelink_"+pileDet[i][10]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=\"comments("+pileDet[i][10]+")\">Select comments from the comment database</span></td></tr>";
					html = html + "<tr><td colspan=\"2\" height=\"10\"></td></tr>";					
				}				
				html = html + "</table>";
				html = html + "<table cellspacing=00 cellpadding=00>";
				if(comm.length == 0){
					var display = "hidden";
				}else{
					var display = "visible"
				}
				html = html + "<tr><td style='visibility:"+display+"' id='comm_row_"+pileDet[i][10]+"' colspan=2>"+commBody+"</td></tr>";
				html = html + "</table>";
			}			
			var piles = new Array();
			var unPiled = ["0", "Unpiled Notecards"];
			// collect the piles in the tabletop
			for (i = 0; i < pileID.length; i++) {
				piles[i] = [pileID[i][0], pileID[i][4]];
			}
			var selectNotes = ["1", "All Selected Notecards"];
			piles.push(selectNotes);
			piles.push(unPiled);
			piles.reverse();
			
			var cmb = new Ext.FormPanel({        		
				bodyStyle:"padding-left:10px;padding-top:5px;",				 
				 items: [{
				 	xtype: 'combo',					
				 	fieldLabel: 'View',					
				 	store: piles,
				 	triggerAction: 'all',
				 	id: 'selectPile',
				 	value: "Pile_"+pileid,
				 	emptyText : 'Select an Option',
				 	listeners: {
		                'select' : {
		                    fn: function(item){
		                      var val = Ext.getCmp('selectPile').getValue();
		                    
		                      if(val == "0"){
		                          	win.close();
		                          	unPiledNotecardDetails("");
		                      }else if(val == "1"){
								  
								  win.close();
								  selectedNotecardDetails();
		                      }else {
								  editNoteID = val.substr(5);
								  win.close();
								  pileDetails(editNoteID);
		                      }
		                    }, 
		                    scope: this
		                }
		            }
				 }]				
			});
			
			var dataGrid = new Ext.Panel({
				id:"pileHTML",
        		html: html,
				height: (YAHOO.util.Dom.getViewportHeight() - 200),
        		autoScroll: true
			});
			
			win = new Ext.Window({
				 width:(YAHOO.util.Dom.getViewportWidth()-100),
				 cls:"../_css/noodlenotes.css",
				 title:pileTitle,	
				 manager: openwindows,
				 buttonAlign: 'center',
				 closable: true,
				 bodyStyle:'padding:5px 5px 5px 5px',				 
				 draggable:false,
					listeners : {
						'close' : 
						{
							fn : function(myWin)
							{
								//retrieve isTeacher boolean									
								var isTeacher = document.getElementById("isTeacher").value;
								if(isTeacher == 0)
								{
									//create an array of notecard ids
									var notes = new Array();
									for (i = 0; i < pileDet.length; i++) {
										notes[notes.length] = pileDet[i][10];
									}
									//create a json string
									var strNotes = YAHOO.lang.JSON.stringify(notes);
									var success = function(o){
										if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
										{			
											showNotesSessionError(Trim(o.responseText));
											return false;
										}
									};
									var failure = function(o){
									};
									//ajax call to the server update viewed flag									
									Ext.Ajax.request({
								   		url: '../notecards/_includes/notecardOperations.php',
								   		method: 'POST',
								   		success: success,				   
								   		failure: failure,
										params: 'toggle=UpdateViewed&notes='+strNotes						
									});									
								}
							}
						},
						'show' : {
							fn: function(win){
								
							}
						}
					},				 
				 modal:true,
				 items:[{
				 	items:[cmb]
				 },{
				 	items:[dataGrid]
				 }],
				  buttons: [{
					text: 'Return to Tabletop',
					handler: function(){
							commInEditMode = "";
							win.close();
					}
				}]
			});
		
			win.show();
		}		
	};
	var failure = function(o)
	{
	};
	
	editNoteID = pileid;
	
	if(Ext.get("li_Pile_"+pileid)){
		var ul_child = YAHOO.util.Dom.getChildren("li_Pile_"+pileid);
		for(i=0;i<pileNotecard.length;i++)
		{
			if(pileNotecard[i][0] == "Pile_"+pileid)
			{
				pileNotecard[i][1] = ul_child[0].id.substr(3);
				ul_child.splice(0,1);
			}
		}
	}
	
	var pileNotedata = Ext.encode(pileNotecard);
	
	//show the window mask before the request
	maskWin = new Ext.Window({
        layout:'fit',
		manager: openwindows,
		baseCls: 'summPopup',
        closable: false,
        resizable: false,
        plain: true,
        border: false,
        shadow:false,
        html: "<img src = '../notecards/_images/ajax-loader.gif'> Loading... ",
		modal: true
	});
	maskWin.show();
			
	//ajax call to the server to retrieve notecard data	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=pileDet&pileID='+pileid+'&projectID='+projectID+'&pileNotedata='+pileNotedata	
   	});	
}

/*
 * function to open dialog for add to pile functionality
 */
function openAddtoPileDg()
{
	hidePopupOnDrag();
	if (stopEditingonTabletop()) {
		var arrSelNotes = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
		if (arrSelNotes.length == 0) {
			showAlertBox("Please select (ctrl-click) notecard(s) on the tabletop.", "tabletop");
		}
		else {
			var piles = new Array();
			// collect the piles in the tabletop
			for (i = 0; i < pileID.length; i++) {
				if(pileID[i][7] == "tabletop"){
					piles[i] = [pileID[i][0], pileID[i][4]];
				}
			}
			piles = piles.sort();
		
    
			var AddtoPileDg = new Ext.Panel({
				frame: true,
				bodyStyle: 'padding:0 10px 0;',
				xtype: 'radiogroup',
				layout: 'form',
				items: [{
					xtype: 'fieldset',
					title: 'Existing Pile',
					autoHeight: true,
					defaults: {
						width: 210
					},
					defaultType: 'textfield',
					collapsible: true,
					layout: 'table',
					id: "existingPile",
					listeners: {
                        'collapse' : {
                            fn: function(item){
                              Ext.getCmp('newPile').expand(true);
							  Ext.getCmp('exPile').clearValue();
                            }, 
                            scope: this
                        },
						'expand' : {
                            fn: function(item){
                               Ext.getCmp('newPile').collapse(true);
                            }, 
                            scope: this
                        }
                    },
					items: [cmb =  new Ext.form.ComboBox({
						id: 'exPile',
						//store: piles,
						store:new Ext.data.JsonStore({
					         id:'persID'
							 ,autoLoad :true
					        ,root:'rows'
					        ,totalProperty:'totalCount'
					        ,fields:[
					             {name:'id', type:'string'}
					            ,{name:'title', type:'string'}
					        ]
					        ,url:'../notecards/_includes/notecardOperations.php'
					        ,baseParams:{
					             toggle:'getPilesInAscOrder'
					        }
					    }),
						valueField: 'id',
    					displayField: 'title',
				        typeAhead: false,
						editable: false,
				        mode: 'local',
				        forceSelection: true,
				        triggerAction: 'all',
				        emptyText:'Select a pile...',
				        selectOnFocus:true
					})]
				}, {
					xtype: 'fieldset',
					title: 'Create New Pile',
					collapsible: true,
					autoHeight: true,
					collapsed: true,
					id: "newPile",
					layout: 'table',
					listeners: {
                        'collapse' : {
                            fn: function(item){
                               Ext.getCmp('existingPile').expand(true);
                            }, 
                            scope: this
                        },
						'expand' : {
                            fn: function(item){
								Ext.getCmp('existingPile').collapse(true);
								Ext.getCmp('exPile').clearValue();
							}, 
                            scope: this
                        }
                    },
					defaults: {
						width: 210
					},
					defaultType: 'textfield',
					items: [{
						name: 'txt_newPile',
						id: 'txt_newPile',
						msgTarget : 'side'
					}]
				}],
				buttons: [{
					text: 'Submit',
					handler: function(){
						var existingPileExpanded = Ext.getCmp('existingPile').collapsed;
						
						if(!existingPileExpanded)
						{
							var val = Ext.getCmp('exPile').getValue();
							if (val != "") {
								//show the window mask before the request
								maskWin = new Ext.Window({
							        layout:'fit',
									manager: openwindows,
									baseCls: 'summPopup',
							        closable: false,
							        resizable: false,
							        plain: true,
							        border: false,
							        shadow:false,
							        html: "<img src = '../notecards/_images/ajax-loader.gif'> Applying changes... ",
									modal: true
								});
								maskWin.show();
                                                              
								addToPile(val);
								addToPileWin.close();
							}
							else {
								addToPileWin.hide();
								function showResult2(){
									addToPileWin.show();
								}
								Ext.MessageBox.show({
									title: 'Error',
									msg: 'Please select a pile to continue.',
									buttons: Ext.MessageBox.OK,
									fn: showResult2,
									icon: Ext.MessageBox.ERROR
								});
							}
						}else{
							var arrSelNotes = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
							var val = Trim(Ext.getCmp('txt_newPile').getValue());
							if (arrSelNotes.length > 1) {
								if (val != "") {
									if(alphaNumPile(val)){
										if (!CheckPileTitle(val, "")) {
                                        //show the window mask before the request
										maskWin = new Ext.Window({
									        layout:'fit',
											manager: openwindows,
											baseCls: 'summPopup',
									        closable: false,
									        resizable: false,
									        plain: true,
									        border: false,
									        shadow:false,
									        html: "<img src = '../notecards/_images/ajax-loader.gif'> Applying changes... ",
											modal: true
										});
										maskWin.show();

											createNewPile(val);
											addToPileWin.close();
										}
										else {
											addToPileWin.hide();
											function showResult(){
												addToPileWin.show();
												Ext.getCmp('txt_newPile').setValue("");
												Ext.getCmp('txt_newPile').focus();
											}
											Ext.MessageBox.show({
												title: 'Error',
												msg: 'A pile with this title already exists.',
												buttons: Ext.MessageBox.OK,
												fn: showResult,
												icon: Ext.MessageBox.ERROR
											});
										}
									}else{
										addToPileWin.hide();
										function showResult(btn){
											if (btn == "ok") {
												addToPileWin.show();
											}
										}
										Ext.MessageBox.show({
											title: 'Error',
											msg: 'Please use only letters and/or numbers in the pile title.',
											buttons: Ext.MessageBox.OK,
											closable: false,
											fn: showResult,
											icon: Ext.MessageBox.ERROR
										});
									}
								}
								else {
									addToPileWin.hide();
									function showResult(){
										addToPileWin.show();
										Ext.getCmp('txt_newPile').setValue("");
										Ext.getCmp('txt_newPile').focus();
									}
									Ext.MessageBox.show({
										title: 'Error',
										msg: 'Please enter a title for the new pile.',
										buttons: Ext.MessageBox.OK,
										fn: showResult,
										icon: Ext.MessageBox.ERROR
									});
								}
							}
							else {
								addToPileWin.hide();
								function showResult1(){
									addToPileWin.show();
									Ext.getCmp('txt_newPile').setValue("");
									Ext.getCmp('txt_newPile').focus();
								}
								Ext.MessageBox.show({
									title: 'Error',
									msg: 'Please select two or more notecards to create a new pile.',
									buttons: Ext.MessageBox.OK,
									fn: showResult1,
									icon: Ext.MessageBox.ERROR
								});
							}
						}
					}
				}]
			});
			// This just creates a window to wrap the login form. 
			// The login object is passed to the items collection.       
			var addToPileWin = new Ext.Window({
				layout: 'fit',
				width: 350,
				height: 180,
				constrain : true,
				closable: true,
				resizable: false,
				plain: true,
				border: false,
				manager: openwindows,
				items: [AddtoPileDg],
				modal: true
			});
			addToPileWin.show();
		}
	}						
}

/*
 * function to add selected notecards to an existing pile
 */
function addToPile(selectedPile){
        var arrSelNotes = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
        var selNotesArray = [];
	for(i=0;i<arrSelNotes.length;i++){
            selNotesArray[i] = arrSelNotes[i].id;
        }
        var selNotesIDS = Ext.encode(selNotesArray);

        var projectID = document.getElementById('projectID').value;
	var success = function(o){
				if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
				{			
					showNotesSessionError(Trim(o.responseText));
					return false;
				}
                var tabtop = Ext.get('tabletop');
                var notesInDom = tabtop.select("div.notecard", true);
                notesInDom.remove();
                var yellowNotesInDom = tabtop.select("div.notecardYellow", true);
                yellowNotesInDom.remove();
                var pilesInDom = tabtop.select("div.pile", true);
                pilesInDom.remove();
                var yellownotesInDom = tabtop.select("div.pileYellow", true);
                yellownotesInDom.remove();
                tabtop = Ext.get('zoneList');
                var zonenotesInDom = tabtop.select("li.noteli", true);
                zonenotesInDom.remove();
                var zonepilesInDom = tabtop.select("li.pileli", true);
                zonepilesInDom.remove();
                tabtop = Ext.get('outer_hawk_eye');
                var zonethumbnotesInDom = tabtop.select("div", true);
                zonethumbnotesInDom.remove();
                tabtop.dom.innerHTML = "<div id='viewable_area'></div>";
                createBirdsEyeView();
                notecardID = [];
                pileID= [];
                pileNotecard = [];
		loadNotes();
                shakeMe(selectedPile);

	};
	//function called on failure
	var failure = function(o)
	{
	};
    //ajax call to the server to add notecard to existing pile	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=ExisttingPile_AddToPile&pos=zone&projectID='+projectID+'&pile_id='+selectedPile+'&selNotesIDS='+selNotesIDS
   	});	
}

/*
 * function to add selected notecards to new pile
 */
function createNewPile(val){
	var pileTitle = Trim(val);
        var arrSelNotes = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
        var selNotesArray = [];
	for(i=0;i<arrSelNotes.length;i++){
            selNotesArray[i] = arrSelNotes[i].id;
        }
        var selNotesIDS = Ext.encode(selNotesArray);

        var projectID = document.getElementById('projectID').value;
	var success = function(o){
				if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
				{			
					showNotesSessionError(Trim(o.responseText));
					return false;
				}
                var tabtop = Ext.get('tabletop');
                var notesInDom = tabtop.select("div.notecard", true);
                notesInDom.remove();
                var yellowNotesInDom = tabtop.select("div.notecardYellow", true);
                yellowNotesInDom.remove();
                var pilesInDom = tabtop.select("div.pile", true);
                pilesInDom.remove();
                var yellownotesInDom = tabtop.select("div.pileYellow", true);
                yellownotesInDom.remove();
                tabtop = Ext.get('zoneList');
                var zonenotesInDom = tabtop.select("li.noteli", true);
                zonenotesInDom.remove();
                var zonepilesInDom = tabtop.select("li.pileli", true);
                zonepilesInDom.remove();
                tabtop = Ext.get('outer_hawk_eye');
                var zonethumbnotesInDom = tabtop.select("div", true);
                zonethumbnotesInDom.remove();
                tabtop.dom.innerHTML = "<div id='viewable_area'></div>";
                createBirdsEyeView();
                notecardID = [];
                pileID= [];
                pileNotecard = [];
		loadNotes();
		
	};
	//function called on failure
	var failure = function(o)
	{
	};
	//ajax call to create a new pile	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
   		params: 'toggle=insertNewPile_AddToPile&pos=zone&title='+pileTitle+'&projectID='+projectID+'&selNotesIDS='+selNotesIDS
	});	
}

// function to remove trash entries of pile
function removeTrashPile()
{
	var tabletop = YAHOO.util.Dom.get('tabletop');
	var notecardCount = 0;
	for(i=0;i<pileID.length;i++)
	{
		this.id = pileID[i][0];
		for(a=0;a<pileNotecard.length;a++)
		{
			if(pileNotecard[a][0] == this.id)
			{
				notecardCount++;
			}
		}
		if(notecardCount == 1)
		{
			for(mno=0;mno<pileNotecard.length;mno++)
			{
				if(pileNotecard[mno][0] == this.id)
				{
					for(k=0;k<notecardID.length;k++)
					{
						if (notecardID[k][0] == pileNotecard[mno][1]) {
							notecardID[k][6] = "block";
						}
					}
					// set the dispaly as block of the notecard that is left in the pile
					document.getElementById(pileNotecard[mno][1]).style.display = "block";
					document.getElementById("thumb_"+this.id).style.display="none";
					document.getElementById("thumb_"+pileNotecard[mno][1]).style.display = "block";
					// bring it to the position of the pile	
					setLeftTopInTabletop(pileNotecard[mno][1], getLeftTopInTabletop(pileNotecard[mno][0]));
					var el = Ext.get(this.id);
					el.remove();
					// shake the notecard
					shakeMe(pileNotecard[mno][1]);
					pileNotecard.splice(mno,1);
					mno=-1;
				}
			}
			DeletePileFromDB(this.id);
			i=-1;
		}
		if(notecardCount == 0)
		{
			var el = Ext.get(this.id);
			el.remove();
			DeletePileFromDB(this.id);
			i=-1;
		}
		notecardCount = 0;
	}
	// get all the notecards back to position
	for(k=0;k<notecardID.length;k++){
		var pos = [notecardID[k][1],notecardID[k][2]];
		setLeftTopInTabletop(notecardID[k][0], pos);
	}
	for(j=0;j<pileID.length;j++){
		var pos = [pileID[j][1],pileID[j][2]];
		setLeftTopInTabletop(pileID[j][0], pos);
	}
}

// function to produce an dialog box to merge the piles
function openYesNo(pileA, pileB)
{
	hidePopupOnDrag();
	this.overPile = pileA;
	this.underPile = pileB;
	var title_pileA = document.getElementById("title_"+pileA).innerHTML;
	if(pileB.match("li_Pi"))
	{
		var title_pileB = document.getElementById("title_"+pileB.substr(3)).innerHTML;
	}
	else
	{
		var title_pileB = document.getElementById("title_"+pileB).innerHTML;
	}
    Ext.MessageBox.show({
           title: 'Confirm',
           msg: "Are you sure you want to add the notecards from "+title_pileA+" to "+title_pileB+"?",
           width:300,
           buttons: Ext.MessageBox.YESNO,
           fn: showResult,
		   icon: Ext.MessageBox.INFO
    });
   	function showResult(btn)
	{
       if(btn == "yes")
	   {
		   	this.overPile = pileA;
			this.underPile = pileB;
			// remove the entry of the pile from the array
			for(i=0;i<pileID.length;i++)
			{
				if(pileID[i][0] == this.overPile)
				{
					DeletePileFromDB(pileID[i][0]);
				}
			}
			// if pile is dropped on another pile
			if(this.underPile.substr(0,5) == "Pile_")
			{
				// hide the pile
				document.getElementById(this.overPile).style.display="none";	
				// call the function to merge the piles
				mergePiles(this.overPile, this.underPile);
				// shake the new pile
				shakeMe(this.underPile);
				// remove the DOM from the page	
				var el = new YAHOO.util.Element('tabletop');
				var child = new YAHOO.util.Element(this.overPile);
				el.removeChild(child);
				// remove the thumb for that pile
				deleteItemThumb(this.overPile);
				// hide the dialogue
			}
			// if pile is dropped on expanded pile
			if(this.underPile.substr(0,5) == "li_Pi")
			{
				// cut the pile id from expanded pile id
				this.underPile = this.underPile.substr(3);
				document.getElementById(this.overPile).style.display="none";
				for(i=0;i<pileNotecard.length;i++)
				{
					if(pileNotecard[i][0] == this.overPile)
					{
						// create the notecards in the expanded pile
						var note_li = new NotesLi(pileNotecard[i][1]);
						var div = document.createElement("ul");
						div.innerHTML = note_li.toHTML();
						document.getElementById("li_"+this.underPile).appendChild(div.firstChild);
						pileNotecard[i][0] = this.underPile;
					}
					
				}				
				var el = YAHOO.util.Dom.get('tabletop');
				var child = YAHOO.util.Dom.get(this.overPile);
				el.removeChild(child);
				deleteItemThumb(child.id);
				DeletePileFromDB(this.overPile);
				updatePileNoteRelInDatabase();
				updateCountInPile();
			}
	   	}
		if (btn == "no") {
			this.overPile = pileA;
			this.underPile = pileB;
			// remove the entry of the pile from the array
			
			// if pile is dropped on another pile
			if (this.underPile.substr(0, 5) == "Pile_") {
				document.getElementById(this.overPile).style.display = "block";
				var pos = getLeftTopInTabletop(this.underPile);
				pos[0]= Number(pos[0])+100;
				document.getElementById(this.overPile).style.left = pos[0]+"px";
				setLeftTopInBirdsEyeView(this.overPile, getLeftTopInTabletop(this.overPile));
				for(i=0;i<pileID.length;i++)
				{
					if(pileID[i][0] == this.overPile)
					{
						pileID[i][1] = pos[0];
						pileID[i][5] = "block";
					}
				}
				
			}
			// if pile is dropped on expanded pile
			if (this.underPile.substr(0, 5) == "li_Pi") {
				this.underPile = "exp"+this.underPile.substr(2);
				document.getElementById(this.overPile).style.display = "block";
				var pos = getLeftTopInTabletop(this.underPile);
				pos[0]= Number(pos[0])+500;
				document.getElementById(this.overPile).style.left = pos[0]+"px";
				setLeftTopInBirdsEyeView(this.overPile, getLeftTopInTabletop(this.overPile));
				for(i=0;i<pileID.length;i++)
				{
					if(pileID[i][0] == this.overPile)
					{
						pileID[i][1] = pos[0];
						pileID[i][5] = "block";
					}
				}
			}
			document.getElementById("thumb_"+this.overPile).style.display = "block";
		}
    };
}
// This is an ext-js confirm dialog that is displayed before working out with the piles
function showConfirmDg()
{
	//hide summ popups
	hidePopupOnDrag();
	//Ext.MessageBox.confirm('Confirm', 'Any expanded piles on the tabletop will be closed. Continue?', showResult);
	//function showResult(btn)
	//{
	//	if (btn == "yes") {
			for (l = 0; l < expandedPileArray.length; l++) {
				flyElementsBack(expandedPileArray[l][0].substr(4));
				l = -1;
			}
			openAddtoPileDg();
	//	}
	//}
}

/*
 * print HTML/RTF format dialog box
 */
function printForDg()
{
	//hide summ popups
	hidePopupOnDrag();
	var htmlRtfDg = new Ext.Panel({
		frame: true,
		bodyStyle: 'padding:0 10px 0;',
		items: [{
			xtype: 'radiogroup',
			fieldLabel: 'Multi-Column<br />(custom widths)',
			columns: [300],
			vertical: true,
			items: [{
				boxLabel: 'Export as Web page (HTML file)',
				name: 'rb-custwidth',
				id: 'html',
				autoWidth: true,
				autoHeight: true,
				inputValue: 1,
				checked: true
			}, {
				boxLabel: 'Export to Word (RTF file)',
				name: 'rb-custwidth',
				id: 'rtf',
				autoWidth: true,
				autoHeight: true,
				inputValue: 2				
			}]		
		}],
		buttons: [{
			text: 'Submit',
			handler: function(){
				if(Ext.getCmp('html').getValue())
				{
					//html format
					prinWin.close();
					printTt();
				}
				else
				{
					prinWin.close();
					convertRTF();
					//rtf format					
				}
			}
		}]
	});

	//window to show format print dialog
	var prinWin = new Ext.Window({
		layout: 'fit',
		width: 300,
		height: 150,
		constrain: true,
		title: 'Options',
		closable: true,
		resizable: false,
		plain: true,
		border: false,
		manager: openwindows,
		items:[htmlRtfDg],
		modal: true,
		listeners:{
			close:
			{
				fn:function()
				{
					prinWin.destroy();
					htmlRtfDg.destroy();
				}	
			}
		}
	});
	prinWin.show();	
}

var bstyle;
if(navigator.appName == "Microsoft Internet Explorer")
{
	bstyle = "padding: 6px 0px 0px 0px;";	
}
else
{
	bstyle = "padding: 0px 0px 0px 0px;";
}

/*
 * function to create dlg for convertRTF options
 */
function convertRTF()
{
	var piles = new Array();
	// collect the piles in the tabletop
	for (i = 0; i < pileID.length; i++) {
		piles[i] = [pileID[i][0], pileID[i][4]];
	}	
	hidePopupOnDrag();
	
	var rtfDg = new Ext.Panel({
		frame: true,
		bodyStyle: 'padding:0 10px 0;',
		items: [{
			xtype: 'radiogroup',
			fieldLabel: 'Multi-Column<br />(custom widths)',
			columns: [320],
			vertical: true,
			items: [{
				boxLabel: 'Export all notecards',
				name: 'rb-custwidth',
				id: 'conAll',
				inputValue: 1,
                                autoWidth: true,
				checked: true
			}, {
				boxLabel: 'Export selected notecards only',
				name: 'rb-custwidth',
				inputValue: 2,
                                autoWidth: true,
				id: 'conSelected'
			}, {
				boxLabel: 'Export notecards from pile...',
				name: 'rb-custwidth',
                                autoWidth: true,
				listeners: {
					'check': {
						fn: function(chkBox, checked)
						{
							if(checked)
							{
								Ext.getCmp('pileList').enable();
							}else
							{
								Ext.getCmp('pileList').disable();
							}
						}
					}
				},				
				inputValue: 3,
				id: 'conPile'
			}, {
				xtype: 'fieldset',
				collapsed: false,
				autoHeight: true,
				layout: 'table',				
				id: 'fromPile',
				name: 'rb-custwidth',
				id: 'fieldsetPile',				
				bodyStyle: bstyle,
				items: [
					cmb = new Ext.form.ComboBox({
					id: 'pileList',
					store:new Ext.data.JsonStore({
				         id:'persID2'
						 ,autoLoad :true
				        ,root:'rows'
				        ,totalProperty:'totalCount'
				        ,fields:[
				             {name:'id', type:'string'}
				            ,{name:'title', type:'string'}
				        ]
				        ,url:'../notecards/_includes/notecardOperations.php'
				        ,baseParams:{
				             toggle:'getPilesInAscOrder'
				        }
				    }),
					valueField: 'id',
					displayField: 'title',
					typeAhead: false,
					editable: false,					
					mode: 'local',
					disabled: true,
					forceSelection: true,
					triggerAction: 'all',
					emptyText: 'Select a pile...',
					selectOnFocus: true
					})]				
				}]
		}],
		buttons: [{
			text: 'Submit',
			handler: function(){
				var conAll = Ext.getCmp('conAll').getValue();
				var conSelected = Ext.getCmp('conSelected').getValue();
				var conPile = Ext.getCmp('conPile').getValue();
				var sltdNotes =  new Array();
				var file;
				if(conAll)
				{
					rftWin.close();
					//determine if there are notecards
					var arrNotes = YAHOO.util.Dom.getElementsByClassName( "notecard" , "div" , "tabletop" , "" );
					var arrSelNotes = YAHOO.util.Dom.getElementsByClassName( "notecardYellow" , "div" , "tabletop" , "" );
					var projectID = document.getElementById("projectID").value;
					if(arrNotes.length>0 || arrSelNotes.length>0)
					{						
						if(isTeacher == 1)
						{													
							var success = function(o)
							{														
								if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
								{			
									showNotesSessionError(Trim(o.responseText));
									return false;
								}
															
								if(navigator.appName == "Microsoft Internet Explorer")
								{	
									var html = "<p style='padding:10px;font-family:verdana;font-size:12px'>If you are using Internet Explorer ";
									html = html + "and your security settings do not allow popups, ";
									html = html + "right-click on the link below and choose the \"Save Target As...\" option.</p>";
									html = html + "<p style='padding:10px;font-family:verdana;font-size:12px'><a href='../../savefiles/notes/"+Trim(o.responseText)+".rtf'>click here</a></p>";
									
									// window to activate file download for ie
									var dldWin = new Ext.Window({
										layout: 'fit',
										cls:"../_css/noodlenotes.css",
										width: 370,
										height: 150,
										constrain: true,
										title: 'Download RTF',
										closable: true,
										resizable: false,
										plain: true,
										border: false,
										html: html,										
										listeners:
										{
											close:
											{
												fn: function()
												{													
													dldWin.destroy();
												}
											}
										},
										modal: true
									});
									dldWin.show();
								}
								else
								{
									location.href="../notecards/_includes/printrtf.php?fileName="+o.responseText;
								}								
							};
								
							var failure = function(o)
							{
								
							};
														
							Ext.Ajax.request({
						   		url: '../notecards/_includes/notecardOperations.php',
						   		method: 'POST',
						   		success: success,				   
						   		failure: failure,
								params: 'toggle=convertRTF&con=all&projectID='+projectID
							});																				
						}
						else
						{
							var success = function(o)
							{
								if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
								{			
									showNotesSessionError(Trim(o.responseText));
									return false;
								}
														
								var success = function(o)
								{														
									if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
									{			
										showNotesSessionError(Trim(o.responseText));
										return false;
									}
									if(navigator.appName == "Microsoft Internet Explorer")
									{
										var html = "<p style='padding:10px;font-family:verdana;font-size:12px'>If you are using Internet Explorer ";
										html = html + "and your security settings do not allow popups, ";
										html = html + "right-click on the link below and choose the \"Save Target As...\" option.</p>";
										html = html + "<p style='padding:10px;font-family:verdana;font-size:12px'><a href='../../savefiles/notes/"+Trim(o.responseText)+".rtf'>click here</a></p>";
										
										// window to activate file download for ie
										var dldWin = new Ext.Window({
											layout: 'fit',
											cls:"../_css/noodlenotes.css",
											width: 370,
											height: 150,
											constrain: true,
											title: 'Download RTF',
											closable: true,
											resizable: false,
											plain: true,
											border: false,
											html: html,										
											listeners:
											{
												close:
												{
													fn: function()
													{													
														dldWin.destroy();
													}
												}
											},
											modal: true
										});
										dldWin.show();
									}
									else
									{
										location.href="../notecards/_includes/printrtf.php?fileName="+o.responseText;
									}								
								};
								
								var failure = function(o)
								{
									
								};
															
								Ext.Ajax.request({
							   		url: '../notecards/_includes/notecardOperations.php',
							   		method: 'POST',
							   		success: success,				   
							   		failure: failure,
									params: 'toggle=convertRTF&con=all&projectID='+projectID
								});							
							};
							
							var failure = function(o)
							{
								
							};
													
							var pileData = Ext.encode(pileNotecard);						
							Ext.Ajax.request({
						   		url: '../notecards/_includes/notecardOperations.php',
						   		method: 'POST',
						   		success: success,				   
						   		failure: failure,
								params: 'toggle=changeOrder&pos=zone&projectId='+projectID+'&pileData='+pileData
						   });							
						}					   
					}
					else
					{
						Ext.MessageBox.alert('Alert', 'There are no notecards to export.');	
					}					
				}
				else if(conSelected)
				{
					rftWin.close();
					var arrSelNotes = YAHOO.util.Dom.getElementsByClassName( "notecardYellow" , "div" , "tabletop" , "" );
					if(arrSelNotes.length>0)
					{						
						var j=0;
						for(i=0;i<arrSelNotes.length;i++)
						{								
							sltdNotes[j] = arrSelNotes[i].id.split("_")[1];
							j++;
						}						
						//create a json string
						var notes = YAHOO.lang.JSON.stringify(sltdNotes);
						var success = function(o)
						{	
							if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
							{			
								showNotesSessionError(Trim(o.responseText));
								return false;
							}
																			
							if(navigator.appName == "Microsoft Internet Explorer")
							{
								var html = "<p style='padding:10px;font-family:verdana;font-size:12px'>If you are using IE 7 ";
								html = html + "and your security settings do not allow popups, ";
								html = html + "right-click on the link below and choose the \"Save Target As...\" option.</p>";
								html = html + "<p style='padding:10px;font-family:verdana;font-size:12px'><a href='../../savefiles/notes/"+Trim(o.responseText)+".rtf'>click here</a></p>";
								
								// window to activate file download for ie
								var dldWin = new Ext.Window({
									layout: 'fit',
									cls:"../_css/noodlenotes.css",
									width: 370,
									height: 150,
									constrain: true,
									title: 'Download RTF',
									closable: true,
									resizable: false,
									plain: true,
									border: false,
									html: html,									
									listeners:
									{
										close:
										{
											fn: function()
											{													
												dldWin.destroy();
											}
										}
									},
									modal: true
								});
								dldWin.show();
							}
							else
							{
								location.href = "../notecards/_includes/printrtf.php?fileName="+o.responseText;
							}							
						};
						var failure = function(o)
						{
							
						};
						
						Ext.Ajax.request({
					   		url: '../notecards/_includes/notecardOperations.php',
					   		method: 'POST',
					   		success: success,				   
					   		failure: failure,
							params: 'toggle=convertRTF&con=selected&notes='+notes					   		
						});						
					}
					else
					{
						Ext.MessageBox.show({
							title: 'Error',
							msg: 'No notecards are selected on the tabletop.',
							buttons: Ext.MessageBox.OK,							
							icon: Ext.MessageBox.ERROR
						});						
					}										
				}
				else if(conPile)
				{					
					var selPile = Ext.getCmp('pileList').getValue();
					var projectID = document.getElementById("projectID").value;
					if (selPile != "") 
					{
						rftWin.close();
						
						if(isTeacher == 1)
						{
							var success = function(o)
							{
								if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
								{			
									showNotesSessionError(Trim(o.responseText));
									return false;
								}
								
								if(navigator.appName == "Microsoft Internet Explorer")
								{
									var html = "<p style='padding:10px;font-family:verdana;font-size:12px'>If you are using IE 7 ";
									html = html + "and your security settings do not allow popups, ";
									html = html + "right-click on the link below and choose the \"Save Target As...\" option.</p>";
									html = html + "<p style='padding:10px;font-family:verdana;font-size:12px'><a href='../../savefiles/notes/"+Trim(o.responseText)+".rtf'>click here</a></p>";
									
									// window to activate file download for ie
									var dldWin = new Ext.Window({
										layout: 'fit',
										cls:"../_css/noodlenotes.css",
										width: 370,
										height: 150,
										constrain: true,
										title: 'Download RTF',
										closable: true,
										resizable: false,
										plain: true,
										border: false,
										html: html,										
										listeners:
										{
											close:
											{
												fn: function()
												{													
													dldWin.destroy();
												}
											}
										},
										modal: true
									});
									dldWin.show();
									//window.open("../notecards/_includes/exportRTF.php?fileName="+o.responseText,"export");
								}
								else
								{
									location.href = "../notecards/_includes/printrtf.php?fileName="+o.responseText;
								}								
							};
							
							var failure =  function(o)
								{																	};																var pileID = selPile.split("_")[1];															Ext.Ajax.request({							   		url: '../notecards/_includes/notecardOperations.php',							   		method: 'POST',							   		success: success,				   							   		failure: failure,									params: 'toggle=convertRTF&con=pile&pileID='+pileID+'&projectID='+projectID						   										});																			
						}
						else
						{
							var success = function(o)
							{
								if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
								{			
									showNotesSessionError(Trim(o.responseText));
									return false;
								}
								var success = function(o)
								{
									if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
									{
										showNotesSessionError();
										return false;
									}																
									if(navigator.appName == "Microsoft Internet Explorer")
									{
										var html = "<p style='padding:10px;font-family:verdana;font-size:12px'>If you are using Internet Explorer ";
										html = html + "and your security settings do not allow popups, ";
										html = html + "right-click on the link below and choose the \"Save Target As...\" option.</p>";
										html = html + "<p style='padding:10px;font-family:verdana;font-size:12px'><a href='../../savefiles/notes/"+Trim(o.responseText)+".rtf'>click here</a></p>";
										
										// window to activate file download for ie
										var dldWin = new Ext.Window({
											layout: 'fit',
											cls:"../_css/noodlenotes.css",
											width: 370,
											height: 150,
											constrain: true,
											title: 'Download RTF',
											closable: true,
											resizable: false,
											plain: true,
											border: false,
											html: html,										
											listeners:
											{
												close:
												{
													fn: function()
													{													
														dldWin.destroy();
													}
												}
											},
											modal: true
										});
										dldWin.show();										
										//window.open("../notecards/_includes/exportRTF.php?fileName="+o.responseText,"export");
									}
									else
									{
										location.href = "../notecards/_includes/printrtf.php?fileName="+o.responseText;
									}								
								};
								
								var failure =  function(o)
								{
									
								};
								
								var pileID = selPile.split("_")[1];							
								Ext.Ajax.request({
							   		url: '../notecards/_includes/notecardOperations.php',
							   		method: 'POST',
							   		success: success,				   
							   		failure: failure,
									params: 'toggle=convertRTF&con=pile&pileID='+pileID+'&projectID='+projectID						   		
								});							
							};
						
							var failure = function(o)
							{
								
							};
													
							var pileData = Ext.encode(pileNotecard);						
							Ext.Ajax.request({
						   		url: '../notecards/_includes/notecardOperations.php',
						   		method: 'POST',
						   		success: success,				   
						   		failure: failure,
								params: 'toggle=changeOrder&pileData='+pileData+'&projectId='+projectID						   		
							});							
						}
					}
					else 
					{
						rftWin.hide();
						function showRtfWin(){
							rftWin.show();
						}
						Ext.MessageBox.show({
							title: 'Error',
							msg: 'Please select a pile to continue.',
							buttons: Ext.MessageBox.OK,
							fn: showRtfWin,
							icon: Ext.MessageBox.ERROR
						});
					}					
				}
			}
		}]
	});
			
	// window to show rtf dialog
	var rftWin = new Ext.Window({
		layout: 'fit',
		width: 370,
		height: 210,
		constrain: true,
		title: 'Options',
		closable: true,
		resizable: false,
		plain: true,
		border: false,
		manager: openwindows,
		items: [rtfDg],
		listeners:
		{
			close:
			{
				fn: function()
				{
					rtfDg.destroy();
					rftWin.destroy();
				}
			}
		},
		modal: true
	});
	rftWin.show();
}

/*
 * function to show the print interface
 */
function printTt()
{	
	var piles = new Array();
	// collect the piles in the tabletop
	for (i = 0; i < pileID.length; i++) {
		piles[i] = [pileID[i][0], pileID[i][4]];
	}	
	hidePopupOnDrag();
	
	var printDg = new Ext.Panel({
		frame: true,
		bodyStyle: 'padding:0 10px 0;',
		items: [{
			xtype: 'radiogroup',
			fieldLabel: 'Multi-Column<br />(custom widths)',
			columns: [320],
			vertical: true,
			items: [{
				boxLabel: 'Export all notecards',
				name: 'rb-custwidth',
				id: 'all',
				inputValue: 1,
                                autoWidth: true,
				checked: true
			}, {
				boxLabel: 'Export selected notecards only',
				name: 'rb-custwidth',
				inputValue: 2,
                                autoWidth: true,
				id: 'selected'
			}, {
				boxLabel: 'Export notecards from pile...',
				name: 'rb-custwidth',
                                autoWidth: true,
				listeners: {
					'check': {
						fn: function(chkBox, checked)
						{
							if(checked)
							{
								Ext.getCmp('pileList').enable();
							}else
							{
								Ext.getCmp('pileList').disable();
							}
						}
					}
				},				
				inputValue: 3,
				id: 'selectPile'
			}, {
				xtype: 'fieldset',
				collapsed: false,
				autoHeight: true,
				layout: 'table',				
				id: 'fromPile',
				name: 'rb-custwidth',
				id: 'fieldsetPile',				
				bodyStyle: bstyle,
				items: [
					cmb = new Ext.form.ComboBox({
					id: 'pileList',
					store:new Ext.data.JsonStore({
					         id:'persID1'
							 ,autoLoad :true
					        ,root:'rows'
					        ,totalProperty:'totalCount'
					        ,fields:[
					             {name:'id', type:'string'}
					            ,{name:'title', type:'string'}
					        ]
					        ,url:'../notecards/_includes/notecardOperations.php'
					        ,baseParams:{
					             toggle:'getPilesInAscOrder'
					        }
					    }),
						valueField: 'id',
    					displayField: 'title',
					typeAhead: false,
					editable: false,					
					mode: 'local',
					disabled: true,
					forceSelection: true,
					triggerAction: 'all',
					emptyText: 'Select a pile...',
					selectOnFocus: true
					})]				
				}]
		}],
		buttons: [{
			text: 'Submit',
			handler: function(){
				var all = Ext.getCmp('all').getValue();
				var selected = Ext.getCmp('selected').getValue();
				var selectPile = Ext.getCmp('selectPile').getValue();
				if(all){
					printWin.close();
					printTableTop('printAll');
				}
				if(selected){
					printWin.close();
					printTableTop('printSel');
				}
				if(selectPile){
					var selPile = Ext.getCmp('pileList').getValue();										
					if (selPile != "") {
						printWin.close();
						printPile(selPile.split("_")[1]);						
					}
					else {
						printWin.hide();
						function showResult3(){
							printWin.show();
						}
						Ext.MessageBox.show({
							title: 'Error',
							msg: 'Please select a pile to continue.',
							buttons: Ext.MessageBox.OK,
							fn: showResult3,
							icon: Ext.MessageBox.ERROR
						});
					}
				}
			}
		}]
	});
			
	// window to show rtf dialog
	var printWin = new Ext.Window({
		layout: 'fit',
		width: 370,
		height: 210,
		constrain: true,
		title: 'Options',
		closable: true,
		resizable: false,
		plain: true,
		border: false,
		manager: openwindows,
		items: [printDg],
		listeners:
		{
			close:
			{
				fn: function()
				{
					printDg.destroy();
					printWin.destroy();
				}
			}
		},
		modal: true
	});
	printWin.show();
}
/*
 * function to show pile details
 */
function unPiledNotecardDetails()
{	
	note_id = editNoteID;
	hidePopupOnDrag()
	var projectID = document.getElementById("projectID").value;	
	var success = function(o)
	{
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		var data;
		try
		{
			data = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch(e)
		{
			alert(e);
		}
		
		var pileDet = data;			
		if(pileDet!=null && pileDet!="")
		{	
			var html = "";
			for(i=0;i<pileDet.length;i++)
			{
				if(pileDet[i][1] == "&nbsp")
				{
					var source = pileDet[i][1];
				}
				else
				{
					var source = Ext.util.Format.htmlEncode(pileDet[i][1]);
				}
				if(pileDet[i][2] == "")
				{
					var url = "&nbsp";
				}
				else
				{
					var url = "<a target='_blank' href="+pileDet[i][2]+">"+pileDet[i][2]+"</a>";
				}
				
				var pages = pileDet[i][3];
				var quote = pileDet[i][4];
				var para = pileDet[i][5];
				var ideas = pileDet[i][6];
				var cdate = pileDet[i][7];
				var mdate = pileDet[i][8];
				var tags = pileDet[i][9];
				var visual_cues = pileDet[i][12];
								
				//button for the comments section
				if(isTeacher == "1"){
					var btnComment = "<a href=# class=smalltext>Add Comment</a> <a href=# onclick=showAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>-</a> | <a href=# class=smalltext>View Comments <a href=# onclick=showComments('comm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideComments('comm_"+pileDet[i][10]+"') class=smalltext>-</a></a></td></tr></table>";
				}else{
					var btnComment = "";
				}
				//button for the notecard section
				if(isTeacher == "1"){
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a></td></tr></tbody></table></th></tr>";
				}else{
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit')><img alt=Edit notecard src=../notecards/_images/edit.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit') class=smalltext>Edit</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete')><img alt=Delete Notecard src=../notecards/_images/cancel.png></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete') class=smalltext>Delete</a></td></tr></tbody></table></th></tr>";
				}
				//button for the notecard section
				if(isTeacher == "1")
				{
					var commBody = "";
					commBody = commBody + "<table style=\"border: none; width: 100%;\"><tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td><td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4><ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];
					for(j=0;j<comm.length;j++){
						commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px; padding-top:5px; margin-bottom:5px'><span width='100%' alt='click to edit' style='display:block;cursor:pointer;' class='commBodyOut' onmouseover=mouseOverCommBody('comm_text_"+comm[j][5]+"') onmouseout=mouseOutCommBody('comm_text_"+comm[j][5]+"') onclick=editCommentText('"+comm[j][5]+"') id='comm_text_"+comm[j][5]+"'>"+comm[j][1]+"</span><span width='100%' style='display:none;' id='txt_comm_body_"+comm[j][5]+"'><textarea id='tb_comm_"+comm[j][5]+"' cols=100 rows=5 style='border:1px solid #7F9DB9'></textarea><br><input type='button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Submit' onclick=endEditCommentText()>&nbsp;<input type = 'button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Cancel' onclick=cancelEditCommentText()></span>";
						if(comm[j][3] != "" && comm[j][3] != null){
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) </i></font>";
						}else{
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) (comment not yet viewed by the author of the list)</i></font>";
						}
						if(comm[j][4] != "" && comm[j][4] != null){
							commBody = commBody + " <font color=#808080><i>(deleted by recipient on "+comm[j][4]+" PST)</i></font>";
						}						
						commBody = commBody + "<br><span align='right'><a id='editComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=editCommentText('"+comm[j][5]+"')>Edit Comment</a> | <a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></span></li>";						
					}
					commBody = commBody + "</ol></td></table>";					
				}
				else
				{
					var commBody = "";
					commBody = commBody + "<table style=\"border: none; width: 100%;\"><tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td><td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4><ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];					
					for(j=0;j<comm.length;j++)
					{
						if(comm[j][4] != "" && comm[j][4] != null)
						{
							
						}
						else
						{
							commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px;padding-top:5px;margin-bottom:5px'>"							
							if(comm[j][3] != "" && comm[j][3] != null && comm[j][3] != 1)
							{
								commBody = commBody + "<img width='28' height='11' border='0' src='./images2/new.gif'/>&nbsp;<span id='comm_text_"+comm[j][5]+"'>";
							}
							commBody = commBody + comm[j][1]+"</span><br><font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST)</i></font><br><a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></li>";
						}
					}
					commBody = commBody + "</ol></td></table>";
				}

				html = html + "<div id ='det_Notecard_"+pileDet[i][10]+"'><table id=notecardtb class=notecardtb cellspacing=0><tbody><tr><th colspan=2><table class=notecardhead border=0><tbody><tr><td width=50% class=noborder><span class=notetitle>"+pileDet[i][0]+"</span>"+btnNotes+"<tr><td class=subhead>Source:</td><td class=noteitem><span>"+source+"</span></td></tr><tr><td class=subhead>URL:</td><td class=noteitem><span>"+url+"</span></td></tr><tr><td class=subhead>Pages:</td><td class=noteitem><span>"+pages+"</span></td></tr><tr><td class=subhead>Tags:</td><td class=noteitem><span>"+tags+"</span></td></tr><tr><td class=subhead>Visual Cues:</td><td class=noteitem><span>"+visual_cues+"</span></td></tr><tr><td class=subhead>Quotation:</td><td class=noteitem><span class=quoteclass>"+quote+"</span></td></tr><tr><td class=subhead>Paraphrase:</td><td class=noteitem><span class=paraclass>"+para+"</span></td></tr><tr><td class=subhead>My Ideas:</td><td class=noteitem><span class=ideasclass>"+ideas+"</span></td></tr><tr><td class=subhead>History:</td><td class=noteitem><span>Notecard Created: "+cdate+"  |  Updated: "+mdate+"</span></td></tr>";
				if(isTeacher == "1")
				{
					html = html + "<tr><td class=subhead>Comment:</td><td class=noteitem><table><tr><td><textarea id='ta_"+pileDet[i][10]+"' rows=5 cols=100></textarea></td><td>&nbsp;&nbsp;&nbsp;<input type=button class=btn value=Submit onclick=addComment('"+pileDet[i][10]+"')></td></tr></table></td></tr>";					
					html = html + "<tr><td></td><td class=noteitem><span id='prelink_"+pileDet[i][10]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=\"comments("+pileDet[i][10]+")\">Select comments from the comment database</span></td></tr>";
					html = html + "<tr><td colspan=\"2\" height=\"10\"></td></tr>";					
				}
				html = html + "</table>";
				html = html + "<table cellspacing=00 cellpadding=00>";
				html = html + "<tr>";
				if(comm.length == 0){
					var display = "hidden";
				}else{
					var display = "visible"
				}				
				html = html + "<td style='visibility:"+display+"' id='comm_row_"+pileDet[i][10]+"'>";
				html = html + commBody;
				html = html + "</td>";
				html = html + "</tr>";
				html = html + "</table>";
			}			
			var piles = new Array();
			var unPiled = ["0", "Unpiled Notecards"];
			var selectedNotes = ["1", "All Selected Notecards"];
			// collect the piles in the tabletop
			for (i = 0; i < pileID.length; i++) {
				piles[i] = [pileID[i][0], pileID[i][4]];
			}	
			piles.push(selectedNotes);
			piles.push(unPiled);
			piles.reverse();
			
			var cmb = new Ext.FormPanel({				
				bodyStyle:"padding-left:10px;padding-top:5px;",
				 items: [{
				 	xtype: 'combo',
				 	fieldLabel: 'View',
				 	store: piles,
				 	id: 'selectPile',
				 	triggerAction: 'all',
				 	value:'0',
				 	emptyText : 'Select an Option',
				 	listeners: {
                        'select' : {
                            fn: function(item){
                              var val = Ext.getCmp('selectPile').getValue();
                              if(val == "1"){
                              	selectedNotecardDetails()
                              }else if(val != "0"){
									editNoteID = val.substr(5);
									win.close();
									pileDetails(editNoteID);
								}							 
                            }, 
                            scope: this
                        }
                    }
				 }]				
			});
			
			var dataGrid = new Ext.Panel({
				id:"unpilednoteHTML",
        		html: html,
				height: (YAHOO.util.Dom.getViewportHeight() - 200),
        		autoScroll: true
			});			
			
			win = new Ext.Window({
				 width:(YAHOO.util.Dom.getViewportWidth()-100),	
				 cls:"../_css/noodlenotes.css",
				 bodyStyle:'padding:5px 5px 5px 5px',
				 title:"Unpiled Notecards",		 
				 autoScroll:true,				 
				 layout: 'form',
				 closable: true,
				 buttonAlign: 'center',
				 manager: openwindows,
				 items: [{
				 	items:[cmb]
				 },{
				 	items:[dataGrid]
				 }],				 
				 buttons: [{
					text: 'Return to Tabletop',					
					handler: function(){
						commInEditMode = "";
						win.close();
					}				
				}],
				 draggable:false,
				 listeners : {
							'show' : {
								fn : function(myWin) {
									if (note_id != "" ) {
										var el1 = Ext.get('det_Notecard_'
												+ note_id);
										if(el1 != null){
											var el2 = Ext.get('det_Notecard_'+pileDet[0][10]);
											if(el2){
												el1.insertBefore(el2);
											}
										}
									}
								},
								scope : this
							},
							'close' : 
							{
								fn : function(myWin)
								{
									//student can only update the viewed flg
									var isTeacher = document.getElementById("isTeacher").value;
									if (isTeacher == 0) 
									{
										//create an array of notecard ids
										var notes = new Array();
										for (i = 0; i < pileDet.length; i++) {
											notes[notes.length] = pileDet[i][10];
										}
										//create a json string
										var strNotes = YAHOO.lang.JSON.stringify(notes);
										var success = function(o){
											if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
											{			
												showNotesSessionError(Trim(o.responseText));
												return false;
											}
										};
										var failure = function(o){
										};
										//ajax call to the server update viewed flag										
										Ext.Ajax.request({
									   		url: '../notecards/_includes/notecardOperations.php',
									   		method: 'POST',
									   		success: success,				   
									   		failure: failure,
											params: 'toggle=UpdateViewed&notes='+strNotes									   		
										});											
									}
								}
							}
						},
				 modal:true		 
			});
		
			win.show();
		}else{
			function showResult(btn) {
				if (btn == "ok") {
					pileDetails(editNoteID);
				}
			}
			Ext.MessageBox.show({
				title : 'Error',
				msg : 'There are no unpiled notecards on your tabletop.',
				buttons : Ext.MessageBox.OK,
				closable : false,
				fn : showResult,
				icon : Ext.MessageBox.ERROR
			});
		}
	};
	var failure = function(o)
	{
	};
		
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=unPiledNotecard&projectID='+projectID  		
	});	
}

function showComments(elem)
{
	document.getElementById(elem).style.display = "block";
}
function showAddComment(elem)
{
	document.getElementById(elem).style.display = "block";
}
function hideComments(elem)
{
	document.getElementById(elem).style.display = "none";
}
function hideAddComment(elem)
{
	document.getElementById(elem).style.display = "none";
}

// function to add a comment entry
function addComment(noteid){
		
	var text = Trim(document.getElementById('ta_'+noteid).value);
	if(text != ""){
		
		var handleSuccess = function(o)
		{
          				
			if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
			{			
				showNotesSessionError(Trim(o.responseText));
				return false;
			}
			
			document.getElementById('comm_row_'+noteid).style.visibility="visible";
			var comm = YAHOO.lang.JSON.parse(o.responseText);
			var childLi = document.createElement("ol");
			childLi.innerHTML = comm;
			var parentul = document.getElementById('list_comments_'+noteid);
			parentul.appendChild(childLi.firstChild);
			var parent = Ext.get('list_comments_'+noteid);
			var firstChild = parent.first();
			var thisChild = parent.last();
			thisChild.insertBefore(firstChild);
			document.getElementById('ta_'+noteid).value = "";
			
		};
		
		var handleFailure = function(o)
		{
		};
				
		text = Ext.util.Format.htmlEncode(text);		
		//ajax request to send comment
		Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,		   
		   failure: handleFailure,
		   params: {
		   		toggle: 'addComment',
				commentText: text,
				noteid: noteid
			}
		});
	}else{
		Ext.MessageBox.show({
			title : 'Error',
			msg : 'Please enter a comment.',
			buttons : Ext.MessageBox.OK,
			closable : false,
			icon : Ext.MessageBox.ERROR
		});
	}
}

/*
 * function to add a comment from bib section
 */ 
function addCommentFromBib(noteid)
{	
	var text = Trim(document.getElementById('ta_'+noteid).value);
	if(text != "")
	{		
		var handleSuccess = function(o)
		{
            
			if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
			{			
				showNotesSessionError(Trim(o.responseText));
				return false;
			}
				
			document.getElementById('comm_row_'+noteid).style.display="block";
			var comm = YAHOO.lang.JSON.parse(o.responseText);
			var childLi = document.createElement("ol");
			childLi.innerHTML = comm;
			var parentul = document.getElementById('list_comments_'+noteid);
			parentul.appendChild(childLi.firstChild);
			var parent = Ext.get('list_comments_'+noteid);
			var firstChild = parent.first();
			var thisChild = parent.last();
			thisChild.insertBefore(firstChild);
			document.getElementById('ta_'+noteid).value = "";			
		};
		
		var handleFailure = function(o)
		{
		};
				
		text = Ext.util.Format.htmlEncode(text);
		//ajax request to send comment
		Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,		   
		   failure: handleFailure,
		   params: {
		   			toggle:'addComment',
					commentText:text,
					noteid:noteid,
					fromBib:true
			}
		});
	}
	else
	{		
		Ext.MessageBox.show({
			title : 'Error',
			msg : 'Please enter a comment.',
			buttons : Ext.MessageBox.OK,
			closable : false,
			icon : Ext.MessageBox.ERROR
		});		
	}
}

/*
 * function to add comment for citation
 */
function addCitationComment(entryID)
{
	var text = Trim(document.getElementById('tac_'+entryID).value);
	if(text != "")
	{
		var handleSuccess = function(o)
		{
            
			if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
			{			
				showNotesSessionError(Trim(o.responseText));
				return false;
			}
								
			document.getElementById('commentsrow_'+entryID).style.display="block";
			var comm = YAHOO.lang.JSON.parse(o.responseText);
			var childLi = document.createElement("ol");
			childLi.innerHTML = comm;
			var parentul = document.getElementById('list_comments_citation_'+entryID);
			parentul.appendChild(childLi.firstChild);
			var parent = Ext.get('list_comments_citation_'+entryID);
			var firstChild = parent.first();
			var thisChild = parent.last();
			thisChild.insertBefore(firstChild);
			document.getElementById('tac_'+entryID).value = "";			
		};
		
		var handleFailure = function(o)
		{
		};
				
		text = Ext.util.Format.htmlEncode(text);
		//ajax request to send comment
		Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,  
		   failure: handleFailure,
		   params: {
		   			toggle:'citationComment',
					commentText:text,
					entryID:entryID
				}
		});		
	}
	else
	{
		Ext.MessageBox.show({
			title : 'Error',
			msg : 'Please enter a comment.',
			buttons : Ext.MessageBox.OK,
			closable : false,
			icon : Ext.MessageBox.ERROR
		});		
	}
}


// function to delete a comment
function deleteComment(id){
	//alert(endEditCommentText());
	if(endEditCommentText()){
		function showResult(btn)
		{
			if (btn == "yes") {
				var success = function(o)
				{                    
					if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
					{			
						showNotesSessionError(Trim(o.responseText));
						return false;
					}
					
					var comm = (o.responseText);
					if(comm == 1){
						var el = Ext.get("comm_"+id);
						var parentol = el.findParent('ol');
						el.remove();
						if(parentol.childNodes.length == 0){
							var noteid = parentol.id.split('_');
							document.getElementById('comm_row_'+noteid[2]).style.visibility = "hidden";
						}
					}
				};
				var failure = function(o)
				{
				};
				
				Ext.Ajax.request({
			   		url: '../notecards/_includes/notecardOperations.php',
			   		method: 'POST',
			   		success: success,				   
			   		failure: failure,
					params: 'toggle=delComment&commId='+id	   		
				});				
			}
		}
		Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete this comment?', showResult);
	}
}

/*
 * function to delete a comment from bib section
 */ 
function deleteCommentFromBib(id)
{	

	Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete this comment?', showResult);
		
	function showResult(btn)
	{
		if (btn == "yes") {
			var success = function(o)
			{
                
				if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
				{			
					showNotesSessionError(Trim(o.responseText));
					return false;
				}
				
				var comm = (o.responseText);
				if(comm == 1){
					var el = Ext.get("comm_"+id);
					var parentol = el.findParent('ol');
					el.remove();
					if(parentol.childNodes.length == 0){
						var noteid = parentol.id.split('_');
						document.getElementById('comm_row_'+noteid[2]).style.visibility = "hidden";
						document.getElementById('comm_row_'+noteid[2]).style.display = "none";
					}
				}
			};
			var failure = function(o)
			{
			};
			
			Ext.Ajax.request({
		   		url: '../notecards/_includes/notecardOperations.php',
		   		method: 'POST',
		   		success: success,				   
		   		failure: failure,
				params: 'toggle=delComment&commId='+id
		   	});						
		}
	}
}


/*
 * function to delete a citation comment
 */ 
function deleteCitationComment(id,entryID)
{
	Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete this comment?', showResult);	
	function showResult(btn)
	{
		if (btn == "yes") {
			var success = function(o)
			{
                
				if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
				{			
					showNotesSessionError(Trim(o.responseText));
					return false;
				}
				
				var comm = (o.responseText);
				if(comm == 1){
					var el = Ext.get("comm_"+id);
					el.remove();
					var ele = document.getElementById("list_comments_citation_"+entryID);
					if(ele.childNodes.length == 0)
					{
						document.getElementById('commentsrow_'+entryID).style.display = "none";
					}
				}
			};
			var failure = function(o)
			{
			};
			
			//ajax call to the server to delete citation comment
			Ext.Ajax.request({
		   		url: '../notecards/_includes/notecardOperations.php',
		   		method: 'POST',
		   		success: success,				   
		   		failure: failure,
				params: 'toggle=delComment&commId='+id
		   	});			
		}
	}
}

//function to change hyperlink css
function changeCss(id)
{						
	document.getElementById(id).style.textDecoration = "underline";
	document.getElementById(id).style.color = "red";					
}

//function to restore hyperlink css
function restoreCss(id)
{
	document.getElementById(id).style.textDecoration = "none";
	document.getElementById(id).style.color = "#1e5b99";
}


// function to highlight the comment body
function mouseOverCommBody(id)
{
	document.getElementById(id).className = 'commBodyOver';
}
// function to highlight the comment body
function mouseOutCommBody(id)
{
	document.getElementById(id).className = 'commBodyOut';
}

// function to edit the comment text
function editCommentText(id)
{
	if(commInEditMode !=""){
		if(cancelEditCommentText()){
			commInEditMode = id;
			document.getElementById('tb_comm_'+id).value = document.getElementById('comm_text_'+id).innerHTML;
			document.getElementById('comm_text_'+id).style.display = "none";
			document.getElementById('txt_comm_body_'+id).style.display = "block";
			document.getElementById('tb_comm_'+id).focus();
		}
	}else{
		commInEditMode = id;
		document.getElementById('tb_comm_'+id).value = document.getElementById('comm_text_'+id).innerHTML;
		document.getElementById('comm_text_'+id).style.display = "none";
		document.getElementById('txt_comm_body_'+id).style.display = "block";
		document.getElementById('tb_comm_'+id).focus();
	}
}

// function to edit the comment text
function endEditCommentText()
{
	if(document.getElementById('tb_comm_'+commInEditMode)){
		var val = Trim(document.getElementById('tb_comm_'+commInEditMode).value);
		if(val != ""){
			var commentText = val;
			var success = function(o)
			{
                
				if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
				{			
					showNotesSessionError(Trim(o.responseText));
					return false;
				}
				
				document.getElementById('comm_text_'+commInEditMode).innerHTML = document.getElementById('tb_comm_'+commInEditMode).value;
				document.getElementById('tb_comm_'+commInEditMode).value = "";
				document.getElementById('comm_text_'+commInEditMode).style.display = "block";
				document.getElementById('txt_comm_body_'+commInEditMode).style.display = "none";
				commInEditMode = "";
				return true;
			};
			var failure = function(o)
			{
			};
			Ext.Ajax.request({
		   		url: '../notecards/_includes/notecardOperations.php',
		   		method: 'POST',
		   		success: success,				   
		   		failure: failure,
				params: 'toggle=doEditComment&commentText='+commentText+'&commId='+commInEditMode
			});			
			return true;
		}else{
			Ext.Msg.alert('Error', 'Comment Text Cannot be blank.');
			var id = commInEditMode;
			commInEditMode = "";
			editCommentText(id);
			return false;
		}
	}else{
		return true;
	}
}


// function to edit the comment text
function cancelEditCommentText()
{
	document.getElementById('tb_comm_'+commInEditMode).value = "";
	document.getElementById('comm_text_'+commInEditMode).style.display = "block";
	document.getElementById('txt_comm_body_'+commInEditMode).style.display = "none";
	commInEditMode = "";
	return true;
}

function createNewNoteWin()
{	
	pileStore = new Ext.data.JsonStore({
								       url: '../notecards/_includes/notecardOperations.php?toggle=loadProjectPiles',
								       root: 'records',
								       autoLoad:true,
	    							   fields: ['name', 'pileid', 'name', 'title']
	
								    })
	projectid = document.getElementById('projectID').value;
	var failure = function(o)
	{
		alert(o.responseText);		
	};
	var success = function(o){
        
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		this.data = YAHOO.lang.JSON.parse(o.responseText);
		var tagArray = new Array();
		hidePopupOnDrag();
		loadTags();
		var myData = this.data[1];
		var citCmb = new Ext.form.ComboBox({
					id : 'txtSource',
					store : this.data[0],
					 width : 400,
					typeAhead : false,					
					editable : false,
					mode : 'local',
					forceSelection : true,
					triggerAction : 'all',
					value : 0,
					listeners: {
						'select': {
							fn: function(cmb, newVal, oldVal){
								Ext.getCmp('sourceID').setValue(citCmb.getValue());
							}
						}
					},
					selectOnFocus : true
				});
		var citTxt = new Ext.form.HtmlEditor({
					enableAlignments : false,
					enableColors : false,
					enableFont : false,
					enableFontSize : false,
					enableFormat : true,
					enableLinks : false,
					enableLists : false,
					enableSourceEdit : false,
					id : 'txtSource',
					name : 'txtSource',
					height : 75
				})
		
		// Here it is to be checked whether its an integrated or stand-alone version
		var srcField = citCmb;
		if (stopEditingonTabletop()) {
			var submit1 = false;
			projectid = document.getElementById('projectID').value;
			var tags = "";
			//string of valid elements
	 		var validElems = "a[accesskey|charset|class|coords|dir<ltr?rtl|href|hreflang|id|lang|name" +
							"|rel|rev" +
							"|shape<circle?default?poly?rect|style|tabindex|title|target|type]," +
							"abbr[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"acronym[class|dir<ltr?rtl|id|id|lang|style" +
							"|title]," +
							"address[class|align|dir<ltr?rtl|id|lang|style|title]," +
							"area[accesskey|alt|class|coords|dir<ltr?rtl|href|id|lang|nohref<nohref" +
							"|shape<circle?default?poly?rect|style|tabindex|title|target]," +
							"base[href|target]," +
							"basefont[color|face|id|size]," +
							"bdo[class|dir<ltr?rtl|id|lang|style|title]," +
							"big[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"blockquote[cite|class|dir<ltr?rtl|id|lang|style|title]," +
							"body[alink|background|bgcolor|class|dir<ltr?rtl|id|lang|link|style|title|text|vlink]," +
							"br[class|clear<all?left?none?right|id|style|title]," +
							"button[accesskey|class|dir<ltr?rtl|disabled<disabled|id|lang|name|style|tabindex|title|type" +
							"|value]," +
							"caption[align<bottom?left?right?top|class|dir<ltr?rtl|id|lang|style|title]," +
							"center[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"cite[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"code[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"col[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl|id" +
							"|lang|span|style|title" +
							"|valign<baseline?bottom?middle?top|width]," +
							"colgroup[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl" +
							"|id|lang|span|style|title" +
							"|valign<baseline?bottom?middle?top|width]," +
							"dd[class|dir<ltr?rtl|id|lang|style|title]," +
							"del[cite|class|datetime|dir<ltr?rtl|id|lang|style|title]," +
							"dfn[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"dir[class|compact<compact|dir<ltr?rtl|id|lang|style|title]," +
							"div[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"dl[class|compact<compact|dir<ltr?rtl|id|lang|style|title]," +
							"dt[class|dir<ltr?rtl|id|lang|style|title]," +
							"em/i[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"fieldset[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"font[class|color|dir<ltr?rtl|face|id|lang|size|style|title]," +
							"form[accept|accept-charset|action|class|dir<ltr?rtl|enctype|id|lang" +
							"|method<get?post|name|style|title|target]," +
							"frame[class|frameborder|id|longdesc|marginheight|marginwidth|name" +
							"|noresize<noresize|scrolling<auto?no?yes|src|style|title]," +
							"frameset[class|cols|id|onload|onunload|rows|style|title]," +
							"h1[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"h2[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"h3[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"h4[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"h5[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"h6[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"head[dir<ltr?rtl|lang|profile]," +
							"hr[align<center?left?right|class|dir<ltr?rtl|id|lang|noshade<noshade|size|style|title|width]," +
							"html[dir<ltr?rtl|lang|version]," +
							"img[align<bottom?left?middle?right?top|alt|border|class|dir<ltr?rtl|height" +
							"|hspace|id|ismap<ismap|lang|longdesc|name|src|style|title|usemap|vspace|width]," +
							"input[accept|accesskey|align<bottom?left?middle?right?top|alt" +
							"|checked<checked|class|dir<ltr?rtl|disabled<disabled|id|ismap<ismap|lang" +
							"|maxlength|name|readonly<readonly|size|src|style|tabindex|title" +
							"|type<button?checkbox?file?hidden?image?password?radio?reset?submit?text" +
							"|usemap|value]," +
							"ins[cite|class|datetime|dir<ltr?rtl|id|lang|style|title]," +
							"isindex[class|dir<ltr?rtl|id|lang|prompt|style|title]," +
							"kbd[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"label[accesskey|class|dir<ltr?rtl|for|id|lang|style|title]," +
							"legend[align<bottom?left?right?top|accesskey|class|dir<ltr?rtl|id|lang" +
							"|style|title]," +
							"li[class|dir<ltr?rtl|id|lang|style|title|type" +
							"|value]," +
							"link[charset|class|dir<ltr?rtl|href|hreflang|id|lang|media|rel|rev|style|title|target|type]," +
							"map[class|dir<ltr?rtl|id|lang|name|style" +
							"|title]," +
							"menu[class|compact<compact|dir<ltr?rtl|id|lang|style|title]," +
							"meta[content|dir<ltr?rtl|http-equiv|lang|name|scheme]," +
							"noframes[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"object[align<bottom?left?middle?right?top|archive|border|class|classid" +
							"|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name" +
							"|standby|style|tabindex|title|type|usemap" +
							"|vspace|width]," +
							"ol[class|compact<compact|dir<ltr?rtl|id|lang|start|style|title|type]," +
							"optgroup[class|dir<ltr?rtl|disabled<disabled|id|label|lang|style|title]," +
							"option[class|dir<ltr?rtl|disabled<disabled|id|label|lang|selected<selected|style|title|value]," +
							"p[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"param[id|name|type|value|valuetype<DATA?OBJECT?REF]," +
							"pre/listing/plaintext/xmp[align|class|dir<ltr?rtl|id|lang|style|title|width]," +
							"q[cite|class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"s[class|dir<ltr?rtl|id|lang|style|title]," +
							"samp[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"select[class|dir<ltr?rtl|disabled<disabled|id|lang|multiple<multiple|name" +
							"|size|style" +
							"|tabindex|title]," +
							"small[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"span[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|style|title]," +
							"strike[class|class|dir<ltr?rtl|id|lang|style|title]," +
							"strong/b[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"style[dir<ltr?rtl|lang|media|title|type]," +
							"sub[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"sup[class|dir<ltr?rtl|id|lang|style" +
							"|title]," +
							"table[align<center?left?right|bgcolor|border|cellpadding|cellspacing|class" +
							"|dir<ltr?rtl|frame|height|id|lang|rules" +
							"|style|summary|title|width]," +
							"tbody[align<center?char?justify?left?right|char|class|charoff|dir<ltr?rtl|id" +
							"|lang|style|title" +
							"|valign<baseline?bottom?middle?top]," +
							"td[abbr|align<center?char?justify?left?right|axis|bgcolor|char|charoff|class" +
							"|colspan|dir<ltr?rtl|headers|height|id|lang|nowrap<nowrap|rowspan|scope<col?colgroup?row?rowgroup" +
							"|style|title|valign<baseline?bottom?middle?top|width]," +
							"textarea[accesskey|class|cols|dir<ltr?rtl|disabled<disabled|id|lang|name" +
							"|readonly<readonly|rows|style|tabindex|title]," +
							"tfoot[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl|id" +
							"|lang|style|title" +
							"|valign<baseline?bottom?middle?top]," +
							"th[abbr|align<center?char?justify?left?right|axis|bgcolor|char|charoff|class" +
							"|colspan|dir<ltr?rtl|headers|height|id|lang|nowrap<nowrap|rowspan|scope<col?colgroup?row?rowgroup" +
							"|style|title|valign<baseline?bottom?middle?top|width]," +
							"thead[align<center?char?justify?left?right|char|charoff|class|dir<ltr?rtl|id" +
							"|lang|style|title" +
							"|valign<baseline?bottom?middle?top]," +
							"title[dir<ltr?rtl|lang]," +
							"tr[abbr|align<center?char?justify?left?right|bgcolor|char|charoff|class" +
							"|rowspan|dir<ltr?rtl|id|lang|style" +
							"|title|valign<baseline?bottom?middle?top]," +
							"tt[class|dir<ltr?rtl|id|lang|style|title]," +
							"u[class|dir<ltr?rtl|id|lang|style|title]," +
							"ul[class|compact<compact|dir<ltr?rtl|id|lang|style|title|type]," +
							"var[class|dir<ltr?rtl|id|lang|style" +
							"|title]";

			var newNoteForm = new Ext.FormPanel({
				url: '../notecards/_includes/notecardOperations.php',
				labelAlign: 'top',
				autoScroll: true,
				frame: true,
				name: 'newNote',
				id: 'newNote',
				bodyStyle: 'padding:5px 5px 0',
				monitorValid: true,
				width: 600,
				items: [{
					layout: 'form',
					items: [{
						layout: 'column',
						items: [{
							columnWidth: .75,
							xtype: 'label',
							id: 'lblTitle',
							bodyStyle: 'padding-top:5px;',
							html: '<b>Title</b>'
						}, {
							columnWidth: .5,
							xtype: 'textfield',
							fieldLabel: 'Title',
							id: 'txtTitle',
							name: 'txtTitle',
							allowBlank: false,
							anchor: '95%'
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'A short phrase that reminds you of the content of this notecard.<br><br>'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,							
							bodyStyle: 'padding-top:5px;',
							html: '<b>Source</b>'
						}, {
							columnWidth: .5,							
							items:[	srcField ],
							anchor: '98%'
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Link this notecard to a source in your list.<br><br>'
						}]
					},{
						layout: 'column',
						items: [{
							columnWidth: .75,
							xtype: 'label',
							id: 'lblTitle',
							bodyStyle: 'padding-top:5px;',
							html: '<b>Pile</b>'
						}, {
							columnWidth: .5,
							items:[new Ext.form.ComboBox({
									id : 'cmbPile',
									store: pileStore,
									displayField: 'title',
									valueField:'pileid',
									width : 400,
									typeAhead : false,					
									editable : false,
									mode : 'local',
									forceSelection : true,
									triggerAction : 'all',
									emptyText: 'Select A Pile',
									selectOnFocus : true,
									listeners: {
										'select': {
											fn: function(combo, newVal, oldVal){
												Ext.getCmp('mypileid').setValue(newVal.data.pileid);
											}
										}
									}
								}),{
									xtype:'textfield',
									hidden:true,
									id:'mypileid',
									value:'0'
								}
							]
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: '&nbsp;<br><br>'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>URL</b>'
						}, {
							columnWidth: .5,
							xtype: 'textfield',
							id: 'txtURL',							
							name: 'txtURL',
							vtype: 'url',
							vtypeText : 'The field should be a url in the format "http://www.abc.com" or "http://abc.com"',
							anchor: '95%'
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Direct, persistent link to the online material, if applicable.<br><br>'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>Pages</b>'
						}, {
							columnWidth: .5,
							xtype: 'textfield',
							id: 'txtPages',
							name: 'txtPages',
							anchor: '95%'
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Page number(s) of material, if given.<br><br>'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>Tags<b>'
						}, {
							columnWidth: .5,
							xtype: 'textfield',
							fieldLabel: 'pages',
							id: 'txtTags',
							name: 'txtTags',
							anchor: '95%'
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Type new tags or select existing tags to add to this notecard. <b>Note</b>: Put multiple-word tags in quotation marks (e.g., \"global warming\") or add an underscore (e.g., global_warming).'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>Existing Tags</b>'
						}
						, {
							columnWidth: .5,
							items: [cmb = new Ext.form.ComboBox({
								id: 'tags',
								store: new Ext.data.JsonStore({
							       url: '../notecards/_includes/notecardOperations.php?toggle=loadProjectTags',
							       root: 'records',
							       autoLoad:true,
    							   fields: ['name', 'ID', 'name', 'Tag']

							    }),
								typeAhead: false,
								editable: false,
								mode: 'local',
								displayField: 'Tag',
    							valueField: 'ID',
								forceSelection: true,
								triggerAction: 'all',
								emptyText: 'Select a tag...',
								selectOnFocus: true,
								listeners: {
									'select': {
										fn: function(combo, newVal, oldVal){
											var str = Ext.getCmp('txtTags').getValue();
											function success(obj){
                                                
												if((Trim(obj.responseText)).match("ERROR"))
												{			
													showNotesSessionError(Trim(obj.responseText));
													return false;
												}
												
												tagArray = [];
												tagArray = Ext.decode(obj.responseText);
												var selectedTag = combo.getValue();
												
												for(i=0;i<allTags.length;i++){
													if(allTags[i][0] == selectedTag){
														selectedTag = allTags[i][1];
													}
												}
												this.exists = false;
												for(i=0;i<tagArray.length;i++){
													if(tagArray[i] == selectedTag){
														this.exists = true;
													}
												}
												if (!this.exists) {
													Ext.getCmp('txtTags').setValue(Ext.getCmp('txtTags').getValue() + " \"" + selectedTag+"\"");
													tagArray[tagArray.length] = selectedTag;
												}
											}
											function failure(){
												alert("Connection failed")
											}
											Ext.Ajax.request({
										   		url: '../notecards/_includes/notecardOperations.php',
										   		method: 'POST',
										   		success: success,				   
										   		failure: failure,
												params: 'toggle=returnTagArray&str='+str
										   	});											
										}
									}
								}
							})]
						},
						{
							columnWidth: .5,							
							bodyStyle: 'padding:5px 0px 0px 10px;',
							cls: 'editViewText',
							html: 'Tags will help you uncover new patterns when you organize your notes. You can wait to tag or add them now and and tidy up later.'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>Direct Quotation</b>'
						}, {
							columnWidth: .55,
							xtype: "tinymce",
							fieldLabel: "Rich text",
							id: "quotation",
							name: "quotation",
							width: 300,
							height: 390,
							tinymceSettings: {
								theme: "advanced",
								plugins: "safari,spellchecker,print,searchreplace,paste", // removed simplepaste and contextmenu for now
								theme_advanced_buttons1: "formatselect,fontselect,fontsizeselect,bold,italic,underline",
								theme_advanced_buttons2: "search,replace,separator,undo,redo,separator,bullist,numlist,outdent,indent,separator,hr,separator,justifyleft,justifycenter,justifyright",
								theme_advanced_buttons3: "pastetext,pasteword,paste,separator,print,spellchecker,strikethrough,forecolor,backcolor,separator,removeformat,separator,charmap,code,separator,link,unlink,image",
								theme_advanced_toolbar_location: "top",
								theme_advanced_toolbar_align: "left",
								theme_advanced_statusbar_location: "bottom",
								spellchecker_languages: "+English=en",
								invalid_elements: "",
								width: "450",
								height: "300",
								accessibility_warnings : false,
								theme_advanced_resizing : false,
								auto_resize : false,
								theme_advanced_resizing_use_cookie : false,
								relative_urls : false,
								remove_script_host: false,
								valid_elements: "" + validElems
							}
						}, {
							columnWidth: .45,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Copy and paste (words, images) from an online source, or retype from a printed work.<br /><br />To copy text from a Web site or electronic document, highlight the text and copy it to the clipboard (Ctrl-C on a PC, Command-C on a Mac). There are a few choices of how to paste the text into your notecard:<br /><br /><ul style="list-style-type:square;margin:10px;padding:10px"><li>To remove formatting and HTML tags, use the <img src=\"/_images_add/paste_text.gif\"> <b>Paste as Plain Text</b> button.</li><li>To paste text from a Word processor like Word, use the <img src=\"/_images_add/paste_word.gif\"> <b>Paste from Word</b> button.</li><li>To paste text and images from a <b>Web site</b>, use the <img src=\"/_images_add/paste_normal.gif\"> <b>Paste</b> button (or Ctrl-V on a PC, Command-V on a Mac). Note: If image does not display, click the <img src=\"/_images_add/image_edit.gif\"> <b>Insert/Edit Image</b> button and check the image URL.</li></ul>'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>Paraphrase</b>'
						}, {
							columnWidth: .55,
							xtype: "tinymce",
							fieldLabel: "Rich text",
							id: "paraphrase",
							name: "paraphrase",
							width: 300,
							height: 390,
							tinymceSettings: {
								theme: "advanced",
								plugins: "safari,spellchecker,print,searchreplace,paste", // removed simplepaste and contextmenu for now
								theme_advanced_buttons1: "formatselect,fontselect,fontsizeselect,bold,italic,underline",
								theme_advanced_buttons2: "search,replace,separator,undo,redo,separator,bullist,numlist,outdent,indent,separator,hr,separator,justifyleft,justifycenter,justifyright",
								theme_advanced_buttons3: "pastetext,pasteword,paste,separator,print,spellchecker,strikethrough,forecolor,backcolor,separator,removeformat,separator,charmap,code,separator,link,unlink,image",
								theme_advanced_toolbar_location: "top",
								theme_advanced_toolbar_align: "left",
								theme_advanced_statusbar_location: "bottom",
								spellchecker_languages: "+English=en",
								invalid_elements: "",
								width: "450",
								height: "300",
								accessibility_warnings : false,
								theme_advanced_resizing : false,
								auto_resize : false,
								theme_advanced_resizing_use_cookie : false,
								relative_urls : false,
								remove_script_host: false,
								valid_elements: "" + validElems
							}
						}, {
							columnWidth: .45,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Rewrite the quotation by restating the idea in your own words. <ul style="list-style-type:square;margin:10px;padding:10px"><li>If you use the author\'s unique word or phrase put it in quotes.</li><li>If there are words you don\'t know, you might highlight the word and write \"define\"</li><li>If there are ideas that you can\'t explain, write questions under \"My Ideas\" (below).</li></ul><br>Compare your paraphrase to the quote: Does your restatement mirror the entire idea?'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding-top:5px;',
							html: '<b>My Ideas</b>'
						}, {
							columnWidth: .55,
							xtype: "tinymce",
							fieldLabel: "Rich text",
							id: "ideas",
							name: "ideas",
							width: 300,
							height: 390,
							tinymceSettings: {
								theme: "advanced",
								plugins: "safari,spellchecker,print,searchreplace,paste", // removed simplepaste and contextmenu for now
								theme_advanced_buttons1: "formatselect,fontselect,fontsizeselect,bold,italic,underline",
								theme_advanced_buttons2: "search,replace,separator,undo,redo,separator,bullist,numlist,outdent,indent,separator,hr,separator,justifyleft,justifycenter,justifyright",
								theme_advanced_buttons3: "pastetext,pasteword,paste,separator,print,spellchecker,strikethrough,forecolor,backcolor,separator,removeformat,separator,charmap,code,separator,link,unlink,image",
								theme_advanced_toolbar_location: "top",
								theme_advanced_toolbar_align: "left",
								theme_advanced_statusbar_location: "bottom",
								spellchecker_languages: "+English=en",
								invalid_elements: "",
								width: "450",
								height: "300",
								accessibility_warnings : false,
								theme_advanced_resizing : false,
								auto_resize : false,
								theme_advanced_resizing_use_cookie : false,
								relative_urls : false,
								remove_script_host: false,
								valid_elements: "" + validElems
							}
						}, {
							columnWidth: .45,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Interpret, evaluate and reflect on what you\'ve just learned. Ask questions about what you don\'t understand. Identify what you want to know more about. List what you need to do next.'
						}]
					}, {
						layout: 'column',
						items: [{
							columnWidth: 1,
							xtype: 'textfield',
							value: projectid,
							name: 'projectID',
							hidden: true,
							anchor: '95%'
						}, {
							columnWidth: .2
						
						}, {
							columnWidth: .2,
							xtype: 'textfield',
							value: "insertNewNote",
							name: 'toggle',
							hidden: true,
							anchor: '95%'
						}, {
							columnWidth: .6,
							xtype: 'textfield',
							value: '0',
							id: 'sourceID',
							name: 'sourceID',
							hidden: true,
							anchor: '95%'
						}]
					}]
				}],
				buttons: [{
					text: 'Save',
					type: 'button',
					listeners: {
						'click': {
							fn: function(){
								if (newNoteForm.getForm().isValid()) {
									var val = Trim(Ext.getCmp('txtTitle').getValue());
									if(alphanumeric(val)){
										if (!CheckNewNoteTitle(val)) {
											var qtext = Ext.getCmp('quotation').getValue();
											var ptext = Ext.getCmp('paraphrase').getValue();
											var itext = Ext.getCmp('ideas').getValue();
											if((qtext.match("meta content=\"Microsoft Word") == "meta content=\"Microsoft Word") ||(qtext.match("<w:WordDocument>") == "<w:WordDocument>"))												
											{
												function emptyQuotation(btn)
												{
													Ext.getCmp('quotation').setValue("");
													return false;
												}

												Ext.MessageBox.show({
													title: 'Error',
													msg: 'The text you are trying to paste into the Direct Quotation field contains Microsoft Word tags. Please use the \"Paste From Word\" button in the editor toolbar to copy this text without these extra tags.',
													buttons: Ext.MessageBox.OK,
													closable: false,
													fn: emptyQuotation,
													icon: Ext.MessageBox.ERROR
												});
											}
											else if((ptext.match("meta content=\"Microsoft Word") == "meta content=\"Microsoft Word") || (ptext.match("<w:WordDocument>") == "<w:WordDocument>"))													
											{
												function emptyPara(btn)
												{
													Ext.getCmp('paraphrase').setValue("");
													return false;	
												}
																		
												Ext.MessageBox.show({
													title: 'Error',
													msg: 'The text you are trying to paste into the Paraphase field contains Microsoft Word tags. Please use the \"Paste From Word\" button in the editor toolbar to copy this text without these extra tags.',
													buttons: Ext.MessageBox.OK,
													closable: false,
													fn: emptyPara,
													icon: Ext.MessageBox.ERROR
												});
											}
											else if((itext.match("meta content=\"Microsoft Word") == "meta content=\"Microsoft Word") || (itext.match("<w:WordDocument>") == "<w:WordDocument>"))													
											{
												function emptyIdeas(btn)
												{
													Ext.getCmp('ideas').setValue("");
													return false;
												}
												
												Ext.MessageBox.show({
													title: 'Error',
													msg: 'The text you are trying to paste into the Myideas field contains Microsoft Word tags. Please use the \"Paste From Word\" button in the editor toolbar to copy this text without these extra tags.',
													buttons: Ext.MessageBox.OK,
													closable: false,
													fn: emptyIdeas,
													icon: Ext.MessageBox.ERROR
												});												
											}
											else if(qtext.length>10000)
											{
												function emptyQuotation(btn)
												{
													Ext.getCmp('quotation').setValue("");
													return false;
												}

												Ext.MessageBox.show({
													title: 'Error',
													msg: 'The Direct Quotation field is limited to 10,000 characters. Note: If you are copying and pasting from a Web page or Word document, try using the \"Paste as Plain Text\" or \"Paste From Word\" buttons in the editor toolbar to eliminate hidden tags that are getting pasted in as well.',
													buttons: Ext.MessageBox.OK,
													closable: false,
													fn: emptyQuotation,												
													icon: Ext.MessageBox.ERROR
												});
											}
											else if(ptext.length>10000)
											{
												function emptyPara(btn)
												{
													Ext.getCmp('paraphrase').setValue("");
													return false;	
												}
												
												Ext.MessageBox.show({
													title: 'Error',
													msg: 'The Paraphrase field is limited to 10,000 characters. Note: If you are copying and pasting from a Web page or Word document, try using the \"Paste as Plain Text\" or \"Paste From Word\" buttons in the editor toolbar to eliminate hidden tags that are getting pasted in as well.',
													buttons: Ext.MessageBox.OK,
													closable: false,
													fn: emptyPara,
													icon: Ext.MessageBox.ERROR
												});
											}
											else if(itext.length>10000)
											{
												function emptyIdeas(btn)
												{
													Ext.getCmp('ideas').setValue("");
													return false;
												}
												
												Ext.MessageBox.show({
													title: 'Error',
													msg: 'The My Ideas field is limited to 10,000 characters. Note: If you are copying and pasting from a Web page or Word document, try using the \"Paste as Plain Text\" or \"Paste From Word\" buttons in the editor toolbar to eliminate hidden tags that are getting pasted in as well.',
													buttons: Ext.MessageBox.OK,
													closable: false,
													fn: emptyIdeas,													
													icon: Ext.MessageBox.ERROR
												});
											}
											else
											{
												if (Trim(val) != "") {
													submit1 = true;
												    if(Ext.getCmp('sourceID').getValue() == "0"){
												    	function showResult1(btn){
															if (btn == "ok") {
																tinyMCE.triggerSave();
																//kill the tiny editors on close	
																
																newNoteForm.getForm().submit({
																	method: 'POST',
																	waitTitle: 'Connecting',
																	waitMsg: 'Saving...',
																	
																	// Functions that fire (success or failure) when the server responds. 
																	// The one that executes is determined by the 
																	// response that comes from login.asp as seen below. The server would 
																	// actually respond with valid JSON, 
																	// something like: response.write "{ success: true}" or 
																	// response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}" 
																	// depending on the logic contained within your server script.
																	// If a success occurs, the user is notified with an alert messagebox, 
																	// and when they click "OK", they are redirected to whatever page
																	// you define as redirect. 
																	
																	success: function(form, action){
																		obj = Ext.util.JSON.decode(action.response.responseText);
																		
																		if ((obj.data.id.match("ERROR_MULTIPLE")) || (obj.data.id.match("ERROR_NOID"))) {
																			showNotesSessionError(obj.data.id);
																			return false;
																		}
																		Ext.getCmp('tags').store.reload();
																		createNotecard(val, obj.data.id, obj.data.pileid);
																		Ext.getCmp('sourceID').setValue('0');
																		newNoteForm.getForm().reset();
																		newNoteWin.hide();
																	},
																	
													
																	failure: function(form, action){
																		form.reset();
																	}
																});
															}else if(btn == "cancel"){
																//win2.toFront();
																//win2.enable();
															}
														}
														Ext.MessageBox.show({
															title: 'Alert',
															msg: 'You have not associated this notecard to a source in your bibliography. Continue anyway?',
															buttons: Ext.MessageBox.OKCANCEL,
															closable: false,
															fn: showResult1,
															icon: Ext.MessageBox.WARNING
														});
														//win2.toBack();
														//win2.disable();
												    }else{
												    	tinyMCE.triggerSave();
														newNoteForm.getForm().submit({
															method: 'POST',
															waitTitle: 'Connecting',
															waitMsg: 'Saving...',
															
															// Functions that fire (success or failure) when the server responds. 
															// The one that executes is determined by the 
															// response that comes from login.asp as seen below. The server would 
															// actually respond with valid JSON, 
															// something like: response.write "{ success: true}" or 
															// response.write "{ success: false, errors: { reason: 'Login failed. Try again.' }}" 
															// depending on the logic contained within your server script.
															// If a success occurs, the user is notified with an alert messagebox, 
															// and when they click "OK", they are redirected to whatever page
															// you define as redirect. 
															
															success: function(form, action){
																obj = Ext.util.JSON.decode(action.response.responseText);
																Ext.getCmp('tags').store.reload();
																createNotecard(val, obj.data.id, obj.data.pileid);
																Ext.getCmp('sourceID').setValue('0');
																newNoteForm.getForm().reset();
																newNoteWin.hide();
															},
															
															// Failure function, see comment above re: success and failure. 
															// You can see here, if login fails, it throws a messagebox
															// at the user telling him / her as much.  
															
															failure: function(form, action){
																form.reset();
															}
														});
												    }
												}
												else {
													function showResult(btn){
														if (btn == "ok") {
															
														}
													}
													Ext.MessageBox.show({
														title: 'Error',
														msg: 'Please enter a title for this notecard.',
														buttons: Ext.MessageBox.OK,
														closable: false,
														fn: showResult,
														icon: Ext.MessageBox.ERROR
													});
													
												}												
											}																						
										}
										else {
											function showResult(btn){
												if (btn == "ok") {
													
												}
											}
											Ext.MessageBox.show({
												title: 'Error',
												msg: 'A notecard with this title already exists.',
												buttons: Ext.MessageBox.OK,
												closable: false,
												fn: showResult,
												icon: Ext.MessageBox.ERROR
											});
											
										}
									}else{
										function showResult(btn){
											if (btn == "ok") {
												
											}
										}										
										Ext.MessageBox.show({
											title: 'Error',
											msg: 'The notecard title may not contain the characters: ~ ^ `',
											buttons: Ext.MessageBox.OK,
											closable: false,
											fn: showResult,
											icon: Ext.MessageBox.ERROR
										});
										
									}
								}
								else {
									function showResult(btn){
										if (btn == "ok") {
											
										}
									}
									Ext.MessageBox.show({
										title: 'Error',
										msg: 'Please check the fields marked in red and then try saving again.',
										buttons: Ext.MessageBox.OK,
										closable: false,
										fn: showResult,
										icon: Ext.MessageBox.ERROR
									});
									
								}
							}
						}
					}
				}, {
					text: 'Cancel',
					type: 'button',
					listeners: {
						'click': {
							fn: function(){
								function showResult1(btn){
										if (btn == "no") {
											//newNoteWin.toFront();
											//newNoteWin.enable();
										}
										if(btn == "yes"){
											newNoteForm.getForm().reset();
											newNoteWin.hide();
										}
									}
								Ext.MessageBox.show({
										title: 'Alert',
										msg: 'Are you sure you want to close this window without saving?',
										buttons: Ext.MessageBox.YESNO,
										closable: false,
										fn: showResult1,
										icon: Ext.MessageBox.WARNING
									});
									
								//newNoteWin.disable();
								//newNoteWin.toBack();
							}
						}
					}
				}]
			
			});
			
			// This just creates a window to wrap the login form. 
			// The login object is passed to the items collection.       
			 newNoteWin = new Ext.Window({
				layout: 'fit',
				cls: "../_css/noodlenotes.css",
				title: 'New Notecard',
				style: 'padding:5px',
				width: (YAHOO.util.Dom.getViewportWidth() - 50),
				height: (YAHOO.util.Dom.getViewportHeight() - 50),
				manager: newEditWindows,
				closable: false,
				resizable: false,
				plain: true,
				border: false,
				items: [newNoteForm],
				modal: true,
				draggable: false,
				listeners: {
					'beforeshow': {
						fn: function(win){
							hidePopupOnDrag();
							win. setWidth(YAHOO.util.Dom.getViewportWidth() - 50);
							win. setHeight(YAHOO.util.Dom.getViewportHeight() - 50);
							newNoteForm.body.dom.scrollTop = 0;
							Ext.getCmp('tags').store.reload();
							
						}
					}, 'show': {
						fn: function(cmb, newVal, oldVal){							
							Ext.getCmp('txtTags').setValue("");
							hidePopupOnDrag();
							Ext.getCmp('txtTitle').focus(false,1500);
						}
					}
				}
				
			});
			newNoteWin.show();
		}
	};
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=getCitations'
   	});	
}

// function to delete a comment in bib section
function deleteCommentinBib(action , entryID, id){
	Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete this comment?', showResult);
	function showResult(btn)
	{
		if (btn == "yes") {
			window.location.href="/noodlebib/commentEntry.php?action="+action+"&entryID="+entryID+"&bcID="+id;
		}
	}
	
}
/*
 * function to display details of individual notecard
 */
function notecardDetail(note_id)
{
	note_id = editNoteID;
	hidePopupOnDrag();
	var projectID = document.getElementById("projectID").value;	
	var success = function(o)
	{
        
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
				
		var data;
		try
		{
			data = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch(e)
		{
			alert(e);
		}
		
		var pileDet = data;			
		if(pileDet!=null && pileDet!="")
		{	
			var html = "";
			for(i=0;i<pileDet.length;i++)
			{
				var source = "";
				var url = "";
				var pages = "";
				var quote = "";
				var para = "";
				var ideas = "";
				var cdate = "";
				var mdate = "";
				var tags = "";
				var title = pileDet[i][0];		
				var visual_cues = pileDet[i][12];				
				
				if(pileDet[i][1] == "")
				{
					source = "&nbsp";
				}
				else
				{
					source = Ext.util.Format.htmlEncode(pileDet[i][1]);
				}				
				if(pileDet[i][2] == "")
				{
					url = "&nbsp";
				}
				else
				{
					url = "<a target='_blank' href="+pileDet[i][2]+">"+pileDet[i][2]+"</a>";
				}
				if(pileDet[i][3] == "")
				{
					pages = "&nbsp";
				}
				else
				{
					pages = pileDet[i][3];
				}
				if(pileDet[i][4] == "")
				{
					quote = "&nbsp";
				}
				else
				{
					quote = pileDet[i][4];
				}
				if(pileDet[i][5] == "")
				{
					para = "&nbsp";
				}
				else
				{
					para = pileDet[i][5];
				}
				if(pileDet[i][6] == "")
				{
					ideas = "&nbsp";
				}
				else
				{
					ideas = pileDet[i][6];
				}
				if(pileDet[i][7] == "")
				{
					cdate = "&nbsp";
				}
				else
				{
					cdate = pileDet[i][7];
				}
				if(pileDet[i][8] == "")
				{
					mdate = "not modified";
				}
				else
				{
					mdate = pileDet[i][8];
				}				
				if(pileDet[i][9] == "")
				{
					tags = "&nbsp";
				}
				else
				{
					tags = pileDet[i][9];
				}
				
				//button for the comments section
				if(isTeacher == "1"){
					var btnComment = "<a href=# class=smalltext>Add Comment</a> <a href=# onclick=showAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>-</a> | <a href=# class=smalltext>View Comments <a href=# onclick=showComments('comm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideComments('comm_"+pileDet[i][10]+"') class=smalltext>-</a></a></td></tr></table>";
				}else{
					var btnComment = "";
				}
				//button for the notecard section
				if(isTeacher == "1"){
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a></td></tr></tbody></table></th></tr>";
				}else{
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit')><img alt=Edit notecard src=../notecards/_images/edit.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit') class=smalltext>Edit</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete')><img alt=Delete Notecard src=../notecards/_images/cancel.png></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete') class=smalltext>Delete</a></td></tr></tbody></table></th></tr>";
				}
				//button for the notecard section
				if(isTeacher == "1")
				{
					var commBody = "";
					commBody = commBody + "<table class=notecardhead style=\"border: none; width: 100%;\">";
					//commBody = commBody + "<tr><td colspan=2><table id='addComm_"+pileDet[i][10]+"' style=display:block><td width=50% class=subhead>Add:</td><td width=50% class=noteitem><span><textarea id='ta_"+pileDet[i][10]+"' cols=100></textarea></span><span><input type='button' value='Submit' onclick=addComment('"+pileDet[i][10]+"')></span></td></table></td></tr>";
					commBody = commBody + "<tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td>";
					commBody = commBody + "<td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4>";
					commBody = commBody + "<ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];
					for(j=0;j<comm.length;j++){
						commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px; padding-top:5px; margin-bottom:5px'><span width='100%' alt='click to edit' style='display:block;cursor:pointer;' class='commBodyOut' onmouseover=mouseOverCommBody('comm_text_"+comm[j][5]+"') onmouseout=mouseOutCommBody('comm_text_"+comm[j][5]+"') onclick=editCommentText('"+comm[j][5]+"') id='comm_text_"+comm[j][5]+"'>"+comm[j][1]+"</span><span width='100%' style='display:none;' id='txt_comm_body_"+comm[j][5]+"'><textarea id='tb_comm_"+comm[j][5]+"' cols=100 rows=5 style='border:1px solid #7F9DB9'></textarea><br><input type='button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Submit' onclick=endEditCommentText()>&nbsp;<input type = 'button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Cancel' onclick=cancelEditCommentText()></span>";
						if(comm[j][3] != "" && comm[j][3] != null){
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) </i></font>";
						}else{
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) (comment not yet viewed by the author of the list)</i></font>";
						}
						if(comm[j][4] != "" && comm[j][4] != null){
							commBody = commBody + " <font color=#808080><i>(deleted by recipient on "+comm[j][4]+" PST)</i></font>";
						}						
						commBody = commBody + "<br><span align='right'><a id='editComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=editCommentText('"+comm[j][5]+"')>Edit Comment</a> | <a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></span></li>";
						
					}
					commBody = commBody + "</ol></td></tr></table>";					
				}
				else
				{
					var commBody = "";
					commBody = commBody + "<table class=notecardhead style=\"border: none; width: 100%;\">";
					commBody = commBody + "<tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td>";
					commBody = commBody + "<td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4>";
					commBody = commBody + "<ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];					
					for(j=0;j<comm.length;j++)
					{
						if(comm[j][4] != "" && comm[j][4] != null)
						{
							
						}
						else
						{
							commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px;padding-top:5px;margin-bottom:5px'>"							
							if(comm[j][3] != "" && comm[j][3] != null && comm[j][3] != 1)
							{
								commBody = commBody + "<img width='28' height='11' border='0' src='./images2/new.gif'/>&nbsp;<span id='comm_text_"+comm[j][5]+"'>";
							}
							commBody = commBody + comm[j][1]+"</span>";
							commBody = commBody + "<br><font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST)</i></font>";
							commBody = commBody + "<br><a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></li>";
						}
					}
					commBody = commBody + "</ol></td></tr></table>";
				}
				html = html + "<div id ='det_Notecard_"+pileDet[i][10]+"'><table id=notecardtb class=notecardtb cellspacing=0>";
				html = html + "<tbody><tr><th colspan=2><table class=notecardhead border=0><tbody><tr><td width=50% class=noborder><span class=notetitle>"+pileDet[i][0]+"</span>";
				html = html + btnNotes;
				html = html + "<tr><td class=subhead>Source:</td><td class=noteitem><span>"+source+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>URL:</td><td class=noteitem><span>"+url+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>Pages:</td><td class=noteitem><span>"+pages+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>Tags:</td><td class=noteitem><span>"+tags+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>Visual Cues:</td><td class=noteitem><span>"+visual_cues+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>Quotation:</td><td class=noteitem><span class=quoteclass>"+quote+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>Paraphrase:</td><td class=noteitem><span class=paraclass>"+para+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>My Ideas:</td><td class=noteitem><span class=ideasclass>"+ideas+"</span>";
				html = html + "</td></tr>";
				html = html + "<tr><td class=subhead>History:</td><td class=noteitem><span>Notecard Created: "+cdate+"  |  Updated: "+mdate+"</span></td></tr>";
				if(isTeacher == "1")
				{
					html = html + "<tr><td class=subhead>Comment:</td><td class=noteitem><table><tr><td><textarea id='ta_"+pileDet[i][10]+"' rows=5 cols=100></textarea></td><td>&nbsp;&nbsp;&nbsp;<input type=button class=btn value=Submit onclick=addComment('"+pileDet[i][10]+"')></td></tr></table></td></tr>";
					html = html + "<tr><td></td><td class=noteitem><span id='prelink_"+pileDet[i][10]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=\"comments("+pileDet[i][10]+")\">Select comments from the comment database</span></td></tr>";
					html = html + "<tr><td colspan=\"2\" height=\"10\"></td></tr>";					
				}								
				html = html + "</table>";
				html = html + "<table cellspacing=00 cellpadding=00>";
				if(comm.length == 0){
					var display = "hidden";
				}else{
					var display = "visible"
				}				
				html = html + "<tr><td style='visibility:"+display+"' id='comm_row_"+pileDet[i][10]+"'>";
				html = html + commBody;
				html = html + "</table>";
			}			
			var piles = new Array();
			var notecard = ["0", "Notecard: "+pileDet[0][0]];
			var unPiled = ["1", "Unpiled Notecards"];
			var selectNotes = ["2", "All Selected Notecards"];
			
			// collect the piles in the tabletop
			for (i = 0; i < pileID.length; i++) {
				piles[i] = [pileID[i][0], pileID[i][4]];
			}	
			piles.push(selectNotes);
			piles.push(unPiled);
			piles.push(notecard);
			piles.reverse();
			
			var cmb = new Ext.FormPanel({				
				bodyStyle:"padding-left:10px;padding-top:5px;",
				 items: [{
				 	xtype: 'combo',
				 	fieldLabel: 'View',
				 	store: piles,
				 	id: 'selectPile1',
				 	triggerAction: 'all',
				 	emptyText : 'Select an Option',
				 	listeners: {
                        'select' : {
                            fn: function(item){
                              var val = Ext.getCmp('selectPile1').getValue();
                              if(val == "1"){
									unPiledNotecardDetails("");
								}else if(val == "0"){
									
								}else if(val == "2"){
									win.close();
									selectedNotecardDetails();
								}else{
									editNoteID = val.substr(5);
									win.close();
									pileDetails(editNoteID);
								}
                            }, 
                            scope: this
                        },
                        'expand': {
                        	fn: function(cmb){
                        		//alert(cmb.store.data.length);
                        	}
                        }
                    }
				 }]				
			});
			
			var dataGrid = new Ext.Panel({
				id:"noteHTML",
        		html: html,
				height: (YAHOO.util.Dom.getViewportHeight() - 200),
        		autoScroll: true
			});			
			
			win = new Ext.Window({
				 width:(YAHOO.util.Dom.getViewportWidth()-100),				 
				 cls:"../_css/noodlenotes.css",
				 bodyStyle:'padding:5px 5px 5px 5px',
				 title:title,		 
				 autoScroll:true,				 
				 layout: 'form',
				 closable: true,
				 buttonAlign: 'center',
				 manager: openwindows,
				 items: [{
				 	items:[cmb]
				 },{
				 	items:[dataGrid]
				 }],				 
				 buttons: [{
					text: 'Return to Tabletop',
					handler: function(){
						commInEditMode = "";
						win.close();
					}
				}],
				 draggable:false,
				 listeners : {
							'show' : {
								fn : function(myWin) {
									Ext.getCmp('selectPile1').setValue("0");
								},
								scope : this
							},
							'close' : 
							{
								fn : function(myWin)
								{
									//student can only update the viewed flg
									var isTeacher = document.getElementById("isTeacher").value;
									if (isTeacher == 0) 
									{
										//create an array of notecard ids
										var notes = new Array();
										for (i = 0; i < pileDet.length; i++) {
											notes[notes.length] = pileDet[i][10];
										}
										//create a json string
										var strNotes = YAHOO.lang.JSON.stringify(notes);
										var success = function(o){
                                            
											if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
											{			
												showNotesSessionError(Trim(o.responseText));
												return false;
											}
										};
										var failure = function(o){
										};
										Ext.Ajax.request({
									   		url: '../notecards/_includes/notecardOperations.php',
									   		method: 'POST',
									   		success: success,				   
									   		failure: failure,
											params: 'toggle=UpdateViewed&notes='+strNotes
									   	});										
									}
								}
							}
						},
				 modal:true		 
			});
		
			win.show();
		}else{
			function showResult(btn) {
				if (btn == "ok") {
					pileDetails(editNoteID);
				}
			}
			Ext.MessageBox.show({
				title : 'Error',
				msg : 'There are no unpiled notecards on your tabletop.',
				buttons : Ext.MessageBox.OK,
				closable : false,
				fn : showResult,
				icon : Ext.MessageBox.ERROR
			});
		}
	};
	
	var failure = function(o)
	{
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=notecardDetail&noteID='+note_id
   	});	
}

/*
 * function to show details of the selected notecards
 */
function selectedNotecardDetails()
{
	var notes = Ext.query("*[class=notecardYellow]");
	var note_id=[];
	if(notes.length>0){
	for(i=0;i<notes.length;i++){
		note_id[i] = notes[i].id;
	}
	
	note_id1 = Ext.util.JSON.encode(note_id);
	hidePopupOnDrag()
	var projectID = document.getElementById("projectID").value;	
	var success = function(o)
	{
        
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
				
		var data;
		try
		{
			data = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch(e)
		{
			alert(e);
		}
		
		var pileDet = data;			
		if(pileDet!=null && pileDet!="")
		{	
			var html = "";
			for(i=0;i<pileDet.length;i++)
			{				
				if (pileDet[i][1] == "&nbsp") {
					var source = pileDet[i][1];
				}
				else 
				{
					var source = Ext.util.Format.htmlEncode(pileDet[i][1]);
				}
				if(pileDet[i][2] == "&nbsp")
				{
					var url = "&nbsp";
				}
				else
				{
					var url = "<a target='_blank' href="+pileDet[i][2]+">"+pileDet[i][2]+"</a>"; 
				}				
				var pages = pileDet[i][3];
				var quote = pileDet[i][4];
				var para = pileDet[i][5];
				var ideas = pileDet[i][6];
				var cdate = pileDet[i][7];
				var mdate = pileDet[i][8];
				var tags = pileDet[i][9];
												
				//button for the comments section
				if(isTeacher == "1"){
					var btnComment = "<a href=# class=smalltext>Add Comment</a> <a href=# onclick=showAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideAddComment('addComm_"+pileDet[i][10]+"') class=smalltext>-</a> | <a href=# class=smalltext>View Comments <a href=# onclick=showComments('comm_"+pileDet[i][10]+"') class=smalltext>+</a>/<a href=# onclick=hideComments('comm_"+pileDet[i][10]+"') class=smalltext>-</a></a></td></tr></table>";
				}else{
					var btnComment = "";
				}
				//button for the notecard section
				if(isTeacher == "1"){
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a></td></tr></tbody></table></th></tr>";
				}else{
					var btnNotes = "</td><td width=50% align=right><a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit')><img alt=Edit notecard src=../notecards/_images/edit.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','edit') class=smalltext>Edit</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print')><img alt=Print notecard src=../notecards/_images/fileprint.png border=0></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','print') class=smalltext>Print</a> <a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete')><img alt=Delete Notecard src=../notecards/_images/cancel.png></a>&nbsp;<a href=# onclick=doNotecardOption('"+pileDet[i][10]+"','delete') class=smalltext>Delete</a></td></tr></tbody></table></th></tr>";
				}
				//button for the notecard section
				if(isTeacher == "1")
				{
					var commBody = "";
					commBody = commBody + "<table style=\"border: none; width: 100%;\">";					
					commBody = commBody + "<tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td>";
					commBody = commBody + "<td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4>";
					commBody = commBody + "<ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];
					for(j=0;j<comm.length;j++){
						commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px; padding-top:5px; margin-bottom:5px'><span width='100%' alt='click to edit' style='display:block;cursor:pointer;' class='commBodyOut' onmouseover=mouseOverCommBody('comm_text_"+comm[j][5]+"') onmouseout=mouseOutCommBody('comm_text_"+comm[j][5]+"') onclick=editCommentText('"+comm[j][5]+"') id='comm_text_"+comm[j][5]+"'>"+comm[j][1]+"</span><span width='100%' style='display:none;' id='txt_comm_body_"+comm[j][5]+"'><textarea id='tb_comm_"+comm[j][5]+"'cols=100 rows=5 style='border:1px solid #7F9DB9'></textarea><br><input type='button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Submit' onclick=endEditCommentText()>&nbsp;<input type = 'button' class='btn' style='margin-top:2px; margin-bottom:2px;' value='Cancel' onclick=cancelEditCommentText()></span>";
						if(comm[j][3] != "" && comm[j][3] != null){
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) </i></font>";
						}else{
							commBody = commBody + "<font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST) (comment not yet viewed by the author of the list)</i></font>";
						}
						if(comm[j][4] != "" && comm[j][4] != null){
							commBody = commBody + " <font color=#808080><i>(deleted by recipient on "+comm[j][4]+" PST)</i></font>";
						}						
						commBody = commBody + "<br><span align='right'><a id='editComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=editCommentText('"+comm[j][5]+"')>Edit Comment</a> | <a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></span></li>";
						
					}
					commBody = commBody + "</ol></td></table>";					
				}
				else
				{
					var commBody = "";
					commBody = commBody + "<table style=\"border: none; width: 100%;\">";
					commBody = commBody + "<tr valign=\"top\"><td width=\"52\" style=\"border-top: none;\"><img src=\"../_images_add/comment.gif\" border=\"0\" width=\"50\" height=\"50\"></td>";
					commBody = commBody + "<td class=\"alignleft\" style=\"border-top: none;\"><h4>Comments</h4>";
					commBody = commBody + "<ol style='list-style-type:none;' id='list_comments_"+pileDet[i][10]+"'>";
					var comm = pileDet[i][11];					
					for(j=0;j<comm.length;j++)
					{
						if(comm[j][4] != "" && comm[j][4] != null)
						{
							
						}
						else
						{
							commBody = commBody + "<li id='comm_"+comm[j][5]+"' style='padding-left:5px;padding-top:5px;margin-bottom:5px'>"							
							if(comm[j][3] != "" && comm[j][3] != null && comm[j][3] != 1)
							{
								commBody = commBody + "<img width='28' height='11' border='0' src='./images2/new.gif'/>&nbsp;<span id='comm_text_"+comm[j][5]+"'>";
							}
							commBody = commBody + comm[j][1]+"</span>";
							commBody = commBody + "<br><font color=#808080><i>"+comm[j][2]+" ("+comm[j][0]+" PST)</i></font>";
							commBody = commBody + "<br><a id='deleteComment"+comm[j][5]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=deleteComment('"+comm[j][5]+"')>Delete Comment</a></li>";
						}
					}
					commBody = commBody + "</ol></td></table>";
				}
				html = html + "<div id ='det_Notecard_"+pileDet[i][10]+"'><table id=notecardtb class=notecardtb cellspacing=0><tbody><tr><th colspan=2><table class=notecardhead border=0><tbody><tr><td width=50% class=noborder><span class=notetitle>"+pileDet[i][0]+"</span>"+ btnNotes +"<tr><td class=subhead>Source:</td><td class=noteitem><span>"+source+"</span></td></tr><tr><td class=subhead>URL:</td><td class=noteitem><span>"+url+"</span></td></tr><tr><td class=subhead>Pages:</td><td class=noteitem><span>"+pages+"</span></td></tr><tr><td class=subhead>Tags:</td><td class=noteitem><span>"+tags+"</span></td></tr><tr><td class=subhead>Quotation:</td><td class=noteitem><span class=quoteclass>"+quote+"</span></td></tr><tr><td class=subhead>Paraphrase:</td><td class=noteitem><span class=paraclass>"+para+"</span></td></tr><tr><td class=subhead>My Ideas:</td><td class=noteitem><span class=ideasclass>"+ideas+"</span></td></tr><tr><td class=subhead>History:</td><td class=noteitem><span>Notecard Created: "+cdate+"  |  Updated: "+mdate+"</span></td></tr>";
				if(isTeacher == "1")
				{
					html = html + "<tr><td class=subhead>Comment:</td><td class=noteitem><table><tr><td><textarea id='ta_"+pileDet[i][10]+"' rows=5 cols=100></textarea></td><td>&nbsp;&nbsp;&nbsp;<input type=button class=btn value=Submit onclick=addComment('"+pileDet[i][10]+"')></td></tr></table></td></tr>";
					html = html + "<tr><td></td><td class=noteitem><span id='prelink_"+pileDet[i][10]+"' class='commNorm' onmouseover='changeCss(this.id)' onmouseout='restoreCss(this.id)' onclick=\"comments("+pileDet[i][10]+")\">Select comments from the comment database</span></td></tr>";
					html = html + "<tr><td colspan=\"2\" height=\"10\"></td></tr>";					
				}
				if(comm.length == 0){
					var display = "hidden";
				}else{
					var display = "visible"
				}
				html = html + "</table>";
				html = html + "<table cellspacing=00 cellpadding=00>";
				html = html + "<tr>";
				html = html + "<td style='visibility:"+display+"' id='comm_row_"+pileDet[i][10]+"'>";
				html = html + commBody;
				html = html + "</td>";
				html = html + "</tr>";
				html = html + "<table>";
			}			
			var piles = new Array();
			var notecard = ["0", "All Selected Notecards"];
			var unPiled = ["1", "Unpiled Notecards"];
			
			
			// collect the piles in the tabletop
			for (i = 0; i < pileID.length; i++) {
				piles[i] = [pileID[i][0], pileID[i][4]];
			}	
			piles.push(unPiled);
			piles.push(notecard);
			piles.reverse();
			
			var cmb = new Ext.FormPanel({				
				bodyStyle:"padding-left:10px;padding-top:5px;",
				 items: [{
				 	xtype: 'combo',
				 	fieldLabel: 'View',
				 	store: piles,
				 	id: 'selectPile1',
				 	triggerAction: 'all',
				 	emptyText : 'Select an Option',
				 	listeners: {
                        'select' : {
                            fn: function(item){
                              var val = Ext.getCmp('selectPile1').getValue();
                              if(val == "1"){
									unPiledNotecardDetails("");
								}else if(val != "0"){
									editNoteID = val.substr(5);
									win.close();
									pileDetails(editNoteID);
								}							 
                            }, 
                            scope: this
                        },
                        'expand': {
                        	fn: function(cmb){
                        		//alert(cmb.store.data.length);
                        	}
                        }
                    }
				 }]				
			});
			
			var dataGrid = new Ext.Panel({
				id:"sltdnoteHTML",
        		html: html,
				height: (YAHOO.util.Dom.getViewportHeight() - 200),
        		autoScroll: true
			});			
			
			win = new Ext.Window({
				 width:(YAHOO.util.Dom.getViewportWidth()-100),				 
				 cls:"../_css/noodlenotes.css",
				 bodyStyle:'padding:5px 5px 5px 5px',
				 title:"Unpiled Notecards",		 
				 autoScroll:true,				 
				 layout: 'form',
				 closable: true,
				 buttonAlign: 'center',
				 manager: openwindows,
				 items: [{
				 	items:[cmb]
				 },{
				 	items:[dataGrid]
				 }],				 
				 buttons: [{
					text: 'Return to Tabletop',
					handler: function(){
						commInEditMode = "";
						win.close();
					}
				}],
				 draggable:false,
				 listeners : {
							'show' : {
								fn : function(myWin) {
									Ext.getCmp('selectPile1').setValue("0");
								},
								scope : this
							},
							'close' : 
							{
								fn : function(myWin)
								{
									//student can only update the viewed flg
									var isTeacher = document.getElementById("isTeacher").value;
									if (isTeacher == 0) 
									{
										//create an array of notecard ids
										var notes = new Array();
										for (i = 0; i < pileDet.length; i++) {
											notes[notes.length] = pileDet[i][10];
										}
										//create a json string
										var strNotes = YAHOO.lang.JSON.stringify(notes);
										var success = function(o){
                                            
											if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
											{			
												showNotesSessionError(Trim(o.responseText));
												return false;
											}

										};
										var failure = function(o){
										};
										//ajax call to the server update viewed flag										
										Ext.Ajax.request({
									   		url: '../notecards/_includes/notecardOperations.php',
									   		method: 'POST',
									   		success: success,				   
									   		failure: failure,
											params: 'toggle=UpdateViewed&notes='+strNotes
									   	});										
									}
								}
							}
						},
				 modal:true		 
			});
		
			win.show();
		}else{
			function showResult(btn) {
				if (btn == "ok") {
					pileDetails(editNoteID);
				}
			}
			Ext.MessageBox.show({
				title : 'Error',
				msg : 'There are no selected notecards on your tabletop.',
				buttons : Ext.MessageBox.OK,
				closable : false,
				fn : showResult,
				icon : Ext.MessageBox.ERROR
			});
		}
	};
	var failure = function(o)
	{
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=selectedNotecardDetail&noteID='+note_id1
   	});	
	
	}else{
		Ext.MessageBox.show({
				title : 'Error',
				msg : 'There are no selected notecards on your tabletop.',
				buttons : Ext.MessageBox.OK,
				closable : false,
				icon : Ext.MessageBox.ERROR
		});
	}
}

function loadNotes(){
    // get the current project id
	var projectID = document.getElementById('projectID').value;
	var success = function(o){
        
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}

		var prod = null;
		try {
			// get complete data of the notecards in the current selected project
	    	prod = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch (e) {
		    alert(e);
		}
		if (prod) {
			// populate the notecard data array for client side utilization
			for (i = 0; i < prod.length; i++) {
				notecardID[notecardID.length] = prod[i];
			}
		}
		var initLeftTop = new Array();
		document.getElementById('zoneList').innerHTML = "";
		// create the notecards
		for (a = 0; a < notecardID.length; a++) {
			var noteCard = new NoteCardTemplate(notecardID[a][0], notecardID[a][4]);
			if(isTeacher != "1"){
				var notec = new YAHOO.example.DDNotecard(notecardID[a][0], "", {
					cont: 'tabletop'
				});
			}
			var div = document.createElement("div");
			div.innerHTML = noteCard.toHTML();
			document.getElementById("tabletop").appendChild(div.firstChild);
			initLeftTop[0] = notecardID[a][1];
			initLeftTop[1] = notecardID[a][2];
			setLeftTopInTabletop(notecardID[a][0], initLeftTop);
			document.getElementById(notecardID[a][0]).style.display = notecardID[a][6];
			// code to check whether the notecard was in selected state
			if (notecardID[a][5] == true) {
				document.getElementById(notecardID[a][0]).className = "notecardYellow";
			}
			else {
				document.getElementById(notecardID[a][0]).className = "notecard";
			}
			createNotecardThumb(notecardID[a][0]);

			document.getElementById('thumb_' + notecardID[a][0]).style.display = notecardID[a][6];
			if (notecardID[a][7] == "zone") {
				if(!document.getElementById('li_Notecard_' + cnt)){
					var zoneNoteCard = new zoneNotesLi(notecardID[a][0],notecardID[a][4]);
					var ol = document.createElement("ol");
					ol.innerHTML = zoneNoteCard.toHTML();
					var parentEl = Ext.get("zoneList");
					if(!parentEl.contains('li_Notecard_' + cnt)){
						document.getElementById('zoneList').appendChild(ol.firstChild);
						var parentEl = Ext.get("zoneList");
						var childEl = Ext.get('li_Notecard_' + cnt);
						parentEl.insertFirst(childEl);
					}
				}
			}
		}

		// apply the in outline cues after refreshment of the tabletop as all
		// the notecards are recreated in the dom
                notecardsOutline = [];
		var notecardLi = YAHOO.util.Dom.getElementsByClassName("li_notecard_outline_selected");
                
                if(notecardLi != null && notecardLi != "")
                {
                        for(this.m=0;this.m<notecardLi.length;this.m++)
                        {
                                if(document.getElementById(notecardLi[this.m].id)){
                                        try{
                                                var child = YAHOO.util.Dom.getChildren(notecardLi[this.m].id);
                                                var noteId = getNotecardId(child[0].id);
                                                if(document.getElementById(noteId) != null){
                                                        notecardsOutline[notecardsOutline.length] = [noteId,notecardLi[this.m].id]
                                                        if(isTeacher != "1"){
                                                                new YAHOO.example.DDPlayer(notecardLi[this.m].id, "topslots");
                                                        }
                                                        applyInOutlineCue(noteId);
                                                }else{
                                                        var el = Ext.get(notecardLi[this.m].id);
                                                        el.remove();
                                                }
                                        }
                                        catch(e){
                                                //alert(e);
                                        }
                                }
                        }
                }
                var notecardLi = YAHOO.util.Dom.getElementsByClassName("li_notecard_outline");
                
                if(notecardLi != null && notecardLi != "")
                {
                        for(this.m=0;this.m<notecardLi.length;this.m++)
                        {
                                if(document.getElementById(notecardLi[this.m].id)){
                                        try{
                                                var child = YAHOO.util.Dom.getChildren(notecardLi[this.m].id);
                                                var noteId = getNotecardId(child[0].id);
                                                if(document.getElementById(noteId) != null){
                                                        notecardsOutline[notecardsOutline.length] = [noteId,notecardLi[this.m].id]
                                                        if(isTeacher != "1"){
                                                                new YAHOO.example.DDPlayer(notecardLi[this.m].id, "topslots");
                                                        }
                                                        applyInOutlineCue(noteId);
                                                }else{
                                                        var el = Ext.get(notecardLi[this.m].id);
                                                        el.remove();
                                                }
                                        }
                                        catch(e){
                                                //alert(e);
                                        }
                                }
                        }
                }
		hidePopupOnDrag();
		loadPileNoteRelData();
	};
	var failure = function(o)
	{
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadNotecardData&projectID='+projectID
   	});	
}
function loadPileNoteRelData(){


	var projectID = document.getElementById('projectID').value;
	var success = function(o){
        
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		var resultArray = new Array();
		try {
	    	var prod2 = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch (e) {
		    alert(e);
		}
		if (prod2) {
			for (i = 0; i < prod2.length; i++) {
				pileNotecard[pileNotecard.length] = prod2[i];
			}
		}

		loadPileDetail();
	}
	
	var failure = function(o)
	{
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadNotePileRel&projectID='+projectID
   	});
}

function loadPileDetail()
{
	var projectID = document.getElementById('projectID').value;
	var success = function(o){
        
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		var resultArray = new Array();
		var prod1 = null;
		try {
	    	prod1 = YAHOO.lang.JSON.parse(o.responseText);
		}
		catch (e) {
		    alert(e);
		}
		if (prod1) {
			for (i = 0; i < prod1.length; i++) {
				pileID[pileID.length] = prod1[i];
			}
		}
		var initLeftTop = new Array();
		// create the piles
		for (a = 0; a < pileID.length; a++) {

			var newPile = new PileTemplate(pileID[a][0], pileID[a][4]);
			if(isTeacher != "1"){
				new YAHOO.example.DDPile(pileID[a][0]);
			}
			var div = document.createElement("div");
			div.innerHTML = newPile.toHTML();
			document.getElementById("tabletop").appendChild(div.firstChild);
			if (pileID[a][7] == "zone") {
				var zonePile = new zonePileLi(pileID[a][0], pileID[a][4]);
				var ol = document.createElement("ol");
				ol.innerHTML = zonePile.toHTML();
				document.getElementById('zoneList').appendChild(ol.firstChild);
				var parentEl = Ext.get("zoneList");
				var childEl = Ext.get('li_'+pileID[a][0])
				parentEl.insertFirst(childEl);
				document.getElementById('li_txt_' + pileID[a][0]).innerHTML = notecardCountInPile(pileID[a][0]);
			}else{
				createPileThumb(pileID[a][0]);
				document.getElementById('thumb_' + pileID[a][0]).style.display = pileID[a][5];
			}
			initLeftTop[0] = pileID[a][1];
			initLeftTop[1] = pileID[a][2];
			setLeftTopInTabletop(pileID[a][0], initLeftTop);
			setLeftTopInBirdsEyeView(pileID[a][0], initLeftTop);
			document.getElementById('txt_' + pileID[a][0]).innerHTML = notecardCountInPile(pileID[a][0]);
			document.getElementById(pileID[a][0]).style.display = pileID[a][5];
			if (pileID[a][6] == true) {
				document.getElementById(pileID[a][0]).className = "pileYellow";
			}
			else {
				document.getElementById(pileID[a][0]).className = "pile";
			}
		}

            hidePopupOnDrag();
            attachColors();
            attachCues();
            var outline = Ext.get("outline");
            var el = outline.select("li.li_notecard_outline_selected", true);			
			var elArray = el.elements;
			if (el != null) {
				for (hj = 0; hj < elArray.length; hj++) {
					elArray[hj].dom.className = "li_notecard_outline";
				}
			}		
	}
	var failure = function(o)
	{
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadPileData&projectID='+projectID
   	});	
}