/**
 * @author amore
 */
 
 var threshold = 1;
 var down_x;
 var down_y;
 var up_x;
 var up_y;
 var x;
 var y;
 
 var mdx;
 var mdy;
 var mux;
 var muy;
 var thresholdx;
 var thresholdy;
 
 var myX;
 var myY;
 var scrollMe = false;
 
 //global variables to store mouse x and y on tabletop
 var mousex;
 var mousey;
 var Colmenu;
 var cuesMenu;
 var tagsMenu;

 var layout = null; 
 
 // array to store selected predefined comment
 var commArr = [];
 
 // variable to store the predifined comment window
 var commentsWin;
 var frmcommentPanel;
/*
 * function to resize layout on window resize
 */ 

function resizeLayout(){
	layout.resize(true);
	if(Ext.getCmp("pileHTML"))
	{
		Ext.getCmp("pileHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
	}
	else if(Ext.getCmp("noteHTML"))
	{
		Ext.getCmp("noteHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
	}
	else if(Ext.getCmp("sltdnoteHTML"))
	{
		Ext.getCmp("sltdnoteHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
	}
	else if(Ext.getCmp("unpilednoteHTML"))
	{
		Ext.getCmp("unpilednoteHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
	}
	
	var active_wind = openwindows.getActive();	
	if(active_wind){
		active_wind.setWidth(YAHOO.util.Dom.getViewportWidth()-100);
		active_wind.center();
	}
	
	openwindows.each(resetBubblePosition);
	//createBirdsEyeView();
	//onWindowResize();
}

/*
 * function to reset the position of help bubbles on window resize
 */
var resetBubblePosition = function(cmp){
	if(cmp.id == "newNoteButton"){
		 var newbReg = YAHOO.util.Dom.getRegion("newNoteButton");
		 var x = newbReg.right-5;
		 var y = newbReg.top-28;
		 cmp.setPosition(x,y);
	}
	else if(cmp.id == "noteRegion")
	{
		var el = Ext.get("notecardRegion");
		var x = el.getX()+90;
		var y = el.getY();		
		cmp.setPosition(x,y);
	}
	else if(cmp.id == "birdsBubble")
	{
		var el = Ext.get("outer_hawk_eye");
		var x = el.getX()+245;
		var y = el.getY()-150;		
		cmp.setPosition(x,y);		
	}
	else if(cmp.id == "outlineBubble")
	{
		var el = Ext.get("outline");
		var x = el.getX()-255;
		var y = el.getY();		
		cmp.setPosition(x,y);		
	}
	else if(cmp.id == "bubbleTags")
	{
		var newbReg = YAHOO.util.Dom.getRegion("menuButton");
		var x = newbReg.right-5;
		var y = newbReg.top-28;		
		cmp.setPosition(x,y);		
	}
}

 /*
  * function to set the initial position of the tabletopContainer for scrolling
  */
 function init()
 {
	createBirdsEyeView();
    layout = new YAHOO.widget.Layout('outerDiv', {
        height: 600,
        units: [            
			{ position: 'center', gutter: '1px', body: 'first-half' },
            {
                    position: 'right',
					header: 'Outline',
                    width: 300,                    
                    gutter: '1px',
                    collapse: true,
					body: 'second-half'
            }
        ]
    });
	layout.on("render", function(){
        initLoading();
	});
    layout.render();	
    
    var oElement = document.getElementById("tabletop");
 	var el = YAHOO.util.Dom.getRegion('outerDiv');	
	var tabletopViewWidth = el.right - el.left;
	var spcaeLeft = 3000 - tabletopViewWidth;
 	document.getElementById('tabletopContainer').scrollTop=((1500-600)/2);
	document.getElementById('tabletopContainer').scrollLeft=spcaeLeft/2;
 	myX = spcaeLeft/2;
 	myY = 450;
 	var oElement = document.getElementById("tabletop");						
 	YAHOO.util.Event.addListener(oElement, "mousedown", tabletopMouseDown);
 	YAHOO.util.Event.addListener(oElement, "mouseup", tabletopMouseUp);
	YAHOO.util.Event.addListener(oElement, "mousemove", tabletopMouseMove);
	
 }

/*
 * function to display session error
 */
function showNotesSessionError(val)
{
	if(val == "[[ERROR_NOID]]")
	{
		if (error_counter > 0) return;
		error_counter++;

		alert("Your session has expired. Please log in again to continue.");
		window.location.href = '../../logout.php';		
	}
	else if(val == "[[ERROR_MULTIPLE]]")
	{
		if (error_counter > 0) return;
		error_counter++;

		alert("This list has been opened by another user. Please re-open the list to continue working on it.");
		window.location.href = '../../noodlebib/index.php?err=error_multiple';
	}
}

/*
 * function to toggle search options
 */
function toggleOptions(val)
{	
	var maskWin;
	//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'> Please wait... ",
		modal: true
	});
	maskWin.show();
	
	if(val == "Color")
	{
		document.getElementById("conSearch").style.display = "none";
		document.getElementById("conBooleans").style.display = "none";
		document.getElementById("conCues").style.display = "none"
		document.getElementById("conSource").style.display = "none";
		document.getElementById("conColors").style.display = "block";
		maskWin.close();
	}
	else if(val == "Cues")
	{
		document.getElementById("conSearch").style.display = "none";
		document.getElementById("conBooleans").style.display = "none";
		document.getElementById("conColors").style.display = "none";
		document.getElementById("conSource").style.display = "none";
		document.getElementById("conCues").style.display = "block";
		maskWin.close();
	}
	else if(val == "tag")
	{
		document.getElementById("conColors").style.display = "none";
		document.getElementById("conCues").style.display = "none";
		document.getElementById("conSource").style.display = "none";
		document.getElementById("conSearch").style.display = "block";
		document.getElementById("conBooleans").style.display = "block";
		maskWin.close();
	}
	else if(val == "keyword")
	{
		document.getElementById("conColors").style.display = "none";
		document.getElementById("conCues").style.display = "none";
		document.getElementById("conSource").style.display = "none";
		document.getElementById("conSearch").style.display = "block";
		document.getElementById("conBooleans").style.display = "block";
		maskWin.close();
	}
	else if(val == "source")
	{
		document.getElementById("conColors").style.display = "none";
		document.getElementById("conCues").style.display = "none";
		document.getElementById("conSearch").style.display = "none";
		document.getElementById("conSource").style.display = "block";
		document.getElementById("conBooleans").style.display = "none";
		maskWin.close();
	}	
}

 /*
  * function to load all the notecards details
  */
function loadNotecardDetailFromDatabase()
{
	// 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
		for (m in notecardsOutline) {
			if (document.getElementById(notecardsOutline[m][0])) {
				document.getElementById('check_' + notecardsOutline[m][0]).style.display = "block";
				var li = document.getElementById('li_' + notecardsOutline[m][0]);
				if (li != null) {
					document.getElementById('li_check_' + notecardsOutline[m][0]).style.display = "block";
				}
			}
		}
		Ext.MessageBox.updateProgress(2/7,'Loading 2 / 7');
		hidePopupOnDrag();
		loadPileNoteRel();
	};
	var failure = function(o)
	{
	};
	
	//ajax call to the server to load notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadNotecardData&projectID='+projectID
   	});	
}

 /*
  * function to attach cues to the notecards
  */
function attachCues()
{
	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;
		}
		
		try
		{
			var cues = YAHOO.lang.JSON.parse(o.responseText);			
		}
		catch(e)
		{
			alert(e);
		}
		if(cues != null)
		{
			for(i=0;i<cues.length;i++)
			{
				if(cues[i][1] == 1)
				{	
					noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];				
					if(document.getElementById("Notecard_"+cues[i][0]) != null)
					{
						document.getElementById("research_Notecard_"+cues[i][0]).style.display = "block";
					}					
				}
				else if(cues[i][1] == 2)
				{
					noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
					if(document.getElementById("Notecard_"+cues[i][0]) != null)
					{
						document.getElementById("help_Notecard_"+cues[i][0]).style.display = "block";
					}					
				}
				else if(cues[i][1] == 3)
				{
					noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
					if(document.getElementById("Notecard_"+cues[i][0]) != null)
					{
						document.getElementById("incomplete_Notecard_"+cues[i][0]).style.display = "block";
					}					
				}
				else if(cues[i][1] == 4)
				{
					noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
					if(document.getElementById("Notecard_"+cues[i][0]) != null)
					{
						document.getElementById("thinking_Notecard_"+cues[i][0]).style.display = "block";
					}					
				}
				else if(cues[i][1] == 5)
				{
					noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
					if(document.getElementById("Notecard_"+cues[i][0]) != null)
					{
						document.getElementById("important_Notecard_"+cues[i][0]).style.display = "block";
					}					
				}
				else if(cues[i][1] == 6)
				{
					noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
					if(document.getElementById("Notecard_"+cues[i][0]) != null)
					{
						document.getElementById("paper_Notecard_"+cues[i][0]).style.display = "block";
					}					
				}
			}									
		}
		Ext.MessageBox.updateProgress(5/7,'Loading 6 / 7');
		//function call to attach colors to the notecards		
		attachColors();
	};
	var failure = function(o) 
	{
	};
	
	//ajax call to the server to load notecard cues
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadCuesData&projectID='+projectID
   	});
}

 /*
  * function to attach colors to the notecards on load
  */
function attachColors()
{
	//retrieve 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;
		}
		
		try
		{
			var colors = YAHOO.lang.JSON.parse(o.responseText);			
		}
		catch(e)
		{
			alert(e);
		}
		
		//make the appropriate divs visible and fill the notecolor array
		if(colors != null)
		{
			for(i=0;i<colors.length;i++)
			{
				if(colors[i][1] == 1)
				{
					noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
					if(document.getElementById("Notecard_"+colors[i][0]) != null)
					{
						document.getElementById("red_Notecard_"+colors[i][0]).style.display = "block";
						document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "red";
					}
				}
				else if(colors[i][1] == 2)
				{
					noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
					if(document.getElementById("Notecard_"+colors[i][0]) != null)
					{
						document.getElementById("orange_Notecard_"+colors[i][0]).style.display = "block";
						document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "orange";						
					}
				}
				else if(colors[i][1] == 3)
				{
					noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
					if(document.getElementById("Notecard_"+colors[i][0]) != null)
					{
						document.getElementById("yellow_Notecard_"+colors[i][0]).style.display = "block";
						document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "yellow";						
					}
				}
				else if(colors[i][1] == 4)
				{
					noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
					if(document.getElementById("Notecard_"+colors[i][0]) != null)
					{
						document.getElementById("green_Notecard_"+colors[i][0]).style.display = "block";
						document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "green";						
					}
				}
				else if(colors[i][1] == 5)
				{
					noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
					if(document.getElementById("Notecard_"+colors[i][0]) != null)
					{
						document.getElementById("blue_Notecard_"+colors[i][0]).style.display = "block";
						document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "blue";						
					}
				}
				else if(colors[i][1] == 6)
				{
					noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
					if(document.getElementById("Notecard_"+colors[i][0]) != null)
					{
						document.getElementById("purple_Notecard_"+colors[i][0]).style.display = "block";
						document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "purple";						
					}
				}
				
			}
		}	
		Ext.MessageBox.updateProgress(6/7,'Loading 7 / 7');
		Ext.MessageBox.updateProgress(7/7,'Loading complete');
		if(deletingNotecard == 0){
			Ext.MessageBox.hide();
			
		}
		//resize the layout after the initial break;
		resizeLayout();
	};
	var failure = function(o)
	{
		
	};

	//ajax call to the server to retrieve notecards with colors
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadColorsData&projectID='+projectID
   	});
}

 /*
  * function to load all the pile details
  */
function loadPileDetailFromDatabase()
{
	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";
			}
		}
		Ext.MessageBox.updateProgress(4/7,'Loading 4 / 7');
		getHTMLTree();
	}
	var failure = function(o)
	{
	};
	//ajax call to the server to load pile data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadPileData&projectID='+projectID
   	});	
}

 /*
  * function to load all the pile details
  */
function loadPileNoteRel()
{
	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];
			}
		}
		Ext.MessageBox.updateProgress(3/7,'Loading 3 / 7');
		loadPileDetailFromDatabase();
	}
	var failure = function(o)
	{
	};
	
	//ajax call to the server to load pile notecard relation
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadNotePileRel&projectID='+projectID
   	});	
}

// function to load Outline HTML tree
function getHTMLTree(){
	
	var projectID = document.getElementById('projectID').value;
	//function called on failure
	var failure = function(o){
	};
	var success = function(o){		
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		if (o.responseText.length > 10) {
			
			var prod1 = null;
			try {
				prod1 = YAHOO.lang.JSON.parse(o.responseText);
				this.body = prod1[0][0];				
				listCnt = prod1[0][1];
				itemCnt = prod1[0][2];
				document.getElementById("outline").innerHTML = this.body;
				createInstancesInOutline();
				Ext.MessageBox.updateProgress(4/7,'Loading 5 / 7');
				attachCues();				
                if(notecardID.length<2 && document.getElementById('help').value == "1"){
                        if(isTeacher != "1"){
                                bubble_NewNoteButton();
                        }
                }				
			} 
			catch (e) {
			}
		}else
		{
			listCnt = 1000;
			itemCnt = 1000;
			var failure = function(o){
		    };
		    var success = function(o){
				if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
				{			
					showNotesSessionError(Trim(o.responseText));
					return false;
				}
		    };
			OutlineHtml = document.getElementById("outline").innerHTML;
	    	
			Ext.Ajax.request({
		   		url: '../notecards/_includes/notecardOperations.php',
		   		method: 'POST',
		   		success: success,				   
		   		failure: failure,
				params: {
					toggle:'insertHTMLTree',
					projectID:projectID,
					data:OutlineHtml
				}
		   	});			
			createInstancesInOutline();
			
			Ext.MessageBox.updateProgress(4/7,'Loading 5 / 7');
			attachCues();
			
			var logsuccess = function(o)
			{
				
			};
			
			var logfailure = function(o)
			{
				
			};
						
			Ext.Ajax.request({
		   		url: '../notecards/_includes/notecardOperations.php',
		   		method: 'POST',
		   		success: logsuccess,				   
		   		failure: logfailure,
				params: {
					toggle:'loggethtml',
					data:OutlineHtml
				}
		   	});			
		}		
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=getHTMLTree&projectID='+projectID
   	});	
}

// function to save Outline HTML tree
	function saveHTMLTree(){
		if (itemInEditMode) {
			var el = Ext.get(itemInEditMode.substr(4));
			var val = Trim(document.getElementById("txt_" + itemInEditMode.substr(4)).value);
			if (val != "") {
				document.getElementById("content_div_" + el.id).innerHTML = document.getElementById("txt_" + itemInEditMode.substr(4)).value;
				document.getElementById("content_div_" + el.id).style.display = "block";
				document.getElementById(itemInEditMode).style.display = "none";
				enableBackSpace = false;
				itemInEditMode = null;
			}
			else {
				document.getElementById("content_div_" + el.id).innerHTML = "SubTopic"
				document.getElementById("content_div_" + el.id).style.display = "block";
				document.getElementById(itemInEditMode).style.display = "none";
				enableBackSpace = false;
				itemInEditMode = null;
			}
		}
		var projectID = document.getElementById('projectID').value;
		//function called on failure
		var handleFailure = function(o){
		};
		var handleSuccess = function(o){
			if ((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID")) {
				showNotesSessionError(Trim(o.responseText));
				return false;
			}
			
			var prod1 = null;
		};
		var callback = {
			success: handleSuccess,
			failure: handleFailure
		};
		// before saving convert the data to JSON string
		var OutlineHtml = (document.getElementById("outline").innerHTML);
		//ajax request to send html data
		Ext.Ajax.request({
			url: '../notecards/_includes/notecardOperations.php',
			method: 'POST',
			success: handleSuccess,
			failure: handleFailure,
			params: {
				toggle: 'saveHTMLTree',
				projectID: projectID,
				data: OutlineHtml,
				listCount: listCnt,
				itemCount: itemCnt
			}
		});
	//console.log('toggle=saveHTMLTree&projectID='+projectID+'&data='+OutlineHtml+'&listCount='+listCnt+'&itemCount='+itemCnt);  
	}

 /*
  * function to generate the tabletop
  */
function initLoading()
{
	var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item">',
            '<span>{title}</span>',
        '</div></tpl>'
    );
	var userID = document.getElementById('userID').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;
		}
		
		/*projects = YAHOO.lang.JSON.parse(o.responseText);
		if (projects != null && projects != "") {
			for (i = 0; i < projects.length; i++) {
				var projectTitle = projects[i][1];
				if(projectTitle.length >25){
					projectTitle = projectTitle.substr(0,25)+"...";
				}
				var opt = new Option(projectTitle, projects[i][0]);
				if (document.getElementById('projectID').value == projects[i][0]) {
					opt.selected = true;
				}
				var app = window.navigator.appName;
				if (!app.match("Netscape")) {
					document.getElementById('projectNames').add(opt);
				}
				else {
					document.getElementById('projectNames').add(opt, null);
				}
			}
		}*/
		
	};
	
	//ajax call to the server to insert notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadproject'
   	});	
	// Show the Panel
	loadNotecardDetailFromDatabase();
}

 /*
  * function to destroy the tabletop
  */
function initUnLoading()
{
	var handleSuccess = function(o)
	{
		
	};
	var handleFailure = function(o)
	{
		
	};
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params: 'toggle=clearWindowSession'
   	});
	/*
	var el  = YAHOO.util.Dom.getChildren('tabletop');
	for(i=0;i<el.length;i++)
	{
		if(el[i].id.match("Not") || el[i].id.match("Pil") || el[i].id.match("exp"))
		{
			var tabletop = new YAHOO.util.Element("tabletop");
			tabletop.removeChild(el[i]);
			var birdsEyeView = new YAHOO.util.Element("outer_hawk_eye");
			if(!el[i].id.match("exp"))
			{
				var thumb = new YAHOO.util.Element("thumb_"+el[i].id);
				birdsEyeView.removeChild(thumb);
			}
		}
	}
	document.getElementById('zoneList').innerHTML = "";
	outlineTxtHideMe();
	refreshPileNoteRelation();
	updateNotecardData();
	updatePileData();
	// This line is commented to make sure that blank outline is not submitted accidently.
	//saveHTMLTree();
	*/
}
// function to send ajax request to update the data related to all the notecards on the tabletop
function updateNotecardData()
{	
	var projectID = document.getElementById('projectID').value;
	
	var tempArr = new Array();
	//create a temporary array
	for(i=0;i<notecardID.length;i++)
	{
		tempArr[i] = [notecardID[i][0],notecardID[i][1],notecardID[i][2],notecardID[i][3],Ext.util.Format.htmlEncode(notecardID[i][4]),notecardID[i][5],notecardID[i][6],notecardID[i][7]];					
	}	
	var noteData = YAHOO.lang.JSON.stringify(tempArr);
	var handleSuccess = function(o)
	{
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
	};
	var handleFailure = function(o)
	{
		
	};
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params: {
			toggle: 'updateNoteDetail',
			data: noteData
		}
   	});
	
	// the following lines are commented to update the data on every enddrag of the notecard
	//notecardID = [];
	//pileNotecard = [];
}
// function to send ajax request to update the data related to all the piles on the tabletop
function updatePileData()
{
	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 failure=function(o)
	{
		alert("failure " + o.responseText);
	}
	
	// update the data of the piles in database
	var pileData = YAHOO.lang.JSON.stringify(pileID);
	
	// update the data of all the piles via ajax call	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: {
			toggle: 'updatePileDetail',
			data: pileData,
			projectID: projectID
		}
   	});		
		
	//the following lines are commented to update the data on every enddrag of the pile
	//pileID = [];
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function loadImages()
{
	MM_preloadImages('../notecards/_images/notecard.gif','../notecards/_images/notecard-selected.gif','../notecards/_images/notecard-pile.gif','../notecards/_images/notecard-pile-selected.gif','../notecards/_images/img/panelLeftBottom/corner-bottom-left.png','../notecards/_images/img/panelLeftBottom/corner-bottom-middle.png','../notecards/_images/img/panelLeftBottom/corner-bottom-right.png','../notecards/_images/img/panelLeftBottom/corner-middle-left.png','../notecards/_images/img/panelLeftBottom/corner-middle-right.png','../notecards/_images/img/panelLeftBottom/corner-top-left.png','../notecards/_images/img/panelLeftBottom/corner-top-middle.png','../notecards/_images/img/panelLeftBottom/corner-top-right.png','../notecards/_images/img/panelLeftTop/corner-bottom-left.png','../notecards/_images/img/panelLeftTop/corner-bottom-middle.png','../notecards/_images/img/panelLeftTop/corner-bottom-right.png','../notecards/_images/img/panelLeftTop/corner-middle-left.png','../notecards/_images/img/panelLeftBottom/corner-middle-right.png','../notecards/_images/img/panelLeftTop/corner-top-left.png','../notecards/_images/img/panelLeftTop/corner-top-middle.png','../notecards/_images/img/panelLeftTop/corner-top-right.png','../notecards/_images/img/panelRightBottom/corner-bottom-left.png','../notecards/_images/img/panelRightBottom/corner-bottom-middle.png','../notecards/_images/img/panelRightBottom/corner-bottom-right.png','../notecards/_images/img/panelRightBottom/corner-middle-left.png','../notecards/_images/img/panelRightBottom/corner-middle-right.png','../notecards/_images/img/panelRightBottom/corner-top-left.png','../notecards/_images/img/panelRightBottom/corner-top-middle.png','../notecards/_images/img/panelRightBottom/corner-top-right.png','../notecards/_images/img/panelRightTop/corner-bottom-left.png','../notecards/_images/img/panelRightTop/corner-bottom-middle.png','../notecards/_images/img/panelRightTop/corner-bottom-right.png','../notecards/_images/img/panelRightTop/corner-middle-left.png','../notecards/_images/img/panelRightTop/corner-middle-right.png','../notecards/_images/img/panelRightTop/corner-top-left.png','../notecards/_images/img/panelRightTop/corner-top-middle.png','../notecards/_images/img/panelRightTop/corner-top-right.png');
}
// handle the mouse down event on tabletop
function tabletopMouseDown(ev)
{
    //displayPopup=false;
	//set the appropriate cursor image on mousedown 
	//retrieve xy on mouse down event	
	mdx = parseInt(YAHOO.util.Event.getXY(ev)[0]);
	mdy = parseInt(YAHOO.util.Event.getXY(ev)[1]);
	down_x = YAHOO.util.Event.getPageX(ev);
	down_y = YAHOO.util.Event.getPageY(ev);	
	stopEditingonTabletop();
	scrollMe = true;
	// get the exploded piles and stop scrolling when clicked on them
	var el = YAHOO.util.Dom.getElementsByClassName('expandedPile');
	for(i=0;i<el.length;i++)
	{
		var expRegion = YAHOO.util.Dom.getRegion(el[0].id);
		var mouseRegion = new YAHOO.util.Point(mdx,mdy);
		if(mouseRegion.intersect(expRegion))
		{
			scrollMe = false;
		}
	}
}
// handle the mouse up event on tabletop
function tabletopMouseUp(ev)
{
    displayPopup = true;
	scrollMe = false;
}
// handle the mouse move on tabletop
function tabletopMouseMove(ev)
{
	if (scrollMe == true) {
		var el = YAHOO.util.Event.getTarget(ev);
		//set the appropriate cursor image on mousedown 
		//YAHOO.util.Dom.setStyle('tabletopContainer', 'cursor', 'url(../notecards/_images/icon-dragcursor.cursor), default');
		YAHOO.util.Dom.setStyle('tabletopContainer', 'cursor', 'move');
		//retrieve xy on mouse up event
		var mux = parseInt(YAHOO.util.Event.getXY(ev)[0]);
		var muy = parseInt(YAHOO.util.Event.getXY(ev)[1]);
		//calculate the difference between xy s of the mousedown and mouseup events
		thresholdx = 0-(mux - mdx);
		thresholdy = 0-(muy - mdy);
		myX = myX + thresholdx;
		myY = myY + thresholdy;
		if(myX < 0)
		{
			myX = 0;
		}
		if(myY < 0)
		{
			myY = 0;
		}
		if(Number(myY)+600 > 1500)
		{
			myY = 898;
		}
		if(Number(myX)+Number(tabletopViewWidth) > 3000)
		{
			myX = 2998-Number(tabletopViewWidth);
		}
		mdx = mux;
		mdy = muy;
		
		if (el.id == "tabletop") {
			document.getElementById('tabletopContainer').scrollTop=myY;
			document.getElementById('tabletopContainer').scrollLeft=myX;
			var birdsEyeViewTop = (document.getElementById('tabletopContainer').scrollTop/12);
			birdsEyeViewTop=birdsEyeViewTop+"px";
			var birdsEyeViewLeft = (document.getElementById('tabletopContainer').scrollLeft/12);
			birdsEyeViewLeft=birdsEyeViewLeft+"px";
			YAHOO.util.Dom.setStyle('viewable_area', 'top', birdsEyeViewTop);
			YAHOO.util.Dom.setStyle('viewable_area', 'left', birdsEyeViewLeft);
		}
	}
	else{
		//retrieve pagex, pagey and store them
		mousex = YAHOO.util.Event.getPageX(ev);
		mousey = YAHOO.util.Event.getPageY(ev);
	}
}

/*
 * function to collapse the outline
 */
function collapseOutline()
{
	var right = layout.getUnitByPosition('right');
	right.collapse();	
	 createBirdsEyeView();
}

function expandOutline()
{
	var right = layout.getUnitByPosition('right');
	right.expand();	
	createBirdsEyeView();
}

// function fired to end any editing on the tabletop
function stopEditingonTabletop()
{
	this.success = false;
	var el = YAHOO.util.Dom.getElementsByClassName('selected');
	if(el.length > 0)
	{
		if(itemInEditMode)
		{
			if(outlineTxtHideMe()){
				this.success = true;
			}else{
				this.success = false;
			}
			
		}
		else{
			document.getElementById(el[0].id).className = "";
			this.success = true;
		}
	}
	if(noteInEditMode)
	{
		hideMe();
		this.success = true;
	}else if(liNoteInEditMode)
	{
		endEditLiNotTitle();
		this.success = true;
	}else if(pileInEditMode){
		pileHideMe();
		this.success = true;
	}else{
		this.success = true;
	}
	
	return this.success;
}

// function to end editing in outline
function stopEditingonOutline()
{
	this.success = false;
	if(noteInEditMode)
	{
		hideMe();
		this.success = true;
	}
	if(liNoteInEditMode)
	{
		endEditLiNotTitle();
		saveHTMLTree();
		this.success = true;
	}
	return this.success;
}

// function to load new project
function LoadProject(projectid)
{	
	if (projectid != 'a') {
		
		//expand the outline
		expandOutline();

		var parent = new YAHOO.util.Dom.get('projectNames');
		var child = YAHOO.util.Dom.getChildren(parent);
		for (i = 1; i < child.length; i++) {
			parent.removeChild(child[i]);
		}
		initUnLoading();
		notecardID = [];
		pileID = [];
		pileNotecard = [];
		notecardsOutline = [];
		document.getElementById("outline").innerHTML = "";
		this.body = "<ol id=list_1 type='I'>";
		this.body = this.body + "<li class=liclass id=item_1 ><div id=content_div_item_1 onmouseover=mouseOverItem('content_div_item_1') onmouseout=mouseOutItem('content_div_item_1') ondblClick=editOutlineItem('content_div_item_1') onClick=actionOnOutlineList('content_div_item_1')>Topic</div><div style='width:auto;display:none;' id=div_item_1><input onclick=javascript:this.focus(); type=text id=txt_item_1 onfocus='javascript:enableBackSpace=true;'></div>";
		this.body = this.body + "<ol id=list_2 ></ol>"
		this.body = this.body + "<ol id=list_3 type='A'>";
		this.body = this.body + "<li class=liclass id=item_2 ><div id=content_div_item_2 onmouseover=mouseOverItem('content_div_item_2') onmouseout=mouseOutItem('content_div_item_2') ondblClick=editOutlineItem('content_div_item_2') onClick=actionOnOutlineList('content_div_item_2')>Sub Topic</div><div style='width:auto;display:none;' id=div_item_2><input onclick=javascript:this.focus(); type=text id=txt_item_2 onfocus='javascript:enableBackSpace=true;'></div>";
		this.body = this.body + "<ol id=list_4></ol><ol id=list_5></ol></li>";
		this.body = this.body + "</ol>"
		this.body = this.body + "</li>";
		this.body = this.body + "</ol>"
		var div = document.createElement("ol");
		div.innerHTML = this.body;
		document.getElementById("outline").appendChild(div.firstChild);
		new YAHOO.util.DDTarget('content_div_item_2', "topslots");
		new YAHOO.util.DDTarget('content_div_item_1', "topslots");
		new YAHOO.util.DragDrop('content_div_item_2');
		new YAHOO.util.DragDrop('content_div_item_1');
		document.getElementById("projectID").value = projectid;
		loadingGraphics();
		initLoading();
		document.getElementById("search_field").value = "";
		document.getElementById("boolean_and").checked = true;
		document.getElementById("boolean_or").checked = false;
	}
}

// function to load menu
function loadTagsMenu()
{
	//hide summ popups
	hidePopupOnDrag();
	var 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);
			allTags = [];
			allTags = this.data;
			var sel = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
			var disabled = false;
			if (sel.length > 0) {
				disabled = false;
			}
			else {
				disabled = true;
			}
			
			// menu for color
			Colmenu = new Ext.menu.Menu({
				id: 'Colmenu'
			});
			var item = Colmenu.add({
				text: 'Red',
				icon: '../notecards/_images/tag-red.gif',
                                id: 'appRed1',
                                handler: setColor,
				menu: {
					items: [{
						id: 'appRed',
						text: 'Apply',
						disabled: disabled,
						handler: setColor
					}, {
						id: 'remRed',
						text: 'Remove',
						disabled: disabled,
						handler: removeColor
					}]
				}
			});
			var item = Colmenu.add({
				text: 'Orange',
                                id: 'appOrange1',
				icon: '../notecards/_images/tag-orange.gif',
                                handler: setColor,
				menu: {
					items: [{
						id: 'appOrange',
						text: 'Apply',
						disabled: disabled,
						handler: setColor
					}, {
						id: 'remOrange',
						text: 'Remove',
						disabled: disabled,
						handler: removeColor
					}]
				}
			});
			var item = Colmenu.add({
				text: 'Yellow',
                                id: 'appYellow1',
				icon: '../notecards/_images/tag-yellow.gif',
                                handler: setColor,
				menu: {
					items: [{
						id: 'appYellow',
						text: 'Apply',
						disabled: disabled,
						handler: setColor
					}, {
						id: 'remYellow',
						text: 'Remove',
						disabled: disabled,
						handler: removeColor
					}]
				}
			});
			var item = Colmenu.add({
				text: 'Green',
                                id: 'appGreen1',
				icon: '../notecards/_images/tag-green.gif',
                                handler: setColor,
				menu: {
					items: [{
						id: 'appGreen',
						text: 'Apply',
						disabled: disabled,
						handler: setColor
					}, {
						id: 'remGreen',
						text: 'Remove',
						disabled: disabled,
						handler: removeColor
					}]
				}
			});
			var item = Colmenu.add({
				text: 'Blue',
                                id: 'appBlue1',
				icon: '../notecards/_images/tag-blue.gif',
                                handler: setColor,
				menu: {
					items: [{
						id: 'appBlue',
						text: 'Apply',
						disabled: disabled,
						handler: setColor
					}, {
						id: 'remBlue',
						text: 'Remove',
						disabled: disabled,
						handler: removeColor
					}]
				}
			});
			var item = Colmenu.add({
				text: 'Purple',
                                id: 'appPur1',
				icon: '../notecards/_images/tag-purple.gif',
                                handler: setColor,
				menu: {
					items: [{
						id: 'appPur',
						text: 'Apply',
						disabled: disabled,
						handler: setColor
					}, {
						id: 'remPur',
						text: 'Remove',
						disabled: disabled,
						handler: removeColor
					}]
				}
			});
			
			// menu for visual cues
			cuesMenu = new Ext.menu.Menu({
				id: 'cuesMenu',
				minWidth : 200
			});
			var item = cuesMenu.add({
				text: 'Needs further research',
				icon: '../notecards/_images/tag-magnify.gif',
                                id: 'addResearch1',
                                handler: setCues,
				menu: {
					items: [{
						id: 'addResearch',
						text: 'Apply',
						disabled: disabled,
						handler: setCues
					}, {
						id: 'remResearch',
						text: 'Remove',
						disabled: disabled,
						handler: removeCues
					}]
				}
			});
			var item = cuesMenu.add({
				text: 'Need help',
				icon: '../notecards/_images/tag-question.gif',
                                id: 'addHelp1',
                                handler: setCues,
				menu: {
					items: [{
						id: 'addHelp',
						text: 'Apply',
						disabled: disabled,
						handler: setCues
					}, {
						id: 'remHelp',
						text: 'Remove',
						disabled: disabled,
						handler: removeCues
					}]
				}
			});
			var item = cuesMenu.add({
				text: 'Incomplete',
				icon: '../notecards/_images/tag-document.gif',
                                id: 'addIncomplete1',
                                handler: setCues,
				menu: {
					items: [{
						id: 'addIncomplete',
						text: 'Apply',
						disabled: disabled,
						handler: setCues
					}, {
						id: 'remIncomplete',
						text: 'Remove',
						disabled: disabled,
						handler: removeCues
					}]
				}
			});
			var item = cuesMenu.add({
				text: 'Original thinking',
				icon: '../notecards/_images/tag-lightbulb.gif',
                                id: 'addThinking1',
                                handler: setCues,
				menu: {
					items: [{
						id: 'addThinking',
						text: 'Apply',
						disabled: disabled,
						handler: setCues
					}, {
						id: 'remThinking',
						text: 'Remove',
						disabled: disabled,
						handler: removeCues
					}]
				}
			});
			var item = cuesMenu.add({
				text: 'Important',
				icon: '../notecards/_images/tag-attention.gif',
                                id: 'addImportant1',
                                handler: setCues,
				menu: {
					items: [{
						id: 'addImportant',
						text: 'Apply',
						disabled: disabled,
						handler: setCues
					}, {
						id: 'remImportant',
						text: 'Remove',
						disabled: disabled,
						handler: removeCues
					}]
				}
			});
			var item = cuesMenu.add({
				text: 'Used in paper',
				icon: '../notecards/_images/tag-checkmark.gif',
                                id: 'addPaper1',
                                handler: setCues,
				menu: {
					items: [{
						id: 'addPaper',
						text: 'Apply',
						disabled: disabled,
						handler: setCues
					}, {
						id: 'remPaper',
						text: 'Remove',
						disabled: disabled,
						handler: removeCues
					}]
				}
			});
			
			// menu for tags		
			tagsMenu = new Ext.menu.Menu({
				id: 'tagsMenu',
				minWidth: 150
			});
			if (allTags != null) {
				for (i = 0; i < allTags.length; i++) {
					var str = allTags[i][1];
					if(str.length > 10){
						var TagText = allTags[i][1].substr(0,10)+"....";
					}else{
						var TagText = allTags[i][1];
					}
					var item = tagsMenu.add({
						text: TagText,
                                                id: "1Apply_"+allTags[i][0],
                                                handler : applyMyTag,
						menu : {
							items : [{
								id: "Apply_"+allTags[i][0],
								text : 'Apply',
								disabled : disabled,
								handler : applyMyTag
							}, {
								id: "Remove_"+allTags[i][0],
								text : 'Remove',
								disabled : disabled,
								handler : removeMyTag
							}]
						}
					});
				}
			}
			else {
				var item = tagsMenu.add({
					text: "Empty",
					disabled: true
				});
			}
			
			var menu = new Ext.menu.Menu({
				id: 'mainMenu'
			});
			var item = menu.add({
				text: 'Colors',
				menu: Colmenu
			});
			var item = menu.add({
				text: 'Visual Cues',
				menu: cuesMenu
			});
			var item = menu.add({
				text: 'Tags',
				menu: tagsMenu
			});
			var item = menu.add({
				text: 'Edit/Delete Tags',
				handler: tagsGrid
			});
			
			
			menu.show('menuButton');
		};
		
		//ajax call to the server to insert notecard data
		Ext.Ajax.request({
	   		url: '../notecards/_includes/notecardOperations.php',
	   		method: 'POST',
	   		success: success,				   
	   		failure: failure,
			params: 'toggle=loadTags&projectid='+projectid
	   	});				
}
 
// function to generate a comments screen
function comments(note){
	
	var successFn = function(o){		
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		var complete_result = Ext.decode(o.responseText);		
		var notecardDetail = complete_result[0];
		var frmTabPanel = new Ext.FormPanel({
			width: 685,
			height: 200,
			frame: true,
			items: [new Ext.TabPanel({
				autoScroll:true,
				activeTab: 0,
				height:200,
				width: 675,
				items: [{
					id:'tabquote',	
					autoScroll:true,	
					title: 'Direct Quotes',
					html: notecardDetail[1]
				}, {
					id:'tabparaphrase',
					title: 'Paraphrase',
					autoScroll:true,
					html: notecardDetail[2]
				}, {
					id:'tabideas',
					title: 'My ideas',
					autoScroll:true,
					html: notecardDetail[3]
				}]
			})]
		});
		frmcommentPanel = new Ext.FormPanel({
			url: '../notecards/_includes/notecardOperations.php',
			labelAlign: 'top',
			frame: true,
			
			width: 685,
			autoScroll: true,
			height: 331,
			cls: "../_css/noodlenotes.css",
			items: [{
				width:610,
				layout: 'column',
				bodyStyle: 'padding:5px 5px 5px 5px',
				items: [{
					xtype: 'label',
					html: '&nbsp;',
					columnWidth: .1
				}, {
					xtype: 'label',
					html: '&nbsp;',
					columnWidth: .3
				}, {
					xtype: 'label',
					html: 'Comment',
					columnWidth: .6
				}, {
					xtype: 'textfield',
					value: 'savePredefinedComment',
					id: 'toggle',
					name: 'toggle',
					hidden: true
					
				}, {
					xtype: 'textfield',
					value: note,
					id: 'noteid',
					name: 'noteid',
					hidden: true
					
				},{
					xtype: 'textfield',
					id: 'selectedComments',
					name: 'selectedComments',
					hidden: true
					
				}]
			}]
		
		});
		
		commentsWin = new Ext.Window({
			width: 700,
			height: 600,
			cls: "../_css/noodlenotes.css",
			title: 'Notecard Comments',			
			buttonAlign: 'center',
			closable: true,
			autoScroll: true,
			bodyStyle: 'padding:0px 0px 0px 0px',
			draggable: false,
			listeners: {
				'close': {
					fn: function(commentsWin){
						//retrieve isTeacher boolean									
						/*var isTeacher = document.getElementById("isTeacher").value;
						if (isTeacher == 0) {
						
						}*/
					}
				},
				'show': {
					fn: function(win){
						//frmTabPanel.setActiveTab('quote');
					}
				}
			},
			modal: true,
			items: [frmTabPanel, frmcommentPanel],
			buttons: [{
				text: 'Submit',
				id: 'submitComm',
				disabled : true,
				handler: function(){
					var submit = true;
					/*for(ij=0;ij<commArr.length;ij++){
						if(Ext.util.Format.trim(Ext.get('preCommText_'+commArr[ij]).getValue()) == ""){
							submit = false;							
						}
					}*/
					if (submit) {
						frmcommentPanel.getForm().submit({
							method: 'POST',
							waitTitle: 'Connecting',
							waitMsg: 'Saving...',
							success: function(form, action){
								document.getElementById('comm_row_' + note).style.visibility = "visible";
								document.getElementById('comm_row_' + note).style.display = "block";
								var comm = Ext.util.JSON.decode(action.response.responseText);
								var parentul = document.getElementById('list_comments_' + note);
								parentul.innerHTML = comm.data.html + parentul.innerHTML;
								commentsWin.close();
								
							},
							
							// 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){
								alert("fail");
							}
						});
					}else{
						Ext.Msg.alert('Error', 'Comment Text cannot be left blank.');
					}
				}
			},{
				text: 'Cancel',
				handler: function(){
					commentsWin.close();
				}
			}]
		});
		
		commentsWin.show();
		var resp = complete_result[1];
		if (resp != null && resp != "") {
			for (k = 0; k < resp.length; k++) {
				addGroup(resp[k][0],resp[k][1]);
			}
		}
	}
	var failFn = function(o){
		
	}
	Ext.Ajax.request({
		url: '../notecards/_includes/notecardOperations.php',
		method: 'POST',
		success: successFn,
		failure: failFn,
		params: 'toggle=getPredefinedCommentOfNotecard&note_id='+note
	});
	commArr = [];
}

function addGroup(groupName,CommentList){
	var grpNameComp = {
						xtype:'label',	
						html: groupName,
						columnWidth: 1
					}
	frmcommentPanel.add(grpNameComp);
	
	addPredefinedCommentComponentToPanel(CommentList);
}

function addPredefinedCommentComponentToPanel(commList){
	
	for (i = 0; i < commList.length; i++) {
		it = {
			layout:'column',
			width:650,
			items: [{
				bodyStyle: 'padding:5px 5px 5px 5px',
				layout: 'column',
				items: [{					
					xtype: 'label',
					html: '&nbsp;',
					columnWidth: .5
				}, {					
					xtype: 'checkbox',
					style: 'margin-top:5px',
					id: 'preComm_' + commList[i][0],
					listeners:{
						'check': {
							fn: function(chkbox, checked){
								var chkBoxID = chkbox.id.split("_");
								if(checked){
									commArr[commArr.length] = chkBoxID[1];
									Ext.getCmp('submitComm').enable();
								}else{
									for(i=0;i<commArr.length;i++){
										if(commArr[i] == chkBoxID[1]){
											commArr.splice(i,1);
											i=-1;
										}
									}
									if(commArr.length == 0){
										Ext.getCmp('submitComm').disable();
									}
								}
								Ext.getCmp('selectedComments').setValue(Ext.encode(commArr));
							}
						}
					},
					columnWidth: .5
				}],
				columnWidth: .1
			}, {
				xtype: 'label',
				style: 'margin-top:5px',
				id: 'CommText_' + commList[i][0],
				text: commList[i][1],
				columnWidth: .15
			}, {
				xtype: 'box',
				height:100,
			    autoEl: {
			        tag: 'textarea',
					id: 'preCommText_' + commList[i][0],
					name: 'preCommText_' + commList[i][0],
			        style: 'width:900px; overflow-y:scroll; margin-top:5px',
					html: commList[i][2]
			    },
				columnWidth: .75
				
			}]
		}
		frmcommentPanel.add(it);
		frmcommentPanel.doLayout();
		
	}
}


function onItemCheck(item)
{
	
}

function loadingGraphics()
{
	Ext.MessageBox.show({
           title: 'Please wait',
           msg: 'Loading...',
           progressText: 'Initializing...',
           width:300,
           progress:true,
           closable:false
       });

      Ext.MessageBox.updateProgress(1/7,'Loading 1 / 7');
}


// function to load all the tags for that project
function loadTags(){
	var arr;
	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);
		allTags = [];
		allTags = this.data;
		arr = allTags;
	};	
	//ajax call to the server to load tags data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: success,				   
   		failure: failure,
		params: 'toggle=loadTags&projectid='+projectid
   	});	
	
	return arr;
}
function alphanumeric(alphane)
{
	var numaric = alphane;
	for(var j=0; j<numaric.length; j++)
	{
		var alphaa = numaric.charAt(j);
		var hh = alphaa.charCodeAt(0);
		if((hh > 32 && hh < 65) || (hh > 64 && hh < 94) || (hh > 96 && hh <= 122 || hh==32 || hh==123 || hh==125 || hh==124 || hh==95))
		{
			
		}
		else	
		{
			 return false;
		}
	}
 	return true;
}

/*
 * function to validate pile title
 */
function alphaNumPile(alpha)
{
	var number = alpha;
	for(var j=0; j<number.length; j++)
	{
		var alphaa = number.charAt(j);
		var hh = alphaa.charCodeAt(0);
		if((hh > 64 && hh < 93) || (hh > 47 && hh < 58) || (hh > 96 && hh <= 122 || hh==32))
		{
			
		}
		else	
		{
			 return false;
		}
	}
 	return true;	
}

// this function only update notecards data

function updateNotecards(){
	var projectID = document.getElementById('projectID').value;
	
	var tempArr = new Array();
	//create a temporary array
	for(i=0;i<notecardID.length;i++)
	{
		tempArr[i] = [notecardID[i][0],notecardID[i][1],notecardID[i][2],notecardID[i][3],Ext.util.Format.htmlEncode(notecardID[i][4]),notecardID[i][5],notecardID[i][6],notecardID[i][7]];					
	}	
	var noteData = Ext.encode(tempArr);
		
	var handleSuccess = function(o)
	{
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
	};
	var handleFailure = function(o)
	{
		
	};
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params: {
			toggle: 'updateNoteDetail',
			data: noteData,
			projectID: projectID
		}
   	});	
}