/**
 * 
 * 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) 2004-2010 Open-Xchange, Inc.
 * Mail: info@open-xchange.com 
 * 
 * @author Andreas Mayer <andreas.mayer@open-xchange.com>
 * 
 */

var bInfoListLoaded = false;
var bInfoListCreated = false;
var gridInfoList;
var editInfoItemId = -1;
var bSearchInfoItemMode = false;
var lockedDetailInformation;

//works only in editr mode...
function deleteSearchInfoItem() {
	if(currentpath[0] == "infostore" && currentpath[1] == "list") {
		loadLiveGridInfo();		
	} else if(currentpath[0] == "infostore" && currentpath[1] == "split") {
		loadLiveGridInfoSplit();		
	}
	infostoreFolderPath.drawDOMNode("infostoreHsplitHeaderOwner", activefolder);
}
function searchInfoItem(sModule,sPattern) {
	if (sModule=="infostore") {
	    bSearchInfoItemMode = true;
        var criteria={};
        var search={ 
            title : sPattern , url : sPattern, filename : sPattern, 
            version_comment : sPattern, categories : sPattern, description : sPattern 
        }; 
	    if(currentpath2[1]=="list") {
	        gridInfoList.disablehover=!configGetKey("gui.effects.hover.infostore");
            gridInfoList.enable(criteria,search,false);
        } else if(currentpath2[1] == "split") {
           gridInfoSplit.disablehover=!configGetKey("gui.effects.hover.infostore");
           gridInfoSplit.enable(criteria,search,false);
	    } else {
           menuswitchInfoStoreView("list");
           gridInfoList.disablehover=!configGetKey("gui.effects.hover.infostore");
           gridInfoList.enable(criteria,search,false);
	    }
	    infostoreFolderPath.drawSearch(sModule, sPattern);
	}
}

function setTagInfoStore(tag) {
	var newInfoItem = new Object();
	newInfoItem['color_label'] = parseInt(tag);	
	var selected = oLastSelectedInfoObject;
	if (currentpath[1] == "detail" && oLastSelectedInfoObject) {
		selected[0]["timestamp"] = OXCache.cachedObjects.get(oLastSelectedInfoObject[0])["timestamp"];
	}
	OXInfoStoreMapping.setTag(tag,selected);
}

function setLastSelected(ids)
{
	if(gridInfoList && gridInfoList.collection)
	{
		oLastSelectedInfoObject = gridInfoList.getSelectedIDs();
	}
	else if(gridInfoSplit && gridInfoSplit.collection)
	{
		oLastSelectedInfoObject = gridInfoSplit.getSelectedIDs();
	}
}
function lockItem() {
	var oItemToLock;
	var bUnlocked = -1;
	var aData;
	if(gridInfoList && gridInfoList.collection) {
		oItemToLock = gridInfoList.getSelectedIDs();
		var obj = OXCache.cachedObjects.get(oItemToLock[0]);
		bUnlocked = (obj["locked_until"] == 0);
	} else if(gridInfoSplit && gridInfoSplit.collection) {
		oItemToLock = gridInfoSplit.getSelectedIDs();
		var obj = OXCache.cachedObjects.get(oItemToLock[0]);
		bUnlocked = (obj["locked_until"] == 0);
	} else if(oLastSelectedInfoObject) {
		oItemToLock = oLastSelectedInfoObject;
		bUnlocked = (lockedDetailInformation==0);			
	}
	if(oItemToLock)  {
		function cb_lock(arg) {
            for(var indx=0;indx<arg.length;indx++) {
                if(arg[indx].error_id) { newServerError(arg[indx]); }       
            }
            OXInfoStoreMapping.editObjectsInternal(oItemToLock, {});
            checkLockUnLock(oItemToLock);
        }
		var aRequests = new Array();
		for(var indx=0;indx<oItemToLock.length;indx++) {
			var oReqObj = new Object();			
			oReqObj["module"] = "infostore";
			if(bUnlocked) {
				oReqObj["action"] = "lock";
			} else {
				oReqObj["action"] = "unlock";				
			}
			oReqObj["id"] = oItemToLock[indx].id;
			aRequests.push(oReqObj);
		}
		doAjaxLockRequest(aRequests,cb_lock);				
	}
}
function doAjaxLockRequest(aRequests,callback)
{
	var JsonObj = new JSON();	
	JsonObj.put(AjaxRoot + "/multiple?session=" + session,aRequests,null,callback)
}
function unLoadLiveGridInfoList()
{
	if(bInfoListLoaded)
	{
		gridInfoList.disable();
		bInfoListLoaded = false;
	}
	unregister('OX_InfoStore_Delete', deleteItems);
	unregister('OX_InfoStore_Edit', editItem);
	unregister('OX_InfoStore_Lock', lockItem);		
	unregister('OX_InfoStore_Unlock', lockItem);	 			
}

function editItem() {	
	if(gridInfoList && gridInfoList.collection)
		var aEditObjectIds = gridInfoList.getSelectedIDs();
	else if(gridInfoSplit && gridInfoSplit.collection)
		var aEditObjectIds = gridInfoSplit.getSelectedIDs();
	else
		return;
	editInfoItemId = aEditObjectIds[0];
	openNewInfoPopup("infostore",editInfoItemId.folder_id);
}

var delJSON = new JSON();
function deleteItems() {
	function cbyes() {
		var ids=infostoreSelection.getSelected();
		OXInfoStoreMapping.deleteObjects(ids, function() {
			triggerEvent("OX_Quota_Update");		
		});
	}
	
	if(gridInfoList && gridInfoList.collection) { var aDeleteObjectIdsCount = gridInfoList.getSelectedIDs().length; }
	else if(gridInfoSplit.collection) { var aDeleteObjectIdsCount = gridInfoSplit.getSelectedIDs().length; }
	
	if (aDeleteObjectIdsCount > 1) {  var confirmTextForDeleteInfoStore = _('Are you sure you want to delete selected items?'); } 
	else { var confirmTextForDeleteInfoStore = _('Are you sure you want to delete the selected item?'); }
	var confirmHeadForDeleteInfoStore = _("Delete Items");
	newConfirm(confirmHeadForDeleteInfoStore,confirmTextForDeleteInfoStore,AlertPopup.YESNO,null,null,cbyes,null);
}
var infoUserStorage;
var listUserMappingArray = new Array();		
	
function replaceUserNames()
{
	for(var nIndx=0;nIndx<listUserMappingArray.length;nIndx++) {
		var aIds = new Array();
		aIds.push(listUserMappingArray[nIndx].uid);
	}
	internalCache.getUsers(aIds, function (arg) {
		for(var nIndx=0;nIndx<listUserMappingArray.length;nIndx++)
		{	
			if(arg[listUserMappingArray[nIndx].uid]) {
				if (listUserMappingArray[nIndx].div.firstChild) {
					listUserMappingArray[nIndx].div.firstChild.data = arg[listUserMappingArray[nIndx].uid].display_name;
				} else {
					listUserMappingArray[nIndx].div.appendChild(document.createTextNode(arg[listUserMappingArray[nIndx].uid].display_name));
				}
			}
		}
	});		
}	

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

function loadLiveGridInfo()
{		
	bSearchInfoItemMode = false;
	register('OX_InfoStore_Delete', deleteItems);
	register('OX_InfoStore_Edit', editItem);
	register('OX_InfoStore_Lock', lockItem);
	register('OX_InfoStore_Unlock', lockItem);	
	if(!bInfoListCreated) {		
		bInfoListCreated = true;
		var clear = LiveGrid.makeClear("");
		var DomListDiv = $("lg_info_list");
		var DomListDivHeader = $("lg_info_listHeader");
	    var constructor= LiveGrid2; 
	    
	    temporary.lists.infostore = temporary.MakeList({
	        updated: function() { gridInfoList.recreate(); },
	        columns: [
                {                   
                    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");
                    }
                }
            ]
	    });
	    
	    gridInfoList = new LiveGrid2(temporary.lists.infostore.columns,
	        infostoreSelection, "infostore");
        
        gridInfoList.contextmenu = globalContextMenus.infostore;
		
		DomListDivHeader.appendChild(gridInfoList.getHeader());
		gridInfoList.getTable(DomListDiv);
		gridInfoList.events.register("Selected", function(ids){
				setLastSelected(ids);
				var selected = gridInfoList.getSelectedIDs()
				checkLockUnLock(selected);
                checkLockUnLock.wait(function() {
                    triggerEvent("Selected", selected);
                });
		});
		gridInfoList.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");
			}
		});		
        gridInfoList.events.register("Delete", function(ids) {
            checkLockUnLock.wait(function() {
                if(   menucheckRight("DELETE") && (ids.length > 0)
                   && (ids.length == menucountlockable))
                {
                    deleteItems();
                }
			});
	    });
		gridInfoList.events.register("Changed",infostore_HeaderUpdate);
	    var hv = gridInfoList.addHover(OXInfostoreHover.getContent().node, function(id) {
	        OXInfostoreHover.actualHover=hv;
	        OXInfostoreHover.refillContent(id.id,id.folder_id);                 
	    });
	    hv.setSize(OXInfostoreHover.contentobject.node);
	}
	if (bInfoSplitCreated) { 
		gridInfoList.setSort(gridInfoSplit.sort_id,gridInfoSplit.sort_order); 
	}
	gridInfoListSort_Func(gridInfoList.sort_id, gridInfoList.sort_order);
	
}
fileloaded();