/**
 * @author amore
 */
 
var threshold = 1;
var down_x;
var down_y;
var up_x;
var up_y;
var x;
var y;
 
var mdx;
var mdy;
var mux;
var muy;
var thresholdx;
var thresholdy;
 
var myX;
var myY;
var scrollMe = false;
var returnGetUpdatesFlag = true;
var isOutlineUpdated = true;
var loadingOutline = false;
var windowname='';
var getUpdatesFailed = 0;
Ext.Ajax.on('beforerequest',function(con, resp, obj){isOutlineUpdated = false;});
 
//global variables to store mouse x and y on tabletop
var mousex;
var mousey;
var Colmenu;
var cuesMenu;
var tagsMenu;

var layout = null; 
 
// array to store selected predefined comment
var commArr = [];
 
// variable to store the predifined comment window
var commentsWin;
var frmcommentPanel;
var hideTotalUsers = function(){
    if(Ext.get("totalUsers_content").dom.style.display!="none"){
        Ext.get("totalUsers_content").ghost("t",{
            remove:false,
            useDisplay: true
        });
    }
};
function calculateHighLightedNotecard(){
    var numselectednotecard = Ext.query("div[class=notecardYellow]");
    for(selCount=0;selCount<numselectednotecard.length;selCount++){
        if(numselectednotecard[selCount].id == "ygddfdiv"){
            numselectednotecard.splice(selCount, 1);
            break;
        }
    }
    if (numselectednotecard.length == 1) {
        document.getElementById('selectedNoteCount').innerHTML = "1 notecard selected";
    } else {
        document.getElementById('selectedNoteCount').innerHTML = numselectednotecard.length + " notecards selected";
    }
}
// function fired to end any editing on the tabletop
function stopEditingonTabletop()
{
    this.success = false;
    var el = YAHOO.util.Dom.getElementsByClassName('selected');
    if(el.length > 0)
    {
        if(itemInEditMode)
        {
            if(outlineTxtHideMe()){
                this.success = true;
            }else{
                this.success = false;
            }

        }
        else{
            document.getElementById(el[0].id).className = "";
            this.success = true;
        }
    }
    if(noteInEditMode)
    {
        hideMe();
        this.success = true;
    }else if(liNoteInEditMode)
    {
        endEditLiNotTitle();
        this.success = true;
    }else if(pileInEditMode){
        pileHideMe();
        this.success = true;
    }else{
        this.success = true;
    }
	
    return this.success;
}
// handle the mouse down event on tabletop
function tabletopMouseDown(ev)
{
    //displayPopup=false;
    //set the appropriate cursor image on mousedown
    //retrieve xy on mouse down event
    mdx = parseInt(YAHOO.util.Event.getXY(ev)[0], 10);
    mdy = parseInt(YAHOO.util.Event.getXY(ev)[1], 10);
    down_x = YAHOO.util.Event.getPageX(ev);
    down_y = YAHOO.util.Event.getPageY(ev);
    stopEditingonTabletop();
    scrollMe = true;
    // get the exploded piles and stop scrolling when clicked on them
    var el = YAHOO.util.Dom.getElementsByClassName('expandedPile');
    for(i=0;i<el.length;i++)
    {
        var expRegion = YAHOO.util.Dom.getRegion(el[0].id);
        var mouseRegion = new YAHOO.util.Point(mdx,mdy);
        if(mouseRegion.intersect(expRegion))
        {
            scrollMe = false;
        }
    }
}
// handle the mouse up event on tabletop
function tabletopMouseUp(ev)
{
    displayPopup = true;
    scrollMe = false;
}
// handle the mouse move on tabletop
function tabletopMouseMove(ev)
{
    if (scrollMe === true) {
        var el = YAHOO.util.Event.getTarget(ev);
        //set the appropriate cursor image on mousedown
        //YAHOO.util.Dom.setStyle('tabletopContainer', 'cursor', 'url(../notecards/_images/icon-dragcursor.cursor), default');
        YAHOO.util.Dom.setStyle('tabletopContainer', 'cursor', 'move');
        //retrieve xy on mouse up event
        var mux = parseInt(YAHOO.util.Event.getXY(ev)[0], 10);
        var muy = parseInt(YAHOO.util.Event.getXY(ev)[1], 10);
        //calculate the difference between xy s of the mousedown and mouseup events
        thresholdx = 0-(mux - mdx);
        thresholdy = 0-(muy - mdy);
        myX = myX + thresholdx;
        myY = myY + thresholdy;
        if(myX < 0)
        {
            myX = 0;
        }
        if(myY < 0)
        {
            myY = 0;
        }
        if(Number(myY)+600 > 1500)
        {
            myY = 898;
        }
        if(Number(myX)+Number(tabletopViewWidth) > 3000)
        {
            myX = 2998-Number(tabletopViewWidth);
        }
        mdx = mux;
        mdy = muy;

        if (el.id == "tabletop") {
            document.getElementById('tabletopContainer').scrollTop=myY;
            document.getElementById('tabletopContainer').scrollLeft=myX;
            var birdsEyeViewTop = (document.getElementById('tabletopContainer').scrollTop/12);
            birdsEyeViewTop=birdsEyeViewTop+"px";
            var birdsEyeViewLeft = (document.getElementById('tabletopContainer').scrollLeft/12);
            birdsEyeViewLeft=birdsEyeViewLeft+"px";
            YAHOO.util.Dom.setStyle('viewable_area', 'top', birdsEyeViewTop);
            YAHOO.util.Dom.setStyle('viewable_area', 'left', birdsEyeViewLeft);
        }
    }
    else{
        //retrieve pagex, pagey and store them
        mousex = YAHOO.util.Event.getPageX(ev);
        mousey = YAHOO.util.Event.getPageY(ev);
    }
}
/*
 * function to resize layout on window resize
 */ 
Ext.onReady(function(){
    myMask = new Ext.LoadMask(Ext.get('main'), {msg:"Please wait..."});
    if(Ext.fly('selectedNoteCount')){
        Ext.EventManager.on(document.body, "click", calculateHighLightedNotecard);
    }
});

function clearSelectionOfNotecards(){
    var numselectedPile = Ext.query("div[class=pileYellow]");
    for(selCount=0;selCount<numselectedPile.length;selCount++){
        ctrlPressed=true;
        ctrlSelectPile(numselectedPile[selCount].id);
        ctrlPressed=false;
    }
    var numselectednotecard1 = Ext.query("div[class=notecardYellow]");
    for(selCount=0;selCount<numselectednotecard1.length;selCount++){
        ctrlPressed=true;
        highlightMe(numselectednotecard1[selCount].id, 'clear');
        // just to make sure all notecards visible in pile also get deselcted
        if(Ext.get("li_"+numselectednotecard1[selCount].id)){
            Ext.get("li_"+numselectednotecard1[selCount].id).dom.className="noteli";
        }
        ctrlPressed=false;
    }
    updateCountInPile();
    if(isTeacher){
        for(mln=0;mln<pileID.length;mln++){
            if(Ext.get("li_txt_"+pileID[mln][0])){
                Ext.get("li_txt_"+pileID[mln][0]).dom.innerHTML=notecardCountInPile(pileID[mln][0]);
                if(Ext.get(pileID[mln][0]).dom.className.match("Yellow")){
                    Ext.get("li_"+pileID[mln][0]).dom.className="pileliYellow";
                }else{
                    Ext.get("li_"+pileID[mln][0]).dom.className="pileli";
                }
            }
        }
    }
    document.getElementById('selectedNoteCount').innerHTML = "0 notecards selected";
}
/*
 * function to reset the position of help bubbles on window resize
 */
var resetBubblePosition = function(cmp){
    var x;
    var y;
    var el;
    var newbReg;
    if(cmp.id == "newNoteButton"){
        newbReg = YAHOO.util.Dom.getRegion("newNoteButton");
        x = newbReg.right-5;
        y = newbReg.top-28;
        cmp.setPosition(x,y);
    }
    else if(cmp.id == "noteRegion")
    {
        el = Ext.get("notecardRegion");
        x = el.getX()+90;
        y = el.getY();
        cmp.setPosition(x,y);
    }
    else if(cmp.id == "birdsBubble")
    {
        el = Ext.get("outer_hawk_eye");
        x = el.getX()+245;
        y = el.getY()-150;
        cmp.setPosition(x,y);
    }
    else if(cmp.id == "outlineBubble")
    {
        el = Ext.get("outline");
        x = el.getX()-255;
        y = el.getY();
        cmp.setPosition(x,y);
    }
    else if(cmp.id == "bubbleTags")
    {
        newbReg = YAHOO.util.Dom.getRegion("menuButton");
        x = newbReg.right-5;
        y = newbReg.top-28;
        cmp.setPosition(x,y);
    }
};
function resizeLayout(){
    layout.resize(true);
    if(Ext.getCmp("pileHTML"))
    {
        Ext.getCmp("pileHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
    }
    else if(Ext.getCmp("noteHTML"))
    {
        Ext.getCmp("noteHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
    }
    else if(Ext.getCmp("sltdnoteHTML"))
    {
        Ext.getCmp("sltdnoteHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
    }
    else if(Ext.getCmp("unpilednoteHTML"))
    {
        Ext.getCmp("unpilednoteHTML").setHeight(YAHOO.util.Dom.getViewportHeight() - 200);
    }
	
    var active_wind = openwindows.getActive();
    if(active_wind){
        active_wind.setWidth(YAHOO.util.Dom.getViewportWidth()-100);
        active_wind.center();
    }
	
    openwindows.each(resetBubblePosition);
//createBirdsEyeView();
//onWindowResize();
}
/*
 * function to display session error
 */
function showNotesSessionError(val)
{
    if(val == "[[ERROR_NOID]]")
    {
        if (error_counter > 0){return;}
        error_counter++;

        alert("Your session has expired. Please log in again to continue.");
        window.location.href = '../../logout.php';
    }
    else if(val == "[[ERROR_MULTIPLE]]")
    {
        if (error_counter > 0){return;}
        error_counter++;

        alert("This list has been opened by another user. Please re-open the list to continue working on it.");
        window.location.href = '../../noodlebib/index.php?err=error_multiple';
    }
}
/*
  * function to load all the pile details
  */
function loadPileNoteRel()
{
    var projectID = document.getElementById('projectID').value;
    var success = function(o){
        if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
        {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }
        var 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];
            }
        }
        Ext.MessageBox.updateProgress(3/7,'Loading (43%)');
        loadPileDetailFromDatabase();
    };
    var failure = function(o)
    {
         showFailureMessage();
    };

    //ajax call to the server to load pile notecard relation
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadNotePileRel&projectID='+projectID+'&windowname=&macfix=1234'
    });
}
/*
  * function to load all the notecards details
  */
function loadNotecardDetailFromDatabase()
{
    // get the current project id
    var projectID = document.getElementById('projectID').value;
    var success = function(o){

        var result = Ext.decode(o.responseText);
        var collborationResponse = fnCollaborationProcessResponse(result);
        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];
            }
        }
        var initLeftTop = [];
        document.getElementById('zoneList').innerHTML = "";
        // create the notecards
        for (a = 0; a < notecardID.length; a++) {
            var noteCard = new NoteCardTemplate(notecardID[a][0], notecardID[a][4]);
            if(isTeacher != "1"){
                var notec = new YAHOO.example.DDNotecard(notecardID[a][0], "", {
                    cont: 'tabletop'
                });
            }
            
            var div = document.createElement("div");
            div.innerHTML = noteCard.toHTML();
            
            document.getElementById("tabletop").appendChild(div.firstChild);
            
            initLeftTop[0] = notecardID[a][1];
            initLeftTop[1] = notecardID[a][2];
            setLeftTopInTabletop(notecardID[a][0], initLeftTop);
            
            if(notecardID[a][7] == "zone"){
                notecardID[a][6] = "none";
            }

            document.getElementById(notecardID[a][0]).style.display = notecardID[a][6];
            
            // code to check whether the notecard was in selected state
            if (notecardID[a][5] === true) {
                document.getElementById(notecardID[a][0]).className = "notecardYellow";
            }
            else {
                document.getElementById(notecardID[a][0]).className = "notecard";
            }
            createNotecardThumb(notecardID[a][0]);
            document.getElementById('thumb_' + notecardID[a][0]).style.display = notecardID[a][6];
        
          if (notecardID[a][7] == "zone") {
                if(!document.getElementById('li_Notecard_' + cnt)){
                    var zoneNoteCard = new zoneNotesLi(notecardID[a][0],notecardID[a][4]);
                    var ol = document.createElement("ol");
                    ol.innerHTML = zoneNoteCard.toHTML();
                    var parentEl = Ext.get("zoneList");
                    if(!parentEl.contains('li_Notecard_' + cnt)){
                        document.getElementById('zoneList').appendChild(ol.firstChild);
                        parentEl = Ext.get("zoneList");
                        var childEl = Ext.get('li_Notecard_' + cnt);
                        parentEl.insertFirst(childEl);
                    }
                }
            }
        }

        // apply the in outline cues after refreshment of the tabletop as all
        // the notecards are recreated in the dom
        for (m=0;m < notecardsOutline.length;m++) {

            if (document.getElementById(notecardsOutline[m][0])) {
                document.getElementById('check_' + notecardsOutline[m][0]).style.display = "block";
                var li = document.getElementById('li_' + notecardsOutline[m][0]);
                if (li !== null) {
                    document.getElementById('li_check_' + notecardsOutline[m][0]).style.display = "block";
                }
            }
        }
        Ext.MessageBox.updateProgress(2/7,'Loading (29%)');
        hidePopupOnDrag();
        loadPileNoteRel();
    }
    };
    var failure = function(o)
    {
         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=&macfix=1234'
    });
}
/*
  * function to generate the tabletop
  */
function initLoading()
{
    var resultTpl = new Ext.XTemplate(
        '<tpl for="."><div class="search-item">',
        '<span>{title}</span>',
        '</div></tpl>'
        );
    var userID = document.getElementById('userID').value;
    var failure = function(o)
    {
         showFailureMessage();
    };
    var success = function(o){
        if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
        {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }
        var resp = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(resp);
        if(collabResp == true){
            windowname = resp.RESPONSE;
        }
    };
    var passWindowName="";
    
    //ajax call to the server to insert notecard data
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadproject&windowname='+passWindowName+'&macfix=1234'
    });
    // loadproject toggle dont need windowname checked as it the first request, we have to assign windowname to its session value
    // every time first request gets called in dashboard/bib/notecard page which handles back button scenario.
    // Show the Panel
    loadNotecardDetailFromDatabase();
}


/*
  * function to set the initial position of the tabletopContainer for scrolling
  */
function init()
{
    createBirdsEyeView();
    layout = new YAHOO.widget.Layout('outerDiv', {
        height: 600,
        units: [            
        {
            position: 'center',
            gutter: '1px',
            body: 'first-half'
        },

        {
            position: 'right',
            header: 'Outline',
            width: 300,
            gutter: '1px',
            collapse: true,
            body: 'second-half'
        }
        ]
    });
    layout.on("render", function(){
        if(Ext.get('windowname')){
            windowname = document.getElementById('windowname').value;
        }
        initLoading();
    });
    layout.render();	
    
    var oElement = document.getElementById("tabletop");
    var el = YAHOO.util.Dom.getRegion('outerDiv');
    var tabletopViewWidth = el.right - el.left;
    var spcaeLeft = 3000 - tabletopViewWidth;
    document.getElementById('tabletopContainer').scrollTop=((1500-600)/2);
    document.getElementById('tabletopContainer').scrollLeft=spcaeLeft/2;
    myX = spcaeLeft/2;
    myY = 450;
    YAHOO.util.Event.addListener(oElement, "mousedown", tabletopMouseDown);
    YAHOO.util.Event.addListener(oElement, "mouseup", tabletopMouseUp);
    YAHOO.util.Event.addListener(oElement, "mousemove", tabletopMouseMove);
	
}



/*
 * function to check if string contains <test or &test
 */
function htmlTags(val)
{
    var regexp=/(\&)|(\<)|(\>)/;
    if(val.search(regexp) >= 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}
/*
 * function to toggle search options
 */
function toggleOptions(val)
{	
    var maskWin;
    //show the window mask before the request
    maskWin = new Ext.Window({
        layout:'fit',
        manager: openwindows,
        baseCls: 'summPopup',
        closable: false,
        resizable: false,
        plain: true,
        border: false,
        shadow:false,
        html: "<img src = '../notecards/_images/ajax-loader.gif'> Please wait... ",
        modal: true
    });
    maskWin.show();
	
    if(val == "Color")
    {
        document.getElementById("conSearch").style.display = "none";
        document.getElementById("conBooleans").style.display = "none";
        document.getElementById("conCues").style.display = "none";
        document.getElementById("conSource").style.display = "none";
        document.getElementById("conColors").style.display = "block";
        maskWin.close();
    }
    else if(val == "Cues")
    {
        document.getElementById("conSearch").style.display = "none";
        document.getElementById("conBooleans").style.display = "none";
        document.getElementById("conColors").style.display = "none";
        document.getElementById("conSource").style.display = "none";
        document.getElementById("conCues").style.display = "block";
        maskWin.close();
    }
    else if(val == "tag")
    {
        document.getElementById("conColors").style.display = "none";
        document.getElementById("conCues").style.display = "none";
        document.getElementById("conSource").style.display = "none";
        document.getElementById("conSearch").style.display = "block";
        document.getElementById("conBooleans").style.display = "block";
        maskWin.close();
    }
    else if(val == "keyword")
    {
        document.getElementById("conColors").style.display = "none";
        document.getElementById("conCues").style.display = "none";
        document.getElementById("conSource").style.display = "none";
        document.getElementById("conSearch").style.display = "block";
        document.getElementById("conBooleans").style.display = "block";
        maskWin.close();
    }
    else if(val == "source")
    {
        document.getElementById("conColors").style.display = "none";
        document.getElementById("conCues").style.display = "none";
        document.getElementById("conSearch").style.display = "none";
        document.getElementById("conSource").style.display = "block";
        document.getElementById("conBooleans").style.display = "none";
        maskWin.close();
    }
}
/*
 * function to apply citation to highlighted notecards
 */
function applySource(citID)
{
    var maskWin;
    //array of highlighted notecards
    var arrSelNotes = [];
    var arrNoteIDs = [];
    arrSelNotes = YAHOO.util.Dom.getElementsByClassName( "notecardYellow" , "div" , "tabletop" , "" );
    for(j=0;j<arrSelNotes.length;j++)
    {
        arrNoteIDs[arrNoteIDs.length] = (arrSelNotes[j].id).split("_")[1];
    }
    var arrStr = Ext.encode(arrNoteIDs);

    var success = function(o)
    {
        var obj = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(obj);
        if(collabResp)
        {
            maskWin.hide();
        }
    };

    var failure = function(o)
    {
         showFailureMessage();
    };

    //show the window mask before the request
    maskWin = new Ext.Window({
        layout:'fit',
        manager: openwindows,
        baseCls: 'summPopup',
        closable: false,
        resizable: false,
        plain: true,
        border: false,
        shadow:false,
        html: "<img src = '../notecards/_images/ajax-loader.gif'> Applying citations... ",
        modal: true
    });
    maskWin.show();

    //ajax request to apply citations
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params:
        {
            toggle:'applycitations',
            entryID:citID,
            noteIDs:arrStr,
            macfix:'1234'
        }
    });
}
/*
 * function to load sources
 */
function loadSources()
{
    var arrSelNotes = [];
    arrSelNotes = YAHOO.util.Dom.getElementsByClassName( "notecardYellow" , "div" , "tabletop" , "" );
    if(arrSelNotes.length>0)
    {
        var srcDg = new Ext.Panel({
            frame: true,
            items: [{
                xtype: 'fieldset',
                autoHeight: true,
                style: {
                    padding: '5px'
                },
                items: [cmb = new Ext.form.ComboBox({
                    id: 'srcList',
                    width: 300,
                    listWidth: 500,
                    autoScroll: false,
                    fieldLabel: 'Select citation',
                    store: new Ext.data.JsonStore({
                        id: 'citID1',
                        autoLoad: true,
                        root: 'rows',
                        fields: [{
                            name: 'id',
                            type: 'string'
                        }, {
                            name: 'citation',
                            type: 'string'
                        }],
                        url: '../notecards/_includes/notecardOperations.php',
                        baseParams: {
                            toggle: 'citationsmenu'
                        }
                    }),
                    valueField: 'id',
                    displayField: 'citation',
                    typeAhead: false,
                    editable: false,
                    mode: 'local',
                    disabled: false,
                    forceSelection: true,
                    triggerAction: 'all',
                    emptyText: 'Select citation',
                    selectOnFocus: true
                })]
            }],
            buttons: [{
                text: 'Submit',
                handler: function(){
                                   


                    var citID = Ext.getCmp('srcList').getValue();
                    if (citID !== "") {
                        srcWin.close();
                        applySource(citID);
                    }
                    else {
                        srcWin.hide();
                        var showResult3 = function(){
                            srcWin.show();
                        };
                        Ext.MessageBox.show({
                            title: 'Error',
                            msg: 'Please select a source to continue.',
                            buttons: Ext.MessageBox.OK,
                            fn: showResult3,
                            icon: Ext.MessageBox.ERROR
                        });
                    }
                }
            }]
        });
		
        // window to show rtf dialog
        var srcWin = new Ext.Window({
            layout: 'fit',
            width: 500,
            height: 150,
            constrain: true,
            title: 'Apply Sources',
            closable: true,
            resizable: false,
            plain: true,
            border: false,
            manager: openwindows,
            items: [srcDg],
            listeners: {
                close: {
                    fn: function(){
                        srcDg.destroy();
                        srcWin.destroy();
                    }
                }
            },
            modal: true
        });
        srcWin.show();
    }
    else
    {
        showAlertBox("Please select (ctrl-click) notecard(s) to apply citations.", "tabletop");
    }
}
function checkdeletednotes(projectID)
{
    var ds; //datastore for grid
    var cm; //columnModel
    var grid; //component

    //var fm = Ext.form, Ed = Ext.grid.EditorGridPanel; // shorthand alias
    //var projectID = document.getElementById('projectID').value;
    //var selectedRow = null, selectedCol = null;

    //create the datastores
    // the data store (created below)
    cm = new Ext.grid.ColumnModel([
    {
        header: '',
        width: 50,
        sortable: false,
        renderer: function(val){
            return '<input type="checkbox" name="chk[]" id="chk[]" value="'+val+'" />';
        },
        dataIndex: 'ID'
    },

    {
        id:'Title',
        header: "Title",
        dataIndex: 'Title',
        width: 400,
        sortable:true
    }
    ]);

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Tags = Ext.data.Record.create([
    // the "name" below matches the tag name to read, except "availDate"
    // which is mapped to the tag "availability"
    {
        name: 'ID'
    },

    {
        name: 'Title'
    }


    ]);

    // create the Data Store
    ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            //where to retrieve data
            url: '../notecards/_includes/notecardOperations.php', //url to data object (server side script)
            method: 'POST'
        }),
        baseParams:{
            toggle: "getDeletedNotes",
            projectID: projectID
        },//this parameter is passed for any HTTP request
        reader: new Ext.data.JsonReader(
        {
            root: 'rows',
            totalProperty: 'results',
            id: 'ID'
        },Tags
        )

    });
    ds.load();

    // create the editor grid
    // Here i need to use a form panel and inside that form panel i will use grid panel

    grid = new Ext.grid.EditorGridPanel({
        store: ds,
        cm: cm,
        width:500,
        bodyBorder : false,
        height:300,
        iconCls:'icon-grid'

    });
    var heading = new Ext.FormPanel({
        labelWidth: 95, // label settings here cascade unless overridden
        frame:true,
        items: [grid,
           {
            xtype: 'textfield',
            value: "undeletenotecard",
            name: 'toggle',
            hidden: true
        },
        {
            xtype: 'textfield',
            value: windowname,
            name: 'windowname',
            id: 'windowname',
            hidden: true
        },
        {
            xtype: 'textfield',
            value: "1234",
            name: 'macfix',
            hidden: true
        }
        ]
    });

    var win = new Ext.Window({

        cls: "../_css/noodlenotes.css",
        title: 'Restore deleted notecards',
        closable:true,
        autoScroll:true,
        bodyBorder:false,
        width:450,
        height:380,
        plain:true,
        items: [heading],
        buttons: [{
            text: 'Undelete',
            handler: function(){
                
                prepareLoadMask();
                heading.getForm().submit({
                    url: '../notecards/_includes/notecardOperations.php',
                    //params : 'toggle=undeletenotecard&windowname='+windowname+'&macfix=1234',
                    success: function(form, action){
                        obj = Ext.decode(action.response.responseText);
                        var collabresponse = fnCollaborationProcessResponse(obj.data.response);
                        if(collabresponse === true)
                        {

                            refreshTabletop();
                            clearSelectionOfNotecards();
                            win.hide();
                        }

                    },

                    failure: function(form, action){
                        showFailureMessage();
                        win.hide();
                    }
                });
            }
        }]

    });
    win.show();
}
function unDeleteNotecard()
{
    
    var projectID = document.getElementById('projectID').value;
    //ajax request to apply citations
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        callback: function (options, success, response) {

            if((Trim(response.responseText)).match("ERROR_MULTIPLE") || (Trim(response.responseText)).match("ERROR_NOID"))
            {
                showNotesSessionError(Trim(o.responseText));
                return false;
            }
            if(response.responseText > 0)
            {
                checkdeletednotes(projectID);
            }
            else
            {
                showAlertBox("No deleted notecard for this project", "tabletop");
            }
        },
        params:
        {
            toggle : 'chkdeletednote',
            windowname : windowname,
            projectID:projectID
	}
                

    });

}
function checkdeletedCitation(projectID)
{
    var ds; //datastore for grid
    var cm; //columnModel
    var grid; //component

    //var fm = Ext.form, Ed = Ext.grid.EditorGridPanel; // shorthand alias
    //var projectID = document.getElementById('projectID').value;
    //var selectedRow = null, selectedCol = null;

    //create the datastores
    // the data store (created below)
    cm = new Ext.grid.ColumnModel([
    {
        header: '',
        width: 50,
        sortable: false,
        renderer: function(val){
            return '<input type="checkbox" name="chk[]" id="chk[]" value="'+val+'" />';
        },
        dataIndex: 'ID'
    },


    {
        id:'EntryType',
        header: "Entry Type",
        dataIndex: 'EntryType',
        width: 150,
        sortable:true
    },
    {
        id:'Title',
        header: "Title",
        dataIndex: 'Title',
        width: 318,
        sortable:true
    }
    ]);

    // this could be inline, but we want to define the Plant record
    // type so we can add records dynamically
    var Tags = Ext.data.Record.create([
    // the "name" below matches the tag name to read, except "availDate"
    // which is mapped to the tag "availability"
    {
        name: 'ID'
    },

    {
        name: 'Title'
    },

    {
        name: 'EntryType'
    }
    ]);

    // create the Data Store
    ds = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            //where to retrieve data
            url: '../notecards/_includes/notecardOperations.php', //url to data object (server side script)
            method: 'POST'
        }),
        baseParams:{
            toggle: "getDeletedCitation",
            projectID: projectID
        },//this parameter is passed for any HTTP request
        reader: new Ext.data.JsonReader(
        {
            root: 'rows',
            totalProperty: 'results',
            id: 'ID'
        },Tags
        )
    });
    ds.load();

    // create the editor grid
    // Here i need to use a form panel and inside that form panel i will use grid panel

    grid = new Ext.grid.EditorGridPanel({
        store: ds,
        cm: cm,
        width:520,
        bodyBorder : false,
        height:300,
        iconCls:'icon-grid'

    });
    var heading = new Ext.FormPanel({
        labelWidth: 95, // label settings here cascade unless overridden
        frame:true,
        items: [grid,{
                xtype:'textfield',
                name:'macfix',
                hidden:true,
                value:'1234'
        }]
    });

    var win = new Ext.Window({

        cls: "../_css/noodlenotes.css",
        title: 'Restore deleted citations',
        closable:true,
        autoScroll:true,
        bodyBorder:false,
        width:550,
        height:380,
        plain:true,
        items: [heading],
        buttons: [{
            text: 'Undelete',
            handler: function(){

                heading.getForm().submit({
                    url: '../notecards/_includes/notecardOperations.php',
                    params : 'toggle=undeletecitation&windowname='+windowname,
                    success: function(form, action){
                        window.location.reload();
                        win.hide();
                    },

                    failure: function(form, action){
                        showFailureMessage();
                        win.hide();
                    }
                });
            }
        }]

    });
    win.show();
}
function unDeleteCitation()
{
    var projectID = document.getElementById('projectID').value;

    //ajax request to apply citations
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        callback: function (options, success, response) {

            if((Trim(response.responseText)).match("ERROR_MULTIPLE") || (Trim(response.responseText)).match("ERROR_NOID"))
            {
                showNotesSessionError(Trim(response.responseText));
                return false;
            }
            if(response.responseText > 0){
                checkdeletedCitation(projectID);
            }
            else
            {
                showAlertBox("No deleted citation for this project", "tabletop");
            }
        },
        params:
        {
            toggle : 'chkdeletedCitation',
            projectID:projectID
        }
    });
}
/*
  * function to load all the pile details
  */
function loadPileDetailFromDatabase()
{
    var projectID = document.getElementById('projectID').value;
    var success = function(o){
        if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
        {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }
        var resultArray = [];
        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];
            }
        }
        var initLeftTop = [];
        var b;
        // create the piles
        for (a = 0; a < pileID.length; a++) {

            var newPile = new PileTemplate(pileID[a][0], pileID[a][4]);
            if(isTeacher != "1"){
              b =  new YAHOO.example.DDPile(pileID[a][0]);
            }
            var div = document.createElement("div");
            div.innerHTML = newPile.toHTML();
            document.getElementById("tabletop").appendChild(div.firstChild);

            if (pileID[a][7] == "zone") {
                var zonePile = new zonePileLi(pileID[a][0], pileID[a][4]);
                var ol = document.createElement("ol");
                ol.innerHTML = zonePile.toHTML();
                document.getElementById('zoneList').appendChild(ol.firstChild);
                var parentEl = Ext.get("zoneList");
                var childEl = Ext.get('li_'+pileID[a][0]);
                parentEl.insertFirst(childEl);
                document.getElementById('li_txt_' + pileID[a][0]).innerHTML = notecardCountInPile(pileID[a][0]);
            }else{
                createPileThumb(pileID[a][0]);
                document.getElementById('thumb_' + pileID[a][0]).style.display = pileID[a][5];
            }
            initLeftTop[0] = pileID[a][1];
            initLeftTop[1] = pileID[a][2];
            setLeftTopInTabletop(pileID[a][0], initLeftTop);
            setLeftTopInBirdsEyeView(pileID[a][0], initLeftTop);
            document.getElementById('txt_' + pileID[a][0]).innerHTML = notecardCountInPile(pileID[a][0]);
            document.getElementById(pileID[a][0]).style.display = pileID[a][5];
            if (pileID[a][6] === true) {
                document.getElementById(pileID[a][0]).className = "pileYellow";
            }
            else {
                document.getElementById(pileID[a][0]).className = "pile";
            }
        }
        Ext.MessageBox.updateProgress(4/7,'Loading (57%)');
        getHTMLTree();
    };
    var failure = function(o)
    {
         showFailureMessage();
    };
    //ajax call to the server to load pile data
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadPileData&projectID='+projectID+'&windowname=&macfix=1234'
    });
}



/*
  * function to attach colors to the notecards on load
  */
function attachColors()
{
    //retrieve the current project id
    var projectID = document.getElementById("projectID").value;
    var success = function(o)
    {
        var colors;
        if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
        {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }

        try
        {
            colors = YAHOO.lang.JSON.parse(o.responseText);
        }
        catch(e)
        {
            alert(e);
        }

        //make the appropriate divs visible and fill the notecolor array
        if(colors !== null)
        {
            noteColor=[];
            for(i=0;i<colors.length;i++)
            {
                if(colors[i][1] == 1)
                {
                    noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
                    if(document.getElementById("Notecard_"+colors[i][0]) !== null)
                    {
                        document.getElementById("red_Notecard_"+colors[i][0]).style.display = "block";
                        document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "red";
                    }
                }
                else if(colors[i][1] == 2)
                {
                    noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
                    if(document.getElementById("Notecard_"+colors[i][0]) !== null)
                    {
                        document.getElementById("orange_Notecard_"+colors[i][0]).style.display = "block";
                        document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "orange";
                    }
                }
                else if(colors[i][1] == 3)
                {
                    noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
                    if(document.getElementById("Notecard_"+colors[i][0]) !== null)
                    {
                        document.getElementById("yellow_Notecard_"+colors[i][0]).style.display = "block";
                        document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "yellow";
                    }
                }
                else if(colors[i][1] == 4)
                {
                    noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
                    if(document.getElementById("Notecard_"+colors[i][0]) !== null)
                    {
                        document.getElementById("green_Notecard_"+colors[i][0]).style.display = "block";
                        document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "green";
                    }
                }
                else if(colors[i][1] == 5)
                {
                    noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
                    if(document.getElementById("Notecard_"+colors[i][0]) !== null)
                    {
                        document.getElementById("blue_Notecard_"+colors[i][0]).style.display = "block";
                        document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "blue";
                    }
                }
                else if(colors[i][1] == 6)
                {
                    noteColor[noteColor.length] = ["Notecard_"+colors[i][0],colors[i][1]];
                    if(document.getElementById("Notecard_"+colors[i][0]) !== null)
                    {
                        document.getElementById("purple_Notecard_"+colors[i][0]).style.display = "block";
                        document.getElementById("thumb_Notecard_"+colors[i][0]).style.background = "purple";
                    }
                }

            }
        }
        Ext.MessageBox.updateProgress(6/7,'Loading (86%)');
        Ext.MessageBox.updateProgress(7/7,'Loading (100%)');
        if(deletingNotecard === 0){
            Ext.MessageBox.hide();

        }
        //resize the layout after the initial break;
        resizeLayout();
        repairTabletop();
    };
    var failure = function(o)
    {
         showFailureMessage();
    };

    //ajax call to the server to retrieve notecards with colors
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadColorsData&projectID='+projectID+'&windowname='+windowname+'&macfix=1234'
    });
}
/*
  * function to attach cues to the notecards
  */
function attachCues()
{
    var projectID = document.getElementById("projectID").value;
    var success = function(o)
    {
        var cues;
        if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
        {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }
		
        try
        {
            cues = YAHOO.lang.JSON.parse(o.responseText);
        }
        catch(e)
        {
            alert(e);
        }
        if(cues !== null)
        {
            for(i=0;i<cues.length;i++)
            {
                if(cues[i][1] == 1)
                {
                    noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
                    if(document.getElementById("Notecard_"+cues[i][0]) !== null)
                    {
                        document.getElementById("research_Notecard_"+cues[i][0]).style.display = "block";
                    }
                }
                else if(cues[i][1] == 2)
                {
                    noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
                    if(document.getElementById("Notecard_"+cues[i][0]) !== null)
                    {
                        document.getElementById("help_Notecard_"+cues[i][0]).style.display = "block";
                    }
                }
                else if(cues[i][1] == 3)
                {
                    noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
                    if(document.getElementById("Notecard_"+cues[i][0]) !== null)
                    {
                        document.getElementById("incomplete_Notecard_"+cues[i][0]).style.display = "block";
                    }
                }
                else if(cues[i][1] == 4)
                {
                    noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
                    if(document.getElementById("Notecard_"+cues[i][0]) !== null)
                    {
                        document.getElementById("thinking_Notecard_"+cues[i][0]).style.display = "block";
                    }
                }
                else if(cues[i][1] == 5)
                {
                    noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
                    if(document.getElementById("Notecard_"+cues[i][0]) !== null)
                    {
                        document.getElementById("important_Notecard_"+cues[i][0]).style.display = "block";
                    }
                }
                else if(cues[i][1] == 6)
                {
                    noteCues[noteCues.length] = ["Notecard_"+cues[i][0],cues[i][1]];
                    if(document.getElementById("Notecard_"+cues[i][0]) !== null)
                    {
                        document.getElementById("paper_Notecard_"+cues[i][0]).style.display = "block";
                    }
                }
            }
        }
        Ext.MessageBox.updateProgress(5/7,'Loading (71%)');
        //function call to attach colors to the notecards
        attachColors();
    };
    var failure = function(o)
    {
         showFailureMessage();
    };
	
    //ajax call to the server to load notecard cues
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadCuesData&projectID='+projectID+'&windowname='+windowname+'&macfix=1234'
    });
}
// function to save Outline HTML tree
function saveHTMLTree(){
    // Commenting this function as this seems to be not required
    // code to end editing
    if (itemInEditMode) {
        var el = Ext.get(itemInEditMode.substr(4));
        var val = Trim(document.getElementById("txt_" + itemInEditMode.substr(4)).value);
        if (val !== "") {
            document.getElementById("content_div_" + el.id).innerHTML = document.getElementById("txt_" + itemInEditMode.substr(4)).value;
            document.getElementById("content_div_" + el.id).style.display = "block";
            document.getElementById(itemInEditMode).style.display = "none";
            enableBackSpace = false;
            itemInEditMode = null;
        }
        else {
            document.getElementById("content_div_" + el.id).innerHTML = "SubTopic";
            document.getElementById("content_div_" + el.id).style.display = "block";
            document.getElementById(itemInEditMode).style.display = "none";
            enableBackSpace = false;
            itemInEditMode = null;
        }
    }
    // get all the nodes in the outline
    var nodeElements = YAHOO.util.Dom.getElementsBy(check, "li", "list_1");
    // loop to store all the relevent information of the node in the array to be sent in ajax request
    var outlineData = [];
    var mycnt = 0;
    for (i = 0; i < nodeElements.length; i++) {

        outlineData[mycnt] = new Array(4);
        // fill the array with necessary details of notecard node
        if (Ext.get(nodeElements[i].id).dom.className.match("li_notecard_outline")) {
            outlineData[mycnt][0] = nodeElements[i].id;
            outlineData[mycnt][1] = Ext.get(nodeElements[i].id).first().id;
            outlineData[mycnt][2] = document.getElementById(Ext.get(nodeElements[i].id).first().id).innerHTML;
            outlineData[mycnt][3] = Ext.get(nodeElements[i].id).parent().id;
            outlineData[mycnt][4] = "1";
        }
        else { // fill the array with necessary details of Topic node

            outlineData[mycnt][0] = nodeElements[i].id;
            // to check if the innerhtml of li is blank and handle exception
            if(Ext.get("content_div_" + nodeElements[i].id) !== null){
                outlineData[mycnt][1] = "content_div_" + nodeElements[i].id;
                outlineData[mycnt][2] = document.getElementById("content_div_" + nodeElements[i].id).innerHTML;
            }else{
                outlineData[mycnt][1] = "";
                outlineData[mycnt][2]="";
            }
            outlineData[mycnt][3] = Ext.get(nodeElements[i].id).parent().id;
            outlineData[mycnt][4] = "0";

        }
        // store the order in which it was in the tree
        outlineData[mycnt][5] = "" + mycnt;
        var parent_li;
        if (Ext.get(nodeElements[i].id).parent("li") !== null) {
            parent_li = Ext.get(nodeElements[i].id).parent("li").id;
        }
        else {
            parent_li = 'root_li';
        }

        outlineData[mycnt][6] = parent_li;
        mycnt++;

    }
    // convert the array in json string
    jsonOutlineData = Ext.encode(outlineData);

    var handleSuccess = function(o){
        if ((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID")) {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }
    };
    var handleFailure = function(o){
         showFailureMessage();
    };

    //ajax request to send xml string
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: handleSuccess,
        failure: handleFailure,
        params: {
            toggle: 'saveHTMLTree',
            jsonOutlineData: jsonOutlineData,
            macfix: '1234'
        }
    });
}
// function to load Outline HTML tree
function getHTMLTree(){
    // 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();

                    Ext.MessageBox.updateProgress(4 / 7, 'Loading (57%)');

                    attachCues();
                    if(Ext.get("showHelpBubble").getValue()=="1"){
                        if (notecardID.length < 2 && document.getElementById('help').value == "1") {
                            if (isTeacher != "1") {
                                bubble_NewNoteButton();
                            }
                        }
                    }
                    saveHTMLTree();
                }
                else {

                    document.getElementById("outline").innerHTML = "<ol id=list_1 level='0'></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);
                    //alert("asdas");
                    }
                    saveHTMLTree();
                    // 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]);
            // save the tree
            saveHTMLTree();
            // make nodes draggable and droppable
            createInstancesInOutline();
            // update the load progress bar
            Ext.MessageBox.updateProgress(4/7,'Loading (57%)');
            // call the next load function
            attachCues();
        }
    };

    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=getHTMLTree&projectID='+projectID+'&windowname='+windowname+'&macfix=1234'
    });
}



/*
  * function to destroy the tabletop
  */
function initUnLoading()
{
    var handleSuccess = function(o)
    {
		
    };
    var handleFailure = function(o)
    {
	 showFailureMessage();
    };
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: handleSuccess,
        failure: handleFailure,
        params: 'toggle=clearWindowSession&windowname='+windowname+'&macfix=1234'
    });
/*
	var el  = YAHOO.util.Dom.getChildren('tabletop');
	for(i=0;i<el.length;i++)
	{
		if(el[i].id.match("Not") || el[i].id.match("Pil") || el[i].id.match("exp"))
		{
			var tabletop = new YAHOO.util.Element("tabletop");
			tabletop.removeChild(el[i]);
			var birdsEyeView = new YAHOO.util.Element("outer_hawk_eye");
			if(!el[i].id.match("exp"))
			{
				var thumb = new YAHOO.util.Element("thumb_"+el[i].id);
				birdsEyeView.removeChild(thumb);
			}
		}
	}
	document.getElementById('zoneList').innerHTML = "";
	outlineTxtHideMe();
	refreshPileNoteRelation();
	updateNotecardData();
	updatePileData();
	// This line is commented to make sure that blank outline is not submitted accidently.
	//saveHTMLTree();
	*/
}
// function to send ajax request to update the data related to all the notecards on the tabletop
function updateNotecardData(notecardId)
{	
    var tempArr = [];
    //create a temporary array
    for(i=0;i<notecardID.length;i++)
    {
        if(notecardID[i][0] == notecardId)
        {
            tempArr[0] = [notecardID[i][0],notecardID[i][1],notecardID[i][2],notecardID[i][3],Ext.util.Format.htmlEncode(notecardID[i][4]),notecardID[i][5],notecardID[i][6],notecardID[i][7]];
        }
    }
    var noteData = YAHOO.lang.JSON.stringify(tempArr);
    var handleSuccess = function(o)
    {
        var resp = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(resp);
        if(collabResp){
            resp = resp.RESPONSE;
            if(resp instanceof Object){
                Ext.get(notecardId).dom.style.display = resp.DISPLAY;
                Ext.get(notecardId).dom.style.top = resp.TOPPOS;
                Ext.get(notecardId).dom.style.left = resp.LEFTPOS;
            }
        }
    };
    var handleFailure = function(o)
    {
	 showFailureMessage();
    };
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: handleSuccess,
        failure: handleFailure,
        params: {
            toggle: 'updateNoteDetail',
            data: noteData,
            windowname:windowname,
            macfix: '1234'
        }
    });
	
// the following lines are commented to update the data on every enddrag of the notecard
//notecardID = [];
//pileNotecard = [];
}
// function to send ajax request to update the data related to all the piles on the tabletop
function updatePileData(pileId)
{
    var projectID = document.getElementById('projectID').value;
    var tempArr = [];
    var success=function(o)
    {
        var resp = Ext.decode(o.responseText);
        fnCollaborationProcessResponse(resp);
    };
		
    var failure=function(o)
    {
         showFailureMessage();
    };


    for (i = 0; i < pileID.length; i++)
    {
        if (pileID[i][0] == pileId)
        {
            tempArr[0] = [pileID[i][0],pileID[i][1],pileID[i][2],pileID[i][3],pileID[i][4],pileID[i][5],pileID[i][6],pileID[i][7]];
        }
    }


    // update the data of the piles in database
    var pileData = YAHOO.lang.JSON.stringify(tempArr);
	
    // update the data of all the piles via ajax call
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: {
            toggle: 'updatePileDetail',
            data: pileData,
            projectID: projectID,
            macfix:'1234'
        }
    });
		
//the following lines are commented to update the data on every enddrag of the pile
//pileID = [];
}

function MM_preloadImages(arr) { //v3.0
    var d=document;
    if(d.images){
        if(!d.MM_p)
        {
            d.MM_p=[];
        }
        var i,j=d.MM_p.length,a=arr;
        for(i=0; i<a.length; i++){
            if (a[i].indexOf("#")!==0){
                d.MM_p[j]=new Image;
                d.MM_p[j++].src=a[i];
            }
        }
    }
}

function loadImages()
{
    var arr = ['../notecards/_images/notecard.gif','../notecards/_images/notecard-selected.gif','../notecards/_images/notecard-pile.gif','../notecards/_images/notecard-pile-selected.gif','../notecards/_images/img/panelLeftBottom/corner-bottom-left.png','../notecards/_images/img/panelLeftBottom/corner-bottom-middle.png','../notecards/_images/img/panelLeftBottom/corner-bottom-right.png','../notecards/_images/img/panelLeftBottom/corner-middle-left.png','../notecards/_images/img/panelLeftBottom/corner-middle-right.png','../notecards/_images/img/panelLeftBottom/corner-top-left.png','../notecards/_images/img/panelLeftBottom/corner-top-middle.png','../notecards/_images/img/panelLeftBottom/corner-top-right.png','../notecards/_images/img/panelLeftTop/corner-bottom-left.png','../notecards/_images/img/panelLeftTop/corner-bottom-middle.png','../notecards/_images/img/panelLeftTop/corner-bottom-right.png','../notecards/_images/img/panelLeftTop/corner-middle-left.png','../notecards/_images/img/panelLeftBottom/corner-middle-right.png','../notecards/_images/img/panelLeftTop/corner-top-left.png','../notecards/_images/img/panelLeftTop/corner-top-middle.png','../notecards/_images/img/panelLeftTop/corner-top-right.png','../notecards/_images/img/panelRightBottom/corner-bottom-left.png','../notecards/_images/img/panelRightBottom/corner-bottom-middle.png','../notecards/_images/img/panelRightBottom/corner-bottom-right.png','../notecards/_images/img/panelRightBottom/corner-middle-left.png','../notecards/_images/img/panelRightBottom/corner-middle-right.png','../notecards/_images/img/panelRightBottom/corner-top-left.png','../notecards/_images/img/panelRightBottom/corner-top-middle.png','../notecards/_images/img/panelRightBottom/corner-top-right.png','../notecards/_images/img/panelRightTop/corner-bottom-left.png','../notecards/_images/img/panelRightTop/corner-bottom-middle.png','../notecards/_images/img/panelRightTop/corner-bottom-right.png','../notecards/_images/img/panelRightTop/corner-middle-left.png','../notecards/_images/img/panelRightTop/corner-middle-right.png','../notecards/_images/img/panelRightTop/corner-top-left.png','../notecards/_images/img/panelRightTop/corner-top-middle.png','../notecards/_images/img/panelRightTop/corner-top-right.png'];
    MM_preloadImages(arr);
}


/*
 * function to collapse the outline
 */
function collapseOutline()
{
    var right = layout.getUnitByPosition('right');
    right.collapse();
    createBirdsEyeView();
}

function expandOutline()
{
    var right = layout.getUnitByPosition('right');
    right.expand();
    createBirdsEyeView();
}



// function to end editing in outline
function stopEditingonOutline()
{
    this.success = false;
    if(noteInEditMode)
    {
        hideMe();
        this.success = true;
    }
    if(liNoteInEditMode)
    {
        endEditLiNotTitle();
        //saveHTMLTree();
        this.success = true;
    }
    return this.success;
}
function loadingGraphics()
{
    Ext.MessageBox.show({
        title: 'Please wait',
        msg: 'Loading...',
        progressText: 'Initializing...',
        width:300,
        progress:true,
        closable:false
    });

    Ext.MessageBox.updateProgress(1/7,'Loading (14%)');
}
// function to load new project
function LoadProject(projectid)
{	
    if (projectid != 'a') {
		
        //expand the outline
        expandOutline();

        var parent = new YAHOO.util.Dom.get('projectNames');
        var child = YAHOO.util.Dom.getChildren(parent);
        for (i = 1; i < child.length; i++) {
            parent.removeChild(child[i]);
        }
        initUnLoading();
        notecardID = [];
        pileID = [];
        pileNotecard = [];
        notecardsOutline = [];
        document.getElementById("outline").innerHTML = "";
        this.body = "<ol id=list_1 type='I'>";
        this.body = this.body + "<li class=liclass id=item_1 ><div id=content_div_item_1 onmouseover=mouseOverItem('content_div_item_1') onmouseout=mouseOutItem('content_div_item_1') ondblClick=editOutlineItem('content_div_item_1') onClick=actionOnOutlineList('content_div_item_1')>Topic</div><div style='width:auto;display:none;' id=div_item_1><input onclick=javascript:this.focus(); type=text id=txt_item_1 onfocus='javascript:enableBackSpace=true;'></div>";
        this.body = this.body + "<ol id=list_2 ></ol>";
        this.body = this.body + "<ol id=list_3 type='A'>";
        this.body = this.body + "<li class=liclass id=item_2 ><div id=content_div_item_2 onmouseover=mouseOverItem('content_div_item_2') onmouseout=mouseOutItem('content_div_item_2') ondblClick=editOutlineItem('content_div_item_2') onClick=actionOnOutlineList('content_div_item_2')>Sub Topic</div><div style='width:auto;display:none;' id=div_item_2><input onclick=javascript:this.focus(); type=text id=txt_item_2 onfocus='javascript:enableBackSpace=true;'></div>";
        this.body = this.body + "<ol id=list_4></ol><ol id=list_5></ol></li>";
        this.body = this.body + "</ol>";
        this.body = this.body + "</li>";
        this.body = this.body + "</ol>";
        var div = document.createElement("ol");
        div.innerHTML = this.body;
        document.getElementById("outline").appendChild(div.firstChild);
        var b;
        b = new YAHOO.util.DDTarget('content_div_item_2', "topslots");
        b = new YAHOO.util.DDTarget('content_div_item_1', "topslots");
        b = new YAHOO.util.DragDrop('content_div_item_2');
        b = new YAHOO.util.DragDrop('content_div_item_1');
        b = null;
        document.getElementById("projectID").value = projectid;
        loadingGraphics();
        initLoading();
        document.getElementById("search_field").value = "";
        document.getElementById("boolean_and").checked = true;
        document.getElementById("boolean_or").checked = false;
    }
}

// function to load menu
function loadTagsMenu()
{
    //hide summ popups
    hidePopupOnDrag();
    var projectid = document.getElementById('projectID').value;
    var failure = function(o)
    {
        alert(o.responseText);
    };
    var success = function(o){
        var resp = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(resp);
        if(collabResp){
            this.data = resp.RESPONSE;
            allTags = [];
            allTags = this.data;
            var sel = YAHOO.util.Dom.getElementsByClassName("notecardYellow", "div", "tabletop", "");
            var disabled = false;
            if (sel.length > 0) {
                disabled = false;
            }
            else {
                disabled = true;
            }
			
            // menu for color
            Colmenu = new Ext.menu.Menu({
                id: 'Colmenu'
            });
            var item = Colmenu.add({
                text: 'Red',
                icon: '../notecards/_images/tag-red.gif',
                id: 'appRed1',
                handler: setColor,
                menu: {
                    items: [{
                        id: 'appRed',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setColor
                    }, {
                        id: 'remRed',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeColor
                    }]
                }
            });
            item = Colmenu.add({
                text: 'Orange',
                id: 'appOrange1',
                icon: '../notecards/_images/tag-orange.gif',
                handler: setColor,
                menu: {
                    items: [{
                        id: 'appOrange',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setColor
                    }, {
                        id: 'remOrange',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeColor
                    }]
                }
            });
            item = Colmenu.add({
                text: 'Yellow',
                id: 'appYellow1',
                icon: '../notecards/_images/tag-yellow.gif',
                handler: setColor,
                menu: {
                    items: [{
                        id: 'appYellow',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setColor
                    }, {
                        id: 'remYellow',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeColor
                    }]
                }
            });
            item = Colmenu.add({
                text: 'Green',
                id: 'appGreen1',
                icon: '../notecards/_images/tag-green.gif',
                handler: setColor,
                menu: {
                    items: [{
                        id: 'appGreen',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setColor
                    }, {
                        id: 'remGreen',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeColor
                    }]
                }
            });
            item = Colmenu.add({
                text: 'Blue',
                id: 'appBlue1',
                icon: '../notecards/_images/tag-blue.gif',
                handler: setColor,
                menu: {
                    items: [{
                        id: 'appBlue',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setColor
                    }, {
                        id: 'remBlue',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeColor
                    }]
                }
            });
            item = Colmenu.add({
                text: 'Purple',
                id: 'appPur1',
                icon: '../notecards/_images/tag-purple.gif',
                handler: setColor,
                menu: {
                    items: [{
                        id: 'appPur',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setColor
                    }, {
                        id: 'remPur',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeColor
                    }]
                }
            });
			
            // menu for visual cues
            cuesMenu = new Ext.menu.Menu({
                id: 'cuesMenu',
                minWidth : 200
            });
            item = cuesMenu.add({
                text: 'Needs further research',
                icon: '../notecards/_images/tag-magnify.gif',
                id: 'addResearch1',
                handler: setCues,
                menu: {
                    items: [{
                        id: 'addResearch',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setCues
                    }, {
                        id: 'remResearch',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeCues
                    }]
                }
            });
            item = cuesMenu.add({
                text: 'Need help',
                icon: '../notecards/_images/tag-question.gif',
                id: 'addHelp1',
                handler: setCues,
                menu: {
                    items: [{
                        id: 'addHelp',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setCues
                    }, {
                        id: 'remHelp',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeCues
                    }]
                }
            });
            item = cuesMenu.add({
                text: 'Incomplete',
                icon: '../notecards/_images/tag-document.gif',
                id: 'addIncomplete1',
                handler: setCues,
                menu: {
                    items: [{
                        id: 'addIncomplete',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setCues
                    }, {
                        id: 'remIncomplete',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeCues
                    }]
                }
            });
            item = cuesMenu.add({
                text: 'Original thinking',
                icon: '../notecards/_images/tag-lightbulb.gif',
                id: 'addThinking1',
                handler: setCues,
                menu: {
                    items: [{
                        id: 'addThinking',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setCues
                    }, {
                        id: 'remThinking',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeCues
                    }]
                }
            });
            item = cuesMenu.add({
                text: 'Important',
                icon: '../notecards/_images/tag-attention.gif',
                id: 'addImportant1',
                handler: setCues,
                menu: {
                    items: [{
                        id: 'addImportant',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setCues
                    }, {
                        id: 'remImportant',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeCues
                    }]
                }
            });
            item = cuesMenu.add({
                text: 'Used in paper',
                icon: '../notecards/_images/tag-checkmark.gif',
                id: 'addPaper1',
                handler: setCues,
                menu: {
                    items: [{
                        id: 'addPaper',
                        text: 'Apply',
                        disabled: disabled,
                        handler: setCues
                    }, {
                        id: 'remPaper',
                        text: 'Remove',
                        disabled: disabled,
                        handler: removeCues
                    }]
                }
            });
			
            // menu for tags
            tagsMenu = new Ext.menu.Menu({
                id: 'tagsMenu',
                minWidth: 150
            });
            if (allTags !== null) {
                var TagText;
                for (i = 0; i < allTags.length; i++) {
                    var str = allTags[i][1];
                    if(str.length > 10){
                        TagText = allTags[i][1].substr(0,10)+"....";
                    }else{
                        TagText = allTags[i][1];
                    }
                    item = tagsMenu.add({
                        text: TagText,
                        id: "1Apply_"+allTags[i][0],
                        handler : applyMyTag,
                        menu : {
                            items : [{
                                id: "Apply_"+allTags[i][0],
                                text : 'Apply',
                                disabled : disabled,
                                handler : applyMyTag
                            }, {
                                id: "Remove_"+allTags[i][0],
                                text : 'Remove',
                                disabled : disabled,
                                handler : removeMyTag
                            }]
                        }
                    });
                }
            }
            else {
                item = tagsMenu.add({
                    text: "Empty",
                    disabled: true
                });
            }
			
            var menu = new Ext.menu.Menu({
                id: 'mainMenu',
                listeners:{
                    'hide': function(menu){
                            menu.removeAll();
                    }
                }

            });
            item = menu.add({
                text: 'Colors',
                menu: Colmenu
            });
            item = menu.add({
                text: 'Visual Cues',
                menu: cuesMenu
            });
            item = menu.add({
                text: 'Tags',
                menu: tagsMenu
            });
            item = menu.add({
                text: 'Edit/Delete Tags',
                handler: tagsGrid
            });
			
            menu.show('menuButton');
        }
    };
		
    //ajax call to the server to insert notecard data
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadTags&projectid='+projectid+'&windowname='+windowname+'&macfix=1234'
    });
}

 function addPredefinedCommentComponentToPanel(commList){
    var listenerFunction = function(chkbox, checked){
                                var chkBoxID = chkbox.id.split("_");
                                if(checked){
                                    commArr[commArr.length] = chkBoxID[1];
                                    Ext.getCmp('submitComm').enable();
                                }else{
                                    for(i=0;i<commArr.length;i++){
                                        if(commArr[i] == chkBoxID[1]){
                                            commArr.splice(i,1);
                                            i=-1;
                                        }
                                    }
                                    if(commArr.length === 0){
                                        Ext.getCmp('submitComm').disable();
                                    }
                                }
                                Ext.getCmp('selectedComments').setValue(Ext.encode(commArr));
                            };
    for (i = 0; i < commList.length; i++) {
        it = {
            layout:'column',
            width:650,
            items: [{
                bodyStyle: 'padding:5px 5px 5px 5px',
                layout: 'column',
                items: [{
                    xtype: 'label',
                    html: '&nbsp;',
                    columnWidth: 0.5
                }, {
                    xtype: 'checkbox',
                    style: 'margin-top:5px',
                    id: 'preComm_' + commList[i][0],
                    listeners:{
                        'check': {
                            fn: listenerFunction
                        }
                    },
                    columnWidth: 0.5
                }],
                columnWidth: 0.1
            }, {
                xtype: 'label',
                style: 'margin-top:5px',
                id: 'CommText_' + commList[i][0],
                text: commList[i][1],
                columnWidth: 0.15
            }, {
                xtype: 'box',
                height:100,
                autoEl: {
                    tag: 'textarea',
                    id: 'preCommText_' + commList[i][0],
                    name: 'preCommText_' + commList[i][0],
                    style: 'width:900px; overflow-y:scroll; margin-top:5px',
                    html: commList[i][2]
                },
                columnWidth: 0.75

            }]
        };
        frmcommentPanel.add(it);
        frmcommentPanel.doLayout();

    }
}
function addGroup(groupName,CommentList){
    var grpNameComp = {
        xtype:'label',
        html: groupName,
        columnWidth: 1
    };
    frmcommentPanel.add(grpNameComp);

    addPredefinedCommentComponentToPanel(CommentList);
}
// function to generate a comments screen
function comments(note){
    var successFn = function(o){
        if((Trim(o.responseText)).match("ERROR_MULTIPLE") || (Trim(o.responseText)).match("ERROR_NOID"))
        {
            showNotesSessionError(Trim(o.responseText));
            return false;
        }
        var complete_result = Ext.decode(o.responseText);
        var notecardDetail = complete_result[0];
        var frmTabPanel = new Ext.FormPanel({
            width: 685,
            height: 200,
            frame: true,
            items: [new Ext.TabPanel({
                autoScroll:true,
                activeTab: 0,
                height:200,
                width: 675,
                items: [{
                    id:'tabquote',
                    autoScroll:true,
                    title: 'Direct Quotes',
                    html: notecardDetail[1]
                }, {
                    id:'tabparaphrase',
                    title: 'Paraphrase',
                    autoScroll:true,
                    html: notecardDetail[2]
                }, {
                    id:'tabideas',
                    title: 'My ideas',
                    autoScroll:true,
                    html: notecardDetail[3]
                }]
            })]
        });
        frmcommentPanel = new Ext.FormPanel({
            url: '../notecards/_includes/notecardOperations.php',
            labelAlign: 'top',
            frame: true,
			
            width: 685,
            autoScroll: true,
            height: 331,
            cls: "../_css/noodlenotes.css",
            items: [{
                width:610,
                layout: 'column',
                bodyStyle: 'padding:5px 5px 5px 5px',
                items: [{
                    xtype: 'label',
                    html: '&nbsp;',
                    columnWidth: 0.1
                }, {
                    xtype: 'label',
                    html: '&nbsp;',
                    columnWidth: 0.3
                }, {
                    xtype: 'label',
                    html: 'Comment',
                    columnWidth: 0.6
                }, {
                    xtype: 'textfield',
                    value: 'savePredefinedComment',
                    id: 'toggle',
                    name: 'toggle',
                    hidden: true
					
                }, {
                    xtype: 'textfield',
                    value: note,
                    id: 'noteid',
                    name: 'noteid',
                    hidden: true
					
                },{
                    xtype: 'textfield',
                    id: 'selectedComments',
                    name: 'selectedComments',
                    hidden: true
					
                }]
            }]
		
        });
		
        commentsWin = new Ext.Window({
            width: 700,
            height: 600,
            cls: "../_css/noodlenotes.css",
            title: 'Notecard Comments',
            buttonAlign: 'center',
            closable: true,
            autoScroll: true,
            bodyStyle: 'padding:0px 0px 0px 0px',
            draggable: false,
            listeners: {
                'close': {
                    fn: function(commentsWin){
                    //retrieve isTeacher boolean
                    /*var isTeacher = document.getElementById("isTeacher").value;
						if (isTeacher == 0) {
						
						}*/
                    }
                },
                'show': {
                    fn: function(win){
                    //frmTabPanel.setActiveTab('quote');
                    }
                }
            },
            modal: true,
            items: [frmTabPanel, frmcommentPanel],
            buttons: [{
                text: 'Submit',
                id: 'submitComm',
                disabled : true,
                handler: function(){
                    var submit = true;
                    /*for(ij=0;ij<commArr.length;ij++){
						if(Ext.util.Format.trim(Ext.get('preCommText_'+commArr[ij]).getValue()) == ""){
							submit = false;							
						}
					}*/
                    if (submit) {
                        frmcommentPanel.getForm().submit({
                            method: 'POST',
                            waitTitle: 'Connecting',
                            waitMsg: 'Saving...',
                            success: function(form, action){

                                var resp = Ext.decode(action.response.responseText);
                                var collabResp = fnCollaborationProcessResponse(resp.data.response);
                                if(collabResp)
                                {
                                    document.getElementById('comm_row_' + note).style.visibility = "visible";
                                    document.getElementById('comm_row_' + note).style.display = "block";
                                    var comm = Ext.util.JSON.decode(action.response.responseText);
                                    var parentul = document.getElementById('list_comments_' + note);
                                    parentul.innerHTML = comm.data.html + parentul.innerHTML;
                                    commentsWin.close();
                                }
								
                            },
							
                            // Failure function, see comment above re: success and failure.
                            // You can see here, if login fails, it throws a messagebox
                            // at the user telling him / her as much.
							
                            failure: function(form, action){
                                 showFailureMessage();
                            }
                        });
                    }else{
                        Ext.Msg.alert('Error', 'Comment Text cannot be left blank.');
                    }
                }
            },{
                text: 'Cancel',
                handler: function(){
                    commentsWin.close();
                }
            }]
        });
		
        commentsWin.show();
        var resp = complete_result[1];
        if (resp !== null && resp !== "") {
            for (k = 0; k < resp.length; k++) {
                addGroup(resp[k][0],resp[k][1]);
            }
        }
    };
    var failFn = function(o){
	 showFailureMessage();
    };
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: successFn,
        failure: failFn,
        params: 'toggle=getPredefinedCommentOfNotecard&note_id='+note+'&windowname='+windowname+'&macfix=1234'
    });
    commArr = [];
}




function onItemCheck(item)
{
	
}



// function to load all the tags for that project
function loadTags(){
    var arr;
    projectid = document.getElementById('projectID').value;
    var failure = function(o)
    {
         showFailureMessage();
    };
    var success = function(o){
        var resp = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(resp);
        if(collabResp){
            this.data = resp.RESPONSE;
            allTags = [];
            allTags = this.data;
            arr = allTags;
        }
    };
    //ajax call to the server to load tags data
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: success,
        failure: failure,
        params: 'toggle=loadTags&projectid='+projectid+'&windowname='+windowname+'&macfix=1234'
    });
	
    return arr;
}
function alphanumeric(alphane)
{
    var a;
    var numaric = alphane;
    for(var j=0; j<numaric.length; j++)
    {
        var alphaa = numaric.charAt(j);
        var hh = alphaa.charCodeAt(0);
        if((hh > 32 && hh < 65) || (hh > 64 && hh < 94) || (hh > 96 && hh <= 122 || hh==32 || hh==123 || hh==125 || hh==124 || hh==95))
        {
		a=true;
        }
        else
        {
            return false;
        }
    }
    return a;
}

/*
 * function to validate pile title
 */
function alphaNumPile(alpha)
{
    var a;
    var number = alpha;
    for(var j=0; j<number.length; j++)
    {
        var alphaa = number.charAt(j);
        var hh = alphaa.charCodeAt(0);
        if((hh > 64 && hh < 93) || (hh > 47 && hh < 58) || (hh > 96 && hh <= 122 || hh==32))
        {
            a=true;
        }
        else
        {
            return false;
        }
    }
    return a;
}

// this function only update notecards data

function updateNotecards(notecardId){
	
    var projectID = document.getElementById('projectID').value;
	
    var tempArr = [];
    //create a temporary array
    for(i=0;i<notecardID.length;i++)
    {
        if(notecardID[i][0] == notecardId)
        {
            tempArr[i] = [notecardID[i][0],notecardID[i][1],notecardID[i][2],notecardID[i][3],Ext.util.Format.htmlEncode(notecardID[i][4]),notecardID[i][5],notecardID[i][6],notecardID[i][7]];
        }
    }
    var noteData = Ext.encode(tempArr);
		
    var handleSuccess = function(o)
    {
        var resp = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(resp);
        if(collabResp){
            resp = resp.RESPONSE;
            if(resp instanceof Object){
                Ext.get(notecardId).dom.style.display = resp.DISPLAY;
                Ext.get(notecardId).dom.style.top = resp.TOPPOS;
                Ext.get(notecardId).dom.style.left = resp.LEFTPOS;
                if(resp.MSG !== undefined){
                    alert(resp.MSG);
                }
            }
        }
    };
    var handleFailure = function(o)
    {
	 showFailureMessage();
    };
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: handleSuccess,
        failure: handleFailure,
        params: {
            toggle: 'updateNoteDetail',
            data: noteData,
            projectID: projectID,
            macfix:'1234'
        }
    });
}

function releaseLockForElementUnderProcess(elementID){
    var handleSuccess = function(o)
    {
        var resp = Ext.decode(o.responseText);
        fnCollaborationProcessResponse(resp);
    };
    var handleFailure = function(o)
    {
         showFailureMessage();
    };
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: handleSuccess,
        failure: handleFailure,
        params: {
            toggle: 'releaseLock',
            elemID: elementID,
            macfix:'1234'
        }
    });
}

function addLockForElementUnderProcess(elementID){

    var handleSuccess = function(o)
    {
        var resp = Ext.decode(o.responseText);
        var collabResp = fnCollaborationProcessResponse(resp);
        if(!collabResp){
            hideMe();
        }
                
    };
    var handleFailure = function(o)
    {
         showFailureMessage();
    };
    Ext.Ajax.request({
        url: '../notecards/_includes/notecardOperations.php',
        method: 'POST',
        success: handleSuccess,
        failure: handleFailure,
        params: {
            toggle: 'addLock',
            elemID: elementID,
            macfix:'1234'
        }
    });
}
Ext.ux.Toast = function() {
    var msgCt;

    function createBox(t, s, boxid, type){
        
        if(t!==""){
            return ['<div id = '+boxid+' class="msg">',
            '<div class="x-box-tl'+type+'"><div class="x-box-tr'+type+'"><div class="x-box-tc'+type+'"></div></div></div>',
            '<div class="x-box-ml'+type+'"><div class="x-box-mr'+type+'"><div class="x-box-mc'+type+'"><span id = '+boxid+'_header class="popup-header'+type+'" onmouseover="showTotalUsersAgain()">'+t+'</span><br /><span id = '+boxid+'_content class="popup-content">'+s+'</span></div></div></div>',
            '<div class="x-box-bl'+type+'"><div class="x-box-br'+type+'"><div class="x-box-bc'+type+'"></div></div></div>',
            '</div>'].join('');
            
        }else{
            if(boxid == "syncing"){
                return ['<div id = '+boxid+' class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><img src=\'../notecards/ext-js/resources/images/default/shared/blue-loading.gif\' height=20px width=20px />&nbsp;<span id = '+boxid+'_content class="popup-content">'+s+'</span></div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
            }else{
                return ['<div id = '+boxid+' class="msg">',
                '<div class="x-box-tl'+type+'"><div class="x-box-tr'+type+'"><div class="x-box-tc'+type+'"></div></div></div>',
                '<div class="x-box-ml'+type+'"><div class="x-box-mr'+type+'"><div class="x-box-mc'+type+'"><span id = '+boxid+'_content class="popup-content">'+s+'</span></div></div></div>',
                '<div class="x-box-bl'+type+'"><div class="x-box-br'+type+'"><div class="x-box-bc'+type+'"></div></div></div>',
                '</div>'].join('');
            }

        }
        
    }

    return {
        msg : function(title, format, delay, boxid, type){
            innerPopup = Ext.get(boxid);
            var s;
            if(innerPopup){
                s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
                if(title!==""){
                    Ext.get(boxid+"_header").dom.innerHTML = title;
                }
                Ext.get(boxid+"_content").dom.innerHTML = s;
                
            }else{
                if(Ext.get('loginMsgs') === null){
                    msgCt = Ext.DomHelper.insertFirst(document.body, {
                        id:'loginMsgs',
                        style:'position:fixed;z-index:10000;width:165px;right:0;top:0;float:right;'
                    }, true);
                    Ext.get('loginMsgs').on('mouseout', hideTotalUsers, this);
                }else{
                    msgCt = Ext.get('loginMsgs');
                }

                s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
                var m = Ext.DomHelper.append(msgCt, {
                    html:createBox(title, s, boxid, type)
                }, true);
                msgCt.alignTo(document, 'tr-tr');
                if(boxid=='totalUsers'){
                    m.slideIn('t');
                    Ext.get(boxid+"_content").pause(delay).ghost("t", {
                        remove:false,
                        useDisplay: true
                    });
                }else if(boxid=='syncing'){
                    m.slideIn('t').pause(delay);
                }else{
                    m.slideIn('t').pause(delay).ghost("t", {
                        remove:true
                    });
                }
            }
            
        }
    };

}();

function showLoggedInUsers(arr){
    var userNames = [];
    for(km=0;km<arr.length;km++){
        userNames[km] = arr[km][1];
    }
    userNamesString = userNames.toString();
    userNamesString = formatTitleLoggedInUsers(userNamesString);
    Ext.ux.Toast.msg("Collaborators Online ("+userNames.length+")", userNamesString, 4, 'totalUsers', 'blue');

}
function formatTitleLoggedInUsers(str){
    //var fntMatrics = Ext.util.TextMetrics.createInstance(Ext.get("sample_title_container"));
    var finalStr="";
    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(strBuffer.length>=20){

                finalStr += "<br>";
                strBuffer="";
                k--;
        }else{
            finalStr += myChar;
        }
    }

    return finalStr;
}

function showSyncPopup(){
    Ext.ux.Toast.msg("", "Syncing tabletop..", 25, 'syncing', '');
}

function showNewlyLoggedInUser(arr){
    var userNames = [];
    for(km=0;km<arr.length;km++){
        userNames[km] = arr[km][1];
    }
    userNames = userNames.toString();
    Ext.ux.Toast.msg("", userNames+" logged in.", 2, 'newUsers', 'green');
}

function showNewlyLoggedOutUser(arr){
    var userNames = [];
    for(km=0;km<arr.length;km++){
        userNames[km] = arr[km][1];
    }
    userNames = userNames.toString();
    Ext.ux.Toast.msg("", userNames+" logged out.", 2, 'loggedOutUsers', 'red');
}

Ext.onReady(function(){
    Ext.QuickTips.init();
    if(Ext.get('windowname')){
        windowname = document.getElementById('windowname').value;
    }
    // turn on validation errors beside the field globally
    Ext.form.Field.prototype.msgTarget = 'side';
    // fetch the updates to show logged in user on bibliography
    if(Ext.get("projectID") && Ext.get("projectID").getValue() !== "" ){
        var blankWindowName = "";
        getUpdates(blankWindowName);
    }
});
function repositionLoginBox(){
    if(Ext.get("loginMsgs")){
        Ext.get("loginMsgs").alignTo(document, 'tr-tr');
    }
    
}
function showTotalUsersAgain(){
    if(Ext.get("totalUsers_content").dom.style.display =="none"){
        Ext.get('totalUsers_content').slideIn("t", {
            stopFx: true
        });
    }
}


var hideSyncWindow = function(){
    if(updateComplete === true){
        //YAHOO.util.DragDropMgr.unlock();
        if(Ext.get("syncing")){
            Ext.get("syncing").ghost("t",{
                remove:true
            });
        }
    }else{
        hideSyncWindow.defer(3000);
    }
};
// function to generate a print menu on Bibliography Proint/Export button
function showPrintMenuOnBib(){
    var printMenuAction = function(selectElementId){
        switch(selectElementId.id)
        {
            case 'word':
                window.location = "exportRTF.php";
                break;
            case 'gdocs':
                window.open("exportBibToGdocs.php","gdocs");
                break;
            case 'webPreview':
                window.open("mybib.php?printBib=1","web");
                break;
            case 'print':
                window.location = "print.php";
                break;
            default:

        }
    };
    // menu for color
    var printMenu = new Ext.menu.Menu({
        id: 'printMenu',
        listeners:{
                    'hide': function(printMenu){
                            printMenu.removeAll();
                    }
                }
    });
    printMenu.add({
        text: 'Print/Export to Word',
        icon: '../_images/word.gif',
        id: 'word',
        handler: printMenuAction
    });
    printMenu.add({
        text: 'Print/Export to Google Docs',
        icon: '../_images/google.gif',
        id: 'gdocs',
        handler: printMenuAction
    });
    printMenu.add({
        text: 'Preview as Web Page (HTML)',
        icon: '../_images/tag-html.gif',
        id: 'webPreview',
        handler: printMenuAction
    });
    printMenu.add({
        text: 'Formatting Options...',
        icon: '../_images/tag-format.gif',
        id: 'print',
        handler: printMenuAction
    });

    printMenu.show('printMenuButton');
}


