//$Id
var DocumentListDB = new Array();
var WorkBookDB = new Array();
var PresentationDB = new Array();
var   SharedDocDB = new Array();
var   SharedShowDB = new Array();
var   SharedSheetDB = new Array();
var shtIndxArr = new Array();
var shwIndxArr = new Array();
var docIndxArr = new Array();
var shared=false;
var lastImg="";
var clicked=false;
var evtstatus="";
//Stores the tags details (tag,count,associated Doc IDs in Array)
var TagsListDB = new Array();

var ticketID = getTicketIDFromCookie();
    
var apikey = getAPIKey() ; //to be fetched from session

//Stores the previous sortBy parameter
var previousSort = "";

//Stores the current tag value
var currentTag = "";

//Stores the username
var userName = getCookieValue("USERNAME");
//sort Images
var upImg="images/Arrow-up.gif";
var downImg="images/Arrow-down.gif";
//
var isAscending_doc_name = "";
var isAscending_doc_time = "";
var isAscending_show_name = "";
var isAscending_show_tim = "";
var isAscending_sheet_name = "";
var isAscending_sheet_time = "";


//Stores the recently uploaded file type
//"document" or "workbook" or "presentation"
var lastUploadedFileType = "";
    
//Message to be displayed on loading
var loadingMsg ="... <img src='" + contextPath + "/images/loading.gif'>";

//Stores Currently displayed tag (top5/all)
var currentTagDisplayType = "";


//Stores the currently selected view, either myDocuemnts or sharedDocuments.
//Used to do perform searching based on it
var currentlySlctdView = "myDocuments";


//doc_name_url is used specificly for Writer and Presentation
function DocumentList(id,name,lastModTime,type,checkBxId,doc_name_url,tagsArray,readOnlyUsers,editUsers)
{
    this.id = id;
    //In Show services, if "'" present in the name, same has
    //been put as "&apos;".To make presentation names sync with the
    //other services, replacing "&apos;" with "'".
    if(type == "presentation")
    {
        name = replaceStr(name,"&apos;","\'");
    }
    this.name = name;
    this.type = type;
    this.lastModTime = lastModTime;
    this.checkBxId = checkBxId;
    this.document_name_url = doc_name_url;
    //Stores the associated tags
    this.tagsArray = tagsArray;
    this.readOnlyUsers = ""+readOnlyUsers;
    this.editUsers = ""+editUsers;
}

function TagDetail(tagName, docCount , docIdArray)
{
    this.tagName = tagName;
    this.docCount = docCount;
    this.docIdArray = docIdArray;
}

function getDocumentsData()
{
    //showLoadingMessage("loadingDiv",loadingMsg);
    var loadg = document.getElementById("loadingDiv");
    loadg.innerHTML=document.getElementById("loading").innerHTML+loadingMsg;
    loadg.style.display="block";
    try
    {
        sendAsyncAJAXRequest('GET',
                contextPath + '/getDocsList.do?method=getCompleteDocsList',responsePrint);
    }    
    catch(e)
    {
        alert(document.getElementById("unable.to.process").innerHTML+e);
    }
//        showNavHeader("My Documents ");
}

 
function responsePrint(xmlhttp)
{
    shared=false;
    if (xmlhttp.readyState == 4)
    {
        //hideLoadingMessage("loadingDiv");
    var loadg = document.getElementById("loadingDiv");
    loadg.innerHTML="";
    loadg.style.display="none";
        var xmll = xmlhttp.responseXML;
        if(xmll == null)
        {
            if(confirm(document.getElementById("unable.to.fetch.data").innerHTML+document.getElementById("tryagain").innerHTML))
            {
                window.location.reload();
            }
        }
        //Error response check
        var errorNode = xmll.getElementsByTagName('ErrorResponseFor');
        
        if(errorNode != null && errorNode.item(0) != null )
        {
            var services = errorNode.item(0).attributes[0].value;
            var servArray = services.split(',');
            var servArrLength = servArray.length;
            var alertMssg ="";
            var unabletofetch = document.getElementById("unable.to.fetch").innerHTML;
            for(var i = 0 ; i < servArrLength ; i++ )
            {
                if(i != 0)
                {
                    alertMssg = alertMssg + " and ";
                }
                alertMssg = alertMssg + servArray[i] ;
            }
            if(alertMssg.indexOf("API Key") !=-1)
            {
                alert(alertMssg);
                return;
            } else if(confirm(alertMssg+document.getElementById("tryagain").innerHTML))
            {
                window.location.reload();
                return;
            }
            //Means the xml doesnt contain response for any of the services
            if(servArrLength == 3)
            {
                return;
            }
        }
        //
        var doccc = xmll.getElementsByTagName('result');
        if(doccc != null && doccc.item(0) != null )
        {
            if(doccc.item(0).getElementsByTagName('documents').length != 0)
            {
                var documents = doccc.item(0).getElementsByTagName('documents')[0];
                parseAndAddInArray(DocumentListDB,documents,"document","documentName","documentId","lastModifiedTime");
            }   
            if(doccc.item(0).getElementsByTagName('workbooks').length != 0)
            {
                var worksheets = doccc.item(0).getElementsByTagName('workbooks')[0];
                parseAndAddInArray(WorkBookDB,worksheets, "workbook", "workbookName","workbookId","lastModifiedTime");
            }   
            if(doccc.item(0).getElementsByTagName('presentations').length != 0)
            {
                var presentations = doccc.item(0).getElementsByTagName('presentations')[0];
                parseAndAddInArray(PresentationDB,presentations,"presentation","presentationName","presentationId","lastModifiedTime");
            }   
            //If no documents available in the Zoho accounts
            if(noDocsAvailable())
            {
                return;
            }
            // displayNoDocDiv();
            
            //Sorting tags based on docCount
            sortTagsOnCount();
            //**************** CAN BE REMOVED ****************************
            //showTagsListDB();
            //Display Tags
            displayTags("Top5");
            
            //Sorts the Documnets by LastEdited time and populates the table
           // sortAndPopulate("Type");
            //Sorts the Documnets by LastEdited time and populates the table
            sortAndPopulate("Time","all");
        }
        //No need of this error handling.Since it has been handled already.
        //In case of error 
        else
        {
            if(confirm(document.getElementById("unable.to.fetch.data").innerHTML+document.getElementById("tryagain").innerHTML))
            {
                window.location.reload();
            }
        }
    }
}

//axn = "Top5" or "All"
function displayTags(axn)
{
    //On delete uses the previously selected display tag type
    if(axn != "onDelete")
    {
        currentTagDisplayType = axn;
    }
    var tagsCnt = TagsListDB.length;
    var tagsDv = document.getElementById("tagsDiv");
    var innerHtml = createTagHTML(currentTagDisplayType);
    tagsDv.innerHTML = innerHtml;
    if(axn == "onDelete")
    {
       //If the deleted tag had only one document, making the 
       //Show All Documents selected
       if(currentTag != "" ) 
       {
           currentTag = '';
           setSelectedTag('');
       }
    }
    tagsDv.style.display = "block";
}

//Checks whether the currently selected tag in top 5 or not
function isCrrntTagInTagsDB(limit)
{
    var isInTop5 = false;
    var tagsCnt = TagsListDB.length;
    if(limit == '5')
    {
        tagsCnt = 5;
    }
    for(var i = 0 ; i < tagsCnt ; i++)
    {
        var tagName = TagsListDB[i].tagName;
        if(currentTag == tagName)
        {
            isInTop5 = true;
            break;
        }
    }
    return isInTop5;
}

//creates inner HTML content for Tag table based on the top5/all display
function createTagHTML(axn)
{
    var tagCnt = TagsListDB.length;
    if(tagCnt == 0)
    {
        return "";
    }
    var tagsLi = "<ul class=\"image\">";
    for(var i = 0 ; i < tagCnt ; i++ )
    {
        var tag = TagsListDB[i].tagName;
        var textDecor = "none";
        if(currentTag == tag)
        {
            textDecor = "underline";
        }
        var titleVal = tag;
        var tagLngth = tag.length;
        if(tagLngth > 15)
        {
            tag = tag.substring(0,15) + "...";
        }
        tagsLi = tagsLi+"<li class=\"Linktxtsmall\"> <a  id=\"tag_"+titleVal+"\" title=\""+titleVal+"\" href=\"javascript:setSelectedTag('"+titleVal+"')\">"+tag+"</a></li>";
    }
    tagsLi = tagsLi+"</ul>";
    return tagsLi;
}

//Checks any documents avaible in the DocumentListDB array.
function noDocsAvailable()
{
    if(DocumentListDB.length == 0 &&  PresentationDB.length==0 && WorkBookDB.length==0)
    {
     return true;
    }
}
function displayNoDocDiv()
{
    var dbCount = DocumentListDB.length;
    if(dbCount == 0)
    {
        displayNoDocDiv("document");
    }
    dbCount = WorkBookDB.length;
    if(dbCount == 0)
    {
        displayNoDocDiv("workbook");
    }
    dbCount = PresentationDB.length;
    if(dbCount == 0)
    {
        displayNoDocDiv("presentation");
    }
}    
function displayNoDocDiv(type)
{
    clearDocumentTable(type);
    addTable(type,false);
    
    var tbodyName=type+"TableTBody";
    var tbody = document.getElementById(tbodyName);
	var createNewRow = document.createElement("tr");
	tbody.appendChild(createNewRow);
	var createNewCell1 = document.createElement("td");
	createNewRow.appendChild(createNewCell1);
    createNewCell1.align="center";
    createNewCell1.className="BoldTextsmall";
    createNewCell1.colSpan="4";
    var dstring=getDisplayString(type);
    createNewCell1.innerHTML = " &nbsp;"+dstring+"&nbsp;";
	var createNewRow1 = document.createElement("tr");
	tbody.appendChild(createNewRow1);
	var createNewCell11 = document.createElement("td");
	createNewRow1.appendChild(createNewCell11);
    createNewCell11.colSpan="4";
    createNewCell11.innerHTML = "&nbsp;";
   // var imgObj=getColapseImg(divName);
  //  imgObj.src="images/CloseArrow.gif";
}

function parseAndAddInArray(arrObj,documents,docType,tag1,tag2,tag3)
{
    var document1 = documents.getElementsByTagName(docType);
    var docCount = document1.length;
    for(var i = 0 ; i < docCount ; i++ )
    {
        var docname = document1.item(i).getElementsByTagName(tag1)[0].firstChild.data;
        var idd = document1.item(i).getElementsByTagName(tag2)[0].firstChild.data;
        var time = document1.item(i).getElementsByTagName(tag3)[0].firstChild.data;
        var checkBxId = idd+"_cb";
        //if(docType == 'workbook')
        //{
        //    time = toTimeInMillis(time);
        //}
        //Specific for Writer documents
        var doc_name_url = "";
        if(docType == "document")
        {
            doc_name_url = document1.item(i)
                .getElementsByTagName("document_name_url")[0].firstChild.data;
            //alert("parseAndAddd::Writer Document::document_name_url::"+doc_name_url);
        }
        else if(docType == "presentation")
        {
            doc_name_url = document1.item(i)
                .getElementsByTagName("presentationNameUrl")[0].firstChild.data;
            //alert("parseAndAdd::Presentaion Document::presentationNameUrl:"+doc_name_url);    
        }
        var tagsArray = fetchTagsFromNode(document1.item(i),idd,"tags"); 

        //************ Shared details ***********
        var sharedDetails = getSharedDetails(document1.item(i),docType);
        var readOnlyUsers = sharedDetails[0];
        var editUsers = sharedDetails[1];
        readOnlyUsers = trim(readOnlyUsers);
        editUsers = trim(editUsers);
        //alert("DocName::"+docname+":::docType:"+docType+":::readOnlyUsers:"+readOnlyUsers+":::editUsers:"+editUsers+"::");
        //***************************************

        arrObj[arrObj.length] = 
            new DocumentList(idd,docname,time,docType,checkBxId,doc_name_url,tagsArray,readOnlyUsers,editUsers);
    }
}

function getSharedDetails(nnode,docType)
{
    var readOnlyUsers = "";
    var editUsers = "";

    var strArr = new Array();

    if(docType == 'document' || docType == 'workbook' || docType == 'presentation')
    {
        if(nnode != null && nnode.getElementsByTagName("share")[0] != null)
        {
            var shareNode = nnode.getElementsByTagName("share")[0];
            var chldrnNdsLn = shareNode.getElementsByTagName("user").length;
            if(chldrnNdsLn > 0)
            {
                for(var j = 0 ; j < chldrnNdsLn ; j++)
                {
                    var mailId = "";
                    var permission = "";
                    var tmpNode = shareNode.getElementsByTagName("user")[j];
                    var attLn = shareNode.getElementsByTagName("user")[j].attributes.length;
                    for(var ij = 0 ; ij < attLn ; ij++ )
                    {
                        var nname = shareNode.getElementsByTagName("user")[j].attributes[ij].name;
                        if(nname == "emailId" || nname == "email")
                        {
                            mailId = shareNode.getElementsByTagName("user")[j].attributes[ij].value;
                        }
                        if(nname == "permission")
                        {
                            permission = shareNode.getElementsByTagName("user")[j].attributes[ij].value;
                        }
                    }
                    if(mailId != null && mailId != "null" && trim(mailId) != "")
                    {
                        if(isReadOnly(docType,permission))
                        {
                            if(trim(readOnlyUsers) != "")
                            {
                                readOnlyUsers = readOnlyUsers + ",";
                            }
                            readOnlyUsers = readOnlyUsers + mailId;
                        }
                        else
                        {
                            if(trim(editUsers) != "")
                            {
                                editUsers = editUsers + ",";
                            }
                            editUsers = editUsers + mailId;
                        }
                    }
                }
            }
        }
    }
    strArr[0] = readOnlyUsers;
    strArr[1] = editUsers;
    return strArr;
}

//readOnlyParam and editParam are used to check the permission assigned.
//for writer, readOnlyParam and editParam are false and true respectively
//for sheet, readOnlyParam and editParam are readOnly and readWrite respectively
function isReadOnly(docType, perm)
{
    var permission = false;
    if(docType == 'document')
    {
        if(perm == "false")
        {
            permission = true;
        }
        else if(perm == "true")
        {
            permission = false;
        }
    }
    else if(docType == 'workbook' || docType == 'presentation')
    {
        if(perm == "readOnly")
        {
            permission = true;
        }
        else if(perm == "readWrite")
        {
            permission = false;
        }
    }
    return permission;
}

//Fetches tags from the node and constructs TagDetails 
//And adds the TagDetails in the TagsDB and 
//also returns a tagsArray
function fetchTagsFromNode(nnode,docId,tagName)
{
    var tagsArray = new Array();
    if(nnode != null && nnode.getElementsByTagName(tagName)[0] != null )
    {
        var tagsNode = nnode.getElementsByTagName(tagName)[0];
        var tagsCnt = tagsNode.getElementsByTagName("tag").length;
        if(tagsCnt > 0 )
        {
            for(var i = 0 ; i < tagsCnt ; i++ )
            {
                var tag = tagsNode.getElementsByTagName("tag")[i].attributes[0].value;
                //log("TagsNode:"+tagsNode.getElementsByTagName("tag")[i].attributes[0].value);
                tagsArray[i] = tag;
                checkAndAddInTagsDB(docId,tag);
            }
        }
        //log("fetchTagsFromNode:::DocId:"+docId+"**TagsArray:"+tagsArray);
    }
    return tagsArray;
}

//Used for displaying TagsListDB content 
// ******************** CAN BE REMOVED ***************************
function showTagsListDB()
{
    var tagsCount = TagsListDB.length;
    for(var i = 0 ; i < tagsCount ; i++)
    {
        alert("TagsList::"+i+"::TagName::"+TagsListDB[i].tagName
                +"*TagCount:"+TagsListDB[i].docCount+"*DocIdArray:"+TagsListDB[i].docIdArray);
    }
}


//If the given tag exists in TagsListDB, increases the docCount by one 
//and adds the docId in the docIdArray.
//If the given tag not exists, sets the docCount to one and creates a 
//new docIdArray with the given docId.
function checkAndAddInTagsDB(docId,tag)
{
    var isTagExist = false;
    var tagsCount = TagsListDB.length;
    for(var i = 0 ; i < tagsCount ; i++)
    {
        var tagName = TagsListDB[i].tagName;
        if(tagName == tag)
        {
            var docCount = TagsListDB[i].docCount;
            var docIdArray = TagsListDB[i].docIdArray;
            docIdArray[docIdArray.length] = docId;
            //
            TagsListDB[i].docCount = docCount+1;
            TagsListDB[i].docIdArray = docIdArray;
            //
            isTagExist = true;
            break;
        }
    }
    if(!isTagExist)
    {
        var docIdArray = new Array();
        docIdArray[0] = docId;
        var docCount = 1;
        TagsListDB[tagsCount] = new TagDetail(tag,docCount,docIdArray); 
    }
}

//converts the time in Millis to "month-date-year hours:minutes" 
function timeInString(timeInMillis)
{
    var datte = new Date();
    datte.setTime(timeInMillis);
    var yyear = datte.getFullYear();
    var mmonth = datte.getMonth()+1;
    var dday = datte.getDate();
    var hhour = datte.getHours();
    var mmin = datte.getMinutes();
    var dateInString = mmonth+"-"+dday+"-"+yyear;//+" "+hhour+":"+mmin;
    //alert("timeInString::: timeInMillis:"+timeInMillis
    //        +"* dateInString::"+dateInString);
    return dateInString;
}



function addrowsInTable( docId, docName, docType, modTime, checkBxId , doc_name_url)
{
    //Name to be used in getting editor page url
    var editorDocName = docName;
    //ImageName w.r.t type
    var imageDisplayNamesArray = getImageNameAndDisplayType(docType);
    var imageName = imageDisplayNamesArray[0]
    //Display Type
    var displayDocType = imageDisplayNamesArray[1];
    //For Writer, document_name_url to be passed in getting the editor.
    if(docType == "document")
    {
        editorDocName = doc_name_url;
        //alert("addrowsInTable::editorDocName For Document::"+editorDocName);
    }
    //Wrapping special characters in docName to avoid problem
    //while passing across functions.
    var wrappedDocName = wrapUnwrapSplChar(docName,"wrap");
    //
    modTime = timeInString(modTime);
    var seperator = " | ";
    var exportId = docId+"_exp";
    var tbodyName=docType+"TableTBody";
    var intable = document.getElementById(tbodyName);
    //Current row count
    var curRowCnt = intable.childNodes.length;
    var rclass = getRowColor(curRowCnt);    
    //
    var newRow = document.createElement("tr");
    newRow.id = docId;
    newRow.className=rclass;
    intable.appendChild(newRow);

    //
    var dispDocName = docName;
    if(dispDocName.length > 18)
    {
        dispDocName = dispDocName.substring(0,16);
        dispDocName = dispDocName+"...";
    }

    var cell1 = document.createElement("td");//newRow.insertCell(0);
    cell1.innerHTML = "<input id ='"+checkBxId+"'type=\"checkbox\" name=\"checkbox2\" value=\"checkbox\" />";
    newRow.appendChild(cell1);

    var cell11 = document.createElement("td");//newRow.insertCell(0);
    cell11.className = "Linktxtsmall";
    cell11.innerHTML = "<span title=\""+docName+"\">"+ dispDocName+"</span>";
    newRow.appendChild(cell11);
   
    var cell3 = document.createElement("td");//newRow.insertCell(2);
    cell3.className = "Linktxtsmall";
    cell3.innerHTML = "<a href=\"javascript:getPreview('"+docId+"','"+docType+"','"+wrappedDocName+"','')\">"+document.getElementById("preview").innerHTML+"</a> | <a href=\"" + contextPath +"/getDocsList.do?method=getEditorPage&docId="+ docId + "&docType=" + docType +"&apiTicket="+ticketID+ "&docName="+editorDocName+"\">"+document.getElementById("edit").innerHTML+"</a> | <a  id='"+exportId+"' href=\"javascript:doExport('"+docId+"','"+wrappedDocName+"','"+docType+"','"+exportId+"','"+doc_name_url+"','')\">"+document.getElementById("export").innerHTML+"</a>";

   cell3.innerHTML = cell3.innerHTML  + " | <a href=\"javascript:shareDoc('"+docType+"','"+docId+"','"+wrappedDocName+"')\">"+document.getElementById("share").innerHTML+"</a>";

    newRow.appendChild(cell3);

    var cell4 = document.createElement("td");//newRow.insertCell(3);
    cell4.className = "Linktxtsmall";
    cell4.innerHTML = "<em>"+modTime+"</em>";
    newRow.appendChild(cell4);
}

//
function shareDoc(docType,docId,docName)
{
    var divEle = document.getElementById("shareDiv");
    divEle.style.left = lastMouseClickX-100;
    divEle.style.top = lastMouseClickY;
    divEle.style.display = "block";
    
    var dispDocName = truncateDisplayString(docName,18);
    document.getElementById("sharedHdrDiv").innerHTML = "<span title=\""+docName+"\">"+document.getElementById("share.your.document").innerHTML+" - "+dispDocName+"</span>";


    showShareDiv();

    var bttnDiv = document.getElementById("shareButtonDiv");
    bttnDiv.innerHTML = "<input id=\"submitBttnShare\" type=\"button\" name=\"Share\" class=\"btnStyle\" value=\""+document.getElementById("share").innerHTML+"\" onclick=\"javascript:shareTheDoc('"+docType+"','"+docId+"')\"> <input id=\"cancelBttnShare\" type=\"button\" name=\"Cancel\" class=\"btnStyle\" value=\""+document.getElementById("cancel").innerHTML+"\" onclick=\"javascript:hideShareDoc()\">";

    formShareTab2(docId,docType);    
}

function formShareTab2(docId,docType)
{
    var readOnlyUsers = "";
    var editUsers = "";
    var listObj=getListObjFor(docType);

    for(var x in listObj)
    {
        var idd = listObj[x].id;
        if(idd == docId)
        {
            readOnlyUsers = readOnlyUsers+listObj[x].readOnlyUsers;
            editUsers = editUsers+listObj[x].editUsers;
            break;
        }
    }

    var shareTab2Div = document.getElementById("shareTab2TableDiv");
    shareTab2Div.innerHTML = "<table cellpadding=\"0\" cellspacing=\"3\" style=\"width:100%;\"><tbody id=\"sharedDetailsTBody\">"+
                            "<tr class=\"Linktxtsmall\"><td width=\"50%\" valign=\"top\"><strong>"+document.getElementById("emailid").innerHTML+"</strong></td><td width=\"25%\" valign=\"top\"><strong>"+document.getElementById("permission").innerHTML+"</strong></td><td width=\"25%\" valign=\"top\"><strong>"+document.getElementById("action").innerHTML+"</strong></td></tr>"+
                            "</tbody></table>";

    var tbbody = document.getElementById("sharedDetailsTBody");
    if(readOnlyUsers == "" && editUsers == "")
    {
        
        return;
    }
   
    var readArr = readOnlyUsers.split(",");
    for(var x in readArr)
    {
        var idd = readArr[x];
        if(idd != null && trim(idd) != "" )
        {
            addRowInSharedDetails(tbbody,docId,docType,idd,"readOnly");
        }
    }

    var editArr = editUsers.split(",");
    for(var y in editArr)
    {
        var idd = editArr[y];
        if(idd != null && trim(idd) != "" )
        {
           addRowInSharedDetails(tbbody,docId,docType,idd,"readWrite")
        }
    }

}

function addRowInSharedDetails(shareTableTbody,docId,docType,mailId,access)
{
    var roww = document.createElement("tr");
    roww.id = docId+"_"+mailId+"_"+access;
    roww.className = "Linktxtsmall";
    shareTableTbody.appendChild(roww);
    
    var cell1 = document.createElement("td");
    cell1.verticalAlign="top";
    var dispMailId = truncateDisplayString(mailId,25);
    cell1.innerHTML = "<span title=\""+mailId+"\">"+dispMailId+"</span>";
    roww.appendChild(cell1);

    var cell2 = document.createElement("td");
    var dispAccess = (access == "readOnly")?"Read Only":"Read / Write";
    cell2.verticalAlign="top";
    cell2.innerHTML = dispAccess;
    roww.appendChild(cell2);

    var cell3 =  document.createElement("td");
    cell3.verticalAlign="top";
    cell3.innerHTML = "<a href=\"javascript:revertSharing('"+docId+"','"+mailId+"','"+docType+"','"+access+"')\">"+document.getElementById("remove").innerHTML+"</a>";
    roww.appendChild(cell3);

}

function revertSharing(docId,mailId,docType,access)
{
    try
    {
        var divEle = document.getElementById("shareLoadingDiv");
        divEle.innerHTML =document.getElementById("processing").innerHTML+"... <img src='" + contextPath + "/images/loading.gif'>";
        divEle.style.display = "block";
        var urll = contextPath + "/getDocsList.do?method=revertSharing&docId="
            +docId+"&type="+docType+"&mailId="+mailId+"&access="+access;
        sendAsyncAJAXRequest('GET',urll,responseRevertShare);
    }
    catch(e)
    {
        alert(document.getElementById("unable.to.revert.shareddoc").innerHTML);

    }
}

function responseRevertShare(xmlhttp)
{
    if(xmlhttp.readyState == 4)
    {
        var resp = xmlhttp.responseText;
        if(resp != null)
        {
            var jsonrsp = eval ( '('+resp+')');
            //alert("Revert Sharing:::::jsonResp:::::::::::::::::"+jsonrsp);
            var docId = jsonrsp.docId;
            var access = jsonrsp.access;
            var mailId = ""+jsonrsp.mailId;
            var result = jsonrsp.result;
            //alert("::::::::::::::::::::::::::::::::::::::::"+docId+":::::::"+result);
            if(result == "success")
            {
                //Removing the row from the shared details table
                var rowId = docId+"_"+mailId+"_"+access;
                removeRowFromSharedDetails(rowId);
                
                //Removing the mail Id from DocumentsDB
                updateSharedMailId(docId,mailId,"remove",access,docType);        
                
                var divEle = document.getElementById("shareLoadingDiv");
                divEle.style.display = "none";
            }
            else
            {
                alert(document.getElementById("unable.to.revert.sharing").innerHTML);
            }
        }
        else
        {
            alert(document.getElementById("unable.to.revert.sharing").innerHTML);
        }
    }
}

function updateSharedMailId(docId,mailId,axn,access,docType)
{
    var mailIds = "";
    var listObj=getListObjFor(docType);
    var ln = listObj.length;
    if(ln == 0)
    {
        return;
    }
    for(var x = 0 ; x < ln ; x++)
    {
        var doc_Id = listObj[x].id;
       if(doc_Id == docId)
        {
            if(access == "readOnly")
            {
                mailIds = ""+listObj[x].readOnlyUsers;
                if(axn == "remove")
                {
                    mailIds = removeMailID(mailIds,mailId);
                }
                else if(axn == "add")
                {
                    mailIds = appendMailID(mailIds,mailId);
                }
                listObj[x].readOnlyUsers = ""+mailIds;
        //        alert("updateMailIds:"+access+":axn:"+axn+":mailId:"+mailId+":mailIds:"+DocumentListDB[x].readOnlyUsers+"**");
            }
            else if(access == "readWrite")
            {
                mailIds = ""+listObj[x].editUsers;
                if(axn == "remove")
                {
                    mailIds = removeMailID(mailIds,mailId);
                }
                else if(axn == "add")
                {
                    mailIds = appendMailID(mailIds,mailId);
                }
                listObj[x].editUsers = ""+mailIds;
        //        alert("updateMailIds:"+access+":axn:"+axn+":mailId:"+mailId+":mailIds:"+DocumentListDB[x].editUsers+"**");
            }
            break;
        }
    }
    return mailIds;
}

function removeMailID(mailIds,mailId)
{
    if(mailIds != null && trim(mailIds) != "")
    {
        if(mailIds.indexOf(mailId) != -1)
        {
            var strArr = mailIds.split(",");
            for (var x in strArr)
            {
                var idd = strArr[x];
                if(idd == mailId)
                {
                    strArr.splice(x,1);
                    break;
                }
            }
            mailIds = strArr.toString();
        }
    }
    return mailIds;
}

function appendMailID(mailIds , mailId)
{
    if(mailIds != null && trim(mailIds) != "" )
    {
        mailIds = mailIds + "," + mailId;
    }
    else
    {
        mailIds = mailId;
    }
    return mailIds;
}

function removeRowFromSharedDetails(rowId)
{
    var rowEle = document.getElementById(rowId);
    var tbbody = document.getElementById('sharedDetailsTBody');
    tbbody.removeChild(rowEle);
}


function hideShareDoc()
{
    document.getElementById("shareDoc_View").value = "";
    document.getElementById("shareDoc_Edit").value = "";
    
    document.getElementById("shareTab2TableDiv").innerHTML = "";

    var divEle = document.getElementById("shareDiv");
    divEle.style.display = "none";
}

//Returns imageName w.r.t document type
function getImageNameAndDisplayType(docType)
{
    var tempArray = new Array();
    var imageName = "";
    var displayType = "";
    if(docType == "document")
    {
        imageName = "large_icons/icon_doc1.gif";
        displayType = "Document";
    }
    else if(docType == "workbook")
    {
        imageName = "large_icons/icon_doc2.gif";
        displayType = "Workbook";
    }
    else if(docType == "presentation")
    {
        imageName = "large_icons/icon_doc3.gif";
        displayType = "Presentation";
    }
    tempArray[0] = imageName;
    tempArray[1] = displayType;
    return tempArray;
}

function getPreview(docId,docType,docName,ownerName)
{
    if(docType == 'presentation')
    {
        var urll = "http://show.zoho.com/View.do?P_ID="+docId+"&TP=true&ticket="+ticketID;
        if(ownerName != null && ownerName != '')
        {
            urll = urll+"&SHRD_BY="+ownerName;
        }
        popupNewWindow(urll);
    }
    else if(docType == 'workbook')
    {
        //get url from server
        getSheetPreviewURL  (docId,docType,docName);
    }
    else if(docType == 'document')
    {
        //get url from server
        //getDocContent(docId,docType,docName);
        var urll = "http://www.writer.zoho.com/docview.do?docId="
            +docId+"&mode=read&nologo=true&ticket="+ticketID;
        alert(urll);
        popupNewWindow(urll);
    }
}

function getDocContent(docId,docType,docName)
{
    try
    {
        var urll = contextPath + "/getDocsList.do?method=getDocContent&docId="
            +docId+"&docName="+docName+"&docType="+docType;
        sendAsyncAJAXRequest('GET',urll,responseDocContent);
    }
    catch(e)
    {
        alert(document.getElementById("unable.to.get.content").innerHTML);
    }
}

function responseDocContent(xmlhttp)
{
    if (xmlhttp.readyState == 4)
    {
        var response = xmlhttp.responseXML;
        var doccc = response.getElementsByTagName('result');
        if(doccc != null && doccc.item(0) != null )
        {
            var docum = doccc.item(0).getElementsByTagName('document')[0];
            var cont = docum.getElementsByTagName('content')[0].firstChild.data;
            previewConsole(cont);
        }
        else
        {
            alert(document.getElementById("unable.to.get.content").innerHTML);
            return;
        }
    }
}

function getSheetPreviewURL(docId,docType,docName)
{
    try
    {
        var urll = contextPath + "/getDocsList.do?method=getSheetPreview&docId="
            +docId+"&docName="+docName+"&docType="+docType;
        sendAsyncAJAXRequest('GET',urll,responseSheetPreVURL);
    }
    catch(e)
    {
        alert(document.getElementById("unable.to.get.content").innerHTML);
    }
}

function responseSheetPreVURL(xmlhttp)
{
    if (xmlhttp.readyState == 4)
    {
        var response = xmlhttp.responseText;
        popupNewWindow(response);
    }
}


function doExport(docId,docName,docType,linkId,doc_name_url,ownerName)
{
    var urlPrefix = docId+"?apikey="+apikey+"&ticket="+ticketID;
    
    var div = document.getElementById("menuDiv");

    var linkEle = document.getElementById(linkId);
    var pointXX = lastMouseClickX;//findPosX(linkEle);
    var pointYY = lastMouseClickY;//findPosY(linkEle);
    var menus = "";
    if(docType == 'document')
    {
        var inDOCUrl = "http://export.writer.zoho.com/api/private/doc/download/"+urlPrefix;
        var inPDFUrl = "http://export.writer.zoho.com/api/private/pdf/download/"+urlPrefix;
        var inHTMLUrl = "http://export.writer.zoho.com/api/private/html/download/"+urlPrefix;
        var inSXWUrl = "http://export.writer.zoho.com/api/private/sxw/download/"+urlPrefix;
        var inODTUrl = "http://export.writer.zoho.com/api/private/odt/download/"+urlPrefix;
        var inRTFUrl = "http://export.writer.zoho.com/api/private/rtf/download/"+urlPrefix;

        menus = menus + 
               "<table class=\"Linktxtsmall\" style=\"font-family:Verdana,sans-serif;font-size:12px;\" cellpadding='3' cellspacing='0'>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inDOCUrl+"')\">Word Document (.doc)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inPDFUrl+"')\">PDF Document (.pdf)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inHTMLUrl+"')\">HTML Document (.html)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inSXWUrl+"')\">OpenOffice Writer (.sxw)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inODTUrl+"')\">Open Document (.odt)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inRTFUrl+"')\">Rich Text File (.rtf)</a></td></tr>" +
                "</table>";
                
    }
    else if(docType == 'workbook')
    {
        var inXLSUrl = "http://sheet.zoho.com/api/private/xls/download/"+urlPrefix;
        var inSXCUrl = "http://sheet.zoho.com/api/private/sxc/download/"+urlPrefix;
        var inPDFUrl = "http://sheet.zoho.com/api/private/pdf/download/"+urlPrefix;
        var inHTMLUrl = "http://sheet.zoho.com/open.do?docid="+docId+"&ticket="+ticketID+"&export=html";

        menus = menus + 
               "<table class=\"Linktxtsmall\" style=\"font-family:Verdana,sans-serif;font-size:12px;\" cellpadding='3' cellspacing='0'>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inXLSUrl+"')\">MS Excel Workbook (.xls)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inPDFUrl+"')\">PDF Document (.pdf)</a></td></tr>"
                    + "<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inSXCUrl+"')\">OpenOffice Spreadsheet (.sxc)</a></td></tr>" 
                    +"<tr><td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\"><a href=\"javascript:openExportInNewTab('"+inHTMLUrl+"')\">HTML Document (.html)</a></td></tr>"+
                "</table>";
            
    }
    else if(docType == 'presentation')
    {
        docName = wrapUnwrapSplChar(docName,"wrap");
        var urll = "http://show.zoho.com/ExportAsHTML.do?ticket="+ticketID+"&P_ID="+docId+"&P_NAME="+docName+"&P_NAME_URL="+doc_name_url+"&TP=true";
        if(ownerName != null && ownerName != '')
        {
            urll = urll + "&SHRD_BY="+ownerName;
        }
        menus = menus + 
               "<table class=\"Linktxtsmall\" style=\"font-family:Verdana,sans-serif;font-size:12px;\" cellpadding='3' cellspacing='0'> <tr> <td onmouseover=\"style.backgroundColor='#DFE8F1'\" onmouseout=\"style.backgroundColor='#ffffff'\">" 
                    + "<a href=\"javascript:openExportInNewTab('"+urll+"')\">HTML Document (.html)</a>"+
                "</td> </tr> </table>";
    }
    div.innerHTML = menus;
    div.className = "tagmenu";
    div.style.right = "";
   // div.style.border = "1px solid black";
    div.style.left = pointXX;
    div.style.top = pointYY;
    div.style.position = "absolute";
    div.style.display = "block";
    div.style.backgroundColor = "#ffffff";
}

function showMenuDiv()
{
    var div = document.getElementById("menuDiv");
    div.style.display="block";
}

function openExportInNewTab(urll)
{
    var wind = window.open(urll,null,'menubar=yes');
    hideMenuDiv();
}

function hideMenuDiv()
{
    var div = document.getElementById("menuDiv");
    div.style.display="none";
}

function previewConsole(content)
{
    var gen = window.open('','name','');
    gen.document.write(content);
    gen.document.close();
}

//Sending synchronous request to server on documents deletion
function deleteDoc()
{
    if(shared)
    {
        alert(document.getElementById("delete.not.supported").innerHTML);
        return ;
    }   
    var dbCount = DocumentListDB.length;
    var docParams = "";
    var confirmed=false;
    var chkCount=0; 
    docIndxArr=[];
    shwIndxArr=[];
    shtIndxArr=[];
    //iterate all selected docs
    for(var i = 0  ; i < dbCount ; i++ )
    {
        var cbId = DocumentListDB[i].checkBxId;
        var ele = document.getElementById(cbId);
        if( ele != null && ele.checked == true)
        {
            if(!confirmed)
            {    
            if(!confirm(document.getElementById("delete.doc.confirmation").innerHTML))
            {
                return;
            }else
            {
              confirmed=true;  
            }
            }
            var docName = DocumentListDB[i].name;
            var docId = DocumentListDB[i].id;
            var docType = DocumentListDB[i].type;
            var param = docId+"_"+docType;
            if(docParams != "")
            {
                docParams = docParams + ",";
            }
            docParams = docParams + param;
            docIndxArr[chkCount]=i;
            chkCount++;
        }
    }
    //iterate all selected workbooks
     dbCount = WorkBookDB.length
      chkCount=0;   
    for(var i = 0  ; i < dbCount ; i++ )
    {
        var cbId = WorkBookDB[i].checkBxId;
        var ele = document.getElementById(cbId);
        if( ele != null && ele.checked == true)
        {
            if(!confirmed)
            {    
            if(!confirm(document.getElementById("delete.doc.confirmation").innerHTML))
            {
                return;
            }else
            {
              confirmed=true;  
            }
            }
            var docName = WorkBookDB[i].name;
            var docId = WorkBookDB[i].id;
            var docType = WorkBookDB[i].type;
            var param = docId+"_"+docType;
            if(docParams != "")
            {
                docParams = docParams + ",";
            }
            docParams = docParams + param;
            shtIndxArr[chkCount]=i;
            chkCount++;
        }
    }
     
    //iterate all selected presentations
     dbCount =PresentationDB.length
     chkCount=0;    
    for(var i = 0  ; i < dbCount ; i++ )
    {
        var cbId = PresentationDB[i].checkBxId;
        var ele = document.getElementById(cbId);
        if( ele != null && ele.checked == true)
        {
            if(!confirmed)
            {    
            if(!confirm(document.getElementById("delete.doc.confirmation").innerHTML))
            {
                return;
            }else
            {
              confirmed=true;  
            }
            }
            var docName = PresentationDB[i].name;
            var docId = PresentationDB[i].id;
            var docType = PresentationDB[i].type;
            var param = docId+"_"+docType;

            if(docParams != "")
            {
                docParams = docParams + ",";
            }
            docParams = docParams + param;
            shwIndxArr[chkCount]=i;
            chkCount++;
        }
    }
    if(!confirmed)
    {
        alert(document.getElementById("nodoc.selected.for.delete").innerHTML);
        return;
    }
    try
    {
        var urll = contextPath + "/getDocsList.do?method=deleteDoc&docParams="+docParams;
        sendAsyncAJAXRequest('GET',urll,docDeleteResponse);
        var loadg = document.getElementById("loadingDiv");
        loadg.innerHTML=document.getElementById("deleting.please.wait").innerHTML +"... <img src='" + contextPath + "/images/loading.gif'>";
        loadg.style.display="block";
    }
    catch(e)
    {
        alert(document.getElementById("unable.delete.doc").innerHTML);
    }
}
function getAllSelectedList()
{

}    

function docDeleteResponse(xmlhttp)
{
    if(xmlhttp.readyState == 4)
    {
        var resp = eval(xmlhttp.responseText);
        deleteDeletedDoc(resp);
    }
}

function deleteDeletedDoc(resp)
{
    if(resp == null || resp.length == 0)
    {
        return;
    }
   
    var notDltdDocs ="";
    var ln = resp.length;
    for(var i = 0 ; i < ln ; i++ )
    {
        var docId = resp[i].docId;
        var rslt = resp[i].result;
        var type=resp[i].docType;
        if(type=="document")
        {    
         notDltdDocs =deleteFromArr(resp[i],docIndxArr,DocumentListDB,notDltdDocs);  
        }else if(type=="presentation")
        {
         notDltdDocs =deleteFromArr(resp[i],shwIndxArr,PresentationDB,notDltdDocs);  
        }else
        {
         notDltdDocs =deleteFromArr(resp[i],shtIndxArr,WorkBookDB,notDltdDocs);  
        }    
            
    }
    var loadg = document.getElementById("loadingDiv");
    loadg.style.display = "none";
    if(notDltdDocs != "")
    {
        alert(document.getElementById("unable.delete.following.docs").innerHTML+": "+ "\n" +notDltdDocs);
    }

    //If all the rows are deleted from the table under search,tag and showAll scenarios,
    //repopulating the all documents.
    var docsInTable = document.getElementById("documentTableTBody").childNodes.length;
    if(docsInTable <= 2)
    {
        setSelectedTag("");
    }
}
function deleteFromArr(resp,indxArr,mainArr,notDltdDocs)
{
        var docLn=indxArr.length;
        var docId=resp.docId
        for(var cn = 0 ; cn < docLn ; cn++ )
        {
            var Obj=mainArr[indxArr[cn]];
            var doc_Id = Obj.id;
            if(doc_Id == docId)
            {
                var docName = Obj.name;
                var docType = Obj.type;
                if(resp.result == "success")
                {
                    //Deleting doc from the table
                    deleteDocFromTable(docName,docId,docType);
                   
                    //Removing this index from DocumentListDB
                    var tagArray = cloneArray(Obj.tagsArray);
                    //
                    mainArr.splice(indxArr[cn],1);
                    changeIndxs(indxArr,cn);
                    //Handling tags on deletion
                    handleTagsOnDocDelete(tagArray,docId);
                    
                    break;
                }
                else
                {
                    notDltdDocs = notDltdDocs + " \n " + docName;
                    break;
                }
            }
        }
    return notDltdDocs;
}    
function  handleDeletedDoc(resp)
{

}   
function getTableBody(docType)
{
 return docType+"TableTBody";
}    

//
function handleTagsOnDocDelete(tagArray,docId)
{
    var assoTagCnt = tagArray.length;
    if(assoTagCnt > 0)
    {
        //var tagsCnt = TagsListDB.length;
        for(var i = 0 ; i < TagsListDB.length ; i++ )
        {
            var tagArrayCnt = tagArray.length;
            if(tagArrayCnt == 0)
            {
                break;
            }
            var tagName = TagsListDB[i].tagName;
            for(var tC = 0 ; tC < tagArrayCnt ; tC++)
            {
                var tempTag = tagArray[tC];
                if(tagName == tempTag)
                {
                    var docCountInTags = TagsListDB[i].docCount;
                    //If docCount for this tag is one, then no
                    //other document is related to this tag.So removing
                    //this tag from the TagsListDB
                    if(docCountInTags == 1)
                    {
                        TagsListDB.splice(i,1);
                        //On splicing TagsListDB count is reduced by one,
                        //so to keep the for loop in sync, reducing the 
                        //current value by 1
                        i = i - 1;
                    }
                    else 
                    {
                        //Reducing the count by 1
                        TagsListDB[i].docCount = docCountInTags-1;
                        //Removing this docId from the docIdArray
                        var docIdArr = TagsListDB[i].docIdArray;
                        var arrCnt = docIdArr.length;
                        for(var cnt = 0 ; cnt < arrCnt ; cnt++ )
                        {
                            var tmpDocId = docIdArr[cnt];
                            if(tmpDocId == docId)
                            {
                                docIdArr.splice(cnt,1);
                            }
                        }
                        
                    }
                    //Removing the processed tag from the tagArray
                    tagArray.splice(tC,1);
                    break;
                }
            }
        }
        //Sorting the tags
        sortTagsOnCount();
        //showTagsListDB();
        displayTags("onDelete");
    }
}

function deleteDocFromTable(docName,docId,docType)
{
    var rowToDel = document.getElementById(docId);
    
    var tableEle = document.getElementById(getTableBody(docType));
    tableEle.removeChild(rowToDel);
}


function clearDocumentTable(type)
{

    var divName=type+"TableDiv";
    var intable = document.getElementById(divName);
    intable.innerHTML = '';
}
/*
function clearHeaderTable()
{
    var hdrDiv = document.getElementById("headerDiv");
    hdrDiv.innerHTML = "";
}
*/
function populateDocTable(type)
{
    var listObj=getListObjFor(type);
    var divObj=document.getElementById(type+"TableDiv");
   // divObj.style.display="block";
    var dbCount = listObj.length;
    if(dbCount >8)
    {
     // listObj.style.height="160px"; 
    }    
    for(var dc = 0 ; dc < dbCount ; dc++ )
    {
        getAndAddRow(listObj[dc]);
    }

}    
function populateTable()
{
    clearDocTableAndAddHeader();
    if(shared)
    {
         populateSharedDoc("document");
         populateSharedDoc("presentation");
         populateSharedDoc("workbook");
    }else
    {    
    populateDocTable("document");
    populateDocTable("presentation");
    populateDocTable("workbook");
    }
}
function addHeading(docType,intable)
{
   // var intable = document.getElementById("documentTableTBody");
    //Current row count
    var curRowCnt = intable.childNodes.length;
    //
    var newRow = document.createElement("tr");
    newRow.id = docType+"11";
    newRow.className="BgColorDark";
    intable.appendChild(newRow);
    if(docType == "document")
    {   
        var cell1 = document.createElement("td");
        cell1.className = "Captiontxt";
        cell1.innerHTML = "<input type=\"checkbox\" name=\"checkbox2\" onclick=\"javascript:selectOrDeselectDoc(true)\" id=\"checkbox2\"/>"+document.getElementById("documents").innerHTML +"<a class=\"Linktxtsmall\" href=\"javascript:getNewDoc('document')\">["+document.getElementById("create.new").innerHTML+"] </a>";
        newRow.appendChild(cell1);
        

    }else if(docType == "presentation")    
    {
        var cell1 = document.createElement("td");
        cell1.className = "Captiontxt";
        cell1.innerHTML = "<input type=\"checkbox\" onclick=\"javascript:selectOrDeselectShow(true)\" name=\"checkbox3\" id=\"checkbox3\"/>"+document.getElementById("presentations").innerHTML+" <a class=\"Linktxtsmall\" href=\"javascript:getNewDoc('presentation')\">["+document.getElementById("create.new").innerHTML+"]  </a>";
        newRow.appendChild(cell1);

    }else
    {
        var cell1 = document.createElement("td");
        cell1.className = "Captiontxt";
        cell1.innerHTML = "<input type=\"checkbox\" name=\"checkbox4\" onclick=\"javascript:selectOrDeselectSheet(true)\"id=\"checkbox4\"/> "+document.getElementById("Spreadsheets").innerHTML+"<a class=\"Linktxtsmall\" href=\"javascript:getNewDoc('workbook')\">["+document.getElementById("create.new").innerHTML+"] </a>";
        newRow.appendChild(cell1);
    }    

}    
/*
function createDocumentTable()
{    
    var inDiv = document.getElementById("docListDiv");
    inDiv.setAttribute("style","width:100%;overflow:auto;height:550px");
    var intable = document.createElement("table");
    intable.id = "documentTable";
    intable.cellSpacing = "0";
    intable.style.width = "100%";
    intable.className="globalText";
    inDiv.appendChild(intable);
    inDiv.style.display = "block";
}
*/
function setCellWidthAndAlign(cll,wdth,algn)
{
    cll.style.width = wdth;
    cll.style.align = algn;
}


function addTableHeader()
{
    //create all table body here
    //documents
    addTable("document",true);
    addTable("presentation",true);
    addTable("workbook",true);

    
}
function addTable(type,header)
{
    var divName=type+"TableDiv";
    var tableName=type+"Table";
    var tableDiv = document.getElementById(divName);
    var mainTable =document.createElement("table");
    mainTable.id = tableName;
    var tbodyName=type+"TableTBody";
    //mainTable.style.width = "793";
    mainTable.style.width = "100%";
    //mainTable.style.border = "0";
   // mainTable.className = "formtext";
    mainTable.cellSpacing = "0";
    mainTable.cellPadding = "0";
	mainTable.className="TblBorder";
    
    var intable = document.createElement("tbody");
    intable.id = tbodyName;
    mainTable.appendChild(intable);
 //   addHeading(type,intable);
	//Adding Create New Row starts
	var createNewRow = document.createElement("tr");
	intable.appendChild(createNewRow);
	var createNewCell1 = document.createElement("td");
	createNewRow.appendChild(createNewCell1);
	var createNewCell2 = document.createElement("td");
	createNewRow.appendChild(createNewCell2);
	var createNewCell3 = document.createElement("td");
	createNewRow.appendChild(createNewCell3);
	var createNewCell4 = document.createElement("td");
	createNewCell4.innerHTML="<a class=\"Linktxtsmall\" href=\"javascript:getNewDoc('"+type+"')\">["+document.getElementById("create.new").innerHTML+"]</a>";
	createNewCell4.className="CreateNew";
	createNewCell4.align="right";
	createNewRow.appendChild(createNewCell4);
	//Adding Create New Row ends
	
    if(!header)
    {
        tableDiv.appendChild(mainTable);
        return; 
    }    
	
    var newRow = document.createElement("tr");
    intable.appendChild(newRow);
    if(!shared)
    {    
    var cell01 = document.createElement("td");//newRow.insertCell(0);
    cell01.id=type+"_cbAll";
    if(type=="document")
    {    
    cell01.innerHTML="<input type=\"checkbox\" name=\"checkboxdoc\" onclick=\"javascript:selectOrDeselectDoc(this)\" id=\"checkboxdoc\"/>";
    }else if(type=="presentation")
    {
      cell01.innerHTML="<input type=\"checkbox\" name=\"checkboxshow\" onclick=\"javascript:selectOrDeselectShow(this)\" id=\"checkboxshow\"/>";
    }else
    {
       cell01.innerHTML="<input type=\"checkbox\" name=\"checkboxsheet\" onclick=\"javascript:selectOrDeselectSheet(this)\" id=\"checkboxsheet\"/>";
    }    
    newRow.appendChild(cell01);
    }else
    {
        var cell1 = document.createElement("td");
        cell1.innerHTML="<img id=\"empty_"+type+"\" src='images/spacer.gif'>";
        newRow.appendChild(cell1);
    } 
    var cell1 = document.createElement("td");//newRow.insertCell(0);
    cell1.align="left";
    cell1.id=type+"_NameCol";
    cell1.className="ColumnHeader";
    cell1.style.width="30%";
    cell1.onclick=function callSortName()
    {
        sortAndPopulate("Name",type);
        evtstatus=evtstatus+"onclick";    
    }
    cell1.onmouseover=function changeBg()
    {
        mouseOverHandler(type,"Name","over");
    }
    cell1.onmouseout=function changeBg()
    {
        mouseOverHandler(type,"Name","out");
    }
    cell1.innerHTML =document.getElementById("filename").innerHTML+ "&nbsp;<img id=\"sortName_"+type+"\" src='images/Arrow-unsorted.gif'>";
    newRow.appendChild(cell1);
    var cell3 = document.createElement("td");//newRow.insertCell(2);
    cell3.align="left";
    cell3.className="ColumnHeader";
    cell3.style.width="45%";
    cell3.innerHTML =document.getElementById("file.actions").innerHTML;
    newRow.appendChild(cell3);
    var cell4 = document.createElement("td");//newRow.insertCell(3);
    cell4.align="left";
    cell4.id=type+"_TimeCol";
    cell4.className="ColumnHeader";
    cell4.style.width="20%";
    cell4.onmouseover=function changeBg()
    {
        mouseOverHandler(type,"Time","over");
    }
    cell4.onmouseout=function changeBg()
    {
        mouseOverHandler(type,"Time","out");
    }
    cell4.onclick=function callSortTime()
    {
        sortAndPopulate("Time",type);
    }
    cell4.innerHTML =document.getElementById("date").innerHTML+" <img id=\"sortTime_"+type+"\" src='images/Arrow-unsorted.gif'>"
    newRow.appendChild(cell4);
    tableDiv.appendChild(mainTable);
    //
}
function selectOrDeselectAll(booleean)
{
    selectOrDeselectDoc(booleean);
    selectOrDeselectSheet(booleean);
    selectOrDeselectShow(booleean);

}
function selectOrDeselectDoc(booleean)
{
  //  selectOrDeselectAll(DocumentListDB);
    var dbCount = DocumentListDB.length;
    for(var c = 0 ; c < dbCount ; c++)
    {
        var checkBxId = DocumentListDB[c].checkBxId;
        if(document.getElementById(checkBxId) != null)
        {
            document.getElementById(checkBxId).checked = booleean.checked;
        }
    }
}
function selectOrDeselectShow(booleean)
{
   // selectOrDeselectAll(PresentationDB);
    var dbCount = PresentationDB.length;
    for(var c = 0 ; c < dbCount ; c++)
    {
        var checkBxId = PresentationDB[c].checkBxId;
        if(document.getElementById(checkBxId) != null)
        {
            document.getElementById(checkBxId).checked = booleean.checked;
        }
    }
}
function selectOrDeselectSheet(booleean)
{
   // selectOrDeselectAll(WorkBookDB);
    var dbCount = WorkBookDB.length;
    for(var c = 0 ; c < dbCount ; c++)
    {
        var checkBxId = WorkBookDB[c].checkBxId;
        if(document.getElementById(checkBxId) != null)
        {
            document.getElementById(checkBxId).checked = booleean.checked;
        }
    }
}

function sortAndPopulate(sortBy,type)
{

    if(type=="all")
    {
        sortByAsc(sortBy,"document");
        sortByAsc(sortBy,"presentation");
        sortByAsc(sortBy,"workbook");
        populateTable(); 
        showMessageForEmptyTable();
    }else
    {    
        if(getSortStatus(sortBy,type) == "true")
        {
            sortByDesc(sortBy,type);
        }
        else
        {
            sortByAsc(sortBy,type);
        }
        populateSortedTable(type);
    }

    showSortImage(sortBy,isAscending,type);
    // searchDocAndPopulate();
}
function setImage(id,image)
{
 if(eval(document.getElementById(id)))
 {
     document.getElementById(id).src=image;
     clicked=true;
 }   
}    
function showSortImage(sortBy,isAscending,type)
{
    var elName="sort"+sortBy;
    if(isAscending == "true")
    {    
    if(type=="all")
    {    
     setImage(elName+"_document",upImg);
     setImage(elName+"_presentation",upImg);
     setImage(elName+"_workbook",upImg);
    }else
    {
     elName=elName+"_"+type;   
     setImage(elName,upImg);
    }    
    }else
    {
    if(type=="all")
    {    
     setImage(elName+"_document",downImg);
     setImage(elName+"_presentation",downImg);
     setImage(elName+"_workbook",downImg);
    }else
    {
     elName=elName+"_"+type;   
     setImage(elName,downImg);
    }    
    }    

}    
function sortByAsc(sortBy,type)
{
    var listObj=getListObjFor(type);
    var docCount = listObj.length;
    if(sortBy == 'Name')
    {
        for(var ext = 0 ; ext < docCount ; ext++ )
        {
            for(var intr = 0 ; intr < docCount-1 ; intr++ )
            {
                var idd1 = listObj[intr].name;
                var idd2 = listObj[intr+1].name;
                if(idd1 > idd2 ) //ascending
                {
                    var tmp = listObj[intr+1];
                    listObj[intr+1] = listObj[intr];
                    listObj[intr] = tmp;
                }
            }
        }
    }
    else if(sortBy == 'Type')
    {
        for(var ext = 0 ; ext < docCount ; ext++ )
        {
            for(var intr = 0 ; intr < docCount-1 ; intr++ )
            {
                var idd1 = listObj[intr].type;
                var idd2 = listObj[intr+1].type;
                if(idd1 > idd2 ) //ascending
                {
                    var tmp = listObj[intr+1];
                    listObj[intr+1] = listObj[intr];
                    listObj[intr] = tmp;
                }
            }
        }
    }
    else if(sortBy == 'Time')
    {
        for(var ext = 0 ; ext < docCount ; ext++ )
        {
            for(var intr = 0 ; intr < docCount-1 ; intr++ )
            {
                var idd1 = 1*(listObj[intr].lastModTime);
                var idd2 = 1*(listObj[intr+1].lastModTime);
                if(idd1 > idd2 ) //ascending
                {
                    var tmp = listObj[intr+1];
                    listObj[intr+1] = listObj[intr];
                    listObj[intr] = tmp;
                }
            }
        }
    }
    isAscending="true";
   setSortStatus(sortBy,type,"true");
}

function sortByDesc(sortBy,type)
{
    var listObj=getListObjFor(type);
    var docCount = listObj.length;
    if(sortBy == 'Name')
    {
        
        for(var ext = 0 ; ext < docCount ; ext++ )
        {
            for(var intr = 0 ; intr < docCount-1 ; intr++ )
            {
                var idd1 = listObj[intr].name;
                var idd2 = listObj[intr+1].name;
                if(idd1 < idd2 ) //descending
                {
                    var tmp = listObj[intr+1];
                    listObj[intr+1] = listObj[intr];
                    listObj[intr] = tmp;
                }
            }
        }
    }
    else if(sortBy == 'Type')
    {
        for(var ext = 0 ; ext < docCount ; ext++ )
        {
            for(var intr = 0 ; intr < docCount-1 ; intr++ )
            {
                var idd1 = listObj[intr].type;
                var idd2 = listObj[intr+1].type;
                if(idd1 < idd2 ) //descending
                {
                    var tmp = listObj[intr+1];
                    listObj[intr+1] = listObj[intr];
                    listObj[intr] = tmp;
                }
            }
        }
    }
    else if(sortBy == 'Time')
    {
        for(var ext = 0 ; ext < docCount ; ext++ )
        {
            for(var intr = 0 ; intr < docCount-1 ; intr++ )
            {
                var idd1 = 1*(listObj[intr].lastModTime);
                var idd2 = 1*(listObj[intr+1].lastModTime);
                if(idd1 < idd2 ) //descending
                {
                    var tmp = listObj[intr+1];
                    listObj[intr+1] = listObj[intr];
                    listObj[intr] = tmp;
                }
            }
        }
    }
    //
   setSortStatus(sortBy,type,"false");
    isAscending="false";
}

//Sorts tags based on docCount in descending order
function sortTagsOnCount()
{
    var tagsCnt = TagsListDB.length;
    if(tagsCnt > 0)
    {
        for(var i = 0 ; i < tagsCnt ; i++ )
        {
            for(var j = 0 ; j < tagsCnt-1 ; j++)
            {
                var tagCnt1 = 1*(TagsListDB[j].docCount);
                var tagCnt2 = 1*(TagsListDB[j+1].docCount);
                if(tagCnt1 < tagCnt2) // descending
                {
                    var tmp = TagsListDB[j+1];
                    TagsListDB[j+1] = TagsListDB[j];
                    TagsListDB[j] = tmp;
                }
            }
        }
    }
}

function searchDocAndPopulate()
{
    //
    showDocsListDiv();

    //Moving the div to top
    //moveTheDocDivToTop("docListDiv");
    
    var searchValue = document.getElementById("searchField").value;
    //If searchField and currently selected tag values are empty ie.
    //they are not provided,populate the table without any check.
    if(searchValue == "" && currentTag == "")
    {
        populateTable();
        currentTag = "";
        showMessageForEmptyTable();
     //   document.getElementById("tag_showAllDocs").style.textDecoration = "underline";
        return;
    }
    clearDocTableAndAddHeader();
    //If searchField has selected
    searchAndAdd(searchValue,DocumentListDB);
    searchAndAdd(searchValue,PresentationDB);
    searchAndAdd(searchValue,WorkBookDB);
    //check for empty table    
    showMessageForEmptyTable();
}

//Called once the table data is populated.
//If the table does not contain any documents, means the
//given search string is not matched with any of the documents.
function actionOnSearchRslt()
{
    var tbody = document.getElementById("documentTableTBody");
    var cnt = tbody.childNodes.length;
    //first two rows correspond to the header and the options
    if(cnt <= 2)
    {
        clearDocumentTable();
        var divE = document.getElementById("noDocMatchedForSearchDiv");
        divE.style.display = "block";
    }

    //Disabling the currently selected tag in the left hand side panel
    var curEle = "";
    if(currentTag == "")
    {
        curEle = document.getElementById("tag_showAllDocs");
    }
    else
    {
        curEle = document.getElementById("tag_"+currentTag);
    }
    curEle.style.textDecoration = "none";
    currentTag = "";
}

function hideDocsNotMatchOnSearchDiv()
{
    var divE = document.getElementById("noDocMatchedForSearchDiv");
    divE.style.display = "none";
}

//Gets the associated docId array for the currentTag
function getAssoDocIDsForCrntTag()
{
    var tagsCnt = TagsListDB.length;
    var associatedDocs = new Array();
    for(var cou = 0 ; cou < tagsCnt ; cou++)
    {
        var tagName = TagsListDB[cou].tagName;
        if(tagName == currentTag)
        {
            var docIdArr = TagsListDB[cou].docIdArray;
            associatedDocs = cloneArray(docIdArr);
            break;
        }
    }
    return associatedDocs;
}

//gets data from the DocumentListDB object and adds a row
function getAndAddRow(documentList)
{
    var docId = documentList.id;
    var docName = documentList.name;
    var docType = documentList.type;
    var modTime = documentList.lastModTime;
    var checkBxId = documentList.checkBxId;
    var doc_name_url = documentList.document_name_url;
    var readOnlyUsers = documentList.readOnlyUsers;
    var editUsers = documentList.editUsers;
    addrowsInTable( docId, docName, docType, modTime, checkBxId , doc_name_url);    
}

function clearDocTableAndAddHeader(shared)
{
    clearDocumentTable("document");
    clearDocumentTable("presentation");
    clearDocumentTable("workbook");
    addTableHeader();
    //createDocumentTable();
}

function hideNoDocsAvailableDiv()
{
  /*  divEle = document.getElementById("noDocsAvailable");
    divEle.innerHTML = "";
    divEle.style.display = "none"; */
}

function uploadDoc(docEle)
{
    var uplEle = document.getElementById("uploadDiv");
    var dimens = getRelativePos(docEle,uplEle,"20");
    uplEle.className = "tagmenu";
    uplEle.style.left = lastMouseClickX;
    uplEle.style.top = lastMouseClickY+10;
    uplEle.style.display = "block";
}

function hideImportView()
{
    var upldLoadg = document.getElementById("uploadLoadingDiv");
    upldLoadg.innerHTML='';
    upldLoadg.style.display="none";
    var uplEle = document.getElementById("uploadDiv");
    var browseFieldId = document.getElementById("browseField");
    browseFieldId.value = '';
    uplEle.style.display = "none";
    //Enabling buttons 
    var uploadBtn = document.getElementById("uploadBttn");
    uploadBtn.disabled = false;    
    var cancelBtn = document.getElementById("cancelBttn");
    cancelBtn.disabled = false;
}

function getFileExtn()
{
    var fExtn;
    var fname;
    browsedoc = document.getElementById("browseField").value;
    if(browsedoc == null || trim(browsedoc) == "")
    {
        return;
    }
    if (browsedoc.lastIndexOf("/") != -1) 
    {
        fname = browsedoc.substring(browsedoc.lastIndexOf('/')+1,browsedoc.length);
    }
    else 
    {
        fname = browsedoc.substring(browsedoc.lastIndexOf('\\')+1,browsedoc.length);
    }

    if(fname.indexOf('.')!=-1)
    {
        fExtn = fname.substring(fname.lastIndexOf('.')+1);
        fname = fname.substring(0,fname.lastIndexOf('.'));
        //alert("file name::::::"+fname);
    }
    
    var arr = new Array();
    arr[0] = fname;
    arr[1] = fExtn;
    return arr;
}

function getFileType(fExtn)
{
    var fType = "";
    if(fExtn == "html" || fExtn == "doc" || fExtn == "sxw"
            || fExtn == "odt" || fExtn == "rtf" || fExtn == "txt")
    {
        fType = "document";
    }
    else if(fExtn == "xls" || fExtn == "ods" || fExtn == "sxc"
            || fExtn == "csv")
    {
        fType = "workbook";
    }
    else if(fExtn == "ppt" || fExtn == "pps" || fExtn == "odp" 
            || fExtn == "sxi")
    {
        fType = "presentation";
    }
    return fType;
}

function importDoc()
{
    //
    var specificDiv = document.getElementById("specificParameters");

    var fileLink = document.getElementById("browseField").value;
    if(fileLink == null || trim(fileLink) == "")
    {
        alert(document.getElementById("please.select.file.upload").innerHTML);
        return;
    }
    var fArray = getFileExtn(fileLink);
    var fName = fArray[0];
    var fileExtn = fArray[1];
    //alert("Extn:::"+fileExtn);
    var fileType = getFileType(fileExtn);
    //alert("FileType::"+fileType);
    if(fileLink == null || trim(fileLink) == "")
    {
        alert(document.getElementById("please.select.file.upload").innerHTML);
        return;
    }
    if(fileType != "document" && fileType != "workbook" && fileType != "presentation")
    {
        alert(document.getElementById("select.valid.file").innerHTML);
        return;
    }
    var actionurll = "";
    if(fileType == "document")
    {
        actionurll = "http://export.writer.zoho.com/api/private/json/uploadDocument?apikey="+apikey+"&ticket="+ticketID;
    }
    else if(fileType == "workbook")
    {
        specificDiv.innerHTML = "<input type=\"hidden\" name=\"contentType\" value=\""+fileExtn+"\">"+
                                "<input type=\"hidden\" name=\"bookName\" value=\""+fName+"\">";
        actionurll = "http://sheet.zoho.com/api/private/json/uploadbook?apikey="+apikey
                  +"&ticket="+ticketID;
    }
    else if(fileType == "presentation")
    {
        specificDiv.innerHTML = "<input type=\"hidden\" name=\"contenttype\" value=\""+fileExtn+"\">"+
                                "<input type=\"hidden\" name=\"presentationname\" value=\""+fName+"\">";
        actionurll = "http://show.zoho.com/api/private/json/uploadpresentation?apikey="+apikey
                 +"&ticket="+ticketID;
    }

    //
    var upFrm = document.getElementById("uploadForm");
    upFrm.action = actionurll;
    lastUploadedFileType = fileType;
    upFrm.submit();
    //
    
    var upldLoadg = document.getElementById("uploadLoadingDiv");
    upldLoadg.innerHTML=document.getElementById("loading").innerHTML+loadingMsg;
    upldLoadg.style.display="block";
    //Disabling buttons 
    var uploadBtn = document.getElementById("uploadBttn");
    uploadBtn.disabled = true;    
    var cancelBtn = document.getElementById("cancelBttn");
    cancelBtn.disabled = true;
}

function iFrameOnLoad()
{
    //
    var spdiv = document.getElementById("specificParameters");
    spdiv.innerHTML = "";

    //Preventing from calling the AJAX call on page load or refresh
    if(lastUploadedFileType == "")
    {
        return;
    }
    
    //
    try
    {
        var urll = contextPath + '/getDocsList.do?method=getDocCount&docType='
                   +lastUploadedFileType;
        sendAsyncAJAXRequest('GET',urll,docCountResponse);
    }
    catch(e)
    {
        alert(document.getElementById("unable.to.upload").innerHTML);
    }
}

function handleUploadResponse(rsltNode, tag1 , tag2)
{
    //alert("firstnode::"+tag1+"** countnode:"+tag2);
    var docNode = rsltNode[0].getElementsByTagName(tag1);
    var cntNode = docNode[0].getElementsByTagName(tag2);
    var countVal = cntNode[0].firstChild.data;
    log("CountVal From Server:::"+countVal);

    //Current count in client
    var currentDocCount = currentDocumentCountFromArray(lastUploadedFileType);
    log("CurrentDocCount in client:"+currentDocCount+"********* TYPE:"+lastUploadedFileType);

    if(countVal == (currentDocCount+1))
    {
        window.location.reload();
    }
    else if(countVal == currentDocCount) 
    {
        alert(document.getElementById("unable.to.upload").innerHTML);
    }
    
    //Setting the lastUploadedFileType to empty string
    lastUploadedFileType = "";
}

function docCountResponse(xmlhttp)
{
    if(xmlhttp.readyState == 4)
    {
        hideImportView(); 
        var response = xmlhttp.responseXML;
        var resultNode = response.getElementsByTagName('result');
        //Unable to get the response from the server
        if(resultNode == null && resultNode[0] == null)
        {
            //alert("Unable to upload the file.Please try again.");
            return;
        }
        if(lastUploadedFileType == 'document')
        {
            handleUploadResponse(resultNode,"documents","documentsCount");
        }
        else if(lastUploadedFileType == 'workbook')
        {
            handleUploadResponse(resultNode,"workbooks","workbooksCount");
        }
        else if(lastUploadedFileType == 'presentation')
        {
            handleUploadResponse(resultNode,"presentations","presentationsCount");
        }
    }
}

function currentDocumentCountFromArray(docType)
{

    var listObj=getListObjFor(docType);
    var dbCount = listObj.length;
    var docCount = 0;
    for(var i = 0 ; i < dbCount ; i++ )
    {
        var docTypeInDB = listObj[i].type;
        if( docTypeInDB == docType)
        {
            docCount = docCount+1;
        }
    }
    return docCount;
}

function setSelectedTag(tag)
{
     //If currently selected tag(incoming tag) is same as
     //that of the previous tag, returns with out any operation
     //if(currentTag == tag)
     //{
     //    return;
     //}
     var curEle = "";
     var nextEle = "";
     if(currentTag == "")
     {
         curEle = document.getElementById("tag_showAllDocs");
     }
     else
     {
         curEle = document.getElementById("tag_"+currentTag);
     }
     if(tag == "")
     {
         nextEle = document.getElementById("tag_showAllDocs");
     }
     else
     {
         nextEle = document.getElementById("tag_"+tag);
     }
     //Making the search field disable
     document.getElementById("searchField").value = "";
     curEle.style.textDecoration = "none";
    // nextEle.style.textDecoration = "underline";
     currentTag = tag;
     if(tag == 'showSharedDocs')
     {
         shared=true;
         currentlySlctdView = "sharedDocuments";
         showSharedDocsTable();
         hideOptions(true);
        // showNavHeader("Shared Documents ");
     }
     else
     {  shared=false; 
        hideOptions(false);
        currentlySlctdView = "myDocuments";
        searchDocAndPopulate();
        var headerContent="";
        if(tag=="")
        {    
         headerContent="My Documents";
        }else
        {
         headerContent="<img src='" + contextPath + "/images/icon_tag.gif'> "+tag;
        }    
        // showNavHeader(headerContent) ;
     }
}

function showDocsListDiv()
{
    //
    hideSharedDocsTable();

 /*   var docDiv = document.getElementById("docListDiv");
    docDiv.style.display = "block"; */
}

function hideDocsListDiv()
{
    var docDiv = document.getElementById("docListDiv");
    docDiv.style.display = "none";
}

function showSharedDocsTable()
{
    //Hiding uplod div 
    hideImportView();
    //Hiding share div
    hideShareDoc();

    //Hiding the docListDiv
   // hideDocsListDiv();

    //
    //Clearing the shared docs table
   // var divEle = document.getElementById("sharedDocTable");
   // divEle.innerHTML = "";

   // var shrDiv = document.getElementById("sharedDocListDiv");
   // shrDiv.style.display = "block";

    //if(isSharedDataFetched)
    //{
    //    populateSharedDocData('');
    //}
    //else
    //{
   
    SharedDocsDB = new Array();
    getSharedDataFromServer();
    //}
}

function hideSharedDocsTable()
{
    var shrDiv = document.getElementById("sharedDocListDiv");
    shrDiv.style.display = "none";
}


var isSharedDataFetched = false;

function SharedDoc(id,type,name,lastModTime,doc_name_url,writePermission,ownerName)
{
    this.id = id;
    //In Show services, if "'" present in the name, same has
    //been put as "&apos;".To make presentation names sync with the
    //other services, replacing "&apos;" with "'".
    if(type == "presentation")
    {
        name = replaceStr(name,"&apos;","\'");
    }
    this.name = name;
    if(type == 'incomingWorkbook')
    {
        type = 'workbook';
    }
    else if(type == 'incomingPresentation')
    {
        type = 'presentation';
    }
    this.type = type;
    this.lastModTime = lastModTime;
    this.document_name_url = doc_name_url;
    this.writePermission = writePermission;
    this.ownerName = ownerName;
}

function getSharedDataFromServer()
{
    try
    {
        var loadg = document.getElementById("loadingDiv");
        loadg.innerHTML=document.getElementById("loading").innerHTML+loadingMsg;
        loadg.style.display="block";
        sendAsyncAJAXRequest('GET',
                contextPath + '/getDocsList.do?method=getSharedDocsList',sharedDocResponse);
    }    
    catch(e)
    {
        alert(document.getElementById("unable.to.process").innerHTML);
    }
}

function sharedDocResponse(xmlhttp)
{
    shared=true;
    if(xmlhttp.readyState == 4)
    {
        var loadg = document.getElementById("loadingDiv");
        loadg.style.display="none";

        var xmll = xmlhttp.responseXML;
        //alert("sharedDocResponse::::::::::"+xmll);
        

        //Error response ***************
        var errorNode = xmll.getElementsByTagName('ErrorResponseFor');
        if(errorNode != null && errorNode.item(0) != null )
        {
            var services = errorNode.item(0).attributes[0].value;
            var servArray = services.split(',');
            //Exception occurs in the Writer or Workbook response or both
            if(servArray != null && servArray.length > 0)
            {
                //
                var servArrLength = servArray.length;
                var alertMssg = "Unable to fetch shared ";
                for(var i = 0 ; i < servArrLength ; i++ )
                {
                    if(i != 0)
                    {
                        alertMssg = alertMssg + " and ";
                    }
                    alertMssg = alertMssg + servArray[i] ;
                }
                if(alertMssg != "Unable to fetch shared ")
                {
                    alert(alertMssg);
                }
                //Means the xml doesnt contain response for any of the services
                if(servArrLength == 3)
                {
                    return;
                }
            }
        }
        //

        var doccc = xmll.getElementsByTagName('result');
        if(doccc != null && doccc.item(0) != null )
        {
            if(doccc.item(0).getElementsByTagName('incomingdocuments').length != 0)
            {
                var documents = doccc.item(0).getElementsByTagName('incomingdocuments')[0];
                SharedDocDB=[];
                parseAndAddInSharedArray(SharedDocDB,documents,"document","documentName","documentId","lastModifiedTime","writePermission","authorName");
            }   
            if(doccc.item(0).getElementsByTagName('incomingWorkbooks').length != 0)
            {
                SharedSheetDB=[];  
                var worksheets = doccc.item(0).getElementsByTagName('incomingWorkbooks')[0];
                parseAndAddInSharedArray(SharedSheetDB,worksheets, "incomingWorkbook", "workbookName","workbookId","lastModifiedTime","allowToWrite","ownerName");
            }   
            if(doccc.item(0).getElementsByTagName('incomingPresentations').length != 0)
            {
                SharedShowDB=[];
                var presenations = doccc.item(0).getElementsByTagName('incomingPresentations')[0];
                parseAndAddInSharedArray(SharedShowDB,presenations,"incomingPresentation","presentationName","presentationId","lastModifiedTime","allowToWrite","ownerName");
                        }    
            populateSharedDocData('');
            isSharedDataFetched = true;
        }
    }
}


function parseAndAddInSharedArray(listObj,documents,docType,tag1,tag2,tag3,tag4,tag5)
{
    var document = documents.getElementsByTagName(docType);
    var docCount = document.length;
    //alert(tag1+":::"+docCount);
    for(var i = 0 ; i < docCount ; i++ )
    {
        var docname = document.item(i).getElementsByTagName(tag1)[0].firstChild.data;
        var idd = document.item(i).getElementsByTagName(tag2)[0].firstChild.data;
        var time = document.item(i).getElementsByTagName(tag3)[0].firstChild.data;
        var doc_name_url = "";
        if(docType == "document")
        {
            doc_name_url = document.item(i)
                .getElementsByTagName("document_name_url")[0].firstChild.data;
        }
        var writePermission = document.item(i).getElementsByTagName(tag4)[0].firstChild.data;
        var ownerName = document.item(i).getElementsByTagName(tag5)[0].firstChild.data;
       // var listObj=getSharedListObjFor(docType);
        listObj[listObj.length] = 
            new SharedDoc(idd,docType,docname,time,doc_name_url,writePermission,ownerName);
    }
}


function populateSharedDocData(enableSearch)
{
  //  alert("SharedDocDB-count:"+SharedDocDB.length+"SharedShowDB-count"+SharedShowDB.length+"SharedSheetDB-count"+SharedSheetDB.length);
    var srchVal = document.getElementById("searchField").value; 
    clearDocTableAndAddHeader();
    if(enableSearch == 'enable' && srchVal != null && srchVal != "")
    {
        SearchAndPopulateSharedDoc(SharedDocDB);
        SearchAndPopulateSharedDoc(SharedShowDB);
        SearchAndPopulateSharedDoc(SharedSheetDB);
    }
    else
    {
         populateSharedDoc("document");
         populateSharedDoc("presentation");
         populateSharedDoc("workbook");
         showMessageForEmptyTable();
    }
}

function addrowsInShareDocTable( docId, docName, docType, modTime, doc_name_url , writePermission,ownerName)
{
    
    //Name to be used in getting editor page url
    var editorDocName = docName;
    //For Writer, document_name_url to be passed in getting the editor.
    if(docType == "document")
    {
        editorDocName = doc_name_url;
        //alert("addrowsInTable::editorDocName For Document::"+editorDocName);
    }
    //Wrapping special characters in docName to avoid problem
    //while passing across functions.
    var wrappedDocName = wrapUnwrapSplChar(docName,"wrap");
    //
    modTime = timeInString(modTime);
    var seperator = " | ";
    var exportId = docId+"_exp";

    var tbodyName=docType+"TableTBody";
    var intable = document.getElementById(tbodyName);
   // var intable = document.getElementById("sharedDocTbody");
    //Current row count
    var curRowCnt = intable.childNodes.length;
    //
    var newRow = document.createElement("tr");
    newRow.id = docId;
    var rclass = getRowColor(curRowCnt);    
    newRow.className=rclass;
    intable.appendChild(newRow);

    var cell01 = document.createElement("td");
    cell01.innerHTML="<img id=\"empty_"+docType+"\" src='images/spacer.gif'>";
    newRow.appendChild(cell01);
    //
    var dispDocName = docName;
    if(dispDocName.length > 23)
    {
        dispDocName = dispDocName.substring(0,20);
        dispDocName = dispDocName+"...";
    }

    var cell1 = document.createElement("td");//newRow.insertCell(0);
    cell1.className = "Linktxtsmall";
    cell1.innerHTML = "<span title=\""+docName+"\">"+ dispDocName+"</span>";
    newRow.appendChild(cell1);

   
    var cell3 = document.createElement("td");//newRow.insertCell(2);
    cell3.className = "Linktxtsmall";
    if(writePermission == "true")
    {
        cell3.innerHTML = "<a href=\"javascript:getPreview('"+docId+"','"+docType+"','"+wrappedDocName+"','"+ownerName+"')\">"+document.getElementById("preview").innerHTML+"</a> | <a href=\"" + contextPath +"/getDocsList.do?method=getEditorPage&docId="+ docId + "&docType=" + docType +"&apiTicket="+ticketID+ "&docName="+editorDocName+"\">"+document.getElementById("edit").innerHTML+"</a> | <a  id='"+exportId+"' href=\"javascript:doExport('"+docId+"','"+wrappedDocName+"','"+docType+"','"+exportId+"','"+doc_name_url+"','"+ownerName+"')\">"+document.getElementById("export").innerHTML+"</a>";
    }
    else
    {
        cell3.innerHTML = "<a href=\"javascript:getPreview('"+docId+"','"+docType+"','"+wrappedDocName+"','"+ownerName+"')\">"+document.getElementById("preview").innerHTML+"</a> |  <a  id='"+exportId+"' href=\"javascript:doExport('"+docId+"','"+wrappedDocName+"','"+docType+"','"+exportId+"','"+doc_name_url+"','"+ownerName+"')\">"+document.getElementById("export").innerHTML+"</a>";
    }

    newRow.appendChild(cell3);

    var cell4 = document.createElement("td");//newRow.insertCell(3);
    cell4.className ="Linktxtsmall";
    cell4.innerHTML = "<em>"+modTime+"</em>";
    newRow.appendChild(cell4);
}

function shareTheDoc(docType,docId)
{
    //alert("shareTheDoc:::::::::::docType:"+docType+"**docId:"+docId+"**");
    var readDoc = document.getElementById("shareDoc_View");
    var editDoc = document.getElementById("shareDoc_Edit");

    var readUsers = readDoc.value;
    var editUsers = editDoc.value;
    if(readUsers == null && editUsers == null )
    {
        alert(document.getElementById("nousers.specified.to.share").innerHTML);
        readDoc.focus();
        return;
    }
    readUsers = ""+readUsers;
    editUsers = ""+editUsers;
    readUsers = trim(readUsers);
    editUsers = trim(editUsers);
    
    if(readUsers == "" && editUsers == "" )
    {
        alert(document.getElementById("nousers.specified.to.share").innerHTML);
        readDoc.focus();
        return;
    }
    if(!checkMailIds(readUsers))
    {
        readDoc.focus();
        return;
    }
    if(!checkMailIds(editUsers))
    {
        editDoc.focus();
        return;
    }
    
    var users = crossCheckSharedDetails(readUsers,editUsers,docId,docType);
    readUsers = users[0];
    editUsers = users[1];

    //If the mails to be shared are already shared
    if(readUsers == "" && editUsers == "")
    {
        showSharedDetailsDiv();
    }

    try
    {
        document.getElementById('submitBttnShare').disabled = true; 
        var urll = contextPath +"/getDocsList.do?method=shareDocument"+
                    "&readOnly="+readUsers+"&edit="+editUsers+"&type="+docType
                    +"&docId="+docId+"&userName="+userName;
        var divEle = document.getElementById("shareLoadingDiv");
        divEle.innerHTML =document.getElementById("sharing").innerHTML +"... <img src='" + contextPath + "/images/loading.gif'>";
        divEle.style.display = "block";
        sendAsyncAJAXRequest('GET', urll,shareResponse);
    }
    catch(e)
    {
        alert(document.getElementById("unable.to.process").innerHTML);
    }
}

function crossCheckSharedDetails(readUsers,editUsers,docId,docType)
{
    var exstReadUsers = "";
    var exstEditUsers = "";
    var listObj=getListObjFor(docType);
    for(var x in listObj)
    {
        var idd = listObj[x].id;
        if(idd == docId)
        {
            exstReadUsers = ""+listObj[x].readOnlyUsers;
            exstEditUsers = ""+listObj[x].editUsers;
            break;
        }
    }

    var cmpltSharedMailIds = "";

    if(exstReadUsers != null && trim(exstReadUsers) != "")
    {
        cmpltSharedMailIds = exstReadUsers ;
    }
    if(exstEditUsers != null && trim(exstEditUsers) != "")
    {
        if(cmpltSharedMailIds == null || cmpltSharedMailIds == "")
        {
            cmpltSharedMailIds = exstEditUsers;
        }
        else
        {
            cmpltSharedMailIds = cmpltSharedMailIds + "," + exstEditUsers;
        }
    }

    //Removing the view mailIds present in the view&write mail ids
    readUsers = removeCommonArray(editUsers,readUsers);

    //Removing the already shared mail ids from read only mail ids to be shared
    readUsers = removeCommonArray(cmpltSharedMailIds,readUsers);

    //Removing the already shared mail ids from edit mail ids to be shared
    editUsers = removeCommonArray(cmpltSharedMailIds,editUsers);

    var tmpArr = new Array();
    tmpArr[0] = trim(readUsers);
    tmpArr[1] = trim(editUsers);
    //alert("TTT:::::::::::::::::::"+tmpArr);
    return tmpArr;

}

//Removes the common mail ids from processMailIds and removes
//the same in string format
function removeCommonArray(mainMailIds,processMailIds)
{
    if(processMailIds != "")
    {
        var arr1 = processMailIds.split(",");
        if(mainMailIds != "")
        {
            var arr2 = mainMailIds.split(",");
            for(var x in arr2)
            {
                var idd = arr2[x];
                idd = trim(idd);
                for(var y in arr1)
                {
                    var tmpidd = arr1[y];
                    tmpidd = trim(tmpidd);
                    if(idd == tmpidd)
                    {
                        arr1.splice(y,1);
                        break;
                    }
                }
            }
        }
        if(arr1.length == 0)
        {
            processMailIds = "";
        }
        else
        {
            processMailIds = arr1.toString();
        }
    }
    return trim(processMailIds);
}

function shareResponse(xmlhttp)
{
    if(xmlhttp.readyState == 4)
    {
        var isErrorOccured = false;
        document.getElementById('submitBttnShare').disabled = false; 
        var divEle = document.getElementById("shareLoadingDiv");
        divEle.style.display = "none";
        var resp = xmlhttp.responseText;
        if(resp != null)
        {
            var evResp = eval('('+resp+')');
            var ln = evResp.length;
            var ttype = evResp[0].type;
            var nonRegisteredUsers = evResp[(ln-1)].nonRegisteredUsers;
            
            var docType = "";
            var allReadOnlyUsers = "";
            var allEditUsers = "";
            var docId = "";
            
            if(ttype == "writer" || ttype == "show")
            {
                if(ttype == "writer")
                {
                    docType = "document";
                }
                else if(ttype == "show")
                {
                    docType = "presentation";
                }
                var errorIn = "";
                for(var i = 1 ; i < ln-1 ; i++)
                {
                    var acRsp = evResp[i];
                    var sharedTo = "";
                    if(evResp[i].readonly != null)
                    {
                        if(evResp[i].readonly.response.result == null)
                        {
                            errorIn = "Read Only";
                        }
                        else
                        {
                           //Writer docs
                           if(ttype == "writer")
                           {
                               sharedTo = evResp[i].readonly.response.result.sharedto;
                               docId = evResp[i].readonly.response.result.documentId;
                               var usr = sharedTo.user;
                               if(usr.length != null || usr.length == 0)
                               {
                                  allReadOnlyUsers = updateSharedMailId(docId,usr,"add","readOnly",docType);
                               }
                               else
                               {
                                   for(var x in usr)
                                   {
                                       var idd = usr[x];
                                       allReadOnlyUsers = updateSharedMailId(docId,idd,"add","readOnly",docType);
                                   }
                               }
                           }
                           //Show docs
                           else if(ttype == "show")
                           {
                                docId = evResp[i].readonly.response.result.presentationId;
                                sharedTo = evResp[i].readonly.response.result.sharedTo;
                                if(sharedTo != null && sharedTo != "")
                                {
                                    var userROInputs = document.getElementById("shareDoc_View").value;
                                    var commonIds = getCommonMailIds(sharedTo,userROInputs);
                                    for(var x in commonIds)
                                    {
                                        var idd = commonIds[x];
                                        allReadOnlyUsers = updateSharedMailId(docId,idd,"add","readOnly",docType);
                                    }
                                }
                           }
                        }
                    }
                    else if(evResp[i].edit != null)
                    {
                        if(evResp[i].edit.response.result == null)
                        {
                            if(errorIn != "")
                            {
                                errorIn = "Read/Write";
                            }
                            else
                            {
                                errorIn = errorIn + " and Read/Write";
                            }
                        }
                        else
                        {
                            //writer docs
                            if(ttype == "writer")
                            {
                                sharedTo = evResp[i].edit.response.result.sharedto;
                                docId = evResp[i].edit.response.result.documentId;
                                var usr = sharedTo.user;
                                if(usr.length != null || usr.length == 0)
                                {
                                    allEditUsers = updateSharedMailId(docId,usr,"add","readWrite",docType);
                                }
                                else
                                {
                                    for(var x in usr)
                                    {
                                        var idd = usr[x];
                                        allEditUsers = updateSharedMailId(docId,idd,"add","readWrite",docType);
                                    }
                                }
                            }
                            //show docs
                            else if(ttype == "show")
                            {
                                docId = evResp[i].edit.response.result.presentationId;
                                sharedTo = evResp[i].edit.response.result.sharedTo;
                                if(sharedTo != null && sharedTo != "")
                                {
                                    var userEdtInputs = document.getElementById("shareDoc_Edit").value;
                                    var commonIds = getCommonMailIds(sharedTo,userEdtInputs);
                                    for(var x in commonIds)
                                    {
                                        var idd = commonIds[x];
                                        allEditUsers = updateSharedMailId(docId,idd,"add","readWrite",docType);
                                    }
                                }
                            }
                        }
                    }
                }
                if(errorIn != "")
                {
                    alert(document.getElementById("unable.share.doc.for.mailids").innerHTML+": "+errorIn);
                    isErrorOccured = true;
                }
            }
            else if(ttype == "sheet")
            {
                docType = "workbook";
                if(ln == 3)
                {
                    var rspp = evResp[1].response.result;
                    if(rspp == null)
                    {
                        alert(document.getElementById("unable.share.doc").innerHTML);
                        //return;
                    }
                    else
                    {
                        var readOnlyUsr = rspp.readOnlyUsers.user;
                        var editUser = rspp.readWriteUsers.user;
                        docId = rspp.workbookId;
                        for(var xy in readOnlyUsr)
                        {
                            var idd = readOnlyUsr[xy].emailId;
                            allReadOnlyUsers = updateSharedMailId(docId,idd,"add","readOnly",docType);
                        }
                        for(var yx in editUser)
                        {
                            var idd = editUser[yx].emailId;
                            allEditUsers = updateSharedMailId(docId,idd,"add","readWrite",docType);
                        }
                    }
                }
            }

            //non registered users
            if(nonRegisteredUsers != null && trim(nonRegisteredUsers) != "")
            {
                var nonRUser = nonRegisteredUsers.toString();
                nonRUser = replaceStr(nonRUser,",","\n");
                alert(document.getElementById("unable.share.doc.for.mailids").innerHTML+" \n \n"+nonRUser);
                isErrorOccured = true;
            }
            
            /*
            hideShareDoc();

            if(!isErrorOccured)
            {
                alert("Document shared successfully.");
            }
            */

            //
            //Forming shared details table
            if(docId != null && docId != "")
            {
               formShareTab2(docId,docType);
            }
            showSharedDetailsDiv();
            

        }
        else
        {
            alert(document.getElementById("unable.share.doc").innerHTML);
        }
    }
}

//Used in finding out the shared show emailids. 
//On sharing,show will give the complete shared emailids.To split
//the currently shared and already shared email ids, this method
//is used. mailIds1 contains the completly shared wheread mailIds2 contains
//currently shared.
//Returns only the currently shared in array format.
function getCommonMailIds(mailIds1,mailIds2)
{
    var arr1 = mailIds1.split(",");
    var arr2 = trim(mailIds2).split(",");
    var tmpArr = new Array();
    for(var x in arr2)
    {
        var idd = trim(arr2[x]);
        for(var y in arr1)
        {
           var tmpidd = trim(arr1[y]);
           if(idd == tmpidd)
           {
               tmpArr[tmpArr.length] = idd;
               break;
           }
        }
    }
    return tmpArr;
}

var mailIdfilter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;

function checkMailIds(mailIds)
{
    var strArr = mailIds.split(",");
    for(var x in strArr)
    {
        var mId = strArr[x];
        mId = trim(mId);
       if(trim(mId) != "" && !mailIdfilter.test(mId))
       {
           alert(document.getElementById("invalid.emailid").innerHTML+":"+mId);
           return false;
       }
    }
    return true;
}

//Returns a string array with first array containing the 
//emailIds available only in usrIds1 and the second containing
//emailIds available only in usrIds2
function compareArrays(usrIds1,usrIds2)
{
    var newIds = "";
    var rmvdIds = "";
    
    var arr1 = usrIds1.split(",");
    var arr2 = usrIds2.split(",");

    var arr2Indxs = new Array();
    for(var x in arr2)
    {
        var idd = arr2[x];
        for(var y in arr1)
        {
            var tmpidd = arr1[y];
            if(idd == tmpidd)
            {
                //Splicing the id from array1
                arr1.splice(y,1);
                arr2Indxs[arr2Indxs.length] = idd;
            }
        }
    }
    
    //Splicing the common ids from arr2 using arr2Indxs
    var arr2ln = arr2Indxs.length;
    if(arr2ln > 0)
    {
        for(var i = arr2ln-1 ; i >= 0 ; i-- )
        {
            var indx = arr2Indxs[i];
            arr2.splice(indx,1);
        }
    }

    newIds = arr1.toString();
    rmvdIds = arr2.toString();

    var tmpArr = new Array();
    tmpArr[0] = newIds;
    tmpArr[1] = rmvdIds;

    return tmpArr;
}

function showShareDiv()
{
    document.getElementById("shareDoc_View").value = "";
    document.getElementById("shareDoc_Edit").value = "";
    document.getElementById("tab1_option").style.borderBottom = "0px";
    document.getElementById("tab2_option").style.borderBottom = "1px solid" ;
    document.getElementById("shareTab2").style.display = "none";
    document.getElementById("shareTab1").style.display = "block";
    //Setting focus on read doc view
    document.getElementById("shareDoc_View").focus();
}

function showSharedDetailsDiv()
{
    document.getElementById("tab2_option").style.borderBottom = "0px";
    document.getElementById("tab1_option").style.borderBottom = "1px solid";
    document.getElementById("shareTab2").style.display = "block";
    document.getElementById("shareTab1").style.display = "none";
}

function doSearchInDoc()
{
    if(currentlySlctdView == "sharedDocuments")
    {
        populateSharedDocData('enable');
    }
    else
    {
        searchDocAndPopulate();
    }
}
function colapseTable(id)
{
//alert(id)
    var obj=document.getElementById(id);
    var imgObj=getColapseImg(id);
    if(obj.style.display=='none')
    {
        obj.style.display='block';
        imgObj.src="images/OpenArrow.gif";
    }else
    {
        obj.style.display='none';
        imgObj.src="images/CloseArrow.gif";
    }    
}
function getListObjFor(docType)
{
    if(docType=="document")
    {
        if(shared)
        {
          return SharedDocDB;  
        }else
        {    
        return DocumentListDB;
        }
    }else if(docType=="presentation")
    {
        if(shared)
        {
          return SharedShowDB;  
        }else
        {    
        return PresentationDB;
        }
    }else
    {
        if(shared)
        {
          return SharedSheetDB;  
        }else
        {    
        return WorkBookDB;
        }
    }  

}    
function getSharedListObjFor(docType)
{
    if(docType=="document")
    {
        return SharedDocDB;
    }else if(docType=="presentation")
    {
        return SharedShowDB;
    }else
    {
        return SharedSheetDB;
    }  

}    
function searchAndAdd(searchValue,listObj)
{
    if(searchValue != "" )
    {
        var dbCount = listObj.length;
        for(var cou = 0 ; cou < dbCount ; cou++)
        {
            var docName = listObj[cou].name;
            if(docName.match(searchValue) != null)
            {
                getAndAddRow(listObj[cou]);
            }
        }
        //
    //    actionOnSearchRslt();
    }
    //If tag has been selected 
    //else if(searchValue == "" && currentTag != "")
    else
    {
        var associatedDocs = getAssoDocIDsForCrntTag();
        var assoDocsCnt = associatedDocs.length;
        if(assoDocsCnt > 0 )
        {
            var dbCnt = listObj.length;
            for(var i = 0 ; i < dbCnt ; i++ )
            {
                var docIdCnt = associatedDocs.length;
                if(docIdCnt == 0)
                {
                    break;
                }
                var docId = listObj[i].id;
                for(var j = 0 ; j < docIdCnt ; j++ )
                {
                    if(docId == associatedDocs[j])
                    {
                        //Splicing the matched docId from the associatedDocs
                        associatedDocs.splice(j,1);
                        getAndAddRow(listObj[i]);
                        //Breaking this internal for loop
                        break;
                    }
                }
            }
        }
    }
    
}    
function showMessageForEmptyTable()
{
    var docsInTable = document.getElementById("documentTableTBody").childNodes.length;
    if(docsInTable <= 2)
    {
        displayNoDocDiv("document");
    }else
    {
      //  document.getElementById("documentTableDiv").style.display="block";
    }    
    docsInTable = document.getElementById("presentationTableTBody").childNodes.length;
    if(docsInTable <= 2)
    {
        displayNoDocDiv("presentation");
    }else
    {
       // document.getElementById("presentationTableDiv").style.display="block";
    } 
    docsInTable = document.getElementById("workbookTableTBody").childNodes.length;
    if(docsInTable <= 2)
    {
        displayNoDocDiv("workbook");
    }else
    {
       // document.getElementById("workbookTableDiv").style.display="block";
    } 
}    
function populateSortedTable(type)
{
   clearDocumentTable(type);
   addTable(type,true);
   if(shared)
   {
       populateSharedDoc(type);
   }else
   {    
    populateDocTable(type); 
   } 
     
    var docsInTable = document.getElementById(type+"TableTBody").childNodes.length;
    if(docsInTable <= 1)
    {
     displayNoDocDiv(type+"TableDiv");
    } 
}    
function SearchAndPopulateSharedDoc(listObj)
{
   var srchVal = document.getElementById("searchField").value; 
   var isMatched = false;
   var ln =listObj.length;
    for(var i = 0 ; i < ln ; i++ )
    {
        var docId = listObj[i].id;
        var docName = listObj[i].name;
        var docType = listObj[i].type;
        var modTime = listObj[i].lastModTime;
        var doc_name_url = listObj[i].document_name_url;
        var writePermission = listObj[i].writePermission;
        var ownerName = listObj[i].ownerName;
        if(docName.match(srchVal) != null)
        {
            addrowsInShareDocTable( docId, docName, docType, modTime, doc_name_url,writePermission,ownerName);
            isMatched = true;
        }
    }
    if(!isMatched)
    {
       
        displayNoDocDiv(docType);
    }

}
function populateSharedDoc(docType)
{
    var listObj=getListObjFor(docType);
    var ln =listObj.length;
        for(var i = 0 ; i < ln ; i++ )
        {
            var docId = listObj[i].id;
            var docName = listObj[i].name;
            var docType = listObj[i].type;
            var modTime = listObj[i].lastModTime;
            var doc_name_url = listObj[i].document_name_url;
            var writePermission = listObj[i].writePermission;
            var ownerName = listObj[i].ownerName;
            addrowsInShareDocTable( docId, docName, docType, modTime, doc_name_url,writePermission,ownerName);
        }
}    
function hideOptions(hide)
{
    if(hide)
    {    
    var uploadCol = document.getElementById("uploadCol");
    uploadCol.innerHTML="";
    }else
    {
 var uploadCol = document.getElementById("uploadCol");
 uploadCol.innerHTML=document.getElementById("perform").innerHTML+": <a href=\"javascript:uploadDoc(this.document)\">"+document.getElementById("upload").innerHTML+"</a> | <a href=\"javascript:deleteDoc()\">"+document.getElementById("delete").innerHTML+"</a>"; 
    }    

}    
function getSortStatus(sortBy,docType)
{
    if(docType=="document")
    {
        if(sortBy=="Name")
        {
            return isAscending_doc_name;
        }else
        {
           return isAscending_doc_time; 
        }  
    }else if(docType=="presentation")
    {
        if(sortBy=="Name")
        {
            return isAscending_show_name;
        }else
        {
           return isAscending_show_time; 
        }  
    }else
    {
        if(sortBy=="Name")
        {
            return isAscending_sheet_name;
        }else
        {
           return isAscending_sheet_time; 
        }  
    }  
    
}    
function setSortStatus(sortBy,docType,sortStatus)
{
    if(docType=="document")
    {
        if(sortBy=="Name")
        {
            isAscending_doc_name=sortStatus;
        }else
        {
            isAscending_doc_time=sortStatus; 
        }  
    }else if(docType=="presentation")
    {
        if(sortBy=="Name")
        {
            isAscending_show_name=sortStatus;
        }else
        {
           isAscending_show_time=sortStatus; 
        }  
    }else
    {
        if(sortBy=="Name")
        {
           isAscending_sheet_name=sortStatus;
        }else
        {
           isAscending_sheet_time=sortStatus; 
        }  
    }  
    
}    
function clearText(obj)
{
    obj.value="";
}    
function mouseOverHandler(type,colName,evt)
{
    var obj=document.getElementById(type+"_"+colName+"Col");  
    var imgObj=document.getElementById("sort"+colName+"_"+type);
    if(evtstatus.indexOf("onclick") !=-1)
    { 
     if(evt=="out")
      {    
       // obj.style.backgroundColor="#FFFFFF";
        evtstatus="";
      }  
        return; 
    }    
    evtstatus=evtstatus+evt;    
    if(evt=="over")
    {    
        //obj.style.backgroundColor="#E6EDF2";
        lastImg=imgObj.src;
        if(getSortStatus(colName,type)=="")
        {
            return;
        }else if(getSortStatus(colName,type)=="true") 
        {    
            //current is ascending   
            imgObj.src=downImg;
        }else
        {
            imgObj.src=upImg;  

        }    

    }else
    {
       // obj.style.backgroundColor="#FFFFFF";
        imgObj.src=lastImg;
        evtstatus="";
    }  
}    
function  showNavHeader(title)
{
  var navObj=document.getElementById("navHeader");  
  navObj.innerHTML=title;
  navObj.align="center";
  navObj.valign="center";
  navObj.className="Captiontxt2";
}    
function getColapseImg(id)
{
    if(id=="documentTableDiv")
    {
      return document.getElementById("docArrow");
        
    }else if(id=="workbookTableDiv")    
    {
      return document.getElementById("sheetArrow");
    }else
    {
      return document.getElementById("showArrow");
    }    

}
 function changeIndxs(indxArr,cn)
 {
       indxArr.splice(cn,1); 
       for(var j=cn;j>indxArr.length-1;j++)
       {
        indxArr[j]=indxArr[j+1]-1  ;
       }    
 }   
function showDocDiv()
{
    document.getElementById("documentTableDiv").style.display="block";
    document.getElementById("presentationTableDiv").style.display="none";
    document.getElementById("workbookTableDiv").style.display="none";
    document.getElementById("documentTab").className="InnerTabSelect";
    document.getElementById("presentationTab").className="InnerTabUnSelect";
    document.getElementById("workbookTab").className="InnerTabUnSelect";

}    
function showShowDiv()
{
    document.getElementById("documentTableDiv").style.display="none";
    document.getElementById("presentationTableDiv").style.display="block";
    document.getElementById("workbookTableDiv").style.display="none";
    document.getElementById("documentTab").className="InnerTabUnSelect";
    document.getElementById("presentationTab").className="InnerTabSelect";
    document.getElementById("workbookTab").className="InnerTabUnSelect";

}    
function showSheetDiv()
{
    document.getElementById("documentTableDiv").style.display="none";
    document.getElementById("presentationTableDiv").style.display="none";
    document.getElementById("workbookTableDiv").style.display="block";
    document.getElementById("documentTab").className="InnerTabUnSelect";
    document.getElementById("presentationTab").className="InnerTabUnSelect";
    document.getElementById("workbookTab").className="InnerTabSelect";

}    
function getDisplayString(docType)
{
    if(docType=="workbook")
    {
       return document.getElementById("no.spreadsheet.available").innerHTML;
    } else if(docType=="presentation")
    {
       return document.getElementById("no.presentation.available").innerHTML;
    }else
    { 
      return document.getElementById("no.documents.available").innerHTML;  
    }    
}    
