/**
 * @author amore
 * class to define the notecard
 */

// var to store the edit notecard window
var editNoteWin;
var newBibNoteWin;
// function to check wether the title is used by some other notecard
function CheckNoteTitle(title, NoteId)
{
    var myTitle = "";
    myTitle = title;
    myTitle = myTitle.toLowerCase();
    this.exists = false;
    for (this.count = 0; this.count < notecardID.length; this.count++) {
        var noteTitle = "";
        noteTitle = notecardID[this.count][4];
        noteTitle = noteTitle.toLowerCase();
        if (myTitle == noteTitle && notecardID[this.count][0] != NoteId) {
            this.exists = true;
        }
    }

return this.exists;
}
// function to hide notecards that exists in pile and show notecards that are not in pile anymore
function repairTabletop(){
if(Ext.get("tabletop")){
    var notecard;
    var exist;
    // block to make the notecard appear if its not in pile
    var arrDisplaynone= Ext.query("div[class=notecard]{display=none}");
    for(j=0;j<arrDisplaynone.length;j++)
    {
        notecard = arrDisplaynone[j];
        exist = false;
        if(Ext.get("li_"+notecard.id) == null){
            for(i=0;i<pileNotecard.length;i++)
            {
                if(pileNotecard[i][1] == notecard.id)
                {
                    if(Ext.get(pileNotecard[i][0])){
                        exist = true;
                    }
                }
            }
            if(!exist)
            {
                if(itemBeingDragged != notecard.id){
                    Ext.get(notecard).dom.style.display = "block";
                    Ext.get("thumb_"+notecard.id).dom.style.display = "block";
                }
                for(i=0;i<notecardID.length;i++){
                    if(notecard.id == notecardID[i][0]){
                        notecardID[i][6] = "block";
                    }
                }
            }else{
                Ext.get(notecard).dom.style.display = "none";
                Ext.get("thumb_"+notecard.id).dom.style.display = "none";
            }
        }
    }
    // block to make the notecard hide if its in pile
    var arrDisplayblock= Ext.query("div[class=notecard]{display=block}");
    for(j=0;j<arrDisplayblock.length;j++)
    {
        notecard = arrDisplayblock[j];
        exist = false;
        if(Ext.get("li_"+notecard.id) === null){
            for(i=0;i<pileNotecard.length;i++)
            {
                if(pileNotecard[i][1] == notecard.id)
                {
                    exist = true;
                }
            }
            if(exist)
            {
                Ext.get(notecard).dom.style.display = "none";
                Ext.get("thumb_"+notecard.id).dom.style.display = "none";
                for(i=0;i<notecardID.length;i++){
                    if(notecard.id == notecardID[i][0]){
                        notecardID[i][6] = "none";
                    }
                }
            }else{
                Ext.get(notecard).dom.style.display = "block";
                if(Ext.get("thumb_"+notecard.id)){
                    Ext.get("thumb_"+notecard.id).dom.style.display = "block";
                }
            }
        }
    }
    updateCountInPile();
}
}
function formatTitleToDisplay(str){
var fntMatrics = Ext.util.TextMetrics.createInstance(Ext.get("sample_title_container"));
var finalStr="";
var brokenOnce = false;
var k=0;
var strBuffer = "";
for(k=0;k<str.length;k++){
    var myChar = str.toString().charAt(k);
    strBuffer += myChar;
    var mySize = fntMatrics.getSize(strBuffer);
    if(mySize.width>=68){
        if(!brokenOnce){
            if(str.toString().charAt(k-1) != " "){
                finalStr += "-<br>";
            }else{
                finalStr += "<br>";
            }
            strBuffer="";
            k--;
            brokenOnce=true;
        }else{
            finalStr += "..";
            break;
        }
    }else{
        finalStr += myChar;
    }
}

return finalStr;
}
// 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;
	}*/

this.title = formatTitleToDisplay(title);

if(isTeacher != "1"){
    this.body = "<div id="+this.id+" ondblclick=directEditNotecard('"+this.id+"') class=notecard onClick=highlightMe('"+this.id +"','click')>" + "<div class=notecardContent onmouseover=invokePopup('"+this.id+"') onmouseout=hideInfoPopup()>" + "<div id=colorsContainer_"+this.id+" class=colorsContainer>" + "<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>" + "<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>" + "<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>" + "<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>" + "<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>" + "<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>" + "<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>" + "</div>" + "<div id=tagsContainer_"+this.id+" class=tagsContainer>" + "<div id=research_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-magnify.gif');></div>" + "<div id=help_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-question.gif');></div>" + "<div id=incomplete_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-document.gif');></div>" + "<div id=thinking_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-lightbulb.gif');></div>" + "<div id=important_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-attention.gif');></div>" + "<div id=paper_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-checkmark.gif');></div>" + "</div>" + "</div>" + "<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>" + "</div>";
}else{
    this.body = "<div id="+this.id+" ondblclick=directEditNotecard('"+this.id+"') class=notecard onClick=highlightMe('"+this.id +"','click')>" + "<div class=notecardContent onmouseover=invokePopup('"+this.id+"') onmouseout=hideInfoPopup()>" + "<div id=colorsContainer_"+this.id+" class=colorsContainer >" + "<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>" + "<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>" + "<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>" + "<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>" + "<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>" + "<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>" + "<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>" + "</div>" + "<div id=tagsContainer_"+this.id+" class=tagsContainer>" + "<div id=research_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-magnify.gif');></div>" + "<div id=help_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-question.gif');></div>" + "<div id=incomplete_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-document.gif');></div>" + "<div id=thinking_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-lightbulb.gif');></div>" + "<div id=important_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-attention.gif');></div>" + "<div id=paper_"+this.id+" style=float:left;display:none;height:16px;width:16px;background-image:url('../notecards/_images/tag-checkmark.gif');></div>" + "</div>" + "</div>" + "<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>" + "</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 fnCollabCreateNotecard(notecard_id,notecardDetails)
{
notecardtitle = notecardDetails.Title;
notecardPosition = notecardDetails.Position;
notecardLeft = notecardDetails.Left;
notecardTop = notecardDetails.Top;
notecardDisplay = notecardDetails.Display;
notecardColors = notecardDetails.Colors;
notecardVisualCues = notecardDetails.VisualCues;

title = notecardtitle;
var noteCard = new NoteCardTemplate('Notecard_' + notecard_id, title);
notes[notecard_id] = new YAHOO.example.DDNotecard("Notecard_" + notecard_id, "", {
    cont: 'tabletop'
});
notes[notecard_id].on('dragEvent', function(ev){
    hideCurrPopup();
}, notes[notecard_id], true);
var div = document.createElement("div");
div.innerHTML = noteCard.toHTML();
document.getElementById("tabletop").appendChild(div.firstChild);
if (navigator.appName == "Microsoft Internet Explorer") {
    YAHOO.util.Dom.setXY('Notecard_' + notecard_id, [22, 270]);
}
else {
    YAHOO.util.Dom.setXY('Notecard_' + notecard_id, [20, 265]);
}
if(notecardLeft!==""){
    document.getElementById("Notecard_" + notecard_id).style.left = notecardLeft+"px";
}
if(notecardTop!==""){
    document.getElementById("Notecard_" + notecard_id).style.top = notecardTop+"px";
}
document.getElementById("Notecard_" + notecard_id).style.display = notecardDisplay;

var leftTop = getLeftTopInTabletop('Notecard_' + notecard_id);
createNotecardThumb('Notecard_' + notecard_id);
//if (pileid == null || pileid == "0" || pileid == "") {
if(notecardPosition == 'zone'){
    var zoneNoteCard = new zoneNotesLi('Notecard_' + notecard_id, title);
    var ol = document.createElement("ol");
    ol.innerHTML = zoneNoteCard.toHTML();
    document.getElementById('zoneList').appendChild(ol.firstChild);
    var parentEl = Ext.get("zoneList");
    var childEl = Ext.get('li_Notecard_' + notecard_id);
    parentEl.insertFirst(childEl);
    notecardID[notecardID.length] = ['Notecard_' + notecard_id, leftTop[0], leftTop[1], "", title, false, "none", "zone"];
}else{
    //pileNotecard[pileNotecard.length]=["Pile_"+pileid, "Notecard_"+cnt];
    notecardID[notecardID.length] = ['Notecard_' + notecard_id, leftTop[0], leftTop[1], "", title, false, "none", "tabletop"];
}
attachColors();
attachCues();
//fnCollabUpdateNotecard(notecard_id,notecardDetails);
loadTags();
}
// Function to update notecard details
function fnCollabUpdateNotecard(notecard_id,notecardDetails)
{
var notecardtitle = notecardDetails.Title;
var notecardPosition = notecardDetails.Position;
var notecardLeft = notecardDetails.Left;
var notecardTop = notecardDetails.Top;
var notecardDisplay = notecardDetails.Display;
var notecardColor = notecardDetails.Colors;
var notecardVisualCues = notecardDetails.VisualCues;
var i;
var title = notecardtitle;
var exists = false;
if(Ext.get("Notecard_"+notecard_id)){
    exists = true;
}
if(exists){
        
    for(i=0;i<notecardID.length;i++){
        var noteIdInArr = notecardID[i][0];
        if(noteIdInArr == "Notecard_"+notecard_id){
            if(notecardPosition != "zone"){
                if(notecardID[i][7]=="zone"){
                    Ext.get("li_Notecard_"+notecard_id).remove();
                }
                if(noteIdInArr != itemBeingDragged){
                    // set left position
                    Ext.get("Notecard_"+notecard_id).dom.style.left = notecardLeft+"px";
                    // set top position
                    Ext.get("Notecard_"+notecard_id).dom.style.top = notecardTop+"px";
                    // set display
                    Ext.get("Notecard_"+notecard_id).dom.style.display = notecardDisplay;

                    // update the array
                    notecardID[i][1] = notecardLeft;
                    notecardID[i][2] = notecardTop;
                    notecardID[i][6] = notecardDisplay;
                }
                Ext.get("thumb_Notecard_"+notecard_id).dom.style.display = notecardDisplay;
                // set title
                Ext.get("title_Notecard_"+notecard_id).dom.innerHTML = formatTitleToDisplay(title);
                // change the position of bird's eye view
                setLeftTopInBirdsEyeView("Notecard_"+notecard_id, getLeftTopInTabletop("Notecard_"+notecard_id));

                // remove all cues first
                Ext.get("research_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_research_Notecard_"+notecard_id)){
                    Ext.get("li_research_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("help_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_help_Notecard_"+notecard_id)){
                    Ext.get("li_help_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("incomplete_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_incomplete_Notecard_"+notecard_id)){
                    Ext.get("li_incomplete_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("thinking_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_thinking_Notecard_"+notecard_id)){
                    Ext.get("li_thinking_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("important_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_important_Notecard_"+notecard_id)){
                    Ext.get("li_important_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("paper_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_paper_Notecard_"+notecard_id)){
                    Ext.get("li_paper_Notecard_"+notecard_id).dom.style.display = "none";
                }
                for(jk=0;jk<noteCues.length;jk++)
                {
                    if(noteCues[jk][0] == noteIdInArr)
                    {
                        noteCues.splice(jk, 1);
                        jk=-1;
                    }
                }
                // apply visual cues
                if(notecardVisualCues.length>0){
                    for(j=0;j<notecardVisualCues.length;j++){
                        exists = 0;
                        //add noteid, cueid to the array
                        noteCues[noteCues.length]= [noteIdInArr,notecardVisualCues[j]];
                        if(notecardVisualCues[j]==1){
                            Ext.get("research_Notecard_"+notecard_id).dom.style.display = "block";
                            if(Ext.get("li_research_Notecard_"+notecard_id)){
                                Ext.get("li_research_Notecard_"+notecard_id).dom.style.display = "block";
                            }
                        }
                        if(notecardVisualCues[j]==2){
                            Ext.get("help_Notecard_"+notecard_id).dom.style.display = "block";
                            if(Ext.get("li_help_Notecard_"+notecard_id)){
                                Ext.get("li_help_Notecard_"+notecard_id).dom.style.display = "block";
                            }
                        }
                        if(notecardVisualCues[j]==3){
                            Ext.get("incomplete_Notecard_"+notecard_id).dom.style.display = "block";
                            if(Ext.get("li_incomplete_Notecard_"+notecard_id)){
                                Ext.get("li_incomplete_Notecard_"+notecard_id).dom.style.display = "block";
                            }
                        }
                        if(notecardVisualCues[j]==4){
                            Ext.get("thinking_Notecard_"+notecard_id).dom.style.display = "block";
                            if(Ext.get("li_thinking_Notecard_"+notecard_id)){
                                Ext.get("li_thinking_Notecard_"+notecard_id).dom.style.display = "block";
                            }
                        }
                        if(notecardVisualCues[j]==5){
                            Ext.get("important_Notecard_"+notecard_id).dom.style.display = "block";
                            if(Ext.get("li_important_Notecard_"+notecard_id)){
                                Ext.get("li_important_Notecard_"+notecard_id).dom.style.display = "block";
                            }
                        }
                        if(notecardVisualCues[j]==6){
                            Ext.get("paper_Notecard_"+notecard_id).dom.style.display = "block";
                            if(Ext.get("li_paper_Notecard_"+notecard_id)){
                                Ext.get("li_paper_Notecard_"+notecard_id).dom.style.display = "block";
                            }
                        }
                    }
                }
                // remove all colors first
                Ext.get("red_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_red_Notecard_"+notecard_id)){
                    Ext.get("li_red_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("orange_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_orange_Notecard_"+notecard_id)){
                    Ext.get("li_orange_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("yellow_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_yellow_Notecard_"+notecard_id)){
                    Ext.get("li_yellow_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("green_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_green_Notecard_"+notecard_id)){
                    Ext.get("li_green_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("blue_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_blue_Notecard_"+notecard_id)){
                    Ext.get("li_blue_Notecard_"+notecard_id).dom.style.display = "none";
                }
                Ext.get("purple_Notecard_"+notecard_id).dom.style.display = "none";
                if(Ext.get("li_purple_Notecard_"+notecard_id)){
                    Ext.get("li_purple_Notecard_"+notecard_id).dom.style.display = "none";
                }
                // apply color
                if(notecardColor !==""){
                    if(notecardColor==1){
                        Ext.get("red_Notecard_"+notecard_id).dom.style.display = "block";
                        Ext.get("thumb_Notecard_"+notecard_id).dom.style.background = "red";
                        if(Ext.get("li_red_Notecard_"+notecard_id)){
                            Ext.get("li_red_Notecard_"+notecard_id).dom.style.display = "block";
                        }
                    }
                    if(notecardColor==2){
                        Ext.get("orange_Notecard_"+notecard_id).dom.style.display = "block";
                        Ext.get("thumb_Notecard_"+notecard_id).dom.style.background = "orange";
                        if(Ext.get("li_orange_Notecard_"+notecard_id)){
                            Ext.get("li_orange_Notecard_"+notecard_id).dom.style.display = "block";
                        }
                    }
                    if(notecardColor==3){
                        Ext.get("yellow_Notecard_"+notecard_id).dom.style.display = "block";
                        Ext.get("thumb_Notecard_"+notecard_id).dom.style.background = "yellow";
                        if(Ext.get("li_yellow_Notecard_"+notecard_id)){
                            Ext.get("li_yellow_Notecard_"+notecard_id).dom.style.display = "block";
                        }
                    }
                    if(notecardColor==4){
                        Ext.get("green_Notecard_"+notecard_id).dom.style.display = "block";
                        Ext.get("thumb_Notecard_"+notecard_id).dom.style.background = "green";
                        if(Ext.get("li_green_Notecard_"+notecard_id)){
                            Ext.get("li_green_Notecard_"+notecard_id).dom.style.display = "block";
                        }
                    }
                    if(notecardColor==5){
                        Ext.get("blue_Notecard_"+notecard_id).dom.style.display = "block";
                        Ext.get("thumb_Notecard_"+notecard_id).dom.style.background = "blue";
                        if(Ext.get("li_blue_Notecard_"+notecard_id)){
                            Ext.get("li_blue_Notecard_"+notecard_id).dom.style.display = "block";
                        }
                    }
                    if(notecardColor==6){
                        Ext.get("purple_Notecard_"+notecard_id).dom.style.display = "block";
                        Ext.get("thumb_Notecard_"+notecard_id).dom.style.background = "purple";
                        if(Ext.get("li_purple_Notecard_"+notecard_id)){
                            Ext.get("li_purple_Notecard_"+notecard_id).dom.style.display = "block";
                        }
                    }
                }
                var colorexists = false;
                for(kj=0;kj<noteColor.length;kj++){
                    if(noteColor[kj][0] == "Notecard_"+notecard_id){
                        colorexists=true;
                        noteColor[kj][1] = notecardColor;
                    }
                }
                if(!colorexists){
                    noteColor[noteColor.length] = ["Notecard_"+notecard_id, notecardColor];
                }
            }
            // update notecard array on tabletop
            notecardID[i][4] = notecardtitle;
            notecardID[i][7] = notecardPosition;
            notecardID[i][3] = "";
        }
    }
}else if(!exists){
    fnCollabCreateNotecard(notecard_id, notecardDetails);
}
}
// function to delete pile
function fnCollabDeletePile(pile_id){
pile_id = "Pile_"+pile_id;

    if(Ext.get(pile_id)){
        Ext.get(pile_id).remove();
    }
    if(Ext.get("thumb_"+pile_id)){
        Ext.get("thumb_"+pile_id).remove();
    }
    if(Ext.get("li_"+pile_id)){
        Ext.get("li_"+pile_id).remove();
    }
    if(Ext.get("exp_"+pile_id)){
        Ext.get("exp_"+pile_id).remove();
    }
// removing pile from js array and dom
for(lm=0;lm<pileID.length;lm++){
    if(pileID[lm][0]==pile_id){
        
        pileID.splice(lm,1);
        lm=-1;
    }
}
for(lm=0;lm<expandedPileArray.length;lm++){
    if(expandedPileArray[lm][0]=="exp_"+pile_id){
        expandedPileArray.splice(lm,1);
        lm=-1;
    }
}
// removing pileNotecard entries
for(lm=0;lm<pileNotecard.length;lm++){
    if(pileNotecard[lm][0]==pile_id){
        pileNotecard.splice(lm, 1);
        lm=-1;
    }
}
}
// delete notecards deleted by other user
function fnCollabDeleteNotecard(notecard_id){
// check if element is in dom
if(Ext.get("Notecard_"+notecard_id)){
    // remove the record from array and dom
    for(k=0;k<notecardID.length;k++){
        if(notecardID[k][0] == "Notecard_"+notecard_id){
            Ext.get("Notecard_"+notecard_id).remove();

            if(Ext.get("thumb_Notecard_"+notecard_id)){
                Ext.get("thumb_Notecard_"+notecard_id).remove();
            }
            if(Ext.get("li_Notecard_"+notecard_id)){
                Ext.get("li_Notecard_"+notecard_id).remove();
            }
            notecardID.splice(k, 1);
            break;
        }
    }

}
}

// Function to create Pile
function fnCollabCreatePile(pile_id,piledetails)
{
pile_id="Pile_"+pile_id;
piletitle = piledetails.Title;
pilePosition = piledetails.Position;
pileLeft = piledetails.Left;
pileTop = piledetails.Top;
pileDisplay = piledetails.Display;
notecardsAssoc = piledetails.NotecardAssoc;

for(l=0;l<notecardsAssoc.length;l++){
    notecard_id=notecardsAssoc[l].ID;
    pileNotecard[pileNotecard.length] = [pile_id,"Notecard_"+notecard_id];
    fnCollabUpdateNotecard(notecardsAssoc[l].ID, notecardsAssoc[l]);
}
var newPile = new PileTemplate(pile_id, piletitle);
    
var div = document.createElement("div");
div.innerHTML = newPile.toHTML();
document.getElementById("tabletop").appendChild(div.firstChild);

if(isTeacher != "1"){
    a = new YAHOO.example.DDPile(pile_id);
}

if (pilePosition == "zone") {
    var zonePile = new zonePileLi(pile_id, piletitle);
    var ol = document.createElement("ol");
    ol.innerHTML = zonePile.toHTML();
    document.getElementById('zoneList').appendChild(ol.firstChild);
    var parentEl = Ext.get("zoneList");
    var childEl = Ext.get('li_'+pile_id);
    parentEl.insertFirst(childEl);
}else{
    createPileThumb(pile_id);
    document.getElementById('thumb_' + pile_id).style.display = pileDisplay;
}
initLeftTop=[];
initLeftTop[0] = pileLeft;
initLeftTop[1] = pileTop;
setLeftTopInTabletop(pile_id, initLeftTop);
setLeftTopInBirdsEyeView(pile_id, initLeftTop);
pileID[pileID.length] = [pile_id,pileLeft,pileTop,"",piletitle, pileDisplay, false, pilePosition];
document.getElementById(pile_id).style.display = pileDisplay;
document.getElementById(pile_id).className = "pile";
updateCountInPile();
    

}
// Function to update pile details
function fnCollabUpdatePile(pile_id,piledetails)
{
    
piletitle = piledetails.Title;
pilePosition = piledetails.Position;
pileLeft = piledetails.Left;
pileTop = piledetails.Top;
pileDisplay = piledetails.Display;
notecardsAssoc = piledetails.NotecardAssoc;
var notecard_id;
if(notecardsAssoc.length >= 2){
    if(Ext.get("Pile_"+pile_id)){
        pile_id="Pile_"+pile_id;
        // updating pile details
        for(lm=0;lm<pileID.length;lm++){
            if(pileID[lm][0]==pile_id){
                pileID[lm][1]=pileLeft;
                pileID[lm][2]=pileTop;
                pileID[lm][4]=piletitle;
                pileID[lm][6]=pileDisplay;
                if(pileID[lm][7] == "zone" && pileID[lm][7] != pilePosition){
                    Ext.get("li_"+pile_id).remove();
                    pileID[lm][7] = pilePosition;
                }
            }
        }
            
        Ext.get("title_"+pile_id).dom.innerHTML=formatTitleToDisplay(piletitle);
        Ext.get(pile_id).dom.style.left=pileLeft+"px";
        Ext.get(pile_id).dom.style.top=pileTop+"px";
        setLeftTopInBirdsEyeView(pile_id, getLeftTopInTabletop(pile_id));
        if(Ext.get("exp_"+pile_id) === null){
            Ext.get(pile_id).dom.style.display=pileDisplay;
        }
        // remove any existing entries for notecards in same or other pile
        for(kl=0;kl<pileNotecard.length;kl++){
            notecard_id = pileNotecard[kl][1];
            for(nm=0;nm<notecardsAssoc.length;nm++){
                if(notecard_id == "Notecard_"+notecardsAssoc[nm].ID){
                    pileNotecard.splice(kl,1);
                    kl=-1;
                }
            }
        }
        // remove all entries of noetcards from the pile that is being updated
        for(kl=0;kl<pileNotecard.length;kl++){
            if(pile_id==pileNotecard[kl][0]){
                pileNotecard.splice(kl,1);
                kl=-1;
            }
        }
        for(lm=0;lm<notecardsAssoc.length;lm++){
            notecard_id=notecardsAssoc[lm].ID;
            pileNotecard[pileNotecard.length] = [pile_id,"Notecard_"+notecard_id];
            fnCollabUpdateNotecard(notecardsAssoc[lm].ID, notecardsAssoc[lm]);
        }
        updateCountInPile();
    }else{
        fnCollabCreatePile(pile_id, piledetails);
        return;
    }
}else{
    fnCollabDeletePile(pile_id);
    for(i=0;i<notecardsAssoc.length;i++){
        fnCollabUpdateNotecard(notecardsAssoc[i].ID, notecardsAssoc[i]);
    }
}
}
// function to load Outline HTML tree
function reloadOutline(){
loadingOutline = true;
setOutlineUpdated();
// remove all entries from notecardOutline array
for(km=0;km<notecardsOutline.length;km++){
    if(Ext.get(notecardsOutline[km][0])){
        Ext.get("check_"+notecardsOutline[km][0]).setDisplayed(false);
    }
}
var projectID = document.getElementById('projectID').value;
//function called on failure
var failure = function(o){
};
var success = function(o){
    if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
    {
        showNotesSessionError(Trim(o.responseText));
        return false;
    }
    var prod1 = null;
    // parse the json resopnse and convert it into the array
    prod1 = YAHOO.lang.JSON.parse(o.responseText);

    // store the outline data
    var temp = prod1[3];
    // check if the outline data was blank
    if (temp.length!==0) {
        try {

            // check if the outline content is in html format
            if (prod1[4] == "1") {

                this.body = temp;
                listCnt = Number(prod1[1]);
                itemCnt = Number(prod1[2]);

                document.getElementById("outline").innerHTML = this.body;
                createInstancesInOutline();
                saveHTMLTree();
                loadingOutline = false;
                setOutlineUpdated();
            }
            else {

                document.getElementById("outline").innerHTML = "<ol id=list_1></ol>";
                // get the outline nodes araay populated
                var nodesArr = prod1[3];

                // populate the counters
                listCnt = Number(prod1[1]);
                itemCnt = Number(prod1[2]);
                // loop through to create all the nodes in the sequesnce they existed
                for (i = 0; i < nodesArr.length; i++) {
                    // get the item id
                    var itmID = nodesArr[i][0];
                    // get the content div id that holds the title
                    var contentDivId = nodesArr[i][1];
                    // get the parent li id where it needs to be appended
                    var parentId = nodesArr[i][5];
                    // get whether its a notecard or not
                    var isNotecard = nodesArr[i][4];
                    // get the tite
                    var myText = nodesArr[i][2];
                    //var myText = nodeArr[i][2];
                    //alert("erwewe");
                    // get the id of ol container which the node was a part of
                    var listId = nodesArr[i][3];
                    // call to a function to append the item in the dom
                    //alert("asdas1111111"+itmID+" : "+contentDivId+" : "+ parentId+" : "+isNotecard+" : "+myText+" : "+listId);
                    appendOutlineItem(itmID, contentDivId, parentId, isNotecard, myText, listId);
                    if(i==(nodesArr.length-1)){
                        loadingOutline = false;
                        setOutlineUpdated();
                    }
                        
                }

                // call the function to make notecard nodes draggable
                createInstancesInOutline();
                // update the progress bar
                Ext.MessageBox.updateProgress(4 / 7, 'Loading (57%)');
                //call the next function in load sequesnce
                attachCues();
                // code to show the help bubble
                if(Ext.get("showHelpBubble").getValue()=="1"){
                    if (notecardID.length < 2 && document.getElementById('help').value == "1") {
                        if (isTeacher != "1") {
                            bubble_NewNoteButton();
                        }
                    }
                }
            }
        }
        catch (e) {
        }
    }else
    {
        // if its a new outline
        OutlineHtml = document.getElementById("outline").innerHTML;
        // if the outline is not converted and the outline content retreived by json are blank
        if (prod1[0] == "0" && temp.length===0) {
            var failure = function(o){
                 showFailureMessage();
            };
            var success = function(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: success,
                failure: failure,
                params: {
                    toggle: 'insertHTMLTree',
                    projectID: projectID,
                    data: OutlineHtml,
                    macfix: '1234'
                }
            });
        }
        // fill the counters
        listCnt = Number(prod1[1]);
        itemCnt = Number(prod1[2]);

        // make nodes draggable and droppable
        createInstancesInOutline();
        loadingOutline = false;
        setOutlineUpdated();
    }
        
    return true;
};

Ext.Ajax.request({
    url: '../notecards/_includes/notecardOperations.php',
    method: 'POST',
    success: success,
    failure: failure,
    params: 'toggle=getHTMLTree&projectID='+projectID+'&windowname='+windowname+'&macfix=1234'
});
}
function fnCollabProcessUpdateDetails(updateDetail)
{
var notecardDetails="";
var notecard_id = "";
var piledetails="";
var pile_id = "";
var hasOutlineUpdates = false;
for(var i=0;i<updateDetail.length;i++)
{
    if(updateDetail[i].Action == "I") // If data has been Inserted
    {
        if(updateDetail[i].Type == "N") // if new notecard has been added
        {
            notecardDetails = updateDetail[i].ItemDetail;
            notecard_id = updateDetail[i].ItemID;
            fnCollabCreateNotecard(notecard_id,notecardDetails);
        }
        else if(updateDetail[i].Type == "P") // If new pile has been added
        {
            piledetails = updateDetail[i].ItemDetail;
            pile_id = updateDetail[i].ItemID;
            fnCollabCreatePile(pile_id,piledetails);
        }
    }
    else if (updateDetail[i].Action == "U") // If data has been updated
    {
        if(updateDetail[i].Type == "N") // if notecard has been updated
        {
            notecardDetails = updateDetail[i].ItemDetail;
            notecard_id = updateDetail[i].ItemID;
            fnCollabUpdateNotecard(notecard_id, notecardDetails);
        }
        else if(updateDetail[i].Type == "P") // If pile has been updated
        {
            piledetails = updateDetail[i].ItemDetail;
            pile_id = updateDetail[i].ItemID;
            fnCollabUpdatePile(pile_id,piledetails);
        }
        else if(updateDetail[i].Type == "O") // If pile has been updated
        {
            hasOutlineUpdates=true;

        }
    }
    else if (updateDetail[i].Action == "D") // If data has been deleted
    {
        if(updateDetail[i].Type == "N") // if notecard has been updated
        {
            notecard_id = updateDetail[i].ItemID;
            fnCollabDeleteNotecard(notecard_id);
        }
        else if(updateDetail[i].Type == "P") // If pile has been updated
        {
            pile_id = updateDetail[i].ItemID;
            fnCollabDeletePile(pile_id);
        }
    }
}
if(hasOutlineUpdates){
    reloadOutline();
}
else
{
    setOutlineUpdated();
}
updateComplete=true;
}
function fnCollabProcessChecks(checkArr){
for(km=0;km<checkArr.length;km++){
    if(checkArr[km].TYPE=="N"){
        if(checkArr[km].ACTION=="U"){
            Ext.get("Notecard_"+checkArr[km].ID).dom.style.display="block";
            Ext.get("thumb_Notecard_"+checkArr[km].ID).dom.style.display="block";
        }
        if(checkArr[km].ACTION=="D"){
            Ext.get("Notecard_"+checkArr[km].ID).remove();
            Ext.get("thumb_Notecard_"+checkArr[km].ID).remove();
        }
    }
    if(checkArr[km].TYPE=="P"){
        if(checkArr[km].ACTION=="D"){
            if(Ext.get("Pile_"+checkArr[km].ID)){
                Ext.get("Pile_"+checkArr[km].ID).remove();
            }
            if(Ext.get("li_Pile_"+checkArr[km].ID)){
                Ext.get("li_Pile_"+checkArr[km].ID).remove();
            }
            if(Ext.get("thumb_Pile_"+checkArr[km].ID)){
                Ext.get("thumb_Pile_"+checkArr[km].ID).remove();
            }
        }
    }
}
}

function setOutlineUpdated()
{
if(!loadingOutline){
    isOutlineUpdated = true;
}
}
// new function for collaborations

function fnCollaborationProcessResponse(resArray)
{
var returnVal = true;
if(resArray.SESSION_ERROR.HAS_ERROR === true)
{
    hidePopupOnDrag();
	var doLogout = false;
    if(!sessionErrorWindowDisPlayed){
        //If session expires when New/Edit notecard window is up, then do the confirmation about close of the window.
		if((document.getElementById('editNoteWin') != null && typeof(document.getElementById('editNoteWin'))!="undefined" && document.getElementById('editNoteWin').style.visibility == "visible") || (document.getElementById('newNotecardWindow') != null && typeof(document.getElementById('newNotecardWindow'))!="undefined" && document.getElementById('newNotecardWindow').style.visibility == "visible")){
			var conf = confirm("Your session has expired and your changes cannot be saved, likely due to opening NoodleTools in more than one browser window.\n\nClick \"Cancel\" to copy and paste your work into a text editor before closing this notecard. Otherwise, click \"OK\" to close this notecard and log back in.");
			if(conf){
				doLogout = true;
			}
		}else{
			doLogout = true;
			//alert(resArray.SESSION_ERROR.MESSAGE);
		}
    }
	if(doLogout){
		sessionErrorWindowDisPlayed = true;
		window.location.href = '../../noodlebib/logout.php';
	}
    returnVal =  false;
}
else if(resArray.MULTIPLE_INST.HAS_ERROR === true)
{
	var doLogout = false;
	var reason = resArray.MULTIPLE_INST.ERROR_REASON;
	//If multiple instances are opened when New/Edit notecard window is up, then do the confirmation about close of the window.
	if((document.getElementById('editNoteWin') != null && typeof(document.getElementById('editNoteWin'))!="undefined" && document.getElementById('editNoteWin').style.visibility == "visible") || (document.getElementById('newNotecardWindow') != null && typeof(document.getElementById('newNotecardWindow'))!="undefined" && document.getElementById('newNotecardWindow').style.visibility == "visible")){
		var conf = confirm("Your session has expired and your changes cannot be saved, likely due to opening NoodleTools in more than one browser window.\n\nClick \"Cancel\" to copy and paste your work into a text editor before closing this notecard. Otherwise, click \"OK\" to close this notecard and log back in.");
		if(conf){
			doLogout = true;
		}
	}else{
		doLogout = true;
	}
	
	if(doLogout){
		window.location.href = '../../onewindowpage.php?reason='+reason;
	}	
    returnVal =  false;
}

else if(resArray.ACCESS_ERROR.HAS_ERROR === true)
{
    alert('You are not authorized to access this project');
    window.location.href = '../../noodlebib/index.php';
    returnVal =  false;
}
else{
    var ProcessUpdatesIfPresent = function(){
        pileNotecard = resArray.NOTEPILE;
        if(resArray.UPDATES.HAS_UPDATES === true)
        {
            if(Ext.get("tabletop")){
                //YAHOO.util.DragDropMgr.lock();
                showSyncPopup();
                hideSyncWindow.defer(3000);
                var updateDetail = resArray.UPDATES.UPDATE_DATA;
                // processing with data
                fnCollabProcessUpdateDetails(updateDetail);
            }
        }
        else{
            setOutlineUpdated();
        }
    };
    if(Ext.get("tabletop")){
        fnCollabProcessChecks(resArray.CHECKS);
    }
    if(resArray.PROCESSING_ERROR.HAS_ERROR === true)
    {
        if(Ext.MessageBox.isVisible()){
            Ext.MessageBox.hide();
        }
        hidePopupOnDrag();
        //alert(resArray.PROCESSING_ERROR.ERROR_MESSAGE);
        Ext.MessageBox.show({
            title: 'Error',
            msg: resArray.PROCESSING_ERROR.ERROR_MESSAGE ,
            buttons: Ext.MessageBox.OK,
            fn: ProcessUpdatesIfPresent,
            icon: Ext.MessageBox.ERROR
        });
        returnVal = false;
    }
    else if(resArray.LOCK.HAS_LOCK === true)
    {
        hidePopupOnDrag();
        if(Ext.get("tabletop")){
            if(resArray.LOCK.ISPILE === true)
            {
                var arrpile = resArray.LOCK.PILEDATA;
                var pile_lock_id = "Pile_"+arrpile[0];
                arrpile.splice(0,1);

                for(i=0;i<pileNotecard.length;i++)
                {
                    if(pileNotecard[i][0] == pile_lock_id)
                    {
                        pileNotecard.splice(i,1);
                        i= -1;
                    }
                }
                for(i=0;i<arrpile.length;i++)
                {
                    pileNotecard[pileNotecard.length] = [pile_lock_id,"Notecard_"+arrpile[i]];
                    Ext.get("Notecard_"+arrpile[i]).dom.style.display = "none";
                    if(Ext.get("thumb_Notecard_"+arrpile[i])){
                        Ext.get("thumb_Notecard_"+arrpile[i]).dom.style.display = "none";
                    }
                }
            }
        }
        //alert(resArray.LOCK.MESSAGE);
        Ext.MessageBox.show({
            title: 'Error',
            msg: resArray.LOCK.MESSAGE ,
            buttons: Ext.MessageBox.OK,
            fn: ProcessUpdatesIfPresent,
            icon: Ext.MessageBox.ERROR
        });
        returnVal = false;
    }else{
        ProcessUpdatesIfPresent();
    }
    //if(Ext.get("tabletop")){
    var totalLoggedInUsers = resArray.LOGGED_USERS;
    var newLoggedInUsers = resArray.NEW_LOGGED_IN_USERS;
    var newLoggedOutUsers = resArray.LOGGED_OUT_USERS;

    if(totalLoggedInUsers.length>0){
        showLoggedInUsers(totalLoggedInUsers);
    }
    if(newLoggedInUsers.length>0){
        showNewlyLoggedInUser(newLoggedInUsers);
    }
    if(newLoggedOutUsers.length>0){
        showNewlyLoggedOutUser(newLoggedOutUsers);
    }
    if(totalLoggedInUsers.length===0){
        if(Ext.get('totalUsers')){
            Ext.get('totalUsers').ghost("t", {
                remove:true
            });
        }
    }
    //}
    //pileNotecard = resArray.NOTEPILE;
    updateCountInPile();
    repairTabletop();
}
return returnVal;
}

// function to call an ajax request to update the title in database
function updateNoteTitleInDatabase(noteid,title,oldNoteTitle)
{
var id = noteid.substr(9);
function handleFailure (o)
{
     showFailureMessage();
}
function handleSuccess (o){

    var resp = Ext.decode(o.responseText);
    if(!fnCollaborationProcessResponse(resp))
    {
        document.getElementById('title_'+ noteid).innerHTML = oldNoteTitle;
    }
}

Ext.Ajax.request({
    url: '../notecards/_includes/notecardOperations.php',
    method: 'POST',
    success: handleSuccess,
    failure: handleFailure,
    params : 'toggle=updateNoteTitle&title='+title+'&id='+id+'&windowname='+windowname+'&macfix=1234'
});
}

// 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)+"...";
			}*/
        title = formatTitleToDisplay(title);

        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)+"...";
		}*/
    title = formatTitleToDisplay(title);

    if(document.getElementById("div_Notecard_"+id+"_title")){
        document.getElementById("div_Notecard_"+id+"_title").innerHTML = title;
    }
}
loadTags();


}

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 prod1 = null;
    try {
        prod1 = YAHOO.lang.JSON.parse(o.responseText);
    }
    catch (e) {
        alert(e);
    }
    if (prod1) {
        for (i = 0; i < prod1.length; i++) {

            // If topX and topY position is blank or null then return random position
            var returnval = getRandomWidthHeight(prod1[i][1],prod1[i][2]);
            prod1[i][1] = returnval[0];
            prod1[i][2] = returnval[1];
            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();
    return true;
}
function handleFailure (o)
{
     showFailureMessage();
}

//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+'&windowname='+windowname+'&macfix=1234'
});
}
function fillPileNoteArray(){
function handleSuccess (o){
    if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
    {
        showNotesSessionError(Trim(o.responseText));
        return false;
    }
    pileNotecard = [];
    var prod2;
    try {
        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();
    return true;
}
function handleFailure (o)
{
     showFailureMessage();
}

//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+'&windowname='+windowname+'&macfix=1234'
});
}
function fillNotecardsAraay(){

projectid = document.getElementById('projectID').value;

function handleFailure (o)
{
     showFailureMessage();
}
function handleSuccess (o){
    var result = Ext.decode(o.responseText);
    var collborationResponse = fnCollaborationProcessResponse(result);
    notecardID=[];
    if(collborationResponse === true){
        prod = result.RESPONSE;
        
    
    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();
    return true;
}
}

Ext.Ajax.request({
    url: '../notecards/_includes/notecardOperations.php',
    method: 'POST',
    success: handleSuccess,
    failure: handleFailure,
    params : 'toggle=loadNotecardData&projectID='+projectid+'&windowname='+windowname+'&macfix=1234'
});




}
// function to open notecard in edit view
function displaywindow(notecardDetails, allTags, tagString, tagArray, src){
editPileStore = new Ext.data.JsonStore({
    url: '../notecards/_includes/notecardOperations.php?toggle=loadProjectPiles',
    root: 'records',
    autoLoad: true,
    fields: ['name', 'pileid', 'name', 'title']

});
var pileField;
var selectedPileDet = notecardDetails[8];
var tempeditNoteID = notecardDetails[7];
    
if (selectedPileDet[0] == '0') {
    pileField = new Ext.form.ComboBox({
        id: 'uCmbPile',
        store: editPileStore,
        typeAhead: false,
        editable: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        displayField: 'title',
        valueField: 'pileid',
        emptyText: 'Select a Pile ...',
        listeners: {
            'select': {
                fn: function(combo, newVal, oldVal){
                    Ext.getCmp('mypileid').setValue(newVal.data.pileid);
                    Ext.getCmp('newPileEntry').setValue('new');
                }
            }
        }
    });
}else{
    var PileTitle=selectedPileDet[1];

    pileField = new Ext.form.ComboBox({
        id: 'uCmbPile',
        store: editPileStore,
        typeAhead: false,
        editable: false,
        mode: 'local',
        disabled: true,
        forceSelection: true,
        triggerAction: 'all',
        displayField: 'title',
        valueField: 'pileid',
        value: PileTitle,
        emptyText: 'Select a Pile ...',
        listeners: {
            'select': {
                fn: function(combo, newVal, oldVal){
                    Ext.getCmp('mypileid').setValue(newVal.data.pileid);
                    Ext.getCmp('newPileEntry').setValue('new');
                }
            }
        }
    });
}
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;
    
//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]";

/*TAB*/
        var IsiPad3 = navigator.userAgent.indexOf("iPad; U; CPU OS 3");
	var IsiPad4 = navigator.userAgent.indexOf("iPad; U; CPU OS 4");
        var disabledEditor = "";
        if((IsiPad4 == -1)&&(IsiPad3 == -1))
	{
            disabledEditor = ",noneditable";
        }
	
	 var texteditor = {
					 columnWidth: 0.55,
					 xtype: "tinymce",
					 fieldLabel: "Rich text",
					 id: "uquotation",
					 name: "uquotation",
					 width: 300,
					 height: 390,
					 tinymceSettings: {
						  theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor,
								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: "top",
								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,
								theme_advanced_path : false
								},
							value: notecardDetails[4]
			 };
		var texteditor1 =  {
                            columnWidth: 0.55,
                            xtype: "tinymce",
                            fieldLabel: "Rich text",
                            id: "uparaphrase",
                            name: "uparaphrase",
                            width: 300,
                            height: 390,
                            tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor, // 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: "top",
                                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,
								theme_advanced_path : false
                            },
							value: notecardDetails[5]
                        };
						
						var texteditor2 =  {
                            columnWidth: 0.55,
                            xtype: "tinymce",
                            fieldLabel: "Rich text",
                            id: "uideas",
                            name: "uideas",
                            width: 300,
                            height: 390,
                            tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor, // 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: "top",
                                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,
								theme_advanced_path : false
                            },
							value: notecardDetails[6]
                        };
	
/*ENDTAB*/


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',
    width: 600,
    items: [{
            layout: 'form',
            items: [{
                    layout: 'column',
                    items: [{
                            columnWidth: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Title</b>'
                        }, {
                            columnWidth: 0.5,
                            xtype: 'textfield',
                            fieldLabel: 'Title',
                            id: 'utxtTitle',
                            name: 'utxtTitle',
                            allowBlank: false,
                            disabled: disableMe,
                            value: notecardDetails[0],
                            anchor: '95%'
                        }, {
                            columnWidth: 0.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: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Source</b>'
                        }, {
                            columnWidth: 0.5,
                            items: [srcField],
                            anchor: '98%'
                        }, {
                            columnWidth: 0.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: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Pile</b>'
                        }, {
                            columnWidth: 0.5,
                            items: [pileField],
                            anchor: '98%'
                        },
                        {
                            columnWidth: 0.5,
                            items: [{
                                    xtype: 'textfield',
                                    hidden: true,
                                    id: 'mypileid',
                                    value: notecardDetails[8]
                                }, {
                                    xtype: 'textfield',
                                    hidden: true,
                                    id: 'newPileEntry',
                                    value: 'old'
                                }]
                        }]
                }, {
                    layout: 'column',
                    items: [{
                            columnWidth: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>URL</b>'
                        }, {
                            columnWidth: 0.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: 0.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: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Pages</b>'
                        }, {
                            columnWidth: 0.5,
                            xtype: 'textfield',
                            id: 'utxtPages',
                            disabled: disableMe,
                            name: 'utxtPages',
                            value: notecardDetails[3],
                            anchor: '95%'
                        }, {
                            columnWidth: 0.5,
                            cls: 'editViewText',
                            bodyStyle: 'padding:0px 0px 0px 10px;',
                            html: 'Page number(s) of material, if given.<br><br>'
                        }]
                }, {
                    layout: 'column',
                    items: [{
                            columnWidth: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Tags<b>'
                        }, {
                            columnWidth: 0.5,
                            xtype: 'textfield',
                            fieldLabel: 'pages',
                            id: 'utxtTags',
                            disabled: disableMe,
                            name: 'utxtTags',
                            value: tagString,
                            anchor: '95%'
                        }, {
                            columnWidth: 0.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: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Existing Tags</b>'
                        }, {
                            columnWidth: 0.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;
                                                    }
                                                    return true;
                                                }
                                                function failFn(){
                                                     showFailureMessage();
                                                }
                                                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+"&windowname="+windowname+"&macfix=1234");
                                            }
                                        }
                                    }
                                })]
                        }, {
                            columnWidth: 0.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 tidy up later.'
                        }]
                }, {
                    layout: 'column',
                    items: [{
                            columnWidth: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Direct Quotation</b>'
                        }, texteditor , {
                            columnWidth: 0.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: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>Paraphrase</b>'
                        }, texteditor1 , {
                            columnWidth: 0.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: 0.75,
                            bodyStyle: 'padding-top:5px;',
                            html: '<b>My Ideas</b>'
                        }, texteditor2 , {
                            columnWidth: 0.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: 0.5,
                            xtype: 'textfield',
                            value: srcIDVal,
                            name: 'usourceID',
                            id: 'usourceID',
                            hidden: true,
                            anchor: '95%'
                        }, {
                            columnWidth: 0.5,
                            xtype: 'textfield',
                            value: tempeditNoteID,
                            name: 'uid',
                            id: 'uid',
                            hidden: true,
                            anchor: '95%'
                        },
                        {
                            columnWidth: 0.5,
                            xtype: 'textfield',
                            value: windowname,
                            name: 'windowname',
                            id: 'windowname',
                            hidden: true
                        },
                        {
                            columnWidth: 0.5,
                            xtype: 'textfield',
                            value: '1234',
                            name: 'macfix',
                            id: 'macfix',
                            hidden: true,
                            anchor: '95%'
                        }
                    ]
                }]
        }],
    buttons: [{
            text: 'Save',
            type: 'button',
            disabled: disableMe,
            listeners: {
                'click': {
                    fn: function(){
                        var showResult = function(btn){

                        };
                        if (editForm.getForm().isValid()) {
                            var val = Trim(Ext.getCmp('utxtTitle').getValue());
                            if (alphanumeric(val)) {
                                if (!htmlTags(val)) {
                                    tempeditNoteID = Ext.getCmp('uid').getValue();
                                    if (!CheckNoteTitle(val, "Notecard_" + tempeditNoteID)) {
                                        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>")) {
                                            var emptyQuotation = function(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>")) {
                                                var emptyPara = function(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>")) {
                                                var emptyIdeas = function(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) {
                                                var emptyQuotation1 = function(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: emptyQuotation1,
                                                icon: Ext.MessageBox.ERROR
                                            });
                                        }
                                        else
                                            if (ptext.length > 10000) {
                                                var emptyPara1 = function(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: emptyPara1,
                                                icon: Ext.MessageBox.ERROR
                                            });
                                        }
                                        else
                                            if (itext.length > 10000) {
                                                var emptyIdeas1 = function(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: emptyIdeas1,
                                                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){
                                                        obj = Ext.decode(action.response.responseText);
                                                        tempeditNoteID = obj.id;
                                                        var collabresponse = fnCollaborationProcessResponse(obj.data.response);

                                                        if(collabresponse === true)
                                                        {
                                                            updateEditedNotecard(tempeditNoteID, Ext.getCmp('utxtTitle').getValue());
                                                            Ext.getCmp('utags1').store.reload();
                                                            Ext.getCmp('usourceID').setValue('0');
                                                            if (Ext.getCmp('newPileEntry').getValue() == "new") {
                                                                if (Ext.getCmp('mypileid').getValue() != '0') {
                                                                    var mypileId = Ext.getCmp('mypileid').getValue();
                                                                    var editnoteid = Ext.getCmp('uid').getValue();
                                                                    if (Ext.get("exp_Pile_" + mypileId)) {
                                                                        var note_li = new NotesLi("Notecard_" + editnoteid);
                                                                        var div = document.createElement("ol");
                                                                        div.innerHTML = note_li.toHTML();
                                                                        document.getElementById("li_Pile_" + mypileId).appendChild(div.firstChild);
                                                                    }
                                                                    for (i = 0; i < notecardID.length; i++) {
                                                                        if (notecardID[i][0] == "Notecard_" + editnoteid) {
                                                                            notecardID[i][6] = "none";
                                                                        }
                                                                    }
                                                                    YAHOO.util.Dom.setStyle("Notecard_" + editnoteid, "display", "none");
                                                                    YAHOO.util.Dom.setStyle("thumb_Notecard_" + editnoteid, "display", "none");
                                                                    inserPileNoteRelation('Pile_' + mypileId, 'Notecard_' + editnoteid);

                                                                    //updatePileNoteRelInDatabase('Pile_' + mypileId);
                                                                    updateCountInPile();
                                                                }
                                                                Ext.getCmp('newPileEntry').setValue('old');
                                                            }
                                                            editNoteWin.hide();
                                                            editForm.getForm().reset();
                                                        }

                                                    },

                                                    // 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();
                                                         showFailureMessage();
                                                    }
                                                });

                                            }
                                            else {
                                                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 {

                                        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 {

                                    Ext.MessageBox.show({
                                        title: 'Error',
                                        msg: 'The characters &, <, and > are reserved characters and cannot be used in the notecard title.',
                                        buttons: Ext.MessageBox.OK,
                                        closable: false,
                                        fn: showResult,
                                        icon: Ext.MessageBox.ERROR
                                    });
                                }
                            }
                            else {

                                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 {

                            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(){
                        submit1=false;
                        releaseLockForElementUnderProcess("Notecard_"+tempeditNoteID);
                        editNoteWin.hide();
                    }
                }
            }
        }]

});

function handlers(cmp){
    editNoteWin.body.dom.scrollTop = 0;
    this.bool = false;
    if (!submit1) {

        var dirty = false;
        if (Ext.getCmp('utxtTitle').isDirty() ||
            Ext.getCmp('mypileid').isDirty() ||
            Ext.getCmp('utxtSource').isDirty() ||
            Ext.getCmp('utxtURL').isDirty()||
            Ext.getCmp('utxtPages').isDirty() ||
            Ext.getCmp('utxtTags').isDirty() ||
            Ext.getCmp('uquotation').isDirty() ||
            Ext.getCmp('uparaphrase').isDirty() ||
            Ext.getCmp('uideas').isDirty()
    ){
            dirty = true;
        }


        if (dirty) {
            var showResult = function(btn){
                if (btn == "yes") {
                    if (editForm.getForm().isValid()) {
                        tempeditNoteID = Ext.getCmp('uid').getValue();
                        var val = Trim(Ext.getCmp('utxtTitle').getValue());
                        if (!htmlTags(val)) {
                            if (alphanumeric(val)) {
                                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>")) {
                                    var emptyQuotation = function(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>")) {
                                        var emptyPara = function(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>")) {
                                        var emptyIdeas = function(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) {
                                        var emptyQuotation1 = function(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: emptyQuotation1,
                                        icon: Ext.MessageBox.ERROR
                                    });
                                }
                                else
                                    if (ptext.length > 10000) {
                                        var emptyPara1 = function(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: emptyPara1,
                                        icon: Ext.MessageBox.ERROR
                                    });
                                }
                                else
                                    if (itext.length > 10000) {
                                        var emptyIdeas1 = function(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: emptyIdeas1,
                                        icon: Ext.MessageBox.ERROR
                                    });
                                }else{
                                    //editNoteWin.un('beforehide', handlers);
                                    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_MULTIPLE")||(Trim(action.responseText)).match("ERROR_NOID")) {
                                                showNotesSessionError(Trim(action.responseText));
                                                return false;
                                            }
                                            var obj = Ext.util.JSON.decode(action.response.responseText);
                                            tempeditNoteID = obj.id;
                                            var MaincollabResp = fnCollaborationProcessResponse(obj.data.response);
                                            if(MaincollabResp){
                                                updateEditedNotecard(tempeditNoteID, Ext.getCmp('utxtTitle').getValue());
                                                Ext.getCmp('utags1').store.reload();
                                                Ext.getCmp('usourceID').setValue('0');
                                                if (Ext.getCmp('newPileEntry').getValue() == "new") {
                                                    if (Ext.getCmp('mypileid').getValue() != '0') {
                                                        var mypileId = Ext.getCmp('mypileid').getValue();
                                                        var editnoteid = Ext.getCmp('uid').getValue();
                                                        if (Ext.get("exp_Pile_" + mypileId)) {
                                                            var note_li = new NotesLi("Notecard_" + editnoteid);
                                                            var div = document.createElement("ol");
                                                            div.innerHTML = note_li.toHTML();
                                                            document.getElementById("li_Pile_" + mypileId).appendChild(div.firstChild);
                                                        }
                                                        for (i = 0; i < notecardID.length; i++) {
                                                            if (notecardID[i][0] == "Notecard_" + editnoteid) {
                                                                notecardID[i][6] = "none";
                                                            }
                                                        }
                                                        YAHOO.util.Dom.setStyle("Notecard_" + editnoteid, "display", "none");
                                                        YAHOO.util.Dom.setStyle("thumb_Notecard_" + editnoteid, "display", "none");
                                                        inserPileNoteRelation('Pile_' + mypileId, 'Notecard_' + editnoteid);
                                                        //updatePileNoteRelInDatabase('Pile_' + mypileId);
                                                        updateCountInPile();
                                                    }
                                                    Ext.getCmp('newPileEntry').setValue('old');
                                                }
												//unset handlers when there is no any session / multilogin error
												editNoteWin.un('beforehide', handlers);
                                                cmp.hide();
                                                editForm.getForm().reset();
                                            }
                                            return true;
                                        },

                                        // 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();
                                             showFailureMessage();
                                        }
                                    });


                                }
                            }
                            else {
                                showResult = function(btn){

                                };
                                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 {
                            showResult = function(btn){

                            };
                            Ext.MessageBox.show({
                                title: 'Error',
                                msg: 'The characters &, <, and > are reserved characters and cannot be used in the notecard title.',
                                buttons: Ext.MessageBox.OK,
                                closable: false,
                                fn: showResult,
                                icon: Ext.MessageBox.ERROR
                            });
                        }
                    }
                    else {
                        showResult = function(btn){

                        };
                        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 your changes?', showResult);
            return false;
        }
        else {
            return true;
        }
    }
    else {
        return true;
    }
}
// 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){
                editNoteWin.on('beforehide', handlers);
                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('uCmbPile').store.reload();

                Ext.getCmp('utxtTitle').focus(true, 1500);
                Ext.getCmp('utags1').clearValue();
                hidePopupOnDrag();
            }
        },
        'hide': {
            fn: function(win){
                editForm.body.dom.scrollTop = 0;
                //editForm.getForm().reset();
            }
        }
    }
});
editNoteWin.show();


}

function hideMe(){
var msg = "";
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 !== "" && alphanumeric(txt_field_value)) {
        //check to see if invalid characters are entered
        if(!htmlTags(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 (im = 0; im < notecardsOutline.length; im++) {
                    if (notecardsOutline[im][0] == notecard_id) {
                        document.getElementById("div_" + notecardsOutline[im][0] + "_" + notecardsOutline[im][1]).innerHTML = document.getElementById(txt_field).value;
                    }
                }
                for (i = 0; i < notecardID.length; i++) {
                    if (notecardID[i][0] == notecard_id) {
                        var oldNoteTitle = notecardID[i][4];
                        notecardID[i][4] = document.getElementById(txt_field).value;
                        updateNoteTitleInDatabase(notecard_id, txt_field_value,oldNoteTitle);
                    }
                }
                shakeMe(notecard_id);
                if (txt_field_value.length > 10) {
                    //document.getElementById(title_div).innerHTML = txt_field_value.substr(0, 9) + "....";
                    document.getElementById(title_div).innerHTML = formatTitleToDisplay(txt_field_value);
                }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;
                saveHTMLTree();
                return true;
            }
            else {
                showAlertBox("A notecard with this title already exists.", "Notecard");
                return false;
            }
        }
        else
        {
            msg = "The characters &, <, and > are reserved characters and cannot be used in the notecard title.";
            showAlertBox(msg, "Notecard");
            return false;
        }
    }
    else if(alphanumeric(txt_field_value) === false && txt_field_value !== "")
    {
        msg = "The notecard title may not contain the characters: ~ ^ ` § ö";
        showAlertBox(msg, "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];

            }
        }
        msg = "Please enter a title for the notecard.";
        showAlertBox(msg, "Notecard");
        return false;
    }
}else{
    return true;
}
}
function getUpdates(blankWindowName){
returnGetUpdatesFlag = false;
var failure1 = function(o){
     if(o.statusText == 'communication failure') {
        getUpdatesFailed++;
        if(getUpdatesFailed<2){
        var task = new Ext.util.DelayedTask(function(){
            getUpdates();
        });
        task.delay(500);
        }
        else{
          getUpdatesFailed = 0;
          showFailureMessage();
        }
     }
     //showFailureMessage();
};
var success1 = function(o){
    var resp = Ext.decode(o.responseText);
    var collabResp = fnCollaborationProcessResponse(resp);
    if(collabResp == true && blankWindowName != undefined){
        windowname = resp.RESPONSE;
    }
    returnGetUpdatesFlag = true;
};
var passedWindowName;
if(blankWindowName != undefined)
{
  passedWindowName = "";
}
else{
 passedWindowName = windowname;
}

Ext.Ajax.request({
    url: '../notecards/_includes/notecardOperations.php',
    method: 'POST',
    success: success1,
    failure: failure1,
    params: 'toggle=getUpdates&windowname='+passedWindowName+'&macfix=1234'
});
}

/*
* function for event handling on notecard
*/

(function() {
var Dom = YAHOO.util.Dom;

YAHOO.example.DDNotecard = function(id, sGroup, config) {
    YAHOO.example.DDNotecard.superclass.constructor.call(this, id, sGroup, config);
    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) {
        overElement = '';
        underElement = '';

        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(0.5, true);
        // store the id of item being dragged
        itemBeingDragged = clickEl.id;

        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();
        getUpdates();
    },

    endDrag: function(e) {

        var srcEl = this.getEl();
        var proxy = this.getDragEl();

        var xy = Dom.getXY(proxy);
        if(this.dropped === true)
        {
            if(document.getElementById(srcEl.id))
            {
                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)
        {
            if(document.getElementById(srcEl.id)){
                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
            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] > 1280)
                    {
                        leftTopPos[1] = "1280";
                        document.getElementById('tabletop').style.width = "3000px";
                        document.getElementById('tabletop').style.height = "1500px";
                    }
                    if(leftTopPos[0] < 50)
                    {
                        leftTopPos[0] = 50;
                        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
            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] > 1280)
                    {
                        leftTopPos[1] = 1280;
                        document.getElementById('tabletop').style.width = "3000px";
                        document.getElementById('tabletop').style.height = "1500px";
                    }
                    if(leftTopPos[0] < 50)
                    {
                        leftTopPos[0] = 50;
                        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 = [];
                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(notecardId);
        //hidePopupOnDrag();
        //itemBeingDragged = "";
    },

    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)
            {
                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;
                        return false;
                    }
                }
            }else if(regionNotecard.intersect(notecardRegion) !== null)
            {
                this.dropped = false;
                return false;
            }
            if (id.match("li_Not")) {
                this.dropped = false;
                return 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);
                if(str !== null){
                    // 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 = "";
                    element_name = str.id;
                    var noteid = this.getEl().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";

                        var actualPileId = element_name.substr(3);
                        xy = "";
                        // insert an entry of this relation
                        insertNotePileRelDragDrop(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";
                            }
                        }
                        updatePileNotecardSequence(actualPileId);
                    }
                    else
                        if (element_name.match("Pile_")) {
                            overElement = this.getEl().id;
                            insertNotePileRelDragDrop(element_name, overElement);
                            // 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);

                        this.formPile = false;

                        if(document.getElementById(this.getEl().id)){
                            shakeMe(element_name);
                            // updatePileNoteRelInDatabase(element_name);

                            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
                        {
                            alert('Notecard have been deleted by another collaborator');
                        }

                    }
                    else
                        if (element_name.match("Not")) {
                            posXY = getLeftTopInTabletop(id);

                            if(document.getElementById(this.getEl().id)){
                                document.getElementById(this.getEl().id).style.display = "block";
                            }


                        // store the items in action
                        overElement = this.getEl().id;
                        underElement = str.id;

                        // show the overlay to get notecard title
                        showPileOverlay();
                    }
                    else
                        if (id.match("content")) {
                            myMask.show();
                            getUpdates();
                            el = Ext.get(id);
                            
                            var checkIfOutlineIsUpdated = function ()
                            {
                                if(isOutlineUpdated)
                                {
                                    Ext.TaskMgr.stopAll();
                                    myMask.hide();
                                    var itemExist = false;
                                    var className = document.getElementById(noteid).className;
                                    if (className.match("Yellow")) {
                                        className = "li_notecard_outline_selected";
                                    }
                                    else {
                                        className = "li_notecard_outline";
                                    }
                                    
                                    if (el) {
                                        sibling = YAHOO.util.Dom.getChildren(el.parent("li").dom);
                                        sibling = sibling[2];
                                        if (!sibling) {
                                            ++listCnt;
                                            var body = "<ol id=list_" + listCnt + " class=licalss></ol>";
                                            var div1 = document.createElement("ol");
                                            div1.innerHTML = body;
                                            document.getElementById(el.parent("li", false).id).appendChild(div1.firstChild);
                                            sibling = Ext.get("list_" + listCnt);
                                            var failure1 = function(o){
                                                 showFailureMessage();
                                            };
                                            var success1 = function(o){
                                                var resp = Ext.decode(o.responseText);
                                                var collabResp = fnCollaborationProcessResponse(resp);
                                                if(collabResp){
                                                    var cntArr = resp.RESPONSE;
                                                    listCnt = cntArr[0][1];
                                                }
                                            };
                                        Ext.Ajax.request({
                                            url: '../notecards/_includes/notecardOperations.php',
                                            method: 'POST',
                                            success: success1,
                                            failure: failure1,
                                            params: 'toggle=incrementOutlineListCounters&count=1&windowname='+windowname+'&macfix=1234'
                                        });

                                    }
                                    var children = YAHOO.util.Dom.getChildren(sibling);
                                    for (i = 0; i < children.length; i++) {
                                        var children1 = YAHOO.util.Dom.getChildren(children[i]);
                                        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
                                                });
                                                itemExist = true;
                                                document.getElementById(id).className = "";
                                            }
                                        }
                                    }

                                    if (!itemExist) {
                                        var failure = function(o){
                                             showFailureMessage();
                                        };
                                        var success = function(o){
                                            var resp = Ext.decode(o.responseText);
                                            var collabResp = fnCollaborationProcessResponse(resp);
                                            if(collabResp){
                                                var cntArr = resp.RESPONSE;
                                                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 + "') ondblclick=\"editOutlineItem('div_" + noteid + "_item_" + itemCnt + "')\"  id = div_" + noteid + "_item_" + itemCnt + "></div></li>";
                                                var div = document.createElement('ol');
                                                div.innerHTML = li_html;
                                                sibling.appendChild(div.firstChild);
                                                var val = "";
                                                for (i = 0; i < notecardID.length; i++) {
                                                    if (notecardID[i][0] == noteid) {
                                                        val = notecardID[i][4];
                                                    }
                                                }
                                                var pEl = el;
                                                if(pEl){
                                                    pEl.frame("C3DAF9", 3, {
                                                        duration: 0.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];
                             }
                                                 */                 if(document.getElementById("div_" + noteid + "_item_" + itemCnt))
                                                    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);
                                                //function call to insert notecard in outline table
                                                functionOnOutline("I","item_"+itemCnt,noteid,"");
                                            }
                                        };
                                        //prepareMaskNote();
                                        Ext.Ajax.request({
                                            url: '../notecards/_includes/notecardOperations.php',
                                            method: 'POST',
                                            success: success,
                                            failure: failure,
                                            params: 'toggle=incrementOutlineCounters&action=attachNotecard&windowname='+windowname+'&macfix=1234'
                                        });
                                    }
                                    //if(el[0] != undefined)
                                    document.getElementById(el.id).className = "";
                                }
                                
                                document.getElementById(noteid).style.display = "block";
                                //make the proxy element empty
                                document.getElementById("ygddfdiv").innerHTML = "";
                            }
                        };
                                            
                    
                    Ext.TaskMgr.start({run: checkIfOutlineIsUpdated,     interval: 500, duration:5000});
                            

                    // up to here

                }
                else
                    if (id.match("item_")) {
                        document.getElementById(noteid).style.display = "block";
                    }
                if(this.target.match("view"))
                {
                    this.dropped = false;
                    return false;
                }
            }else{
                this.dropped = false;
                return false;
            }
            //updateNotecards(this.getEl().id);
        }
    }

},

onDrag: function(e) {
    if(Ext.get(this.getEl().id))
    {
        Ext.get(this.getEl().id).dom.style.display = "none";
        hidePopupOnDrag();
    }
},

onDragOver: function(e, id) {
    if(Ext.get(id)!==null){
        // 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)
            {
                if(document.getElementById(id)){
                    document.getElementById(id).className = "hover_li";
                }
            }
            else{
                document.getElementById(el[0].id).className = "";
                document.getElementById(id).className = "hover_li";
            }
        }
    }
},
onDragOut : function(e,id)
{
    if(Ext.get(id)!==null){
        if (id.match("div_item_")) {
            if(document.getElementById(id)){
                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 el = YAHOO.util.Dom.getElementsByClassName('selected');
if (el.length > 0) {
outlineTxtHideMe();
document.getElementById(el[0].id).className = "";
}
if(pileInEditMode){
pileHideMe();
}
if (hideMe()) {
addLockForElementUnderProcess(note_Id);
document.getElementById(txt_container).style.display = "block";
document.getElementById(title_div).style.display = "none";
var val = "";
for(i=0;i<notecardID.length;i++){
    if(notecardID[i][0] == divId.substr(6)){
        val = notecardID[i][4];
    }
}
document.getElementById(txt_field).value = val;
document.getElementById(txt_field).select();
noteInEditMode = divId;

}

}



function CheckNewNoteTitle(title)
{
if(notecardID){
var myTitle = "";
myTitle = title;
myTitle = myTitle.toLowerCase();
this.exists = false;
for(this.count = 0; this.count<notecardID.length;this.count++)
{
    var noteTitle = "";
    noteTitle = notecardID[this.count][4];
    noteTitle = noteTitle.toLowerCase();
    if(myTitle == noteTitle)
    {
        this.exists = true;
    }
}
return this.exists;
}else{
return false;
}
}


//function to get the notecard data
function openNoteEditView(tempeditNoteID){

if(tempeditNoteID === "")
{
tempeditNoteID = editNoteID;
}

prepareMaskNote();
projectid = document.getElementById('projectID').value;
function handleFailure (o)
{
    showFailureMessage();
}
function handleSuccess (o)
{

obj = Ext.decode(o.responseText);
var allowEditingNotecard = fnCollaborationProcessResponse(obj);

if(allowEditingNotecard){
    this.data = obj.RESPONSE;
            
    tempeditNoteID = obj.id;
    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('uCmbPile').setValue('');
        Ext.getCmp('uCmbPile').enable();

        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);
        Ext.getCmp('uid').setValue(this.data[0][7]);
        var pileArr = this.data[0][8];
        if (pileArr[0] != "0") {
            var PileTitle=pileArr[1];
            Ext.getCmp('uCmbPile').setValue(PileTitle);
            Ext.getCmp('uCmbPile').disable();
            Ext.getCmp('newPileEntry').setValue('old');
        }else{
            Ext.getCmp('uCmbPile').enable();
            Ext.getCmp('newPileEntry').setValue('old');
        }
        Ext.getCmp('mypileid').setValue(pileArr[0]);
        editNoteWin.doLayout();
        editNoteWin.show();
    }
}
hidePopupOnDrag();
}
    
//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='+tempeditNoteID+'&windowname='+windowname+'&addlock=yes&macfix=1234'
});
}


// 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)
{
     showFailureMessage();
}
function handleSuccess (o)
{
var resp = Ext.decode(o.responseText);
fnCollaborationProcessResponse(resp);

}
var arrSelNotesData = [];
for(i=0;i<arrSelNotes.length;i++)
{
    if(arrSelNotes[i].id != "" && arrSelNotes[i].id != undefined){
    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+'&windowname='+windowname+'&macfix=1234'
});

var parentEl = "";
var childEl = "";
//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) {
        parentEl = document.getElementById('outer_hawk_eye');
        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])) {
            parentEl = document.getElementById("li_" + pileNotecard[counter2][0]);
            childEl = document.getElementById("li_" + pileNotecard[counter2][1]);
            parentEl.removeChild(childEl);
        }
        pileNotecard.splice(counter2, 1);
    }

}
var outlineModified = false;
// 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) {
        outlineModified = true;
        parentEl = YAHOO.util.Dom.getAncestorByTagName(notecardsOutline[counter][1], "ol");

        childEl = document.getElementById(notecardsOutline[counter][1]);
        if(Ext.get(childEl)){
            Ext.get(childEl).remove();
        }
        notecardsOutline.splice(counter, 1);
        arrLength = notecardsOutline.length;
        counter = -1;
    }
}
if(outlineModified){
    saveHTMLTree();
}
}
//hidePopupOnDrag();
updateCountInPile();
calculateHighLightedNotecard();
}

function deleteSingleNoteCardsFromTabletop(){

//retrieve all the selected notecards here
var tempeditNoteID = editNoteID;
var arrSelNotes = [ document.getElementById('Notecard_'+tempeditNoteID) ];

function handleFailure (o)
{
     showFailureMessage();
}
function handleSuccess (o){
        
var resp = Ext.decode(o.responseText);
var candeleteNotecard = fnCollaborationProcessResponse(resp);
if(candeleteNotecard){
    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_'+tempeditNoteID) {
            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_'+tempeditNoteID).remove();
    Ext.get('thumb_Notecard_'+tempeditNoteID).remove();
    fillNotecardsAraay();
    // remove the entry of notecard from the outline notecard array

    editNoteID = "";

}
hidePopupOnDrag();
calculateHighLightedNotecard();
return true;
}
var arrSelNotesData = [];
for(i=0;i<arrSelNotes.length;i++)
{
    if(arrSelNotes[i].id != "" && arrSelNotes[i].id != undefined){
        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+'&windowname='+windowname+'&macfix=1234'
});
}

function deletePileFromDom(pile_id)
{
var i;
var arrSelNoteArr = [];
var j=0;
var isPileExist = false;
for (i = 0; i < pileNotecard.length; i++) {

if(pileNotecard[i][0] == pile_id)
{
    arrSelNoteArr[j++] = pileNotecard[i][1];
    isPileExist = true;
}
}
if(isPileExist) {
function handleSuccess (o){
var resp = Ext.decode(o.responseText);
var continueProcess = fnCollaborationProcessResponse(resp);
if(continueProcess){
    //prepareLoadMask();
    if(Ext.get(pile_id))
    {
        Ext.fly(pile_id).remove();
        Ext.fly("thumb_"+pile_id).remove();
    }
    var outlineModified = false;
    // remove notecards from the tabletop
    for(i=0;i<arrSelNoteArr.length;i++)
    {
        if(Ext.get(arrSelNoteArr[i]))
        {
            Ext.fly(arrSelNoteArr[i]).remove();
            Ext.fly("thumb_"+arrSelNoteArr[i]).remove();
        }
        for (counter = 0; counter < notecardsOutline.length; counter++) {
            if (notecardsOutline[counter][0] == arrSelNoteArr[i]) {
                outlineModified = true;
                var childEl = document.getElementById(notecardsOutline[counter][1]);
                if(Ext.get(childEl)){
                    Ext.get(childEl).remove();
                }
                notecardsOutline.splice(counter, 1);
                arrLength = notecardsOutline.length;
                counter = -1;
            }
        }
    }
    if(outlineModified){
        saveHTMLTree();
    }
    fillNotecardsAraay();
    calculateHighLightedNotecard();
}
}

function handleFailure (o)
{
     showFailureMessage();
}

arrSelNotesData1 = YAHOO.lang.JSON.stringify(arrSelNoteArr);
//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+'&windowname='+windowname+'&macfix=1234'
});
}
else
{
     Ext.MessageBox.show({
        title: 'Error',
        msg: 'Pile does not exist',
        buttons: Ext.MessageBox.OK,
        closable: false,
        icon: Ext.MessageBox.ERROR
    });
}
}

function deleteMultipleNotecardsFromDom(){

//retrieve all the selected notecards here
var arrSelNotes = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");

function handleFailure (o)
{
     showFailureMessage();
}
function handleSuccess (o){
var resp = Ext.decode(o.responseText);
var continueProcess = fnCollaborationProcessResponse(resp);
if(continueProcess){
    var outlineModified = false;
   // prepareLoadMask();
    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 = "";
                        mtop = "";
                        if(document.getElementById(expandedPileArray[l][0].substr(4)))
                        {
                            mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;
                            document.getElementById(noteid).style.left = mLeft;
                            mTop = document.getElementById(expandedPileArray[l][0].substr(4)).style.top;
                            document.getElementById(noteid).style.top = mTop;
                            // remove the pile from dom
                            Ext.get(expandedPileArray[l][0].substr(4)).remove();
                            Ext.get("thumb_"+expandedPileArray[l][0].substr(4)).remove();
                        }
                        //mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;

                        // assign the same dimensions to the notecard left, as of the pile
                        //remove the exploded pile from dom
                        Ext.get(expandedPileArray[l][0]).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);
                        if(Ext.get(noteid)){
                            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
                        mtop = "";
                        mleft = "";
                        if(document.getElementById(expandedPileArray[l][0]))
                        {
                            if(document.getElementById(expandedPileArray[l][0].substr(4))){
                                mLeft = document.getElementById(expandedPileArray[l][0].substr(4)).style.left;
                                document.getElementById(noteid).style.left = mLeft;
                                mTop = document.getElementById(expandedPileArray[l][0].substr(4)).style.top;
                                document.getElementById(noteid).style.top = mTop;
                            }


                            //document.getElementById(noteid).style.left = mLeft;


                            //remove the exploded pile from dom
                            Ext.get(expandedPileArray[l][0]).remove();
                            if(Ext.get(expandedPileArray[l][0].substr(4))){
                                // 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))){
                    // remove notecards dom from pile div
                    Ext.fly("li_"+arrSelNotes[i].id).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) {
                outlineModified = true;
                var childEl = document.getElementById(notecardsOutline[counter][1]);
                if(Ext.get(childEl)){
                    Ext.get(childEl).remove();
                }
                notecardsOutline.splice(counter, 1);
                arrLength = notecardsOutline.length;
                counter = -1;
            }
        }
        for(c=0;c<noteColor.length;c++)
        {
            if(arrSelNotes[i].id == noteColor[c][0])
            {
                noteColor.splice(c,1);
                c=-1;
            }
        }
                
    }
    if(outlineModified){
        saveHTMLTree();
    }
    fillNotecardsAraay();
    calculateHighLightedNotecard();
}
}
var arrSelNotesData = [];
for(i=0;i<arrSelNotes.length;i++)
{
    if(arrSelNotes[i].id != "" && arrSelNotes[i].id != undefined){
        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+'&windowname='+windowname+'&macfix=1234'
});

}
function deleteSingleNoteCardsFromPile(tempeditNoteID){

if(tempeditNoteID === "")
{
tempeditNoteID = editNoteID;
}
//retrieve all the selected notecards here
var arrSelNotes = [ document.getElementById('Notecard_'+tempeditNoteID) ];


function handleFailure (o)
{
     showFailureMessage();
}
function handleSuccess (o){
var resp = Ext.decode(o.responseText);
var candeleteNotecard = fnCollaborationProcessResponse(resp);
var noteid;
if(candeleteNotecard){
    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 a;
                    if(childs[0].id != "li_"+arrSelNotes[i].id){
                        var pile_exp = expandedPileArray[l][0];
                        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(pile_exp).style.left;
                        mTop = document.getElementById(pile_exp).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
                        if(Ext.get("thumb_"+expandedPileArray[l][0].substr(4)))
                        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]).style.left;
                        mTop = document.getElementById(expandedPileArray[l][0]).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]).remove();
                        if(Ext.get("thumb_"+expandedPileArray[l][0].substr(4)))
                            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))){
                    // remove notecards dom from pile div
                    Ext.fly("li_"+arrSelNotes[i].id).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();
calculateHighLightedNotecard();

}
var arrSelNotesData = [];
for(i=0;i<arrSelNotes.length;i++)
{
    if(arrSelNotes[i].id != "" && arrSelNotes[i].id != undefined){
        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+'&windowname='+windowname+'&macfix=1234'
});
}

function deleteConfirmDgNotecard(){
function showResult(btn)
{
if (btn == "yes") {
    var tempEditNoteID = editNoteID;
    if(Ext.get('li_Notecard_'+tempEditNoteID)){
        prepareLoadMask();
                
        deleteSingleNoteCardsFromPile(tempEditNoteID);
    }else{
        prepareLoadMask();
        deleteSingleNoteCardsFromTabletop();
    }

}
}

hidePopupOnDrag();
Ext.MessageBox.confirm('Confirm', 'Are you sure you want to delete this notecard?', showResult);


}

// function to be called in while creating the notecard in Bib Section
function createNoteInBib(entryid,val){
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){
var result = Ext.decode(o.responseText);
var collborationResponse = fnCollaborationProcessResponse(result);
if(collborationResponse === true)
{
function success (m)
{
    var resultM = Ext.decode(m.responseText);
    var collborationResponseM = fnCollaborationProcessResponse(resultM);
    if(collborationResponseM === true){
        notecardID = resultM.RESPONSE;
        return true;
    }
}
function failure (m)
{
    showFailureMessage();
}


//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+'&windowname='+windowname+'&macfix=1234'
});

this.data = result.RESPONSE;
var tagArray = [];
hidePopupOnDrag();
var allTags = this.data[2];
var myData = entryID;
        
// Here it is to be checked whether its an integrated or stand-alone version
if (stopEditingonTabletop()) {
    projectid = document.getElementById('projectID').value;
    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]";
		
		/*TAB*/

	var IsiPad3 = navigator.userAgent.indexOf("iPad; U; CPU OS 3");
	var IsiPad4 = navigator.userAgent.indexOf("iPad; U; CPU OS 4");
        var disabledEditor = "";
        if((IsiPad4 == -1)&&(IsiPad3 == -1))
	{
            disabledEditor = ",noneditable";
        }
        
	 var texteditor = {
                                columnWidth: 0.55,
                                xtype: "tinymce",
                                fieldLabel: "Rich text",
                                id: "quotation",
                                name: "quotation",
                                width: 300,
                                height: 390,
                                tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor,
								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: "top",
								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,
								theme_advanced_path : false
								}
							
			 };
		var texteditor1 =  {
                            columnWidth: 0.55,
                            xtype: "tinymce",
                            fieldLabel: "Rich text",
                            id: "paraphrase",
                            name: "paraphrase",
                            width: 300,
                            height: 390,
                            tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor, // 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: "top",
                                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,
								theme_advanced_path : false
                            }
							};
						
						var texteditor2 =  {
                            columnWidth: 0.55,
                            xtype: "tinymce",
                            fieldLabel: "Rich text",
                            id: "ideas",
                            name: "ideas",
                            width: 300,
                            height: 390,
                            tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor, // 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: "top",
                                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,
								theme_advanced_path : false
                            }
						
                        };
	
/*ENDTAB*/



    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',
        width: 600,
        items: [{
                layout: 'form',
                items: [{
                        layout: 'column',
                        items: [{
                                columnWidth: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Title</b>'
                            }, {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                fieldLabel: 'Title',
                                id: 'txtTitle',
                                name: 'txtTitle',
                                allowBlank: false,
                                anchor: '95%'
                            }, {
                                columnWidth: 0.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: 0.75,
                                //xtype: 'label',
                                //id: 'lblTitle',
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Pile</b>'
                            }, {
                                columnWidth: 0.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: 0.5,
                                cls: 'editViewText',
                                bodyStyle: 'padding:0px 0px 0px 10px;',
                                html: '&nbsp;<br><br>'
                            }]
                    },{
                        layout: 'column',
                        items: [{
                                columnWidth: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>URL</b>'
                            }, {
                                columnWidth: 0.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: 0.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: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Pages</b>'
                            }, {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                id: 'txtPages',
                                name: 'txtPages',
                                anchor: '95%'
                            }, {
                                columnWidth: 0.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: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Tags<b>'
                            }, {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                fieldLabel: 'pages',
                                id: 'txtTags',
                                name: 'txtTags',
                                anchor: '95%'
                            }, {
                                columnWidth: 0.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: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Existing Tags</b>'
                            }, {
                                columnWidth: 0.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;
                                                        }
                                                        return true;
                                                    }
                                                    function failFn(){
                                                         showFailureMessage();
                                                    }
                                                    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+"windowname="+windowname+"&&macfix=1234");
                                                }
                                            }
                                        }
                                    })]
                            }, {
                                columnWidth: 0.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 tidy up later.</span>'
                            }]
                    }, {
                        layout: 'column',
                        items: [{
                                columnWidth: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Direct Quotation</b>'
                            }, texteditor , {
                                columnWidth: 0.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: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>Paraphrase</b>'
                            }, texteditor1 , {
                                columnWidth: 0.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: 0.75,
                                bodyStyle: 'padding-top:5px;',
                                html: '<b>My Ideas</b>'
                            }, texteditor2 , {
                                columnWidth: 0.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: 0.2

                            }, {
                                columnWidth: 0.2,
                                xtype: 'textfield',
                                value: "insertNewNote",
                                name: 'toggle',
                                hidden: true,
                                anchor: '95%'
                            }, {
                                columnWidth: 0.6,
                                xtype: 'textfield',
                                value: myData,
                                name: 'sourceID',
                                id: 'sourceID',
                                hidden: true,
                                anchor: '95%'
                            },
                            {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                value: windowname,
                                name: 'windowname',
                                id: 'windowname',
                                hidden: true
                            },
                            {
                                columnWidth: 0.5,
                                xtype: 'textfield',
                                value: '1234',
                                name: 'macfix',
                                id: 'macfix',
                                hidden: true,
                                anchor: '95%'
                            }]
                    }]
            }],
        buttons: [{
                text: 'Save',
                type: 'button',
                listeners: {
                    'click': {
                        fn: function(){
                            var showResult="";
                            if (newNoteForm.getForm().isValid()) {
                                var val = Trim(Ext.getCmp('txtTitle').getValue());
                                if (alphanumeric(val)) {
                                    if (!htmlTags(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>")) {
                                                var emptyQuotation = function(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>")) {
                                                    var emptyPara = function(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>")) {
                                                    var emptyIdeas = function(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) {
                                                    var emptyQuotation1 = function(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: emptyQuotation1,
                                                    icon: Ext.MessageBox.ERROR
                                                });
                                            }
                                            else
                                                if (ptext.length > 10000) {
                                                    var emptyPara1 = function(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: emptyPara1,
                                                    icon: Ext.MessageBox.ERROR
                                                });
                                            }
                                            else
                                                if (itext.length > 10000) {
                                                    var emptyIdeas1 = function(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: emptyIdeas1,
                                                    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){


                                                            obj1 = 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;
                                                                                                                                                                    }*/
                                                                
                                                            var collabresponseMain = fnCollaborationProcessResponse(obj1.data.response);
                                                            if(collabresponseMain)
                                                            {
                                                                var resdata = obj1.data.response;
                                                                var obj = Ext.decode(resdata.RESPONSE);

                                                                var handleFailure = function(o){
                                                                    alert(o.responseText);
                                                                };
                                                                var handleSuccess = function(o){

                                                                    var resp = Ext.decode(o.responseText);
                                                                    if(fnCollaborationProcessResponse(resp))
                                                                    {
                                                                        this.data = resp.RESPONSE;
                                                                        //this.data = YAHOO.lang.JSON.parse(o.responseText);
                                                                        entryID = Ext.getCmp('sourceID').getValue();
                                                                        var el = Ext.get('notesdiv_' + entryID);
                                                                        if (el) {
                                                                            var quoteclass;
                                                                            var paraclass;
                                                                            var ideasclass;
                                                                            var child = el.child('div');
                                                                            if (child !== null) {
                                                                                if (this.data[0][4] !== "") {
                                                                                    quoteclass = "class=quoteclass";
                                                                                }
                                                                                else {
                                                                                    this.data[0][4] = "&nbsp";
                                                                                    quoteclass = "";
                                                                                }
                                                                                if (this.data[0][5] !== "") {
                                                                                    paraclass = "class=paraclass";
                                                                                }
                                                                                else {
                                                                                    this.data[0][5] = "&nbsp";
                                                                                    paraclass = "";
                                                                                }
                                                                                if (this.data[0][6] !== "") {
                                                                                    ideasclass = "class=ideasclass";
                                                                                }
                                                                                else {
                                                                                    this.data[0][6] = "&nbsp";
                                                                                    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=\"javascript:editNoteFromBib('" + obj.data.id + "');\">";
                                                                                blockhtml += "<img alt=\"Edit notecard\" src=\"/_images_add/noteicons/edit.png\" border=\"0\"></a>";
                                                                                blockhtml += "&nbsp;<a class=\"smalltext\" href=\"javascript:editNoteFromBib('" + obj.data.id + "');\">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 += "&nbsp;<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 += "&nbsp;<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 + "\">" + wordwrap(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>";

                                                                                if(this.data[0][11] === ""){
                                                                                    blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">History:</td><td class=\"noteitem\"><span  id=\"history_" + obj.data.id + "\">Notecard Created: "+this.data[0][9]+" | Updated: "+this.data[0][10]+"</span></td></tr>";
                                                                                }else
                                                                                {
                                                                                    if(this.data[0][12]!== ""){
                                                                                        this.data[0][12] = " ("+this.data[0][12]+")";
                                                                                    }
                                                                                    blockhtml += "<tr id=\"notecontent_" + obj.data.id + "\" class=\"notecontent\"><td class=\"subhead noteitem\">History:</td><td class=\"noteitem\"><span  id=\"history_" + obj.data.id + "\">Notecard Created By: "+this.data[0][11]+this.data[0][12]+" on "+this.data[0][9]+"  | Updated: "+this.data[0][10]+"</span></td></tr>";
                                                                                }

                                                                                blockhtml += "</tbody></table></div>";

                                                                                var dh = Ext.DomHelper;
                                                                                dh.append('notesdiv_' + entryID, {
                                                                                    id: "note_" + obj.data.id,
                                                                                    tag: 'div',
                                                                                    html: blockhtml,
                                                                                    cls: 'lineitem_static'
                                                                                });
                                                                                el = Ext.get('notesdiv_' + entryID);
                                                                                el.setVisibilityMode(Element.DISPLAY);
                                                                                el.setVisible(true);
                                                                                var m;
                                                                                m =  new Effect.ScrollTo("note_" + obj.data.id, {
                                                                                    queue: 'end'
                                                                                });
                                                                                m = new Effect.Pulsate("note_" + obj.data.id, {
                                                                                    queue: 'end',
                                                                                    from: 0.4
                                                                                });
                                                                            }
                                                                        }
                                                                        el = Ext.get('showhidelink_' + entryID);
                                                                        var innerhtml = document.getElementById('showhidelink_' + entryID).innerHTML;
                                                                        if (innerhtml === "") {
                                                                            el.remove();
                                                                            var handleSuccessEn = function(m)
                                                                            {
                                                                                if((Trim(m.responseText)).match("ERROR_MULTIPLE")||(Trim(m.responseText)).match("ERROR_NOID"))
                                                                                {
                                                                                    showNotesSessionError(Trim(m.responseText));
                                                                                    return false;
                                                                                }
                                                                                var list_entryid = Ext.decode(m.responseText);
                                                                                blockhtml = "&nbsp;<a onclick=\"showhideCitation('" + entryID + "','"+list_entryid+"'); return false; \" href='#'><span id='showhidetxt_" + entryID + "'>Show</span></a>&nbsp;|";
                                                                                var dh = Ext.DomHelper;
                                                                                dh.insertAfter('numnotes_' + entryID, {
                                                                                    id: 'showhidelink_' + entryID,
                                                                                    tag: 'span',
                                                                                    html: blockhtml
                                                                                });
                                                                                return true;
                                                                            };
                                                                            var handleFailureEn = function(m){
                                                                                 showFailureMessage();
                                                                            };
                                                                            // we need list of bib entry for showhideCitation function's second parameter
                                                                            Ext.Ajax.request({
                                                                                url: '../notecards/_includes/notecardOperations.php',
                                                                                method: 'POST',
                                                                                success: handleSuccessEn,
                                                                                failure: handleFailureEn,
                                                                                params : 'toggle=getListEntryID&windowname='+windowname+'&macfix=1234'
                                                                            });
                                                                        }
                                                                        var numOfNotes = document.getElementById('numnotes_' + entryID).innerHTML;
                                                                        var intNum = Number(numOfNotes) + 1;
                                                                        document.getElementById('numnotes_' + entryID).innerHTML = intNum;
                                                                        newNoteForm.getForm().reset();
                                                                        newBibNoteWin.hide();
                                                                    }
                                                                };

                                                                //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+'&windowname='+windowname+'&macfix=1234'
                                                                });
                                                            }
                                                        },

                                                        // 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){
                                                            showFailureMessage();
                                                            //form.reset();
                                                        }
                                                    });
                                                }
                                                else {
                                                    showResult = function(btn){
                                                        if (btn == "ok") {
                                                            newBibNoteWin.toFront();
                                                            newBibNoteWin.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
                                                    });
                                                    newBibNoteWin.toBack();
                                                    newBibNoteWin.disable();
                                                }


                                            }

                                        }
                                        else {
                                            showResult = function(btn){
                                                if (btn == "ok") {
                                                    newBibNoteWin.toFront();
                                                    newBibNoteWin.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
                                            });
                                            newBibNoteWin.toBack();
                                            newBibNoteWin.disable();
                                        }
                                    }
                                    else {
                                        showResult = function(btn){
                                            if (btn == "ok") {
                                                newBibNoteWin.toFront();
                                                newBibNoteWin.enable();
                                            }
                                        };
                                        Ext.MessageBox.show({
                                            title: 'Error',
                                            msg: 'The characters &, <, and > are reserved characters and cannot be used in the notecard title.',
                                            buttons: Ext.MessageBox.OK,
                                            closable: false,
                                            fn: showResult,
                                            icon: Ext.MessageBox.ERROR
                                        });
                                        newBibNoteWin.toBack();
                                        newBibNoteWin.disable();
                                    }
                                }
                                else {
                                    showResult = function(btn){
                                        if (btn == "ok") {
                                            newBibNoteWin.toFront();
                                            newBibNoteWin.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
                                    });
                                    newBibNoteWin.toBack();
                                    newBibNoteWin.disable();
                                }
                            }
                            else {
                                showResult = function(btn){
                                    if (btn == "ok") {
                                        newBibNoteWin.toFront();
                                        newBibNoteWin.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
                                });
                                newBibNoteWin.toBack();
                                newBibNoteWin.disable();
                            }
                        }
                    }
                }
            }, {
                text: 'Cancel',
                type: 'button',
                listeners: {
                    'click': {
                        fn: function(){
                            var showResult1 = function(btn){
                                if (btn == "no") {
                                    newBibNoteWin.toFront();
                                    newBibNoteWin.enable();
                                }
                                if(btn == "yes"){
                                    //kill the tiny editors on close
                                    /*var t = tinyMCE.editors, e;
										    for (e in t)
											{
												t[e].remove();
										    }*/
                                    newNoteForm.getForm().reset();
                                    newBibNoteWin.hide();
                                }
                            };

                            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
                            });

                            newBibNoteWin.disable();
                            newBibNoteWin.toBack();
                        }
                    }
                }
            }]

    });

    // This just creates a window to wrap the login form.
    // The login object is passed to the items collection.
     newBibNoteWin = new Ext.Window({
        layout: 'fit',
        cls: "../_css/noodlenotes.css",
        title: 'New Notecard',
        id:'newNotecardWindow',
        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);
                }
            }
        }
    });

    newBibNoteWin.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]);
							newBibNoteWin.show();
			}, 2000);*/
}
return true;
}
}


//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+'&windowname='+windowname+'&macfix=1234'
});
}
function dispOverlay(entryid,val)
{
    
   //alert(val);
    hidePopupOnDrag();
    prepareMaskNote();
    if(!newBibNoteWin){
        //alert('mad');
        createNoteInBib(entryid,val);
    }else{
          Ext.getCmp('mypileid').setValue("0");
          pileStore.reload();
          Ext.getCmp('sourceID').setValue(entryid);
        //Ext.getCmp(val).setValue(val);
        //alert(entryid);
        //alert(val);
        newBibNoteWin.enable();
        newBibNoteWin.show();
    }
	
}
// function to open notecard in edit view
function displaywindowToEditNoteFromBib(notecardDetails, allTags, tagString, tagArray, src){
    
projectid = document.getElementById('projectID').value;
function success (m)
{
    var resultM = Ext.decode(m.responseText);
    var collborationResponseM = fnCollaborationProcessResponse(resultM);
    if(collborationResponseM === true){
        notecardID = resultM.RESPONSE;
    }
}
function failure (m)
{
    showFailureMessage();
}

//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+'&windowname='+windowname+'&macfix=1234'
});
var disableMe = false;
editPileStore = new Ext.data.JsonStore({
url: '../notecards/_includes/notecardOperations.php?toggle=loadProjectPiles',
root: 'records',
autoLoad: true,
fields: ['name', 'pileid', 'name', 'title']

});
var pileField;
var selectedPiledet = notecardDetails[8];
if (selectedPiledet[0] == '0') {
pileField = new Ext.form.ComboBox({
    id: 'uCmbPile',
    store: editPileStore,
    typeAhead: false,
    editable: false,
    mode: 'local',
    forceSelection: true,
    triggerAction: 'all',
    displayField: 'title',
    valueField: 'pileid',
    emptyText: 'Select a Pile ...',
    listeners: {
        'select': {
            fn: function(combo, newVal, oldVal){
                Ext.getCmp('mypileid').setValue(newVal.data.pileid);
                Ext.getCmp('newPileEntry').setValue('new');
            }
        }
    }
});
}else{
var PileTitle=selectedPiledet[1];

pileField = new Ext.form.ComboBox({
    id: 'uCmbPile',
    store: editPileStore,
    typeAhead: false,
    editable: false,
    mode: 'local',
    disabled: true,
    forceSelection: true,
    triggerAction: 'all',
    displayField: 'title',
    valueField: 'pileid',
    value: PileTitle,
    emptyText: 'Select a Pile ...',
    listeners: {
        'select': {
            fn: function(combo, newVal, oldVal){
                Ext.getCmp('mypileid').setValue(newVal.data.pileid);
                Ext.getCmp('newPileEntry').setValue('new');
            }
        }
    }
});
}
    
var srcIDVal = notecardDetails[1];
var ucitCmb = null;
var tempeditNoteID = notecardDetails[7];
    
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
});


// Here it is to be checked whether its an integrated or stand-alone version
var submit1 = false;
projectid = document.getElementById('projectID').value;
//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 IsiPad3 = navigator.userAgent.indexOf("iPad; U; CPU OS 3");
	var IsiPad4 = navigator.userAgent.indexOf("iPad; U; CPU OS 4");
        var disabledEditor = "";
        if((IsiPad4 == -1)&&(IsiPad3 == -1))
	{
            disabledEditor = ",noneditable";
        }

/*TAB*/
	 var texteditor = {
					 columnWidth: 0.55,
					 xtype: "tinymce",
					 fieldLabel: "Rich text",
					 id: "uquotation",
					 name: "uquotation",
					 width: 300,
					 height: 390,
					 tinymceSettings: {
						  theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor,
								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: "top",
								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,
								theme_advanced_path : false
								},
							value: notecardDetails[4]
			 };
		var texteditor1 =  {
                            columnWidth: 0.55,
                            xtype: "tinymce",
                            fieldLabel: "Rich text",
                            id: "uparaphrase",
                            name: "uparaphrase",
                            width: 300,
                            height: 390,
                            tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor, // 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: "top",
                                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,
								theme_advanced_path : false
                            },
							value: notecardDetails[5]
                        };
						
						var texteditor2 =  {
                            columnWidth: 0.55,
                            xtype: "tinymce",
                            fieldLabel: "Rich text",
                            id: "uideas",
                            name: "uideas",
                            width: 300,
                            height: 390,
                            tinymceSettings: {
                                theme: "advanced",
                                plugins: "safari,spellchecker,print,searchreplace,paste,wordcount,htmlcharcount"+disabledEditor, // 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: "top",
                                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,
								theme_advanced_path : false
                            },
							value: notecardDetails[6]
                        };
	
/*ENDTAB*/



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',
width: 600,
items: [{
        layout: 'form',
        items: [{
                layout: 'column',
                items: [{
                        columnWidth: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Title</b>'
                    }, {
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        fieldLabel: 'Title',
                        id: 'utxtTitle',
                        name: 'utxtTitle',
                        allowBlank: false,
                        disabled: disableMe,
                        value: notecardDetails[0],
                        anchor: '95%'
                    }, {
                        columnWidth: 0.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: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Source</b>'
                    }, {
                        columnWidth: 0.5,
                        items:[ucitCmb]
                    }, {
                        columnWidth: 0.5,
                        cls: 'editViewText',
                        bodyStyle: 'padding:0px 0px 0px 10px;',
                        html: '<span style="font-family:verdana;font-size:8pt;"></span><br><br>'
                    }]
            },{
                layout: 'column',
                items: [{
                        columnWidth: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Pile</b>'
                    }, {
                        columnWidth: 0.5,
                        items: [pileField],
                        anchor: '98%'
                    }, {
                        columnWidth: 0.5,
                        items: [{
                                xtype: 'textfield',
                                hidden: true,
                                id: 'mypileid',
                                value: notecardDetails[8]
                            }, {
                                xtype: 'textfield',
                                hidden: true,
                                id: 'newPileEntry',
                                value: 'old'
                            }]
                    }]
            },{
                layout: 'column',
                items: [{
                        columnWidth: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>URL</b>'
                    }, {
                        columnWidth: 0.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: 0.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: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Pages</b>'
                    }, {
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        id: 'utxtPages',
                        disabled: disableMe,
                        name: 'utxtPages',
                        value: notecardDetails[3],
                        anchor: '95%'
                    }, {
                        columnWidth: 0.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: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Tags<b>'
                    }, {
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        fieldLabel: 'pages',
                        id: 'utxtTags',
                        disabled: disableMe,
                        name: 'utxtTags',
                        value: tagString,
                        anchor: '95%'
                    }, {
                        columnWidth: 0.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: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Existing Tags</b>'
                    }, {
                        columnWidth: 0.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;
                                                }
                                                return true;
                                            }
                                            function failFn(){
                                                 showFailureMessage();
                                            }


                                            //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+'&windowname='+windowname+'&macfix=1234'
                                            });
                                        }
                                    }
                                }
                            })]
                    }, {
                        columnWidth: 0.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 tidy up later.</span>'
                    }]
            }, {
                layout: 'column',
                items: [{
                        columnWidth: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Direct Quotation</b>'
                    },texteditor , {
                        columnWidth: 0.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: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>Paraphrase</b>'
                    }, texteditor1 , {
                        columnWidth: 0.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: 0.75,
                        bodyStyle: 'padding-top:5px;',
                        html: '<b>My Ideas</b>'
                    }, texteditor2 , {
                        columnWidth: 0.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: 0.5,
                        xtype: 'textfield',
                        value: srcIDVal,
                        name: 'usourceID',
                        id: 'usourceID',
                        hidden: true,
                        anchor: '95%'
                    }, {
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        value: notecardDetails[7],
                        name: 'uid',
                        id: 'uid',
                        hidden: true,
                        anchor: '95%'
                    },{
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        value: 'fromBib',
                        name: 'fromBib',
                        id: 'fromBib',
                        hidden: true,
                        anchor: '95%'
                    },
                    {
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        value: windowname,
                        name: 'windowname',
                        id: 'windowname',
                        hidden: true
                    },
                    {
                        columnWidth: 0.5,
                        xtype: 'textfield',
                        value: '1234',
                        name: 'macfix',
                        id: 'macfix',
                        hidden: true,
                        anchor: '95%'
                    }]
            }]
    }],
buttons: [{
        text: 'Save',
        type: 'button',
        disabled: disableMe,
        listeners: {
            'click': {
                fn: function(){
                    var emptyQuotation;
                    var emptyPara;
                    var emptyIdeas;
                    var showResult;
                    if (editForm.getForm().isValid()) {
                        var val = Trim(Ext.getCmp('utxtTitle').getValue());
                        tempeditNoteID = Ext.getCmp('uid').getValue();
                        if(alphanumeric(val)){
                            if (!htmlTags(val)) {
                                if (!CheckNoteTitle(val, "Notecard_" + tempeditNoteID)) {

                                    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>")) {
                                        emptyQuotation = function(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>")) {
                                            emptyPara = function(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>")) {
                                            emptyIdeas = function(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) {
                                            emptyQuotation = function(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) {
                                            emptyPara = function(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) {
                                            emptyIdeas = function(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){
                                                    var submitResp = Ext.decode(action.response.responseText);
                                                    var subRes = submitResp.data.response;
                                                    tempeditNoteID = submitResp.id;
                                                    var mainCollabResp = fnCollaborationProcessResponse(subRes);
                                                        
                                                    if(mainCollabResp)
                                                    {
                                                        Ext.getCmp('utags1').store.reload();
                                                        Ext.getCmp('usourceID').setValue('0');
                                                        var handleFailure1 = function(o){
                                                             showFailureMessage();
                                                        };

                                                        var handleSuccess1 = function(o){

                                                            var resp = Ext.decode(o.responseText);
                                                            var collabResp = fnCollaborationProcessResponse(resp);
                                                            if(collabResp)
                                                            {
                                                                this.data = resp.RESPONSE;
                                                                //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'>" + wordwrap(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 = "";
                                                                }
                                                                if (this.data[0][9] !== "") {

                                                                    if(this.data[0][11] === ""){
                                                                        document.getElementById('history_' + this.data[0][7]).innerHTML = "Notecard Created: " + this.data[0][9] + " | Updated: " + this.data[0][10];
                                                                    }else
                                                                    {
                                                                        if(this.data[0][12] !== ""){
                                                                            this.data[0][12] = " ("+this.data[0][12]+")";
                                                                        }
                                                                        document.getElementById('history_' + this.data[0][7]).innerHTML = "Notecard Created By: "+this.data[0][11]+this.data[0][12]+" on " + this.data[0][9] + " | Updated: " + this.data[0][10];
                                                                    }
                                                                }
                                                                //editNoteWin.hide();
                                                                var my_parent = Ext.fly('note_'+this.data[0][7]).parent();
                                                                var parent_id = my_parent.id.split("_");

                                                                if(parent_id[1]==this.data[0][1]){
                                                                    var b;
                                                                    // show the effects without changing
                                                                    b = new Effect.ScrollTo("note_" + this.data[0][7], {
                                                                        queue: 'end'
                                                                    });
                                                                    b = new Effect.Pulsate("note_" + this.data[0][7], {
                                                                        queue: 'end',
                                                                        from: 0.4
                                                                    });
                                                                }else{
                                                                    var orgCount;
                                                                    if(this.data[0][1]!='0'){

                                                                        if(parent_id.length>1){
                                                                            orgCount = Ext.get('numnotes_'+parent_id[1]).dom.innerHTML;
                                                                            orgCount = Number(orgCount)-1;
                                                                            Ext.get('numnotes_'+parent_id[1]).dom.innerHTML = orgCount;
                                                                            if(orgCount === 0){
                                                                                Ext.get('showhidelink_'+parent_id[1]).dom.innerHTML = "";
                                                                            }
                                                                        }
                                                                        var newCount = Ext.get('numnotes_'+this.data[0][1]).dom.innerHTML;
                                                                        newCount = Number(newCount)+1;
                                                                        Ext.get('numnotes_'+this.data[0][1]).dom.innerHTML = newCount;

                                                                        if(Ext.get('showhidelink_'+this.data[0][1]).dom.innerHTML === ""){
                                                                            Ext.get('showhidelink_'+this.data[0][1]).dom.innerHTML = "<a onclick='showhide("+this.data[0][1]+"); return false; ' href='#'><span id='showhidetxt_"+this.data[0][1]+"'>Show</span></a> | ";
                                                                        }
                                                                        Ext.get('showhidelink_'+this.data[0][1]).setDisplayed(true);

                                                                        if(newCount != 1){
                                                                            if(Ext.get('notesdiv_'+this.data[0][1]).dom.innerHTML!==""){
                                                                                Ext.fly('note_'+this.data[0][7]).appendTo(Ext.get('notesdiv_'+this.data[0][1]).id);
                                                                                var m;
                                                                                // show the effects without changing
                                                                                m =  new Effect.ScrollTo("note_" + this.data[0][7], {
                                                                                    queue: 'end'
                                                                                });
                                                                                m = new Effect.Pulsate("note_" + this.data[0][7], {
                                                                                    queue: 'end',
                                                                                    from: 0.4
                                                                                });
                                                                            }else{
                                                                                Ext.fly('note_'+this.data[0][7]).remove();
                                                                            }
                                                                        }else{
                                                                            Ext.fly('note_'+this.data[0][7]).remove();
                                                                        }

                                                                    }else{

                                                                        if(parent_id.length>1){
                                                                            orgCount = Ext.get('numnotes_'+parent_id[1]).dom.innerHTML;
                                                                            orgCount = Number(orgCount)-1;
                                                                            Ext.get('numnotes_'+parent_id[1]).dom.innerHTML = orgCount;
                                                                            if(orgCount === 0){
                                                                                Ext.get('showhidelink_'+parent_id[1]).dom.innerHTML = "";
                                                                            }
                                                                        }
                                                                        Ext.fly('note_'+this.data[0][7]).appendTo(Ext.get('notes').id);
                                                                        var m1;
                                                                        // show the effects without changing
                                                                        m1 = new Effect.ScrollTo("note_" + this.data[0][7], {
                                                                            queue: 'end'
                                                                        });
                                                                        m1 = new 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=" + tempeditNoteID+"&windowname="+windowname+"&macfix=1234");
	                                                    //If there is no SESSION_ERROR.HAS_ERROR then close the editNoteWin window, else do not close. So shifted below hide statement in this TRUE condintion.
														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){
                                                     showFailureMessage();
                                                }
                                            });

                                        }
                                        else {
                                            showResult = function(btn){
                                                    
                                            };
                                            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 {
                                    showResult = function(btn){
                                            
                                    };
                                    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 {
                                showResult = function(btn){
                                        
                                };
                                Ext.MessageBox.show({
                                    title: 'Error',
                                    msg: 'The characters &, <, and > are reserved characters and cannot be used in the notecard title.',
                                    buttons: Ext.MessageBox.OK,
                                    closable: false,
                                    fn: showResult,
                                    icon: Ext.MessageBox.ERROR
                                });
                            }
                        }else{
                            showResult = function(btn){
                                    
                            };
                            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 {
                        showResult = function(btn){
                                
                        };
                        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(){
                    submit1=false;
                    editNoteWin.hide();
                }
            }
        }
    }]

});
function handler(cmp){
releaseLockForElementUnderProcess("Notecard_"+tempeditNoteID);
editNoteWin.body.dom.scrollTop = 0;
this.bool = false;

if (!submit1) {
    var dirty = false;
    if(Ext.getCmp('utxtTitle').isDirty()||
        Ext.getCmp('utxtSource').isDirty()||
        Ext.getCmp('utxtURL').isDirty()||
        Ext.getCmp('utxtPages').isDirty()||
        Ext.getCmp('utxtTags').isDirty()||
        Ext.getCmp('uquotation').isDirty()||
        Ext.getCmp('uparaphrase').isDirty()||
        Ext.getCmp('uideas').isDirty()){
        dirty = true;
    }

    if(dirty){
        var showResult = function(btn){
            var emptyQuotation;
            var emptyPara;
            var emptyIdeas;
            var showResult;
            if (btn == "yes") {

                if (editForm.getForm().isValid()) {
                    var val = Trim(Ext.getCmp('utxtTitle').getValue());
                    if (!htmlTags(val)) {
                        if (!CheckNoteTitle(val, "Notecard_" + tempeditNoteID)) {
                            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>")) {
                                emptyQuotation = function(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>")) {
                                    emptyPara = function(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>")) {
                                    emptyIdeas = function(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) {
                                    emptyQuotation = function(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) {
                                    emptyPara = function(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) {
                                    emptyIdeas = function(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');
											
											if ((Trim(action.responseText)).match("ERROR_MULTIPLE")||(Trim(action.responseText)).match("ERROR_NOID")) {
                                                showNotesSessionError(Trim(action.responseText));
                                                return false;
                                            }
											
											var obj = Ext.util.JSON.decode(action.response.responseText);
                                            tempeditNoteID = obj.id;
                                            var MaincollabResp = fnCollaborationProcessResponse(obj.data.response);
                                            if(MaincollabResp){
											
											
                                            var handleFailure1 = function(o){
                                                 showFailureMessage();
                                            };
                                            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);
                                                var resp = Ext.decode(o.responseText);
                                                tempeditNoteID = resp.id;
                                                var collabResp = fnCollaborationProcessResponse(resp);
                                                if(collabResp){
                                                    this.data = resp.RESPONSE;
                                                }
                                                //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'>" + wordwrap(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 = "";
                                            }
                                            if (this.data[0][9] !== "") {
                                                if(this.data[0][11] === ""){
                                                    document.getElementById('history_' + this.data[0][7]).innerHTML = "Notecard Created: " + this.data[0][9] + " | Updated: " + this.data[0][10];
                                                }else
                                                {
                                                    if(this.data[0][12] !== ""){
                                                        this.data[0][12] = " ("+this.data[0][12]+")";
                                                    }
                                                    document.getElementById('history_' + this.data[0][7]).innerHTML = "Notecard Created By: "+this.data[0][11]+this.data[0][12]+" on " + this.data[0][9] + " | Updated: " + this.data[0][10];
                                                }
                                            }
                                            //editNoteWin.hide();
                                            var my_parent = Ext.fly('note_'+this.data[0][7]).parent();
                                            var parent_id = my_parent.id.split("_");

                                            if(parent_id[1]==this.data[0][1]){
                                                var m;
                                                // show the effects without changing
                                                m = new Effect.ScrollTo("note_" + this.data[0][7], {
                                                    queue: 'end'
                                                });
                                                m = new Effect.Pulsate("note_" + this.data[0][7], {
                                                    queue: 'end',
                                                    from: 0.4
                                                });
                                            }else{
                                                var orgCount;
                                                if(this.data[0][1]!='0'){

                                                    if(parent_id.length>1){
                                                        orgCount = Ext.get('numnotes_'+parent_id[1]).dom.innerHTML;
                                                        orgCount = Number(orgCount)-1;
                                                        Ext.get('numnotes_'+parent_id[1]).dom.innerHTML = orgCount;
                                                        if(orgCount === 0){
                                                            Ext.get('showhidelink_'+parent_id[1]).dom.innerHTML = "";
                                                        }
                                                    }
                                                    var newCount = Ext.get('numnotes_'+this.data[0][1]).dom.innerHTML;
                                                    newCount = Number(newCount)+1;
                                                    Ext.get('numnotes_'+this.data[0][1]).dom.innerHTML = newCount;

                                                    if(Ext.get('showhidelink_'+this.data[0][1]).dom.innerHTML === ""){
                                                        Ext.get('showhidelink_'+this.data[0][1]).dom.innerHTML = "<a onclick='showhide("+this.data[0][1]+"); return false; ' href='#'><span id='showhidetxt_"+this.data[0][1]+"'>Show</span></a> | ";
                                                    }
                                                    Ext.get('showhidelink_'+this.data[0][1]).setDisplayed(true);

                                                    if(newCount != 1){
                                                        if(Ext.get('notesdiv_'+this.data[0][1]).dom.innerHTML!==""){
                                                            var m1;
                                                            Ext.fly('note_'+this.data[0][7]).appendTo(Ext.get('notesdiv_'+this.data[0][1]).id);
                                                            // show the effects without changing
                                                            m1 = new Effect.ScrollTo("note_" + this.data[0][7], {
                                                                queue: 'end'
                                                            });
                                                            m1 = new Effect.Pulsate("note_" + this.data[0][7], {
                                                                queue: 'end',
                                                                from: 0.4
                                                            });
                                                        }else{
                                                            Ext.fly('note_'+this.data[0][7]).remove();
                                                        }
                                                    }else{
                                                        Ext.fly('note_'+this.data[0][7]).remove();
                                                    }

                                                }else{

                                                    if(parent_id.length>1){
                                                        orgCount = Ext.get('numnotes_'+parent_id[1]).dom.innerHTML;
                                                        orgCount = Number(orgCount)-1;
                                                        Ext.get('numnotes_'+parent_id[1]).dom.innerHTML = orgCount;
                                                        if(orgCount === 0){
                                                            Ext.get('showhidelink_'+parent_id[1]).dom.innerHTML = "";
                                                        }
                                                    }
                                                    Ext.fly('note_'+this.data[0][7]).appendTo(Ext.get('notes').id);
                                                    var m2;
                                                    // show the effects without changing
                                                    m2 = new Effect.ScrollTo("note_" + this.data[0][7], {
                                                        queue: 'end'
                                                    });
                                                    m2 = new Effect.Pulsate("note_" + this.data[0][7], {
                                                        queue: 'end',
                                                        from: 0.4
                                                    });
                                                }

                                            }
                                            return true;

                                        };
                                        var callback = {
                                            success: handleSuccess1,
                                            failure: handleFailure1
                                        };
										
										//unset handlers when there is no any session / multilogin error
										editNoteWin.un('beforehide', handler);
                                                
                                        //ajax call to the server to insert notecard data
                                        YAHOO.util.Connect.asyncRequest('POST', '../notecards/_includes/loadNoteData.php', callback, "projectid=" + projectid + "&id=" + tempeditNoteID+"&windowname="+windowname+"&macfix=1234");
                                        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){
                                        showFailureMessage();
                                    }
                                });

                            }
                            else {
                                showResult = function(btn){
                                            
                                };

                                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 {
                            showResult = function(btn){
                                        
                            };
                            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 {
                        showResult = function(btn){
                                    
                        };
                        Ext.MessageBox.show({
                            title: 'Error',
                            msg: 'The characters &, <, and > are reserved characters and cannot be used in the notecard title.',
                            buttons: Ext.MessageBox.OK,
                            closable: false,
                            fn: showResult,
                            icon: Ext.MessageBox.ERROR
                        });
                    }
                }
                else {
                    showResult = function(btn){
                                
                    };
                    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', handler);
                cmp.hide();
            }
        };
        Ext.MessageBox.confirm('Confirm', 'Do you want to save your changes?', showResult);
        return false;
    }else{
        return true;
    }
}else{
    return true;
}
releaseLockForElementUnderProcess(tempeditNoteID);
}
// 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: handler
    },
    'beforeshow': {
        fn: function(win){
            editNoteWin.on('beforehide', handler);
            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 to edit Notecard from Bib

function editNoteFromBib(NoteId){
   
Ext.WindowGroup.zseed = 1000000000000;
editNoteID = NoteId;
//prepareMaskBib();
projectid = document.getElementById('projectID').value;
function handleFailure (o)
{
 showFailureMessage();
}
function handleSuccess (o){
var resp = Ext.decode(o.responseText);
var allowEditingNotecard = fnCollaborationProcessResponse(resp);
if(allowEditingNotecard){
    var data = resp.RESPONSE;
            
    if(!editNoteWin){
        displaywindowToEditNoteFromBib(data[0],data[1],data[2],data[3], data[4]);
    }else{
                
        editPileStore.reload(null);
        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('uCmbPile').setValue('');
        Ext.getCmp('uCmbPile').enable();
        Ext.getCmp('utxtSource').reset();
        Ext.getCmp('utxtSource').setValue(data[0][1]);
        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(data[0][7]);
        var pileArr = data[0][8];
        if (pileArr[0] != "0") {
            var PileTitle=pileArr[1];
            Ext.getCmp('uCmbPile').setValue(PileTitle);
            Ext.getCmp('uCmbPile').disable();
            Ext.getCmp('newPileEntry').setValue('old');
        }else{
            Ext.getCmp('uCmbPile').enable();
            Ext.getCmp('newPileEntry').setValue('old');
        }
        Ext.get('mypileid').dom.value = pileArr[0];
                
        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='+NoteId+'&projectid='+projectid+'&addlock=yes&windowname='+windowname+'&macfix=1234'
});

}



function directEditNotecard(id){
var a = id.split("_");
editNoteID = a[1];
if(isTeacher == "1"){
        
notecardDetail(a[1]);
}
else{
editNotecard(a[1]);
}
}
function showFailureMessage()
{
    hidePopupOnDrag();
    Ext.MessageBox.show({
        title: 'Error',
        minWidth:550,
        msg: 'Internet connection failed. Your changes have not been saved. Please check your connection and try again. If the problem persists, log out completely and restart NoodleBib.',
        buttons: Ext.MessageBox.OK,
        closable: false,
        icon: Ext.MessageBox.ERROR
    });
}
function wordwrap( str, width, brk, cut ) {
    brk = brk || '<br />\n';
    width = width || 100;
    cut = cut || true;

    if (!str) { return str; }

    var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');

    return str.match( RegExp(regex, 'g') ).join( brk );

}



