/**
 * 
 * All content on this website (including text, images, source
 * code and any other original works), unless otherwise noted,
 * is licensed under a Creative Commons License.
 * 
 * http://creativecommons.org/licenses/by-nc-sa/2.5/
 * 
 * Copyright (C) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Andreas Mayer <andreas.mayer@open-xchange.com>
 * 
 */

var bInfoSplitLoaded = false;
var bInfoSplitCreated = false;
var gridInfoSplit;
var editInfoItemId = -1;
var newInfoJson = new JSON();
var infostoreRequest;
var gridVersionsInfoSplit;
var aCoumnsToFetch = new Array(705,705,4,702,703,704,710,2,709);
var versionsStorage, nCurrentDetailItemTimestamp = -1;
var bDetailVersionLoaded = false, bVersionCreated = false;
var infostore_folderPathDetail;

function InfoStore() {}
InfoStore.IMAGE_MAX_FILE_SIZE=100000;

register("Loaded", function() {
	infostore_folderPathDetail = new FolderPath("infostore");
	infostore_folderPathDetail.className="linkstyle";
});

function fn_infostore_getDetails(objects, forceUpdate) {	
    if (!objects.length || activemodule != "infostore") return;
        
    // changing the selection jumps back to overview tab
    if (currentpath2[1] == "split" && currentpath2[2] != "overview") { 
        triggerEvent("OX_Switch_View", "infostore/split/overview");
    }
    
    enableInfostoreLoadingScreen(true);
        
    var collection={}
    collection.objects=[objects[0]];
    collection.columns=null;
    if (infostoreRequest) {
        OXCache.unregister(infostoreRequest.uniqueName);
        delete(infostoreRequest);
    }
        
    infostoreRequest=OXCache.newRequest(null, "infostore", collection, function(daten) {
        if (!daten || !daten.objects) {
            enableInfostoreLoadingScreen(false);
            return;
        }
        getVersions(); // updating versions
        updateInfostoreSplit(daten.objects[0]);
    }, function(daten) {
        if (!daten || !daten.objects) {
            enableInfostoreLoadingScreen(false);
            return;
        }
        updateInfostoreSplit(daten.objects[0]);
    }, forceUpdate);
    
}

function expandInfostoreSplitHeader(fullHeader) {
    if (fullHeader) $('infosplit.header_ext').style.display = "";
    $("infosplit.expand_plus").getElementsByTagName("img")[0].src =
        getFullImgSrc("img/" + (fullHeader ? "minus" : "plus") + ".gif");
    configSetKey("gui.infostore.fullsplitheader", fullHeader);    
    var steps = 6*pxPerEm;
    animate(configGetKey("gui.effects.fading") ? 250 : 0, steps, function(stepN) { 
        var an = fullHeader ? stepN : steps-stepN;
        setTimeout(function() { 
           resizeSplit("infosplit.header_ext", Math.round(an/pxPerEm) + "em"); 
        }, 0);
    }, function() { 
        if (!fullHeader) $('infosplit.header_ext').style.display = "none";
    });    
}

function resizeInfostoreSplitHeader(fullHeader) {
   setTimeout(function() {
   	    $('infosplit.header_ext').style.display = fullHeader ? "" : "none";
   	    resizeSplit("infosplit.header_ext", fullHeader ? "6em" : "0em"); 
   }, 0);
}

function enableInfostoreLoadingScreen(enabled) {
    if (enabled && $("infosplit.detail_container.content").style.display != "none") {
        $("infosplit.detail_container.content").style.display="none";
    } else if (!enabled && $("infosplit.detail_container.content").style.display != "block") {
        $("infosplit.detail_container.content").style.display="block";
    }
    if (!enabled && $("infosplit.detail_container.loading").style.display != "none") {
        $("infosplit.detail_container.loading").style.display="none";
    } else if (enabled && $("infosplit.detail_container.loading").style.display != "block") {
        $("infosplit.detail_container.loading").style.display="block";
    }    
}

function openInfostoreFile(evt, sValueCl, nObjectIdCl, triggerSave) {
    
    // Chrome always downloads or directly opens a file (i.e., it never shows content inline)
    if (triggerSave || ox.browser.Chrome) {
        // download
        ox.api.infostore.download({
            id: nObjectIdCl,
            filename: sValueCl
        });
    } else {
        ox.api.infostore.open({
            id: nObjectIdCl,
            filename: sValueCl
        });
    }
    stopEvent(evt);
}

function updateInfostoreSplit(object) {
    if (!object || activemodule != "infostore") return;
    
    // changing the selection jumps back to overview tab
//    if (currentpath2[2] != "overview") { 
//        triggerEvent("OX_Switch_View", "infostore/split/overview");
//    }
    
    activeTaskId = new Array();
    activeTaskId[0]=object;
    aPrintDetailInfoStore=object;
    
    // disable or enable some of the areas before we go on
    if ($("infosplit.file_info").style.display != "none") {
        $("infosplit.file_info").style.display="none";
    }
    if ($("infosplit.link_info").style.display != "none") {
        $("infosplit.link_info").style.display="none";
    }
    if ($("infosplit.expand_plus").style.display != "") {
    	$("infosplit.expand_plus").style.display = "";
    }
    $("infosplit.preview_image").src=getFullImgSrc("img/dummy.gif");
    $("infosplit.preview_image").style.border="none";
    
    $("infosplit.direct_link").firstChild.data = getDirectLinkLocal(object);
    
    var finalResize = configGetKey("gui.infostore.fullsplitheader");
    writeBottomString(object,"infosplit.bottom_str");
    
    for (idfield in object) {
        var idvalue = object[idfield];         
        switch (idfield) {
        	case "description":
                  removeChildNodes($("infosplit." + idfield));
                  idvalue = idvalue || "";                    
                  var nText = idvalue.split("\n");
                  for (var i in nText) {
                      $("infosplit." + idfield).appendChild(document.createTextNode(nText[i]));
                      $("infosplit." + idfield).appendChild(newnode("br"));
                  }
                  continue;
                  break;            
            case "color_label":
                  var img = idvalue || "0";
                  $("infosplit." + idfield).src = getFullImgSrc("img/menu/tag_"+img+".gif");
                  continue;
                  break;
            case "filename":
                  if (!idvalue) continue;
                  removeChildNodes($("infosplit."+idfield));
                  
                  var oNodAncS = newnode("img", { paddingRight:"5px" },{ className: "cursorPointer", align:"absmiddle", src:getFullImgSrc("img/menu/attachment_save.gif") })
                  oNodAncS.onclick = (function(idvalue, object) { 
            	         return function(e) {
            	            // save
            	         	openInfostoreFile(e || event, idvalue, object["id"], true);
            	         } 
    	          })(idvalue, object);
	              $("infosplit."+idfield).appendChild(oNodAncS);
                  
	              function _openFile(idvalue, object) { 
                	  return function(e) {
                	      // called from link
                		  openInfostoreFile(e || event, idvalue, object["id"]);
                	  }
                  }
	              
                  var oNodAnc = newnode("span", 0, {className:"linkstyle"},
                        [ document.createTextNode(idvalue) ]);  
                  oNodAnc.onclick = _openFile(idvalue, object);
                  
                  var img = newnode("img", { paddingRight:"5px" },{ className: "cursorPointer", align:"absmiddle", src:getFullImgSrc("img/mail/open_ISattachment.gif") });
                  img.onclick = _openFile(idvalue, object);
                  
                  $("infosplit."+idfield).appendChild(img);
                  $("infosplit."+idfield).appendChild(oNodAnc);
                  
                  $("infosplit.file_info").style.display="";
                  continue;
                  break;
            case "url":
                  // hide document details if no document is available
                  if (!object["filename"] && $("infosplit.expand_plus").style.display != "none") {
                  	    $("infosplit.expand_plus").style.display="none";                  	
                  	    finalResize = false;
                  }
                  // if URL is available hide show it
                  if (idvalue && $("infosplit.link_info").style.display != "") {
                        $("infosplit.link_info").style.display="";
                  }
                  removeChildNodes($("infosplit."+idfield));
                  $("infosplit."+idfield).appendChild(
                        newnode("a",0,{className:"linkstyle", href: idvalue, target: "_blank"},
                                [ document.createTextNode(idvalue)]));
                  continue;
                  break;
            case "file_size":
                  // image pre-loader
                  $("infosplit.preview_image").width="25";
                  $("infosplit.preview_image").height="25";
                  // check if file is image and smaller as the pre-defined size
                  // if so, we start to pre-load the image              
                  if (idvalue && idvalue <= (InfoStore.IMAGE_MAX_FILE_SIZE) && object["file_mimetype"] && 
                      object["file_mimetype"].match(/image\//g) && object["filename"]) {
                  	   $("infosplit.preview_image").style.border="1px solid";
                  	   $("infosplit.preview_image").src=getFullImgSrc("img/ox_animated_withoutbg.gif");
                  	   img = AjaxRoot + '/infostore/' 
                                        + encodeURIComponent(object["filename"])
                                        + '?action=document&session=' + session
                                        + '&content_type=' + encodeURIComponent(object["file_mimetype"])
                                        + '&id=' + encodeURIComponent(object["id"]);
                       var preImg = new Image();
                       preImg.src = img;
                       var timer, control = 1;
                       // check if image has been loaded, then set new image
                       // the check will be done each second, 10 times max 
                       function checkLoaded() {
                            if (preImg.complete) {
                            	$("infosplit.preview_image").src=preImg.src;                            	
                            	var newWidth = Math.floor(preImg.width/Math.floor(preImg.height/72));
                            	$("infosplit.preview_image").width = newWidth != "Infinity" ? newWidth : preImg.width;
                            	$("infosplit.preview_image").height= preImg.height > 72 ? 72 : preImg.height;
                            	clearTimeout(timer);
                            	delete(timer);
                            } else if (control <= 10) {
                                control++;
                                timer = setTimeout(checkLoaded,1000);
                            }
                       }
                       checkLoaded();               
                  }                  
                  idvalue = idvalue ? bytesToString(idvalue) : null;
                  break;
            case "file_mimetype":
                  if (!idvalue) continue;
                  removeChildNodes($("infosplit."+idfield));
                  $("infosplit."+idfield).appendChild(
                    newnode("img", { paddingRight: "5px"}, { src: getMimeImage(idvalue), align: "absmiddle"}));
                  $("infosplit."+idfield).appendChild(document.createTextNode(idvalue));
                  continue;
                  break;
            case "modified_by":
                  if (!idvalue || !object["locked_until"]) {
                  	idvalue = null;
                  	break;
                  }
                  var fnSetModifiedBy = (function fnSetModifiedBy(idfield, idvalue, lockedUntil) {
                      return function(arg) {
                          $("infosplit." + idfield).firstChild.data =
                                //#. Information about a locked InfoItem
                                //#. %1$s is the name of the user who locked the Infoitem.
                                //#. %2$s is the expiration date of the lock.
                                //#, c-format
                                format(_("by %1$s until %2$s"), arg[idvalue].display_name, 
                                        formatDate(lockedUntil, "datetime")); 
                      }
                  })(idfield, idvalue, object["locked_until"]);
                  internalCache.getUsers([idvalue],fnSetModifiedBy);
                  continue;
                  break;
            case "categories":
        		  var cat = (idvalue || "");
                  $("infosplit."+idfield).style.display = cat.length ? "" : "none";                  
                  if (cat.length) {
	                  if (Object.prototype.toString.call(cat) == "[object Array]") {
	                	  cat = cat.join(", ");
	                  }
	                  ox.categories.ui.drawCategoriesList(ox.categories.getByString(cat), 
	                		  $("infosplit."+idfield+"_d"));
                  } else {
                	  removeChildNodes($("infosplit."+idfield+"_d"));
                  }
                  continue;
                  break;
            case "folder_id":
                  if (!idvalue) continue;
                  infostore_folderPathDetail.drawDOMNode("infosplit.folder_id", idvalue);
                  continue;
                  break;
        }        
        if ($("infosplit." + idfield)) {
            $("infosplit." + idfield).firstChild.data = idvalue != null ? idvalue : _("Not set");
        }
    }
    enableInfostoreLoadingScreen(false);
    setTimeout(function() {
    	   resizeInfostoreSplitHeader(finalResize);
        },0);
}

function cb_infostore_selection_changed() {
    if (!infostoreSelection.getSelected().length) return;   
    fn_infostore_getDetails(infostoreSelection.getSelected());        
}

function clearInfostoreSplitDetails() {
    $("infosplit.detail_container.content").style.display="none";
    $("infosplit.detail_container.loading").style.display="none";
    if ($("infosplit.bottom_str").firstChild) {
    	$("infosplit.bottom_str").firstChild.data="\u00a0"; // clean bottom str
    }
    if (currentpath2[1] == "split" && currentpath2[2] != "overview") { 
        triggerEvent("OX_Switch_View", "infostore/split/overview");
    }
}

function clearInfoTable(sId) {
    var DOMSplitTable = $(sId);
    var aDivs = DOMSplitTable.getElementsByTagName('div');
    var len = aDivs.length;
    for(nDiv=0;nDiv < len;nDiv++) { 
        if(aDivs[nDiv]) { removeChildNodes(aDivs[nDiv]); }
    }
}

function gridInfoSplitSort_Func(id, order) {
	var criteria= { "folder_id" : activefolder };
	gridInfoSplit.disablehover=!configGetKey("gui.effects.hover.infostore");
    gridInfoSplit.enable(criteria,false);
    bInfoSplitLoaded = true;
}

function loadLiveGridInfoSplit() {	
	bSearchInfoItemMode = false;	
	if(!bInfoSplitCreated) {
		bInfoSplitCreated = true;
		var clear = LiveGrid.makeClear("");
		var DomListDiv = $("lg_info_split");
		var DomListDivHeader = $("lg_info_splitHeader");
		gridInfoSplit = new LiveGrid2([
			{					
				name : ["locked_until", "modified_by"],
				text: "&#xa0;",
				width: "20px",
				style: { padding: 0, textAlign: "center" },
				sortable: false,		
				set: function(div, content) {
					if (!div.firstChild) {
						div.appendChild(newnode("img", { paddingTop: "1px", width: "16", height: "16" },{ align: "top" }));
					}
					div.firstChild.src = content["locked_until"] > 0 ? 
					       getFullImgSrc("img/folder/document_locked.gif") : 
					       getFullImgSrc("img/folder/document.gif");
				},
				clear: function(div) {
					if (!div.firstChild) {
						div.appendChild(newnode("img", { paddingTop: "1px", width: "16", height: "16" },{ align: "top" }));
					}
					div.firstChild.src = getFullImgSrc("img/mail/noattachment.gif");
				}
			}, {
				name : ["file_size", "filename", "id", "folder_id"],
				text: "&#xa0;",
				sortable: false,
				width: "11px",	
				style: { padding: 0, textAlign: "center" },
				set: function(div, content) {
					if (!div.firstChild) {
						div.appendChild(newnode("img", { paddingTop: "2px", width: "7", height: "14"  },{ align: "top" }));
					}
					div.firstChild.src = (content["file_size"]>0) ? getFullImgSrc("img/mail/attachment.gif")
					                             : getFullImgSrc("img/mail/noattachment.gif");
					                             
					if (content["file_size"]>0) {
                        div.firstChild.onclick = (function(idvalue, object) { 
                             return function(e) {
                                openInfostoreFile(e || event, idvalue, object["id"]);
                             } 
                        })(content["filename"], content);
                        div.firstChild.style.cursor="pointer";
                        div.firstChild.title=_("Download") + " " + content["filename"];
                    } else {
                    	div.firstChild.onclick = null;
                    	div.firstChild.style.cursor="default";
                        div.firstChild.title="";
                    }
				},
				clear: function(div) {
					if (!div.firstChild) {
						div.appendChild(newnode("img", { paddingTop: "2px", width: "7", height: "14" },{ align: "top" }));
					}
					div.firstChild.src = getFullImgSrc("img/mail/noattachment.gif");
				}
			}, {
				name : ["title"],
                i18n: "description", /*i18n context*/
				text: "Title", /*i18n*/
				sortable: true,
				sort : "title",
				set: LiveGrid.defaultSet,					
				clear: LiveGrid.makeClear("")
			}, {
				name : ["file_size"],
				text: "Size", /*i18n*/
				i18n: true,
				sortable: true,
				sort : "file_size",
				width: "6em",
				set: function (div, text) {
					if (text < 0) {
						var sDisplayString = "";
					} else {
						var sDisplayString = bytesToString(text);
					}
					if (div.firstChild) {
						div.firstChild.data = sDisplayString;
					} else {
						div.appendChild(document.createTextNode(sDisplayString));
					}
				},
				clear: LiveGrid.makeClear("")
			}, {
				name : ["creation_date"],
				text: "Created on", /*i18n*/
				i18n: true,
				sortable: true,
				sort : "creation_date",
				width: "8em",
				set: LiveGrid.dateSet,
				clear: LiveGrid.makeClear("")
			}, {
				name : ["created_by"],
				text: "Created by", /*i18n*/
				i18n: true,
				sortable: true,
				sort : "created_by",
				width: "20%",			
				set: function  (div, text) {
					var nId = parseInt(text);											
					function cb_fetchUserFromCache(){
						return function (arg) {
							if (div.firstChild) {
								div.firstChild.data = arg[nId].display_name;
							} else {
								div.appendChild(document.createTextNode(arg[nId].display_name));
							}
						}
					}
					internalCache.getUsers([nId],cb_fetchUserFromCache());		
				},
				clear: LiveGrid.makeClear("")
			}, {
				name : ["version"],			
				text: "Version", /*i18n*/
				i18n: true,
				style:{textAlign:"center"},
				sortable: true,
				sort : "version",
				width: "6em",			
				set: LiveGrid.defaultSet,					
				clear: LiveGrid.makeClear("")
			}, {				
				name : ["last_modified"],
				text: "Last modified", /*i18n*/
				i18n: true,				
				sortable: true,
				sort : "last_modified",
				width: "10em",
				set: function(div, modified) {
					var dateToShow = modified ? formatDate(modified, isToday(modified) ? "time" : "datetime") : "";
				    if (!div.firstChild) {
				    	div.appendChild(div.ownerDocument.createTextNode(dateToShow));
				    } else {
				    	div.firstChild.data = dateToShow;
				    }
				},
				clear: LiveGrid.makeClear("")
			}, {
				name : ["color_label"],		
				text: "Flag", /*i18n*/
				i18n: true,				
				sortable: true,
				sort : "color_label",
				width: "4em",
				style: { padding: 0, textAlign: "center" },
				set: function(div, content) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", { paddingTop: "2px", width: "16", height: "16" },{ align: "top" }));
                    }
                    div.firstChild.src = getFullImgSrc("img/menu/tag_"+ (content || 0 ) +".gif");
                },
                clear: function(div) {
                    if (!div.firstChild) {
                        div.appendChild(newnode("img", { paddingTop: "2px", width: "16", height: "16" },{ align: "top" }));
                    }
                    div.firstChild.src = getFullImgSrc("img/menu/tag_0.gif");
                }
			}
		], infostoreSelection, "infostore");
        gridInfoSplit.contextmenu = globalContextMenus.infostore;
		//gridInfoSplit.sort = gridInfoSplitSort_Func;
		DomListDivHeader.appendChild(gridInfoSplit.getHeader());
		gridInfoSplit.getTable(DomListDiv);
		gridInfoSplit.events.register("Selected", function(ids){
			setLastSelected(ids);			
			if (ids == 1)  {                
                cb_infostore_selection_changed();                
            } else if (currentpath2[1]=="split") {
                clearInfostoreSplitDetails();
            }
            var selected = gridInfoSplit.getSelectedIDs();
			checkLockUnLock(selected);
            checkLockUnLock.wait(function() {
                triggerEvent("Selected", selected);
            });
		});
		gridInfoSplit.events.register("Activated", function(ids){
			if(ids && ids.length > 0) {
			    // instead of edit, download them
			    // firefox - for whatever reason - needs a delay (some conflict with doubleclick)
			    setTimeout(function () {
                    saveFileinInfoStore(ids);
                }, 250);
			} else {
				triggerEvent("OX_Before_Create_InfoStore");
			}
		});
        gridInfoSplit.events.register("Delete", function(ids) {
            checkLockUnLock.wait(function() {
                if (   menucheckRight("DELETE") && (ids.length > 0)
                    && (ids.length == menucountlockable))
                {
                    deleteItems();
                }
            });
        });
		gridInfoSplit.events.register("Changed",infostore_HeaderUpdate);
		var hv = gridInfoSplit.addHover(OXInfostoreHover.getContent().node, function(id) {
	        OXInfostoreHover.actualHover=hv;
	        OXInfostoreHover.refillContent(id.id,id.folder_id);                 
	    });
	    hv.setSize(OXInfostoreHover.contentobject.node);
	}
    if (bInfoListCreated) {    
        gridInfoSplit.setSort(gridInfoList.sort_id,gridInfoList.sort_order);        
    }
	gridInfoSplitSort_Func(gridInfoSplit.sort_id, gridInfoSplit.sort_order);
}

/********************************** VERSION TAB **********************************/

function loadDetailDocumentVersions(arg, cb_functionDetail) {   
    if(arg=='version') {
        var oObjectIdObj = oLastSelectedInfoObject[0];
        function setDocSize(div, text) {
            if(text < 0 ) { var sDisplayString = ''; }
            else { var sDisplayString = bytesToString(text); }
            
            if (div.firstChild) { div.firstChild.data = sDisplayString; }
            else { div.appendChild(document.createTextNode(text)); }
        }   
        if(!bVersionCreated) {
	        bVersionCreated = true; 
	        var clear = LiveGrid.makeClear("...");
	        var DomListDiv = $("lg_versions_info_split");
	        var DomListDivHeader = $("lg_versions_info_splitHeader");
	        gridVersionsInfoSplit = new LiveGrid([
	        {
	            index: 1,
	            text: "Version", /*i18n*/
	            i18n: true,                     
	            width: "6em",                               
	            sortable: false,
	            set: LiveGrid.defaultSet,                   
	            clear: LiveGrid.makeClear("...")
	        }, {
	            index: 2,
	            text: "Created", /*i18n*/
	            i18n: true,                     
	            width: "8em",                               
	            sortable: false,
	            set: LiveGrid.dateSet,              
	            clear: LiveGrid.makeClear("...")
	        }, {
	            index: 3,                   
	            text: "File", /*i18n*/
	            i18n: true,                     
	            sortable: false,
	            set: LiveGrid.defaultSet,                   
	            clear: LiveGrid.makeClear("...")
	        }, {
	            index: 4,       
	            text: "Mime Type", /*i18n*/
	            i18n: true,                     
	            sortable: true,
	            width: "15em",          
	            set: LiveGrid.defaultSet,                   
	            clear: LiveGrid.makeClear("...")
	        }, {
	            index: 5,                   
	            text: "Size", /*i18n*/
	            i18n: true,                     
	            width: "8em",                                                       
	            sortable: false, 
	            set: setDocSize,
	            clear: LiveGrid.makeClear("...")
	        }, {
	            index: 6,                   
	            text: "Current", /*i18n*/
	            i18n: true,                     
	            width: "6em",                                                       
	            sortable: false, 
	            set: function (div, text) {
	                if(text) var sDisplayString = _('Yes');
	                else
	                {
	                    var sDisplayString = _('No');
	                }
	                if (div.firstChild)
	                    div.firstChild.data = sDisplayString;
	                else
	                    div.appendChild(document.createTextNode(sDisplayString));
	            },              
	            clear: LiveGrid.makeClear("")
	        }], new Selection());
	        DomListDivHeader.appendChild(gridVersionsInfoSplit.getHeader());
	        gridVersionsInfoSplit.getTable(DomListDiv);
	        gridVersionsInfoSplit.events.register("Selected", function(ids) {
	            refreshDetailVersions(ids);
	            // map current array f|_|ck3l selection to a valid object selection
	            var result = [];
	            versionsStorage.newIterate(gridVersionsInfoSplit.getSelectedIDs(), jQuery.noop, 
                function(id, obj) {
	                // 705,705,4,702,703,704,710,2,709
	                result.push({ version: obj[1], creation_date: obj[2], 
	                    filename: obj[3], file_mimetype: obj[4], file_size: obj[5], 
	                    current_version: obj[6], created_by: obj[7], 
	                    version_comment: obj[8] });
	            }, function() { 
	                triggerEvent("SubSelected", result);
	            });
	        });
	        getVersions();
            var menu = gridVersionsInfoSplit.contextmenu = new ContextMenu();
            var current = new MenuItem(_("Current"),
                function() { triggerEvent('OX_InfoStore_Version_Current'); });
            current.setIcon("img/menu/infostorecurrentversion.gif",
                            "img/menu/infostorecurrentversion_d.gif");
            menu.addItem(current);
            var del = new MenuItem(_("Delete"),
                function() { triggerEvent('OX_InfoStore_Version_Delete'); });
            del.setIcon("img/menu/delete.gif", "img/menu/delete_d.gif");
            menu.addItem(del);
            var req;
            menu.onShow = function() {
                var collection = {
                    columns: ["created_by", "modified_by", "locked_until",
                              "file_size", "filename"],
                    objects: infostoreSelection.getSelected()
                };
                req = OXCache.newRequest(null, "infostore", collection,
                                   callback, callback);
                function callback(objects) {
                    var count = menu.getContext().count;
                    var hasRights;
                    if (count)
                        hasRights = menuhasRight(objects.objects, "WRITE")
                                 && checkRights(objects.objects);
                    current.setEnabled(count == 1 && hasRights);
                    del.setEnabled(count > 0 && hasRights);
                }
                function checkRights(objects) {
                    var me = configGetKey("identifier");
                    for(var i in objects) {
                        var obj = objects[i];
                        if(obj.locked_until && obj.modified_by != me) return false;
                    }
                    return true;
                }
            };
            menu.onHide = function() { OXCache.unregister(req.uniqueName); };
        } else {  
        	getVersions(cb_functionDetail); 
        }
    }
}

function getVersions(cb_functionVersion) {
    versionsStorage = new Storage(0, []);
    function cb_versions(arg) {
        versionsStorage.append(arg.data);
        versionsStorage.timestamp = arg.timestamp;
        nCurrentDetailItemTimestamp = versionsStorage.timestamp;
        gridVersionsInfoSplit.enable(versionsStorage);
        bDetailVersionLoaded = true; 
        if(cb_functionVersion) cb_functionVersion();
    }
    if (gridVersionsInfoSplit) {
        doAjaxFetchAllVersions(cb_versions);
    } else {
        if (cb_functionVersion) cb_functionVersion();
    };
}

function doAjaxFetchAllVersions(callback) {
    var sColumns = aCoumnsToFetch.join(",");
    var oObjectIdObj = oLastSelectedInfoObject[0];
    var sAjaxRequest = AjaxRoot + "/infostore?action=versions&id=" + oObjectIdObj.id + "&columns="+sColumns+"&session=" + session;
    new JSON().get(sAjaxRequest, null,callback);
}

function refreshDetailVersions(ids) {
    clearInfoTable('version_det_table');
    if (ids > 0) {
        var aSelIds = gridVersionsInfoSplit.getSelectedIDs();
        var aData = versionsStorage.data.data;
        var oObj = oLastSelectedInfoObject[0];
        var nVersionId =  aSelIds[0];
        var aDataSelected  =aData[nVersionId];

        for (nInd=0; nInd<aDataSelected.length; nInd++) {
            var nColumn = aCoumnsToFetch[nInd];         
            var PREFIX = "vers_detail_";
            var sDOMID = PREFIX + nColumn;      
            var sValue = aDataSelected[nInd];   
            if(nColumn == 2) {
                var newValue = sValue;
                var stopId = sDOMID;
                var arr = new Array();
                arr[0] = sValue;
                function fnSetUserColumn(arg) {                   
                    if (document.getElementById(stopId)) {
                        if ($(stopId).firstChild)
                            removeChildNodes($(stopId));
                        $(stopId).appendChild(document.createTextNode(arg[newValue].display_name || ""))
                    }
                }
                sValue = internalCache.getUsers(arr,fnSetUserColumn);
                continue;
            }
            if (nColumn == 702) {
                var oNodAnc = newnode("span",0,{className:"linkstyle"});
                function openFIleInfoStore(evt) {               
                    var sContentType = 'application/octet-stream';
                    var sURL = AjaxRoot + '/infostore/' + encodeURIComponent(sValue)
                            + '?action=document&session=' + session
                            + '&content_type=' + encodeURIComponent(sContentType)
                            + '&id=' + encodeURIComponent(oObj.id)
                            + '&version=' + encodeURIComponent(nVersionId);
                    $('dlIframe').src = sURL;   
                    stopEvent(evt);
                }
                var oTextNode = document.createTextNode(sValue);                
                addDOMEvent(oNodAnc,"click",openFIleInfoStore);             
                document.getElementById(sDOMID).appendChild(oNodAnc);                       
                oNodAnc.appendChild(oTextNode);       
                continue;
            }
            if ($(sDOMID)) {   
                if ($(sDOMID).firstChild)
                    removeChildNodes($(sDOMID));        
                 //version comment
                if (nColumn == 709 && typeof(sValue) == "string") {
                    //sValue = sValue.replace(/\n/g,'<BR>');
                    var text = sValue.split("\n");
                    for (var i = 0; i < text.length; i++) {
                        $(sDOMID).appendChild(document.createTextNode(text[i]));
                        $(sDOMID).appendChild(newnode("br"));
                    }                   
                } else {
                    $(sDOMID).appendChild(document.createTextNode(sValue));             
                }
            }
        }
    }
}

function deleteDetailVersion() {
    function cbyes() {
        var oObjectIdObj = oLastSelectedInfoObject[0];  
        var aVersions = gridVersionsInfoSplit.getSelectedIDs();
        var nTimeStamp = versionsStorage.timestamp;
        
        function cb_detach_version(arg) { getVersions(); }
        doAjaxDetachVersion(oObjectIdObj,aVersions,nTimeStamp,cb_detach_version);
    }
    newConfirm(_("Delete Version"),_('Are you sure you want to delete the selected version?'),AlertPopup.YESNO,null,null,cbyes);
}

function setCurrentVersion() {   
    var oObjectIdObj = oLastSelectedInfoObject[0];  
    var aVersions = gridVersionsInfoSplit.getSelectedIDs();
    var nVersion = aVersions[0]; //one Selected...
    var nTimeStamp = versionsStorage.timestamp;
    function cb_set_current(arg)  { 
    	getVersions(findVersion); 
    }
    function findVersion() {
        versionsStorage.newIterate([nVersion], emptyFunction, updateCache);
    }
    function updateCache(n, data) {
    	OXCache.newRequest(null, "infostore", { columns: null,
            objects: [oObjectIdObj] }, null, emptyFunction, true);
    }
    var newInfoItem = new Object();
    newInfoItem['version'] = parseInt(nVersion);
    doAjaxRequestUpdateItem(oObjectIdObj,newInfoItem,nTimeStamp,cb_set_current);
}

function doAjaxRequestUpdateItem(oId,newInfoItem,nTimeStamp,callback) {
    var sAjaxRequest = AjaxRoot + "/infostore?action=update&id="+oId.id+"&timestamp="+nTimeStamp+"&session=" + session;
    new JSON().put(sAjaxRequest, newInfoItem, null,callback);      
}

function doAjaxDetachVersion(oObjectIdObj,aVersions,nTimeStamp,callback) {
    var sAjaxRequest = AjaxRoot + "/infostore?action=detach&id=" + oObjectIdObj.id +"&session=" + session + 
                                    "&folder=" +oObjectIdObj.folder + "&timestamp=" + nTimeStamp;
    new JSON().put(sAjaxRequest, aVersions,null,callback);
}

fileloaded();