/**
 * @author amore
 * class to define the notecard
 */

// var to store the edit notecard window
var editNoteWin;

// function to create a HTML structure for the notecard
function NoteCardTemplate(id, title)
{
	/*
	 * property to set id for the notecard
	 */
	this.id = id;
	
	/*
	 * property to set title for the notecard
	 */
	if (title.length > 10) {
		this.title = title.substr(0,9)+"...";
	}else{
		this.title = title;
	}
	if(isTeacher != "1"){
		this.body = "<div id="+this.id+" ondblclick=directEditNotecard('"+this.id+"') class=notecard onClick=highlightMe('"+this.id +"','click')>";
		this.body = this.body + "<div class=notecardContent onmouseover=invokePopup('"+this.id+"') onmouseout=hideInfoPopup()>";
		this.body = this.body + "<div id=colorsContainer_"+this.id+" class=colorsContainer>";
		this.body = this.body + "<div id=check_"+this.id+" style=float:left;display:none;height:6px;width:6px;padding:1px;background-image:url('../notecards/_images/check-mark-icon.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=red_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-red1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=orange_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-orange1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=yellow_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-yellow1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=green_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-green1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=blue_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-blue1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=purple_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-purple1.gif');background-repeat:no-repeat;></div>";				
		this.body = this.body + "</div>";
		this.body = this.body + "<div id=tagsContainer_"+this.id+" class=tagsContainer>";	
		this.body = this.body + "<div id=research_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-magnify.gif');></div>";
		this.body = this.body + "<div id=help_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-question.gif');></div>";
		this.body = this.body + "<div id=incomplete_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-document.gif');></div>";
		this.body = this.body + "<div id=thinking_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-lightbulb.gif');></div>";		
		this.body = this.body + "<div id=important_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-attention.gif');></div>";
		this.body = this.body + "<div id=paper_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-checkmark.gif');></div>";	
		this.body = this.body + "</div>";
		this.body = this.body + "</div>";
		this.body = this.body + "<div id=title_"+this.id+" class=notecardTitle onClick=editMe('title_"+this.id+"') onmouseover=mouseOverTitle('title_"+this.id+"') onmouseout=mouseOutTitle('title_"+this.id+"')>"+this.title+"</div><div class=notecardEdit id=txt_container_"+this.id+"><input type=text id=txt_title_"+this.id+" class=editableText onclick=javascript:this.focus();></div>";
		this.body = this.body + "</div>";
	}else{
		this.body = "<div id="+this.id+" ondblclick='editNoteID=\'"+this.id+"\';editNotecard();' class=notecard onClick=highlightMe('"+this.id +"','click')>";
		this.body = this.body + "<div class=notecardContent onmouseover=invokePopup('"+this.id+"') onmouseout=hideInfoPopup()>";
		this.body = this.body + "<div id=colorsContainer_"+this.id+" class=colorsContainer >";
		this.body = this.body + "<div id=check_"+this.id+" style=float:left;display:none;height:6px;width:6px;padding:1px;background-image:url('../notecards/_images/check-mark-icon.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=red_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-red1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=orange_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-orange1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=yellow_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-yellow1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=green_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-green1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=blue_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-blue1.gif');background-repeat:no-repeat;></div>";
		this.body = this.body + "<div id=purple_"+this.id+" style=float:left;display:none;height:6px;width:6px;background-image:url('../notecards/_images/tag-purple1.gif');background-repeat:no-repeat;></div>";				
		this.body = this.body + "</div>";
		this.body = this.body + "<div id=tagsContainer_"+this.id+" class=tagsContainer>";	
		this.body = this.body + "<div id=research_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-magnify.gif');></div>";
		this.body = this.body + "<div id=help_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-question.gif');></div>";
		this.body = this.body + "<div id=incomplete_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-document.gif');></div>";
		this.body = this.body + "<div id=thinking_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-lightbulb.gif');></div>";		
		this.body = this.body + "<div id=important_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-attention.gif');></div>";
		this.body = this.body + "<div id=paper_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-checkmark.gif');></div>";	
		this.body = this.body + "</div>";
		this.body = this.body + "</div>";
		this.body = this.body + "<div id=title_"+this.id+" class=notecardTitle >"+this.title+"</div><div class=notecardEdit id=txt_container_"+this.id+"><input type=text id=txt_title_"+this.id+" class=editableText onclick=javascript:this.focus();></div>";
		this.body = this.body + "</div>";
	}
	
	/*
	 * function to return html for the notecard
	 */
	NoteCardTemplate.prototype.toHTML = function()
	{
		return this.body;
	};
	
	/*
	 * function to return the title of the notecard
	 */
	NoteCardTemplate.prototype.showTitle = function()
	{
		return this.title;
	};
}

/*
 * function for event handling on notecard
 */
 
(function() {
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;
var target = "";


YAHOO.example.DDNotecard = function(id, sGroup, config) {
    YAHOO.example.DDNotecard.superclass.constructor.call(this, id, sGroup, config);
    var el = this.getDragEl();
	var body = document.getElementById('outerDiv');
	var div = document.getElementById('ygddfdiv');
	body.insertBefore(div, body.firstChild);
	YAHOO.example.DDNotecard.mode = 2;
};

YAHOO.extend(YAHOO.example.DDNotecard, YAHOO.util.DDProxy, {
    startDrag: function(x, y) {
    	hideHelpBubble();
        stopEditingonTabletop();
		this.dropped=false;
        // make the proxy look like the source element
        var dragEl = this.getDragEl();
        var clickEl = this.getEl();
        var el = Ext.get(dragEl.id);
        el. setOpacity(.5, true);
        
        Dom.setStyle(clickEl, "display", "none");
		hideMe();
        dragEl.innerHTML = clickEl.innerHTML;
		document.getElementById(dragEl.id).className = document.getElementById(clickEl.id).className;
        Dom.setStyle(dragEl, "border", "0px solid gray");
        Dom.setStyle(dragEl, "cursor", "pointer");
		this.target = "";
		// change the id of inner child of proxy element
      	var children = YAHOO.util.Dom.getChildren(this.getDragEl().id);
		document.getElementById(children[1].id).id = "";
		
		hidePopupOnDrag();
    },

    endDrag: function(e) {
		var srcEl = this.getEl();
        var proxy = this.getDragEl();
		var xy = Dom.getXY(proxy);
		if(this.dropped == true)
		{
			if(!this.target.match("li_Not") && this.target.match("Not"))
			{
				document.getElementById(srcEl.id).style.display = "block";
			}
			else if(this.target.match("view"))
			{
				document.getElementById(srcEl.id).style.display = "block";
			}else if(this.target.match("content"))
			{
				document.getElementById(srcEl.id).style.display = "block";
			}
			else{
				document.getElementById(srcEl.id).style.display = "none";
			}
		}
		if(this.dropped == false)
		{
			document.getElementById(srcEl.id).style.display = "block";
		}
		Dom.setXY(srcEl, xy);
		var regionNotecard = YAHOO.util.Region.getRegion(this.getDragEl());
		var regionOutline = YAHOO.util.Region.getRegion(YAHOO.util.Dom.get('outline'));
		var regionbirdseyeView = YAHOO.util.Region.getRegion(YAHOO.util.Dom.get('outer_hawk_eye'));
		var notecardRegion = YAHOO.util.Dom.getRegion('notecardRegion');
		if(regionNotecard.intersect(regionOutline) == null && regionNotecard.intersect(notecardRegion) == null)
		{
			// update the position of notecards
			var leftTopPos = getLeftTopInTabletop(this.getEl().id);
			for(i=0;i<notecardID.length;i++)
			{
				if(notecardID[i][0] == this.getEl().id)
				{
					if(leftTopPos[0] > 2932)
					{
						leftTopPos[0] = "2932";
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if(leftTopPos[1] > 1400)
					{
						leftTopPos[1] = "1400";
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if(leftTopPos[0] < 10)
					{
						leftTopPos[0] = 10;
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if(leftTopPos[1] < 10)
					{
						leftTopPos[1] = 10;
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if (!regionNotecard.intersect(regionbirdseyeView)) {
						notecardID[i][1] = leftTopPos[0];
						notecardID[i][2] = leftTopPos[1];
					}
					document.getElementById('tabletop').style.width = "3000px";
					document.getElementById('tabletop').style.height = "1500px";
				}
			}
		}
		else if(document.getElementById('second-half').style.visibility == "hidden")
		{
			// update the position of notecards
			var leftTopPos = getLeftTopInTabletop(this.getEl().id);
			for(i=0;i<notecardID.length;i++)
			{
				if(notecardID[i][0] == this.getEl().id)
				{
					if(leftTopPos[0] > 2932)
					{
						leftTopPos[0] = 2932;
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if(leftTopPos[1] > 1400)
					{
						leftTopPos[1] = 1400;
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if(leftTopPos[0] < 10)
					{
						leftTopPos[0] = 10;
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if(leftTopPos[1] < 100)
					{
						leftTopPos[1] = 100;
						document.getElementById('tabletop').style.width = "3000px";
						document.getElementById('tabletop').style.height = "1500px";
					}
					if (!regionNotecard.intersect(regionbirdseyeView)) {
						notecardID[i][1] = leftTopPos[0];
						notecardID[i][2] = leftTopPos[1];
					}
					document.getElementById('tabletop').style.width = "3000px";
					document.getElementById('tabletop').style.height = "1500px";
				}
			}
		}
		
		for(i=0;i<notecardID.length;i++)
		{
			if(notecardID[i][0] == this.getEl().id)
			{
				var pos = new Array(); 
				pos[0] = notecardID[i][1];
				pos[1] = notecardID[i][2];
				setLeftTopInTabletop(this.getEl().id, pos);
			}
		}
		var notecardId = this.getEl().id;
		setLeftTopInBirdsEyeView(notecardId,getLeftTopInTabletop(notecardId));
		
		this.dropped= false;
		document.getElementById("ygddfdiv").innerHTML = "";
		updateNotecardData();
		hidePopupOnDrag();
    },

    onDragDrop: function(e, id) {
    	hidePopupOnDrag();
    	if(YAHOO.util.DragDropMgr.interactionInfo.drop.length>0){
    		id = YAHOO.util.DragDropMgr.getBestMatch(YAHOO.util.DragDropMgr.interactionInfo.drop);
	    	var el = YAHOO.util.DragDropMgr.getElement(id);
	    	id = el.id;
	    	YAHOO.util.DragDropMgr.interactionInfo.drop = [];
	    	this.dropped = true;
    		var regionNotecard = YAHOO.util.Region.getRegion(this.getDragEl());
			var outlineRegion = YAHOO.util.Dom.getRegion('outline');
			var notecardRegion = YAHOO.util.Dom.getRegion('notecardRegion');
			if(regionNotecard.intersect(outlineRegion) != null)
			{
				var el = YAHOO.util.Dom.getElementsByClassName('hover_li');
				if (el != null && el != "") {
					id = "content";
					YAHOO.util.DragDropMgr.interactionInfo.drop = [];
					this.dropped = true;
				}else{
					if(id.match("item")){
						this.dropped = false;
					}
				}
			}else if(regionNotecard.intersect(notecardRegion) != null)
			{
				this.dropped = false;
			}
			if (id.match("li_Not")) {
				this.dropped = false;
			}
			else 
				if (id.match("li_Pile")) {
					this.dropped = true;
				}
			if(this.dropped){
				this.target = id;
				// Get the id of notecard over which this element was dragged
				var str = YAHOO.util.DragDropMgr.getElement(id);
				// check if the element over which our notecard is dragged, is visible or not
				this.dropped=true;
				// set the indication to form pile as true
				this.formPile = true;
				var element_name = new String();
				element_name = str.id;
				
				if (element_name.match("li_Pi")) {
				
					
					// create an li element
					var note_li = new NotesLi(this.getEl().id);
					var div = document.createElement("ol");
					div.innerHTML = note_li.toHTML();
					document.getElementById(str.id).appendChild(div.firstChild);
					// set the visibility of li element as hidden
					YAHOO.util.Dom.setStyle("li_" + this.getEl().id, "display", "none");
					// set the position of proxy element to that of notecard
					var xy = YAHOO.util.Dom.getXY(this.getEl().id);
					
					YAHOO.util.Dom.setStyle("ygddfdiv", "visibility", "visible");
					document.getElementById("ygddfdiv").className = "noteli";
					// create the animation
					var a = new YAHOO.util.Motion("ygddfdiv", {
						points: {
							to: YAHOO.util.Dom.getXY("li_" + this.getEl().id)
						}
					}, 0.2, YAHOO.util.Easing.easeOut);
					var proxyid = "ygddfdiv";
					var thisid = "li_" + this.getEl().id;
					
					// Hide the proxy and show the source element when finished with the animation
					a.onComplete.subscribe(function(){
						YAHOO.util.Dom.setStyle(proxyid, "visibility", "hidden");
						YAHOO.util.Dom.setStyle(thisid, "display", "block");
					});
					document.getElementById(proxyid).style.visibility = "visible";
					a.animate();
					//set the xy coordinates of the notecard to 0,0 
					document.getElementById(this.getEl().id).style.left = "0px";
					document.getElementById(this.getEl().id).style.top = "0px";
					
					xy = "";
					// insert an entry of this relation
					inserPileNoteRelation(element_name.substr(3), this.getEl().id);
					this.formPile = false;
					element_name = "";
					document.getElementById("thumb_" + this.getEl().id).style.display = "none";
					// hide the current notecard
					document.getElementById(this.getEl().id).style.display = "none";
					for (i = 0; i < notecardID.length; i++) {
						if (notecardID[i][0] == this.getEl().id) {
							notecardID[i][6] = "none";
						}
					}
					updatePileNoteRelInDatabase();
				}
				else 
					if (element_name.match("Pile_")) {
						overElement = this.getEl().id;
						
						// insert an entry of this relation
						inserPileNoteRelation(element_name, overElement);
						for (i = 0; i < notecardID.length; i++) {
							if (notecardID[i][0] == overElement) {
								notecardID[i][3] = "";
							}
						}
						document.getElementById('txt_' + str.id).innerHTML = notecardCountInPile(element_name);
						shakeMe(element_name);
						this.formPile = false;
						updatePileNoteRelInDatabase();
						document.getElementById(this.getEl().id).style.display = "none";
						document.getElementById("thumb_" + this.getEl().id).style.display = "none";
						for (i = 0; i < notecardID.length; i++) {
							if (notecardID[i][0] == this.getEl().id) {
								notecardID[i][6] = "none";
							}
						}
					}
					else 
						if (element_name.match("Not")) {
							posXY = getLeftTopInTabletop(id);
							
							document.getElementById(this.getEl().id).style.display = "block";
							// show the overlay to get notecard title
							showPileOverlay();
							
							// store the items in action
							overElement = this.getEl().id;
							underElement = str.id;
							
						}
						else 
							if (id.match("content")) {
								var noteid = this.getEl().id;
								var className = document.getElementById(noteid).className;
								if (className.match("Yellow")) {
									className = "li_notecard_outline_selected";
								}
								else {
									className = "li_notecard_outline";
								}
								var el = YAHOO.util.Dom.getElementsByClassName('hover_li');
								if (el.length == 1) {
									this.exists = false;
									var sibling1 = YAHOO.util.Dom.getNextSibling(el[0].id);
									var sibling = YAHOO.util.Dom.getNextSibling(sibling1.id);
									if (sibling == null) {
										var body = "<ol id=list_" + ++listCnt + " class=licalss></ol>";
										var div = document.createElement("ol");
										div.innerHTML = body;
										document.getElementById(Ext.get(el[0].id).parent("li", false).id).appendChild(div.firstChild);
										sibling = Ext.get("list_" + listCnt);
										var failure1 = function(o){
										};
										var success1 = function(o){
											if ((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID")) {
												showNotesSessionError(Trim(o.responseText));
												return false;
											}
											var cntArr = Ext.decode(o.responseText);
											listCnt = cntArr[0][1];
										}
										Ext.Ajax.request({
											url: '../notecards/_includes/notecardOperations.php',
											method: 'POST',
											success: success1,
											failure: failure1,
											params: 'toggle=incrementOutlineListCounters&count=1'
										});
										
									}
									var children = YAHOO.util.Dom.getChildren(sibling.id);
									for (i = 0; i < children.length; i++) {
										var children1 = YAHOO.util.Dom.getChildren(children[i].id);
										for (j = 0; j < children1.length; j++) {
											if (children1[j].id.match(noteid + "_")) {
												Ext.MessageBox.show({
													title: 'Notecard Exists',
													msg: 'This notecard already exists under this topic.',
													buttons: Ext.MessageBox.OK,
													icon: Ext.MessageBox.ERROR
												});
												this.exists = true;
												var el1 = YAHOO.util.Dom.getElementsByClassName('hover_li');
												document.getElementById(id).className = "";
											}
										}
									}
									
									if (this.exists == false) {
										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;
											}
											
											hidePopupOnDrag();
											var cntArr = Ext.decode(o.responseText)
											listCnt = cntArr[0][1];
											itemCnt = cntArr[0][2];
											var li_html = "<li class=" + className + " id = item_" + itemCnt + "><div class=unbold onclick=actionOnOutlineList('div_" + noteid + "_item_" + itemCnt + "') id = div_" + noteid + "_item_" + itemCnt + "></div></li>";
											var div = document.createElement('ol')
											div.innerHTML = li_html;
											document.getElementById(sibling.id).appendChild(div.firstChild);
											for (i = 0; i < notecardID.length; i++) {
												if (notecardID[i][0] == noteid) {
													var val = notecardID[i][4];
												}
											}
											var pEl = Ext.get(el[0].id);
											pEl.frame("C3DAF9", 3, {
												duration: .5 //duration of each individual ripple.
											// Note: Easing is not configurable and will be ignored if included
											});
											/* alert(notecardID.search(noteid));
			 if(pos!=-1){
			 var val = notecardID[pos][4];
			 }
			 */
											document.getElementById("div_" + noteid + "_item_" + itemCnt).innerHTML = val;
											document.getElementById(id).className = "";
											players[players.length] = new YAHOO.example.DDPlayer("item_" + itemCnt, "topslots");
											notecardsOutline[notecardsOutline.length] = [noteid, "item_" + itemCnt];
											
											//document.getElementById(this.getDragEl().id).innerHTML = "";
											applyInOutlineCue(noteid);
											saveHTMLTree();
										}
										prepareMaskNote();
										Ext.Ajax.request({
											url: '../notecards/_includes/notecardOperations.php',
											method: 'POST',
											success: success,
											failure: failure,
											params: 'toggle=incrementOutlineCounters&action=attachNotecard'
										});
									}
								}
								document.getElementById(el[0].id).className = "";
								document.getElementById(noteid).style.display = "block";						
								//make the proxy element empty
								document.getElementById("ygddfdiv").innerHTML = "";
								
							}
							else 
								if (id.match("item_")) {
									document.getElementById(noteid).style.display = "block";
								}
				if(this.target.match("view"))
				{
					this.dropped = false;
				}
				updateNotecards();
			}
    	}
    },

    onDrag: function(e) {
		hidePopupOnDrag();
    },

    onDragOver: function(e, id) {		
		// highlight the outline item
    	if(id.match("div_item_"))
		{
			var el1 = YAHOO.util.Dom.getElementsByClassName('selected');
			if(el1.length>0)
			{
				document.getElementById(el1[0].id).className='';
			}
			
			var el = YAHOO.util.Dom.getElementsByClassName('hover_li');
			if(el.length == 0)
			{
				document.getElementById(id).className = "hover_li";
			}
			else{
				document.getElementById(el[0].id).className = "";
				document.getElementById(id).className = "hover_li";
			}
		}
    },
	onDragOut : function(e,id)
	{
		if (id.match("div_item_")) {
			var el1 = YAHOO.util.Dom.getElementsByClassName('hover_li');
			document.getElementById(id).className = "";
		}
	},
	onMouseDown : function(e)
	{
		displayPopup = false;
	},
	onMouseUp : function(e)
	{
		displayPopup = true;
	}

});
})();

// function to highlight the title portion of the notecard in minimal view
function mouseOverTitle(divId)
{
	document.getElementById(divId).className = "notecardTitleHover";
}

function mouseOutTitle(divId)
{
	document.getElementById(divId).className = "notecardTitle";
}
// function to begin editing of the notecard title
function editMe(divId)
{
	hidePilePopup();
	hideInfoPopup();
	var title_div = divId;
	var txt_container = "txt_container_"+divId.substr(6);
	var note_Id = divId.substr(6);
	var txt_field = "txt_title_"+divId.substr(6);
	var txt_field_value = Trim(document.getElementById(txt_field).value);
	var el = YAHOO.util.Dom.getElementsByClassName('selected');
	if (el.length > 0) {
		outlineTxtHideMe();
		document.getElementById(el[0].id).className = "";
	}
	if(pileInEditMode){
		pileHideMe();
	}
	if (hideMe()) {
		document.getElementById(txt_container).style.display = "block";
		document.getElementById(title_div).style.display = "none";
		for(i=0;i<notecardID.length;i++){
			if(notecardID[i][0] == divId.substr(6)){
				var val = notecardID[i][4];
			}
		}
		document.getElementById(txt_field).value = val;
		document.getElementById(txt_field).select();
		noteInEditMode = divId;
	}
	
}

function hideMe(){
	if (noteInEditMode != null) {
		var title_div = noteInEditMode;
		var txt_container = "txt_container_" + noteInEditMode.substr(6);
		var notecard_id = noteInEditMode.substr(6);
		var txt_field = "txt_" + noteInEditMode;
		var txt_field_value = Trim(document.getElementById(txt_field).value);
		
		if (txt_field_value != "") {
			//if(alphanumeric(txt_field_value)){
				if (!CheckNoteTitle(txt_field_value, notecard_id)) {
					notecard_id = noteInEditMode.substr(6);
					// update the title in outline if the item exists there
					for (i = 0; i < notecardsOutline.length; i++) {
						if (notecardsOutline[i][0] == notecard_id) {
							document.getElementById("div_" + notecardsOutline[i][0] + "_" + notecardsOutline[i][1]).innerHTML = document.getElementById(txt_field).value;
							saveHTMLTree();
						}
					}
					for (i = 0; i < notecardID.length; i++) {
						if (notecardID[i][0] == notecard_id) {
							notecardID[i][4] = document.getElementById(txt_field).value;
							updateNoteTitleInDatabase(notecard_id, txt_field_value);
						}
					}
					shakeMe(notecard_id);
					if (txt_field_value.length > 10) {
						document.getElementById(title_div).innerHTML = txt_field_value.substr(0, 9) + "....";
					}else{
						document.getElementById(title_div).innerHTML = txt_field_value;
					}
					document.getElementById(txt_field).value = "";
					document.getElementById('txt_title_tabletop').style.visibility = "hidden";
					document.getElementById(txt_container).style.display = "none";
					document.getElementById(title_div).style.display = "block";
					noteInEditMode = null;
					enableBackSpace = false;
					return true;
				}
				else {
					showAlertBox("A notecard with this title already exists.", "Notecard");
					return false;
				}
			
		}
		else {
                        for (i = 0; i < notecardID.length; i++) {
                            if (notecardID[i][0] == notecard_id) {
                               document.getElementById(txt_field).value =  notecardID[i][4];

                            }
                        }
			var msg = "Please enter a title for the notecard.";
			showAlertBox(msg, "Notecard");
			return false;
		}
	}else{
		return true;
	}
}

// function to check wether the title is used by some other notecard
function CheckNoteTitle(title, NoteId)
{
	var myTitle = new String();
	myTitle = title;
	myTitle = myTitle.toLowerCase();
	this.exists = false;
	
		for (this.count = 0; this.count < notecardID.length; this.count++) {
			var noteTitle = new String();
			noteTitle = notecardID[this.count][4];
			noteTitle = noteTitle.toLowerCase();
			if (myTitle == noteTitle && notecardID[this.count][0] != NoteId) {
				this.exists = true;
			}
		}
	
	return this.exists;
}


function CheckNewNoteTitle(title)
{
	if(notecardID){
		var myTitle = new String();
		myTitle = title;
		myTitle = myTitle.toLowerCase();
		this.exists = false;
		for(this.count = 0; this.count<notecardID.length;this.count++)
		{
			var noteTitle = new String();
			noteTitle = notecardID[this.count][4];
			noteTitle = noteTitle.toLowerCase();
			if(myTitle == noteTitle)
			{
				this.exists = true;
			}
		}
		return this.exists;
	}
}

// function to call an ajax request to update the title in database
function updateNoteTitleInDatabase(noteid,title)
{
	 var id = noteid.substr(9);
	 function handleFailure (o)
	{
	};
	function handleSuccess (o){
		
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
	};
	
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params : 'toggle=updateNoteTitle&title='+title+'&id='+id
	});	
}


//function to get the notecard data
function openNoteEditView(){
	
	prepareMaskNote();
	projectid = document.getElementById('projectID').value;
	function handleFailure (o)
	{
		alert(o.responseText);		
	};
	function handleSuccess (o){

		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		this.data = Ext.decode(o.responseText);
		
		if(!editNoteWin){
			displaywindow(this.data[0],this.data[1],this.data[2],this.data[3], this.data[4]);
		}else{
			Ext.getCmp('utxtTitle').reset();
			Ext.getCmp('utxtSource').reset();
			Ext.getCmp('utxtURL').reset();
			Ext.getCmp('utxtPages').reset();
			Ext.getCmp('utxtTags').reset()
			Ext.getCmp('utags1').clearValue();
			Ext.getCmp('uquotation').reset();
			Ext.getCmp('uparaphrase').reset();
			Ext.getCmp('uideas').reset();
			Ext.getCmp('uid').reset();
			
			Ext.getCmp('utxtTitle').setValue(this.data[0][0]);
			Ext.getCmp('utxtSource').setValue(this.data[0][1]);
			Ext.getCmp('usourceID').setValue(this.data[0][1]);
			Ext.getCmp('utxtURL').setValue(this.data[0][2]);
			Ext.getCmp('utxtPages').setValue(this.data[0][3]);
			Ext.getCmp('utxtTags').setValue(this.data[2]);
			Ext.getCmp('uquotation').setValue(this.data[0][4]);
			Ext.getCmp('uparaphrase').setValue(this.data[0][5]);
			Ext.getCmp('uideas').setValue(this.data[0][6]);
			Ext.getCmp('uid').setValue(editNoteID);
			editNoteWin.doLayout();
			editNoteWin.show();
		}
	};
	
	//ajax call to the server to insert notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/loadNoteData.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params : 'projectid='+projectid+'&id='+editNoteID
	});	
}


// function to update the edited notecard on this window
function updateEditedNotecard(id, title)
{
	var outlineTitle = "";
	outlineTitle = title;
	// update the notecard in DOM
	for(m=0;m<notecardID.length;m++){
		if (notecardID[m][0] == "Notecard_" + id) {
			notecardID[m][4] = title;
			if(title.length>10){
				title = title.substr(0,9)+"...";
			}
			if(document.getElementById("title_"+notecardID[m][0])){
				document.getElementById("title_"+notecardID[m][0]).innerHTML = title;
			}
			shakeMe(notecardID[m][0]);
		}
	}
	// update the notecard in outline
	if(notecardsOutline.length > 0)
	{
		for (m = 0; m < notecardsOutline.length; m++) {
			if (notecardsOutline[m][0] == "Notecard_" + id) {
				if(document.getElementById("div_Notecard_" + id + "_" + notecardsOutline[m][1])){
					document.getElementById("div_Notecard_" + id + "_" + notecardsOutline[m][1]).innerHTML = outlineTitle;
					saveHTMLTree();
				}
			}
		}
	}
	// update the notecard in exploded pile
	
	if(document.getElementById('li_Notecard_'+id))
	{
		if(title.length>10){
				title = title.substr(0,9)+"...";
		}
		if(document.getElementById("div_Notecard_"+id+"_title")){
			document.getElementById("div_Notecard_"+id+"_title").innerHTML = title;
		}
	}
	loadTags();
	
	
}

// function to open notecard in edit view
function displaywindow(notecardDetails, allTags, tagString, tagArray, src){	
	var disableMe = false;
        var srcIDVal = "";
	if(notecardDetails[1] != 0){
		srcIDVal = src[1];
	}else{
		srcIDVal = 0;
	}	
	var ucitCmb = null;
	ucitCmb = new Ext.form.ComboBox({
				id : 'utxtSource',
				store : src[0],
				width : 400,
				typeAhead : false,
				editable : false,
				mode : 'local',
				forceSelection : true,
				disabled: disableMe,
				triggerAction : 'all',
				value : notecardDetails[1],
				emptyText : 'Select a Citation ...',
				listeners: {
					'change': {
						fn: function(cmb, newVal, oldVal){
							Ext.getCmp('usourceID').setValue(newVal);
						}
					}
				},
				selectOnFocus : true
			});
			/*
	var citTxt = new Ext.form.HtmlEditor({
				enableAlignments : false,
				enableColors : false,
				enableFont : false,
				enableFontSize : false,
				enableFormat : true,
				disabled: disableMe,
				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 = ucitCmb;
	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 editForm = new Ext.FormPanel({
		url: '../notecards/_includes/updateNotecard.php',
		labelAlign: 'top',
		autoScroll: true,
		frame: true,
		name: 'editNote',
		id: 'editNote',
		bodyStyle: 'padding:5px 5px 0',
		monitorValid: true,
		width: 600,
		items: [{
			layout: 'form',
			items: [{
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Title</b>'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					fieldLabel: 'Title',
					id: 'utxtTitle',
					name: 'utxtTitle',
					allowBlank: false,
					disabled: disableMe,
					value: notecardDetails[0],
					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,
					bodyStyle: 'padding-top:5px;',
					html: '<b>URL</b>'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					id: 'utxtURL',
					value: notecardDetails[2],
					disabled: disableMe,
					name: 'utxtURL',
					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: 'utxtPages',
					disabled: disableMe,
					name: 'utxtPages',
					value: notecardDetails[3],
					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: 'utxtTags',
					disabled: disableMe,
					name: 'utxtTags',
					value: tagString,
					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: [cmb1 = new Ext.form.ComboBox({
						id: 'utags1',
						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',
						
						disabled: disableMe,
						displayField: 'Tag',
    					valueField: 'ID',
						triggerAction: 'all',
						emptyText: 'Select a tag...',
						selectOnFocus: true,
						listeners: {
							'select': {
								fn: function(combo, newVal, oldVal){
									var str = Ext.getCmp('utxtTags').getValue();
										function successFn(obj){
											if((Trim(obj.responseText)).match("ERROR_MULTIPLE") || (Trim(obj.responseText)).match("ERROR_NOID"))
											{			
												showNotesSessionError(Trim(obj.responseText));
												return false;
											}
											tagArray = [];
											tagArray = Ext.decode(obj.responseText);
											var selectedTag = newVal.get('Tag');
											this.exists = false;
											for(i=0;i<tagArray.length;i++){
												if(tagArray[i] == selectedTag){
													this.exists = true;
												}
											}
											if (!this.exists) {
												Ext.getCmp('utxtTags').setValue(Ext.getCmp('utxtTags').getValue() + " \"" + selectedTag+"\"");
												tagArray[tagArray.length] = selectedTag;
											}
										}
										function failFn(){
											alert("Connection failed")
										}
										var callback =
											{
												success:successFn,
												failure:failFn		
											};
										//ajax call to the server to insert notecard data
										YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/notecardOperations.php', callback, "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: "uquotation",
					name: "uquotation",
					disabled: disableMe,
					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
					},
					value: notecardDetails[4]
				
				}, {
					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: "uparaphrase",
					name: "uparaphrase",
					disabled: disableMe,
					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
			  },
					value: notecardDetails[5]
				
				}, {
					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: "uideas",
					name: "uideas",
					disabled: disableMe,
					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
				},
					value: notecardDetails[6]
				
				}, {
					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: 'uprojectID',
					hidden: true,
					anchor: '95%'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					value: srcIDVal,
					name: 'usourceID',
					id: 'usourceID',
					hidden: true,
					anchor: '95%'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					value: editNoteID,
					name: 'uid',
					id: 'uid',
					hidden: true,
					anchor: '95%'
				}]
			}]
		}],
		buttons: [{
			text: 'Save',
			type: 'button',
			disabled: disableMe,
			listeners: {
				'click': {
					fn: function(){
						if (editForm.getForm().isValid()) {
							var val = Trim(Ext.getCmp('utxtTitle').getValue());
							if(alphanumeric(val)){
								if (!CheckNoteTitle(val, "Notecard_" + editNoteID)) {
									var qtext = Ext.getCmp('uquotation').getValue();
									var ptext = Ext.getCmp('uparaphrase').getValue();
									var itext = Ext.getCmp('uideas').getValue();
									
									if ((qtext.match("meta content=\"Microsoft Word") == "meta content=\"Microsoft Word") || (qtext.match("<w:WordDocument>") == "<w:WordDocument>")) {
										function emptyQuotation(btn){
											Ext.getCmp('uquotation').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('uparaphrase').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('uideas').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('uquotation').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('uparaphrase').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('uideas').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;
																tinyMCE.triggerSave();
																editForm.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){
																		if((Trim(action.responseText)).match("ERROR"))
																		{
																			showNotesSessionError(Trim(action.responseText));
																			return false;
																		}					

																		updateEditedNotecard(editNoteID, Ext.getCmp('utxtTitle').getValue());
																		Ext.getCmp('utags1').store.reload();
																		Ext.getCmp('usourceID').setValue('0');
																		editNoteWin.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){
																		alert("inside failure.." + 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(){						
						editNoteWin.hide();
					}
				}
			}
		}]
	
	});
	
	// This just creates a window to wrap the login form. 
	// The login object is passed to the items collection.       
    editNoteWin = new Ext.Window({
        layout:'fit',
		cls:"../_css/noodlenotes.css",
		title: 'Edit Notecard',
		style: 'padding:5px',
		width: (YAHOO.util.Dom.getViewportWidth()-50),
		height:	(YAHOO.util.Dom.getViewportHeight()-50),
		manager: newEditWindows,
        closable: false,
        resizable: false,
        plain: true,
        id:'editNoteWin',
        border: false,
		items: [editForm],
		modal: true,
		draggable: false,
		listeners: {
			'beforehide': {
				fn: handlers
			},
			'beforeshow': {
				fn: function(win){
					win.manager.zseed = 8000;
					win. setWidth(YAHOO.util.Dom.getViewportWidth() - 50);
					win. setHeight(YAHOO.util.Dom.getViewportHeight() - 50);
					Ext.getCmp('utags1').store.reload();
       				Ext.getCmp('utxtTitle').focus(true,1500);
       				Ext.getCmp('utags1').clearValue();
					hidePopupOnDrag();
				}
			},
			'hide' : {
				fn: function(win){
					editForm.body.dom.scrollTop = 0;
				}
			}
		}
	});
	editNoteWin.show();
	
	function handlers(cmp){
		editNoteWin.body.dom.scrollTop = 0;
					this.bool = false;
					if (!submit1) {
						var dirty = false;
						if(Ext.getCmp('utxtTitle').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtSource').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtURL').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtPages').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtTags').isDirty()) dirty = true;
						
						if(Ext.getCmp('uquotation').isDirty()) dirty = true;
						
						if(Ext.getCmp('uparaphrase').isDirty()) dirty = true;
						
						if(Ext.getCmp('uideas').isDirty()) dirty = true;
						
						if(dirty){
							function showResult(btn){
								if (btn == "yes") {
									editNoteWin.un('beforehide', handlers);
									if (editForm.getForm().isValid()) {
										var val = Trim(Ext.getCmp('utxtTitle').getValue());
										if(alphanumeric(val)){
											tinyMCE.triggerSave();
											editForm.getForm().submit();
											Ext.getCmp('utags1').store.reload();
											Ext.getCmp('usourceID').setValue('0');
											updateEditedNotecard(editNoteID, Ext.getCmp('utxtTitle').getValue());
											editForm.getForm().reset();
											cmp.hide();
										}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,
											fn: showResult,
											closable: false,
											icon: Ext.MessageBox.ERROR
										});
										
									}
								}
								else {
									editNoteWin.un('beforehide', handlers);
									cmp.hide();
								}
							}
							Ext.MessageBox.confirm('Confirm', 'Do you want to save changes?', showResult);
							return false;
						}else{
							return true;
						}
					}else{
						return true;
					}
				}
}


Ext.onReady(function(){
	Ext.QuickTips.init();
	// turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';
});

// function to delete single notecard
function deleteSingleNotecard(){
	//retrieve all the selected notecards here
	var arrSelNotes = [ document.getElementById('Notecard_'+editNoteID) ];
	var ttop = document.getElementById('tabletop');
		
	
	function handleFailure (o)
	{
		
	}
	function handleSuccess (o)
	{
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
	}
	var arrSelNotesData = new Array();
	for(i=0;i<arrSelNotes.length;i++)
	{
		arrSelNotesData[arrSelNotesData.length] = arrSelNotes[i].id;
	}
	arrSelNotesData1 = YAHOO.lang.JSON.stringify(arrSelNotesData);
	
	//ajax call to the server to load notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params : 'toggle=delNotecards&arrSelNotesData='+arrSelNotesData1
	});	
	
	
	//delete the notecard by looping through them
	for (this.iCount = 0; this.iCount<arrSelNotes.length;this.iCount++) {			
		// remove the entry of notecard from notecard array
		for (counter1 = 0; counter1 < notecardID.length; counter1++) {
			if (notecardID[counter1][0] == arrSelNotes[this.iCount].id) {
				var parentEl = document.getElementById('outer_hawk_eye');
				var childEl = document.getElementById("thumb_" + notecardID[counter1][0]);
				parentEl.removeChild(childEl);
				notecardID.splice(counter1, 1);
				var notecard_id = document.getElementById(arrSelNotes[this.iCount].id);
				ttop.removeChild(notecard_id);
			}
		}
		 // remove the entry of notecard from the pile notecard array
		for (counter2 = 0; counter2 < pileNotecard.length; counter2++) {
			if (pileNotecard[counter2][1] == arrSelNotes[this.iCount].id) {
				if (document.getElementById("li_" + pileNotecard[counter2][1])) {
					var parentEl = document.getElementById("li_" + pileNotecard[counter2][0]);
					var childEl = document.getElementById("li_" + pileNotecard[counter2][1]);
					parentEl.removeChild(childEl);
				}
				pileNotecard.splice(counter2, 1);
			}
			
		}
		// remove the entry of notecard from the outline notecard array
		for (counter = 0; counter < notecardsOutline.length; counter++) {
			if (notecardsOutline[counter][0] == arrSelNotes[this.iCount].id) {
				var parentEl = YAHOO.util.Dom.getAncestorByTagName(notecardsOutline[counter][1], "ol");
				var childEl = document.getElementById(notecardsOutline[counter][1])
				parentEl.removeChild(childEl);
				notecardsOutline.splice(counter, 1);
				arrLength = notecardsOutline.length;
				counter = -1;
			}
		}
	}
	//hidePopupOnDrag();
	updateCountInPile();
}

function deleteSingleNoteCardsFromTabletop(){
    
    //retrieve all the selected notecards here
	var arrSelNotes = [ document.getElementById('Notecard_'+editNoteID) ];
	var ttop = document.getElementById('tabletop');

	
	function handleFailure (o)
	{

	}
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		for (counter = 0; counter < notecardsOutline.length; counter++) {
			if (notecardsOutline[counter][0] == 'Notecard_'+editNoteID) {
				var parentEl = YAHOO.util.Dom.getAncestorByTagName(notecardsOutline[counter][1], "ol");
				var childEl = document.getElementById(notecardsOutline[counter][1])
				parentEl.removeChild(childEl);
				notecardsOutline.splice(counter, 1);
				arrLength = notecardsOutline.length;
				counter = -1;
			}
		}
                Ext.get('Notecard_'+editNoteID).remove();
                Ext.get('thumb_Notecard_'+editNoteID).remove();
                fillNotecardsAraay();
                // remove the entry of notecard from the outline notecard array
		
                editNoteID = "";
				hidePopupOnDrag();

	};
	var arrSelNotesData = new Array();
	for(i=0;i<arrSelNotes.length;i++)
	{
		arrSelNotesData[arrSelNotesData.length] = arrSelNotes[i].id;
	}
	arrSelNotesData1 = YAHOO.lang.JSON.stringify(arrSelNotesData);

	//ajax call to the server to insert notecard data
	//YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/notecardOperations.php', callback, "toggle=delNotecards&arrSelNotesData="+arrSelNotesData1);
         Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,
		   failure: handleFailure,
		   params : 'toggle=delNotecards&arrSelNotesData='+arrSelNotesData1
		});
}

function deleteMultipleNotecardsFromDom(){
    
    //retrieve all the selected notecards here
	var arrSelNotes = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
        
	var ttop = document.getElementById('tabletop');

	
	function handleFailure (o)
	{

	};
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
                for(i=0;i<arrSelNotes.length;i++){

                    for (l = 0; l < expandedPileArray.length; l++) {
                        var childs = YAHOO.util.Dom.getChildren("li_"+expandedPileArray[l][0].substr(4));
                       
                        if(childs.length == 2){
                            if(Ext.fly("li_"+expandedPileArray[l][0].substr(4)).contains(Ext.get("li_"+arrSelNotes[i].id))){
                                var noteid;
                                var a;
                                if(childs[0].id != "li_"+arrSelNotes[i].id){
                                    a = Ext.get(childs[0].id);
                                    a.setDisplayed(true);
                                    noteid = childs[0].id.substr(3);
                                    document.getElementById(noteid).style.display="block";
                                    document.getElementById("thumb_"+noteid).style.display="block";
                                    // get the same dimensions to the notecard left, as of the pile
                                    mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;
                                    mTop = document.getElementById(expandedPileArray[l][0].substr(4)).style.top;
                                    // assign the same dimensions to the notecard left, as of the pile
                                    document.getElementById(noteid).style.left = mLeft;
                                    document.getElementById(noteid).style.top = mTop;

                                    //remove the exploded pile from dom
                                    Ext.get(expandedPileArray[l][0]).remove();
                                    // remove the pile from dom
                                    Ext.get(expandedPileArray[l][0].substr(4)).remove();
                                    Ext.get("thumb_"+expandedPileArray[l][0].substr(4)).remove();
                                    // remove exploded pile from the array
                                    expandedPileArray.splice(l,1);
                                    l = -1;
                                }else{
                                    a = Ext.get(childs[1].id);
                                    a.setDisplayed(true);
                                    noteid = childs[1].id.substr(3);
                                    document.getElementById(noteid).style.display="block";
                                    document.getElementById("thumb_"+noteid).style.display="block";
                                    // get the same dimensions to the notecard left, as of the pile
                                    mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;
                                    mTop = document.getElementById(expandedPileArray[l][0].substr(4)).style.top;
                                    // assign the same dimensions to the notecard left, as of the pile
                                    document.getElementById(noteid).style.left = mLeft;
                                    document.getElementById(noteid).style.top = mTop;

                                    //remove the exploded pile from dom
                                    Ext.get(expandedPileArray[l][0]).remove();
                                    // remove the pile from dom
                                    Ext.get(expandedPileArray[l][0].substr(4)).remove();
                                    Ext.get("thumb_"+expandedPileArray[l][0].substr(4)).remove();
                                    // remove exploded pile from the array
                                    expandedPileArray.splice(l,1);
                                    l = -1;
                                }
                            }
                        }else{
                            if(Ext.fly("li_"+expandedPileArray[l][0].substr(4)).contains(Ext.get("li_"+arrSelNotes[i].id))){
                                noteid = arrSelNotes[i].id;
                               // remove notecards dom from pile div
                                Ext.fly("li_"+noteid).remove();
                            }
                        }
                    }
                    var selectedPile = Ext.get("tabletop").query("div.pileYellow", true);
                
                    if(selectedPile != null){
                        for(kl=0;kl<selectedPile.length;kl++){
                            var pileid = selectedPile[kl].id;
                            var totalCount = getTotalNotecardCountinPile(pileid);
                            var selectCount = getSelectedNotecardCountInPile(pileid);
                            if((totalCount-selectCount) == 0){
                                Ext.fly(pileid).remove();
                                Ext.fly("thumb_"+pileid).remove();
                            }else if((totalCount-selectCount) < 2){
                                for(pl=0;pl<pileNotecard.length;pl++){
                                    if(pileNotecard[pl][0] == pileid){
                                        noteid1 = pileNotecard[pl][1];
                                        actualDomNote = Ext.get(noteid1);
                                        if(actualDomNote != null){
                                            if(!document.getElementById(noteid1).className.match("Yellow")){
                                                document.getElementById(noteid1).style.display="block";
                                                document.getElementById(noteid1).style.left = document.getElementById(pileid).style.left;
                                                document.getElementById(noteid1).style.top = document.getElementById(pileid).style.top;
                                                Ext.fly(pileid).remove();
                                                Ext.fly("thumb_"+pileid).remove();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // remove notecards from the tabletop
                    Ext.fly(arrSelNotes[i].id).remove();
                    Ext.fly("thumb_"+arrSelNotes[i].id).remove();

                    for (counter = 0; counter < notecardsOutline.length; counter++) {
                            if (notecardsOutline[counter][0] == arrSelNotes[i].id) {
                                    var parentEl = YAHOO.util.Dom.getAncestorByTagName(notecardsOutline[counter][1], "ol");
                                    var childEl = document.getElementById(notecardsOutline[counter][1])
                                    parentEl.removeChild(childEl);
                                    notecardsOutline.splice(counter, 1);
                                    arrLength = notecardsOutline.length;
                                    counter = -1;
                            }
                    }
                }
                
		fillNotecardsAraay();


	};
	var arrSelNotesData = new Array();
	for(i=0;i<arrSelNotes.length;i++)
	{
		arrSelNotesData[arrSelNotesData.length] = arrSelNotes[i].id;
	}
	arrSelNotesData1 = YAHOO.lang.JSON.stringify(arrSelNotesData);

	//ajax call to the server to insert notecard data
	//YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/notecardOperations.php', callback, "toggle=delNotecards&arrSelNotesData="+arrSelNotesData1);
         Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,
		   failure: handleFailure,
		   params : 'toggle=delNotecards&arrSelNotesData='+arrSelNotesData1
		});
        
}
function deleteSingleNoteCardsFromPile(){
    
    //retrieve all the selected notecards here
	var arrSelNotes = [ document.getElementById('Notecard_'+editNoteID) ];
	var ttop = document.getElementById('tabletop');

	
	function handleFailure (o)
	{

	}
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
                editNoteID = "";
                for(i=0;i<arrSelNotes.length;i++){
                   
                    for (l = 0; l < expandedPileArray.length; l++) {
                        var childs = YAHOO.util.Dom.getChildren("li_"+expandedPileArray[l][0].substr(4));
                        
                        if(childs.length == 2){
                            if(Ext.fly("li_"+expandedPileArray[l][0].substr(4)).contains(Ext.get("li_"+arrSelNotes[i].id))){
                                var noteid;
                                var a;
                                if(childs[0].id != "li_"+arrSelNotes[i].id){
                                    a = Ext.get(childs[0].id);
                                    a.setDisplayed(true);
                                    noteid = childs[0].id.substr(3);
                                    document.getElementById(noteid).style.display="block";
                                    document.getElementById("thumb_"+noteid).style.display="block";
                                    // get the same dimensions to the notecard left, as of the pile
                                    mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;
                                    mTop = document.getElementById(expandedPileArray[l][0].substr(4)).style.top;
                                    // assign the same dimensions to the notecard left, as of the pile
                                    document.getElementById(noteid).style.left = mLeft;
                                    document.getElementById(noteid).style.top = mTop;

                                    //remove the exploded pile from dom
                                    Ext.get(expandedPileArray[l][0]).remove();
                                    // remove the pile from dom
                                    Ext.get(expandedPileArray[l][0].substr(4)).remove();
                                    Ext.get("thumb_"+expandedPileArray[l][0].substr(4)).remove();
                                    // remove exploded pile from the array
                                    expandedPileArray.splice(l,1);
                                    l = -1;
                                }else{
                                    a = Ext.get(childs[1].id);
                                    a.setDisplayed(true);
                                    noteid = childs[1].id.substr(3);
                                    document.getElementById(noteid).style.display="block";
                                    document.getElementById("thumb_"+noteid).style.display="block";
                                    // get the same dimensions to the notecard left, as of the pile
                                    mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;
                                    mTop = document.getElementById(expandedPileArray[l][0].substr(4)).style.top;
                                    // assign the same dimensions to the notecard left, as of the pile
                                    document.getElementById(noteid).style.left = mLeft;
                                    document.getElementById(noteid).style.top = mTop;

                                    //remove the exploded pile from dom
                                    Ext.get(expandedPileArray[l][0]).remove();
                                    // remove the pile from dom
                                    Ext.get(expandedPileArray[l][0].substr(4)).remove();
                                    Ext.get("thumb_"+expandedPileArray[l][0].substr(4)).remove();
                                    // remove exploded pile from the array
                                    expandedPileArray.splice(l,1);
                                    l = -1;
                                }
                            }
                        }else{
                            if(Ext.fly("li_"+expandedPileArray[l][0].substr(4)).contains(Ext.get("li_"+arrSelNotes[i].id))){
                                noteid = arrSelNotes[i].id;
                               // remove notecards dom from pile div
                                Ext.fly("li_"+noteid).remove();
                            }
                        }
                    }
                    // remove notecards from the tabletop
                    Ext.fly(arrSelNotes[i].id).remove();
                    Ext.fly("thumb_"+arrSelNotes[i].id).remove();
                    // remove the entry of notecard from the outline notecard array
                    for (counter = 0; counter < notecardsOutline.length; counter++) {
                            if (notecardsOutline[counter][0] == arrSelNotes[i].id) {
                                    var parentEl = YAHOO.util.Dom.getAncestorByTagName(notecardsOutline[counter][1], "ol");
                                    var childEl = document.getElementById(notecardsOutline[counter][1])
                                    parentEl.removeChild(childEl);
                                    notecardsOutline.splice(counter, 1);
                                    arrLength = notecardsOutline.length;
                                    counter = -1;
                            }
                    }


                    for(qw=0;qw<pileNotecard.length;qw++){
                        if(pileNotecard[qw][1]==arrSelNotes[i].id){
                            pileid = pileNotecard[qw][0];
                        
                            totalCount = getTotalNotecardCountinPile(pileid);
                            if(totalCount <= 2){
                                
                                if(Ext.get("exp_"+pileid) == null){
                                    if(Ext.get(pileid) != null){
                                        for(df=0;df<pileNotecard.length;df++){
                                            if(pileNotecard[df][0]==pileid){
                                                if(pileNotecard[df][1] != arrSelNotes[i].id){
                                                    noteid = pileNotecard[df][1];
                                                    document.getElementById(noteid).style.display="block";
                                                    document.getElementById("thumb_"+noteid).style.display="block";
                                                    if(Ext.get(pileid) != null){
                                                         // get the same dimensions to the notecard left, as of the pile
                                                        mLeft = document.getElementById(pileid).style.left;
                                                        mTop = document.getElementById(pileid).style.top;
                                                        // assign the same dimensions to the notecard left, as of the pile
                                                        document.getElementById(noteid).style.left = mLeft;
                                                        document.getElementById(noteid).style.top = mTop;
                                                    }

                                                }
                                            }
                                        }
                                        Ext.fly(pileid).remove();
                                        Ext.fly("thumb_"+pileid).remove();
                                    }
                                }
                            }
                        }
                    }
                }
                fillNotecardsAraay();

                
	};
	var arrSelNotesData = new Array();
	for(i=0;i<arrSelNotes.length;i++)
	{
		arrSelNotesData[arrSelNotesData.length] = arrSelNotes[i].id;
	}
	arrSelNotesData1 = YAHOO.lang.JSON.stringify(arrSelNotesData);

	//ajax call to the server to insert notecard data
	//YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/notecardOperations.php', callback, "toggle=delNotecards&arrSelNotesData="+arrSelNotesData1);
         Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,
		   failure: handleFailure,
		   params : 'toggle=delNotecards&arrSelNotesData='+arrSelNotesData1
		});
}
function fillNotecardsAraay(){
   
    projectid = document.getElementById('projectID').value;
   
	function handleFailure (o)
	{

	}
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
            notecardID=[];
		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];
			}
		}
                for (counter = 0; counter < notecardsOutline.length; counter++) {
			if (notecardsOutline[counter][0] == 'Notecard_'+editNoteID) {
				var parentEl = YAHOO.util.Dom.getAncestorByTagName(notecardsOutline[counter][1], "ol");
				var childEl = document.getElementById(notecardsOutline[counter][1])
				parentEl.removeChild(childEl);
				notecardsOutline.splice(counter, 1);
				arrLength = notecardsOutline.length;
				counter = -1;
			}
		}
                fillPileNoteArray();
	};
	
        Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,
		   failure: handleFailure,
		   params : 'toggle=loadNotecardData&projectID='+projectid
		});
	
	


}

function fillPileNoteArray(){
 
    var projectID = document.getElementById('projectID').value;
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
                pileNotecard = [];
		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];
			}
		}
		fillPileArray();
	}
	function handleFailure (o)
	{
	}
	
	//ajax call to the server to insert notecard data
	
        Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,
		   failure: handleFailure,
		   params : 'toggle=loadNotePileRel&projectID='+projectid
		});
}

function fillPileArray(){
  
        var projectID = document.getElementById('projectID').value;
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
                pileID = [];
		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];
			}
		}
	    updateCountInPile();
            attachColors();
            attachCues();
            var outline = Ext.get("outline");
            var el = outline.select("li.li_notecard_outline_selected", true);
            el.replaceClass("li_notecard_outline_selected","li_notecard_outline");
            hidePopupOnDrag();
	}
	function handleFailure (o)
	{
	}
	
	//ajax call to the server to insert notecard data
        Ext.Ajax.request({
		   url: '../notecards/_includes/notecardOperations.php',
		   method: 'POST',
		   success: handleSuccess,
		   failure: handleFailure,
		   params : 'toggle=loadPileData&projectID='+projectID
		});
}
function deleteConfirmDgNotecard(){
	hidePopupOnDrag();
	Ext.MessageBox.confirm('Confirm', 'Are you sure you want to permanently delete this notecard?', showResult);
	function showResult(btn)
	{
		if (btn == "yes") {
			
                        if(Ext.get('li_Notecard_'+editNoteID)){
                            prepareLoadMask();
                            
                            deleteSingleNoteCardsFromPile();
                        }else{
							prepareLoadMask();
                            deleteSingleNoteCardsFromTabletop();
                        }
			
		}
	}
}

// function to be called in while creating the notecard in Bib Section
function createNoteInBib(entryid){
	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 entryID = entryid;
	function handleFailure (o)
	{
		alert(o.responseText);		
	}
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		function success (m)
		{
			if(Trim(m.responseText) == "[[ERROR_NOID]]")
			{
				showNotesSessionError();
				return false;
			}
			notecardID = YAHOO.lang.JSON.parse(m.responseText);
		};
		function failure (m)
		{
			alert(m.responseText);		
		};
		
		
		//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
	});	
	
		this.data = YAHOO.lang.JSON.parse(o.responseText);
		var tagArray = new Array();
		hidePopupOnDrag();
		var allTags = this.data[2];
		var myData = entryID;
		var citCmb = new Ext.form.ComboBox({
					id : 'txtSource',
					store : this.data[0],
					 width : 400,
					typeAhead : false,
					editable : false,
					mode : 'local',
					forceSelection : true,
					triggerAction : 'all',
					emptyText : 'Select a Citation ...',
					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 = "";
			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,
							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: '<span style="font-family:verdana;font-size:8pt">A short phrase that reminds you of the content of this notecard.</span><br><br>'
						}]
					}, /*{
						layout: 'column',
						items: [{
							columnWidth: .75,
							bodyStyle: 'padding:5px 0px 5px 0px;',
							html: '<b>Source</b>'
						}, {
							columnWidth: .5,
							items:[{
								columnWidth: 1
								},
								srcField
								],
							anchor: '98%'
						}, {
							columnWidth: .5,
							cls: 'editViewText',
							bodyStyle: 'padding:0px 0px 0px 10px;',
							html: 'Link this notecard to a source in your list.'
						}]
					}, */{
						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: '<span style="font-family:verdana;font-size:8pt">Direct, persistent link to the online material, if applicable.</span><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: '<span style="font-family:verdana;font-size:8pt">Page number(s) of material, if given.</span><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: '<span style="font-family:verdana;font-size:8pt">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).</span>'
						}]
					}, {
						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: allTags,
								typeAhead: false,
								editable: false,
								mode: 'local',
								forceSelection: true,
								triggerAction: 'all',
								emptyText: 'Select a tag...',
								selectOnFocus: true,
								listeners: {
									'select': {
										fn: function(combo, newVal, oldVal){
											var str = Ext.getCmp('txtTags').getValue();
											function successFn(obj){
												if((Trim(obj.responseText)).match("ERROR_MULTIPLE") || (Trim(obj.responseText)).match("ERROR_NOID"))
												{
													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 failFn(){
												alert("Connection failed")
											}
											var callback =
												{
													success:successFn,
													failure:failFn		
												};
											//ajax call to the server to insert notecard data
											YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/notecardOperations.php', callback, "toggle=returnTagArray&str="+str);
										}
									}
								}
							})]
						}, {
							columnWidth: .5,							
							bodyStyle: 'padding:5px 0px 0px 10px;',
							cls: 'editViewText',
							html: '<span style="font-family:verdana;font-size:8pt">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.</span>'
						}]
					}, {
						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: 400,
							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: '<span style="font-family:verdana;font-size:8pt;">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></span>'
						}]
					}, {
						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: 400,
							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: '<span style="font-family:verdana;font-size:8pt">Rewrite the quotation by restating the idea in your own words. <ul style="list-style-type:square;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>Compare your paraphrase to the quote: Does your restatement mirror the entire idea?</span>'
						}]
					}, {
						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: 400,
							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: '<span style="font-family:verdana;font-size:8pt">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.</span>'
						}]
					}, {
						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: myData,
							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;
																		tinyMCE.triggerSave();
																		//kill the tiny editors on close	
																		/*var t = tinyMCE.editors, e;
																		 for (e in t)
																		 {
																		 t[e].remove();
																		 }*/
																		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;
																				}
																				function handleFailure(o){
																					alert(o.responseText);
																				}
																				function handleSuccess(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 el = Ext.get('notesdiv_' + entryID);
																					if (el) {
																						var child = el.child('div');
																						if (child != null) {
																							if (this.data[0][4] != "") {
																								var quoteclass = "class=quoteclass";
																							}
																							else {
																								this.data[0][4] = "&nbsp";
																								var quoteclass = "";
																							}
																							if (this.data[0][5] != "") {
																								var paraclass = "class=paraclass";
																							}
																							else {
																								this.data[0][5] = "&nbsp";
																								var paraclass = "";
																							}
																							if (this.data[0][6] != "") {
																								var ideasclass = "class=ideasclass";
																							}
																							else {
																								this.data[0][6] = "&nbsp";
																								var ideasclass = "";
																							}
																							if (this.data[0][3] == "") {
																								this.data[0][3] = "&nbsp";
																							}
																							if (this.data[2] == "") {
																								this.data[2] = "none";
																							}
																							var blockhtml = "";
																							//html += "<div class=\"lineitem_static\" id=\"note_"+obj.data.id+"\">";
																							blockhtml += "<div class=\"tablewrapper\"><table class=\"notecard_static\" id=\"note_" + obj.data.id + "\" cellspacing=\"0\"><tbody>";
																							blockhtml += "<tr><th colspan=\"2\"><table class=\"fullwidth\" border=\"0\"><tbody><tr>";
																							blockhtml += "<td class=\"noborder\"><h3 id=\"note_" + obj.data.id + "_title\" class=\"notetitle\">" + this.data[0][0] + "</h3></td>";
																							blockhtml += "<td class=\"alignright noborder\" id=\"ncoptions_15\" nowrap=\"nowrap\">";
																							blockhtml += "<a href=\"#\" onclick=\"editNoteFromBib('" + obj.data.id + "'); return false;\">";
																							blockhtml += "<img alt=\"Edit notecard\" src=\"/_images_add/noteicons/edit.png\" border=\"0\"></a>";
																							blockhtml += "<a href=\"#\" class=\"smalltext\" onclick=\"editNoteFromBib('" + obj.data.id + "'); return false;\">Edit</a>";
																							blockhtml += "&nbsp;&nbsp;&nbsp;<a href=\"#\" onclick=\"doNotecardOption(" + projectid + ", '" + obj.data.id + "', 'printnotecard'); return false;\">";
																							blockhtml += "<img alt=\"Print notecard\" src=\"/_images_add/noteicons/fileprint.png\" border=\"0\"></a>";
																							blockhtml += "<a href=\"#\" class=\"smalltext\" onclick=\"doNotecardOption(" + projectid + ", '" + obj.data.id + "', 'printnotecard'); return false;\">Print</a>";
																							blockhtml += "&nbsp;&nbsp;&nbsp;<a href=\"#\" onclick=\"doNotecardOption(" + projectid + ", '" + obj.data.id + "', 'deletenotecardfrombib', '" + entryID + "'); return false;\">";
																							blockhtml += "<img alt=\"Delete notecard\" src=\"/_images_add/noteicons/cancel.png\" border=\"0\"></a>";
																							blockhtml += "<a href=\"#\" class=\"smalltext\" onclick=\"doNotecardOption(" + projectid + ", '" + obj.data.id + "', 'deletenotecardfrombib', '" + entryID + "'); return false;\">Delete</a></td></tr></tbody>";
																							blockhtml += "</table></th></tr><tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">URL:</td>";
																							blockhtml += "<td class=\"noteitem\"><span id=\"url_" + obj.data.id + "\"><a href=\"" + this.data[0][2] + "\" target=\"_blank\" id=\"url_" + obj.data.id + "\">" + this.data[0][2] + "</a></span></td></tr>";
																							blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">Pages:</td><td class=\"noteitem\"><span id=\"pages_" + obj.data.id + "\">" + this.data[0][3] + "</span></td></tr>";
																							blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">Tags:</td><td class=\"noteitem\"><span id=\"tagspan_" + obj.data.id + "\">" + this.data[2] + "</span></td></tr>";
																							blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">Cues:</td><td class=\"noteitem\"><span id=\"cuespan_" + obj.data.id + "\">none</span></td></tr>";
																							blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">Quotation:</td><td class=\"noteitem\"><span " + quoteclass + " id=\"quote_" + obj.data.id + "\"><p>" + this.data[0][4] + "</p></span></td></tr>";
																							blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">Paraphrase:</td><td class=\"noteitem\"><span " + paraclass + " id=\"para_" + obj.data.id + "\"><p>" + this.data[0][5] + "</p></span></td></tr>";
																							blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">My Ideas:</td><td class=\"noteitem\"><span " + ideasclass + " id=\"ideas_" + obj.data.id + "\"><p>" + this.data[0][6] + "</p></span></td></tr>";
																							blockhtml += "</tbody></table></div>";
																							
																							var dh = Ext.DomHelper;
																							var list = dh.append('notesdiv_' + entryID, {
																								id: "note_" + obj.data.id,
																								tag: 'div',
																								html: blockhtml,
																								cls: 'lineitem_static'
																							});
																							var el = Ext.get('notesdiv_' + entryID);
																							el.setVisibilityMode(Element.DISPLAY);
																							el.setVisible(true);
																							new Effect.ScrollTo("note_" + obj.data.id, {
																								queue: 'end'
																							});
																							Effect.Pulsate("note_" + obj.data.id, {
																								queue: 'end',
																								from: 0.4
																							});
																						}
																					}
																					var el = Ext.get('showhidelink_' + entryID);
																					var innerhtml = document.getElementById('showhidelink_' + entryID).innerHTML;
																					if (innerhtml == "") {
																						el.remove();
																						blockhtml = "&nbsp;<a onclick=\"showhide('" + entryID + "'); return false; \" href='#'><span id='showhidetxt_" + entryID + "'>Show</span></a>&nbsp;|";
																						var dh = Ext.DomHelper;
																						var list = dh.insertAfter('numnotes_' + entryID, {
																							id: 'showhidelink_' + entryID,
																							tag: 'span',
																							html: blockhtml
																						});
																					}
																					var numOfNotes = document.getElementById('numnotes_' + entryID).innerHTML;
																					var intNum = Number(numOfNotes) + 1;
																					document.getElementById('numnotes_' + entryID).innerHTML = intNum;
																					win2.close();
																				};
																				
																				//ajax call to the server to insert notecard data
																				
																				Ext.Ajax.request({
																					url: '../notecards/_includes/loadNoteData.php',
																					method: 'POST',
																					success: handleSuccess,
																					failure: handleFailure,
																					params: 'id=' + obj.data.id + '&projectid=' + projectid
																				});
																			},
																			
																			// 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") {
																				win2.toFront();
																				win2.enable();
																			}
																		}
																		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
																		});
																		win2.toBack();
																		win2.disable();
																	}
																	
																	
																}
											
										}
										else {
											function showResult(btn){
												if (btn == "ok") {
													win2.toFront();
													win2.enable();
												}
											}
											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
											});
											win2.toBack();
											win2.disable();
										}
									}else{
										function showResult(btn){
											if (btn == "ok") {
												win2.toFront();
												win2.enable();
											}
										}										
										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
										});
										win2.toBack();
										win2.disable();
									}
								}
								else {
									function showResult(btn){
										if (btn == "ok") {
											win2.toFront();
											win2.enable();
										}
									}
									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
									});
									win2.toBack();
									win2.disable();
								}
							}
						}
					}
				}, {
					text: 'Cancel',
					type: 'button',
					listeners: {
						'click': {
							fn: function(){
								function showResult1(btn){
										if (btn == "no") {
											win2.toFront();
											win2.enable();
										}
										if(btn == "yes"){
											//kill the tiny editors on close	
											/*var t = tinyMCE.editors, e;
										    for (e in t) 
											{
												t[e].remove();
										    }*/
											win2.close();
										}
									}
								
								Ext.MessageBox.show({
										title: 'Error',
										msg: 'Are you sure you want to close this window without saving?',
										buttons: Ext.MessageBox.YESNO,
										closable: false,
										fn: showResult1,
										icon: Ext.MessageBox.ERROR
									});
									
								win2.disable();
								win2.toBack();
							}
						}
					}
				}]
			
			});
			
			// This just creates a window to wrap the login form. 
			// The login object is passed to the items collection.       
			var win2 = 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: openwindows,
				closable: false,
				resizable: false,
				plain: true,
				border: false,
				items: [newNoteForm],
				modal: true,
				draggable: false,
				listeners: {
					'beforeshow': {
						fn: function(win){
							win.manager.zseed = 8000;
							hidePopupOnDrag();
							Ext.getCmp('mypileid').setValue("0");
							pileStore.reload();
						}
					},
					'show':{
						fn: function(){
							Ext.getCmp('txtTitle').focus(false,1500);
						}
					}
				}
			});
			
			win2.show();
			/*prepareMaskBib();
			setTimeout(function() {
							// This simulates a long-running operation like a database
							// save or XHR call.
							// In real code, this would be in a callback function.
							//displaywindowToEditNoteFromBib(data[0],data[1],data[2],data[3], data[4]);
							win2.show();
			}, 2000);*/
		}
	};
	
	
	//ajax call to the server to insert notecard data
	
	//ajax call to the server to load notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params : 'toggle=getCitations&projectid='+projectid   		
	});	
}

// function to edit Notecard from Bib

function editNoteFromBib(NoteId){
	Ext.WindowGroup.zseed = 1000000000000;
	editNoteID = NoteId;
	//prepareMaskBib();
	projectid = document.getElementById('projectID').value;
	function handleFailure (o)
	{
		alert(o.responseText);		
	}
	function handleSuccess (o){
		if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
		{			
			showNotesSessionError(Trim(o.responseText));
			return false;
		}
		
		var data = YAHOO.lang.JSON.parse(o.responseText);
		if(!editNoteWin){
			displaywindowToEditNoteFromBib(data[0],data[1],data[2],data[3], data[4]);
		}else{
			Ext.getCmp('utxtTitle').reset();
			Ext.getCmp('usourceID').reset();
			Ext.getCmp('utxtURL').reset();
			Ext.getCmp('utxtPages').reset();
			Ext.getCmp('utxtTags').reset();
			Ext.getCmp('uquotation').reset();
			Ext.getCmp('uparaphrase').reset();
			Ext.getCmp('uideas').reset();
			Ext.getCmp('uid').reset();
			
			Ext.getCmp('utxtTitle').setValue(data[0][0]);
			Ext.getCmp('usourceID').setValue(data[0][1]);
			Ext.getCmp('utxtURL').setValue(data[0][2]);
			Ext.getCmp('utxtPages').setValue(data[0][3]);
			Ext.getCmp('utxtTags').setValue(data[2]);
			Ext.getCmp('uquotation').setValue(data[0][4]);
			Ext.getCmp('uparaphrase').setValue(data[0][5]);
			Ext.getCmp('uideas').setValue(data[0][6]);
			Ext.getCmp('uid').setValue(editNoteID);
			editNoteWin.doLayout();
			editNoteWin.show();
		}
		
		
	};
	
	
	//ajax call to the server to insert notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/loadNoteData.php',
   		method: 'POST',
   		success: handleSuccess,				   
   		failure: handleFailure,
		params : 'id='+editNoteID+'&projectid='+projectid   		
	});	
	
}

// function to open notecard in edit view
function displaywindowToEditNoteFromBib(notecardDetails, allTags, tagString, tagArray, src){
	projectid = document.getElementById('projectID').value;
	function success (m)
	{
		if((Trim(m.responseText)).match("ERROR"))
		{			
			showNotesSessionError(Trim(m.responseText));
			return false;
		}
		
		notecardID = YAHOO.lang.JSON.parse(m.responseText);
	}
	function failure (m)
	{
		alert(m.responseText);		
	}
	
	//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     		
	});	
	var disableMe = false;
	
	var myData = notecardDetails[1];
	
	var srcIDVal = notecardDetails[1]
	var ucitCmb = null;
	ucitCmb = new Ext.form.ComboBox({
				id : 'utxtSource',
				store : src[0],
				width : 400,
				typeAhead : false,
				hidden: true,
				editable : false,
				mode : 'local',
				forceSelection : true,
				disabled: disableMe,
				triggerAction : 'all',
				value : notecardDetails[1],
				emptyText : 'Select a Citation ...',
				listeners: {
					'change': {
						fn: function(cmb, newVal, oldVal){
							Ext.getCmp('usourceID').setValue(newVal);
						}
					}
				},
				selectOnFocus : true
			});
			

	// Here it is to be checked whether its an integrated or stand-alone version
	var srcField = ucitCmb;
	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 editForm = new Ext.FormPanel({
		url: '../notecards/_includes/updateNotecard.php',
		labelAlign: 'top',
		autoScroll: true,
		frame: true,
		name: 'editNote',
		id: 'editNote',
		bodyStyle: 'padding:5px 5px 0',
		monitorValid: true,
		width: 600,
		items: [{
			layout: 'form',
			items: [{
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Title</b>'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					fieldLabel: 'Title',
					id: 'utxtTitle',
					name: 'utxtTitle',
					allowBlank: false,
					disabled: disableMe,
					value: notecardDetails[0],
					anchor: '95%'
				}, {
					columnWidth: .5,
					cls: 'editViewText',
					bodyStyle: 'padding:0px 0px 0px 10px;',
					html: '<span style="font-family:verdana;font-size:8pt;">A short phrase that reminds you of the content of this notecard.</span><br><br>'
				}]
			},{
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>URL</b>'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					id: 'utxtURL',
					value: notecardDetails[2],
					disabled: disableMe,
					name: 'utxtURL',
					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: '<span style="font-family:verdana;font-size:8pt;">Direct, persistent link to the online material, if applicable.</span><br><br>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Pages</b>'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					id: 'utxtPages',
					disabled: disableMe,
					name: 'utxtPages',
					value: notecardDetails[3],
					anchor: '95%'
				}, {
					columnWidth: .5,
					cls: 'editViewText',
					bodyStyle: 'padding:0px 0px 0px 10px;',
					html: '<span style="font-family:verdana;font-size:8pt;">Page number(s) of material, if given.</span><br><br>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Tags<b>'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					fieldLabel: 'pages',
					id: 'utxtTags',
					disabled: disableMe,
					name: 'utxtTags',
					value: tagString,
					anchor: '95%'
				}, {
					columnWidth: .5,
					cls: 'editViewText',
					bodyStyle: 'padding:0px 0px 0px 10px;',
					html: '<span style="font-family:verdana;font-size:8pt;">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).</span>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Existing Tags</b>'
				}, {
					columnWidth: .5,
					items: [cmb1 = new Ext.form.ComboBox({
						id: 'utags1',
						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',
						disabled: disableMe,
						displayField: 'Tag',
    					valueField: 'ID',
						triggerAction: 'all',
						emptyText: 'Select a tag...',
						selectOnFocus: true,
						listeners: {
							'select': {
								fn: function(combo, newVal, oldVal){
									var str = Ext.getCmp('utxtTags').getValue();
										function successFn(obj){
											if((Trim(obj.responseText)).match("ERROR_MULTIPLE") || (Trim(obj.responseText)).match("ERROR_NOID"))
											{
												showNotesSessionError(Trim(obj.responseText));
												return false;
											}					
											
											tagArray = [];
											tagArray = Ext.decode(obj.responseText);
											var selectedTag = newVal.get('Tag');
											this.exists = false;
											for(i=0;i<tagArray.length;i++){
												if(tagArray[i] == selectedTag){
													this.exists = true;
												}
											}
											if (!this.exists) {
												Ext.getCmp('utxtTags').setValue(Ext.getCmp('utxtTags').getValue() + " \"" + selectedTag+"\"");
												tagArray[tagArray.length] = selectedTag;
											}
										}
										function failFn(){
											alert("Connection failed")
										}
										
										
										//ajax call to the server to load notecard data
	Ext.Ajax.request({
   		url: '../notecards/_includes/notecardOperations.php',
   		method: 'POST',
   		success: successFn,				   
   		failure: failFn,
		params : 'toggle=returnTagArray&str='+str    		
	});	
								}
							}
						}
					})]
				}, {
						columnWidth: .5,							
						bodyStyle: 'padding:5px 0px 0px 10px;',
						cls: 'editViewText',
						html: '<span style="font-family:verdana;font-size:8pt;">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.</span>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Direct Quotation</b>'
				}, {
					columnWidth: .55,
					xtype: "tinymce",
					fieldLabel: "Rich text",
					id: "uquotation",
					name: "uquotation",
					disabled: disableMe,
					width: 300,
					height: 400,
					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
					},
					value: notecardDetails[4]
				
				}, {
					columnWidth: .45,
					cls: 'editViewText',
					bodyStyle: 'padding:0px 0px 0px 10px;',
					html: '<span style="font-family:verdana;font-size:8pt;">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></span>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>Paraphrase</b>'
				}, {
					columnWidth: .55,
					xtype: "tinymce",
					fieldLabel: "Rich text",
					id: "uparaphrase",
					name: "uparaphrase",
					disabled: disableMe,
					width: 300,
					height: 400,
					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
			  },
					value: notecardDetails[5]
				
				}, {
					columnWidth: .45,
					cls: 'editViewText',
					bodyStyle: 'padding:0px 0px 0px 10px;',
					html: '<span style="font-family:verdana;font-size:8pt;">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>Compare your paraphrase to the quote: Does your restatement mirror the entire idea?</span>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: .75,
					bodyStyle: 'padding-top:5px;',
					html: '<b>My Ideas</b>'
				}, {
					columnWidth: .55,
					xtype: "tinymce",
					fieldLabel: "Rich text",
					id: "uideas",
					name: "uideas",
					disabled: disableMe,
					width: 300,
					height: 400,
					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
				},
					value: notecardDetails[6]
				
				}, {
					columnWidth: .45,
					cls: 'editViewText',
					bodyStyle: 'padding:0px 0px 0px 10px;',
					html: '<span style="font-family:verdana;font-size:8pt;">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.</span>'
				}]
			}, {
				layout: 'column',
				items: [{
					columnWidth: 1,
					xtype: 'textfield',
					value: projectid,
					name: 'uprojectID',
					hidden: true,
					anchor: '95%'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					value: srcIDVal,
					name: 'usourceID',
					id: 'usourceID',
					hidden: true,
					anchor: '95%'
				}, {
					columnWidth: .5,
					xtype: 'textfield',
					value: editNoteID,
					name: 'uid',
					id: 'uid',
					hidden: true,
					anchor: '95%'
				}]
			}]
		}],
		buttons: [{
			text: 'Save',
			type: 'button',
			disabled: disableMe,
			listeners: {
				'click': {
					fn: function(){
						if (editForm.getForm().isValid()) {
							var val = Trim(Ext.getCmp('utxtTitle').getValue());
							if(alphanumeric(val)){
								if (!CheckNoteTitle(val, "Notecard_" + editNoteID)) {
									
									var qtext = Ext.getCmp('uquotation').getValue();
									var ptext = Ext.getCmp('uparaphrase').getValue();
									var itext = Ext.getCmp('uideas').getValue();
									
									
									if ((qtext.match("meta content=\"Microsoft Word") == "meta content=\"Microsoft Word") || (qtext.match("<w:WordDocument>") == "<w:WordDocument>")) {
										function emptyQuotation(btn){
											Ext.getCmp('uquotation').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('uparaphrase').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('uideas').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('uquotation').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('uparaphrase').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('uideas').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;
																tinyMCE.triggerSave();
																editForm.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){
																	
																		Ext.getCmp('utags1').store.reload();
																		Ext.getCmp('usourceID').setValue('0');
																		var handleFailure1 = function(o){
																			alert(o.responseText);
																		};
																		var handleSuccess1 = 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);
																			
																			//displaywindow(this.data[0],this.data[1],this.data[2],this.data[3], this.data[4]);
																			document.getElementById('note_' + this.data[0][7] + "_title").innerHTML = this.data[0][0];
																			if (this.data[0][2] != "") {
																				document.getElementById('url_' + this.data[0][7]).innerHTML = "<a href="+this.data[0][2]+" target='_blank'>"+this.data[0][2]+"</a>";
																			}
																			else {
																				document.getElementById('url_' + this.data[0][7]).innerHTML = "&nbsp";
																			}
																			if (this.data[0][3] != "") {
																				document.getElementById('pages_' + this.data[0][7]).innerHTML = this.data[0][3];
																			}
																			else {
																				document.getElementById('pages_' + this.data[0][7]).innerHTML = "&nbsp";
																			}
																			if (this.data[2] != "") {
																				document.getElementById('tagspan_' + this.data[0][7]).innerHTML = this.data[2];
																			}
																			else {
																				document.getElementById('tagspan_' + this.data[0][7]).innerHTML = "none";
																			}
																			if (this.data[0][4] != "") {
																				document.getElementById('quote_' + this.data[0][7]).innerHTML = this.data[0][4];
																				document.getElementById('quote_' + this.data[0][7]).className = "quoteclass";
																			}
																			else {
																				document.getElementById('quote_' + this.data[0][7]).innerHTML = "&nbsp";
																				document.getElementById('quote_' + this.data[0][7]).className = "";
																			}
																			if (this.data[0][5] != "") {
																				document.getElementById('para_' + this.data[0][7]).innerHTML = this.data[0][5];
																				document.getElementById('para_' + this.data[0][7]).className = "paraclass";
																			}
																			else {
																				document.getElementById('para_' + this.data[0][7]).innerHTML = "&nbsp";
																				document.getElementById('para_' + this.data[0][7]).className = "";
																			}
																			if (this.data[0][6] != "") {
																				document.getElementById('ideas_' + this.data[0][7]).innerHTML = this.data[0][6];
																				document.getElementById('ideas_' + this.data[0][7]).className = "ideasclass";
																			}
																			else {
																				document.getElementById('ideas_' + this.data[0][7]).innerHTML = "&nbsp";
																				document.getElementById('ideas_' + this.data[0][7]).className = "";
																			}
																			//editNoteWin.hide();
																			new Effect.ScrollTo("note_" + this.data[0][7], {
																				queue: 'end'
																			});
																			Effect.Pulsate("note_" + this.data[0][7], {
																				queue: 'end',
																				from: 0.4
																			});
																		};
																		var callback = {
																			success: handleSuccess1,
																			failure: handleFailure1
																		};
																		
																		//ajax call to the server to insert notecard data
																		YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/loadNoteData.php', callback, "projectid=" + projectid + "&id=" + editNoteID);
																		editNoteWin.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){
																		alert("inside failure.." + action);
																		form.reset();
																	}
																});
																
															}
															else {
																function showResult(btn){
																	if (btn == "ok") {
																	}
																}
																Ext.MessageBox.show({
																	title: 'Error',
																	msg: 'Please enter a title for the 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(){						
						editNoteWin.hide();
					}
				}
			}
		}]
	
	});
	
	// This just creates a window to wrap the login form. 
	// The login object is passed to the items collection.       
    editNoteWin = new Ext.Window({
        layout:'fit',
		cls:"../_css/noodlenotes.css",
		title: 'Edit Notecard',
		style: 'padding:5px',
		width: (YAHOO.util.Dom.getViewportWidth()-50),
		height:	(YAHOO.util.Dom.getViewportHeight()-50),
        closable: false,
        resizable: false,
        plain: true,
        id:'editNoteWin',
        border: false,
		items: [editForm],
		modal: true,
		draggable: false,
		listeners: {
			'beforehide': {
				fn: handlers
			},
			'beforeshow': {
				fn: function(win){
					win. setWidth(YAHOO.util.Dom.getViewportWidth() - 50);
					win. setHeight(YAHOO.util.Dom.getViewportHeight() - 50);
					Ext.getCmp('utags1').store.reload();
       				editForm.body.dom.scrollTop = 0;
       				Ext.getCmp('utxtTitle').focus(true,1500);
       				win.manager.zseed = 8000;
					//hidePopupOnDrag();
				}
			}
		}
	});
	editNoteWin.show();
	
	function handlers(cmp){
					editNoteWin.body.dom.scrollTop = 0;
					this.bool = false;
					if (!submit1) {
						var dirty = false;
						if(Ext.getCmp('utxtTitle').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtSource').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtURL').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtPages').isDirty()) dirty = true;
						
						if(Ext.getCmp('utxtTags').isDirty()) dirty = true;
						
						if(Ext.getCmp('uquotation').isDirty()) dirty = true;
						
						if(Ext.getCmp('uparaphrase').isDirty()) dirty = true;
						
						if(Ext.getCmp('uideas').isDirty()) dirty = true;
						
						if(dirty){
							function showResult(btn){
								if (btn == "yes") {
									editNoteWin.un('beforehide', handlers);
									if (editForm.getForm().isValid()) {
										var val = Trim(Ext.getCmp('utxtTitle').getValue());
										//if(alphanumeric(val)){
											if (!CheckNoteTitle(val, "Notecard_" + editNoteID)) {
												if (Trim(val) != "") {
													submit1 = true;
													tinyMCE.triggerSave();
													editForm.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){													
																
																Ext.getCmp('utags1').store.reload();
																Ext.getCmp('usourceID').setValue('0');
																var handleFailure1 = function(o)
																{
																	alert(o.responseText);		
																};
																var handleSuccess1 = 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);
																	//displaywindow(this.data[0],this.data[1],this.data[2],this.data[3], this.data[4]);
																	document.getElementById('note_'+this.data[0][7]+"_title").innerHTML = this.data[0][0];
																	document.getElementById('url_'+this.data[0][7]).innerHTML = this.data[0][2];
																	document.getElementById('pages_'+this.data[0][7]).innerHTML = this.data[0][3];
																	document.getElementById('tagspan_'+this.data[0][7]).innerHTML = this.data[2];
																	document.getElementById('quote_'+this.data[0][7]).innerHTML = this.data[0][4];
																	document.getElementById('para_'+this.data[0][7]).innerHTML = this.data[0][5];
																	document.getElementById('ideas_'+this.data[0][7]).innerHTML = this.data[0][6];
																	editNoteWin.hide();
																	new Effect.ScrollTo("note_"+this.data[0][7], {queue: 'end'});
																	Effect.Pulsate("note_"+this.data[0][7], {queue: 'end', from: 0.4});
																};
																var callback =
																{
																	success:handleSuccess1,
																	failure:handleFailure1		
																};
																
																//ajax call to the server to insert notecard data
																YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/loadNoteData.php', callback, "projectid="+projectid+"&id="+editNoteID);
																editNoteWin.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){
																alert("inside failure.."+action);
																form.reset();
															}
														});
													
												}
												else {
													function showResult(btn){
														if (btn == "ok") {
														}
													}
													Ext.MessageBox.show({
														title: 'Error',
														msg: 'Please enter a title for the 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: 'Please use only letters and/or numbers in the notecard title.',
												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
										});
									}
								}
								else {
									editNoteWin.un('beforehide', handlers);
									cmp.hide();
								}
							}
							Ext.MessageBox.confirm('Confirm', 'Do you want to save changes?', showResult);
							return false;
						}else{
							return true;
						}
					}else{
						return true;
					}
				}
}

function directEditNotecard(id){
	var a = id.split("_");
	editNoteID = a[1];
	editNotecard();
}