/**
 * 
 * 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 infostoreSelection = new Selection2();
var infoSplitTabsList;
var infoSplitPanelsList;
var infoSplitEventList;
var oLastSelectedInfoObject = -1;
var propertiesPopUp;
var bLoadedDetailViewOverView = false;
var aPrintDetailInfoStore;
var infostoreFolderPath;

registerPrintView("infostore/list");
registerPrintView("infostore/split/overview");
registerModule("infostore", _("InfoStore"), 60);
registerModuleView("infostore","InfoStore",5,{x:0,y:1,ww:1,hw:1});

register("Loaded", function() {	
	infostoreFolderPath = new FolderPath("infostore");
    register("OX_Switch_InfoStore_Detail",function(param) { menuswitchInfoStoreDetail(param) }); 
	infoSplitTabsList = new Array('tab_infodetail1','tab_infodetail2');
    infoSplitPanelsList = new Array('panel_infodetail1','panel_infodetail2');
    infoSplitEventList = new Array(
            ['OX_Switch_InfoStore_Detail','overview'],
            ['OX_Switch_InfoStore_Detail','version']
    );
	
    var menu = new PulldownMenu($("arrowForInfostoreListOptions"));
    menu.addItem((new MenuItem(_("Options"), showOptions))
                  .setIcon("img/folder/settings.gif"));
    var menu = new PulldownMenu($("arrowForInfostoreSplitOptions"));
    menu.addItem((new MenuItem(_("Options"), showOptions))
                  .setIcon("img/folder/settings.gif"));
    function showOptions() {
        var elem=currentpath2.join("/");
        if(elem.indexOf("infostore") == 0) {
            ox.UIController.setModule({
                module: "configuration",
                view :"configuration/infostore/preferences",
                success: function() {
                    ox.widgets.configTree.get("configuration/infostore").open();
                    ox.widgets.configTree.selection.click("configuration/infostore/preferences", false,
                        false, true);
                }
            });
        }   
    }
});

registerView("infostore",
        null,
        null,       
        function() {
            triggerEvent("Selected",[]);        
        }, 
        function() {
            if (infostoreRequest) {
                OXCache.unregister(infostoreRequest.uniqueName);
                infostoreRequest=null;
            }
            triggerEvent('OX_Delete_Search');
        },
        null        
);

registerView("infostore/list",
        function() { 
			showNode("infostore_list"); 
			$("infostore_list").style.display=""; 
		}, 
		function() { 
			loadLiveGridInfo();
			if (gridInfoList) {				
				infostore_setFocus(gridInfoList);
			}
			register('OX_InfoStore_Delete', deleteItems);
            register('OX_InfoStore_Edit', editItem);
            register('OX_InfoStore_Lock', lockItem);
            register('OX_InfoStore_Unlock', lockItem);
			register('OX_Add_Flag',setTagInfoStore);			
			register("OX_New_Search",searchInfoItem);
			register("OX_Delete_Search",deleteSearchInfoItem);			
			register("OX_Print",infostore_print);
			register("OX_InfoStore_Send_Attachment",infostore_sendAttachment);
			if ("infostore_sendLink" in window) {
				register("OX_InfoStore_Send_Link",infostore_sendLink);
			}
			register("OX_InfoStore_Open_Attachment",openFileinInfoStore);
            register("OX_InfoStore_Save_Attachment",saveFileinInfoStore);
        }, 
        function() {
			unLoadLiveGridInfoList();
			infostoreFolderPath.clear();
			unregister('OX_InfoStore_Delete', deleteItems);
            unregister('OX_InfoStore_Edit', editItem);
            unregister('OX_InfoStore_Lock', lockItem);
            unregister('OX_InfoStore_Unlock', lockItem);
			unregister('OX_Add_Flag',setTagInfoStore);		
			unregister("OX_New_Search",searchInfoItem); 
			unregister("OX_Delete_Search",deleteSearchInfoItem);									
			unregister("OX_Print",infostore_print);	
			unregister("OX_InfoStore_Send_Attachment",infostore_sendAttachment);
			if ("infostore_sendLink" in window) {
				unregister("OX_InfoStore_Send_Link",infostore_sendLink);
			}
			unregister("OX_InfoStore_Open_Attachment",openFileinInfoStore);
            unregister("OX_InfoStore_Save_Attachment",saveFileinInfoStore);
            triggerEvent('OX_Delete_Search');
        },
        function() {
			hideNode("infostore_list"); 
			$("infostore_list").style.display="none";
		},
        function(changedFolder) {
        	if (changedFolder != undefined) {
        	    triggerEvent('OX_Delete_Search');
        		 loadLiveGridInfo();
        		 if (gridInfoList) {
        		    infostore_setFocus(gridInfoList); 				    
        		 }
        	}	
        }
);

registerView("infostore/split",
        function() { 
            showNode("infostore_split"); 
            $("infostore_split").style.display=""; }, 
        function() {
            loadLiveGridInfoSplit();                      
            setTabLists(infoSplitTabsList, infoSplitPanelsList, infoSplitEventList);
            if (gridInfoSplit) {            	
                infostore_setFocus(gridInfoSplit);
            }           

            // re-select id, if it's a direct link for example
            if (oLastSelectedInfoObject.length && oLastSelectedInfoObject[0].directLink &&
                oLastSelectedInfoObject[0].id) {
                delete(oLastSelectedInfoObject[0].directLink);
                gridInfoSplit.selection.selectIDs([ Key.createfromObject(oLastSelectedInfoObject[0]) ])
            } else {
                gridInfoSplit.selection.selectIDs(
                    gridInfoSplit.selection.getSelected());
            }
            expandInfostoreSplitHeader(configGetKey("gui.infostore.fullsplitheader"));
            
            register('OX_InfoStore_Delete', deleteItems);
            register('OX_InfoStore_Edit', editItem);
            register('OX_InfoStore_Lock', lockItem);
            register('OX_InfoStore_Unlock', lockItem);  
            register('OX_Add_Flag', setTagInfoStore);
            register("OX_New_Search", searchInfoItem);
            register("OX_Delete_Search", deleteSearchInfoItem); 
            register("OX_Print",infostore_print);     
            register("OX_InfoStore_Send_Attachment", infostore_sendAttachment);
            if ("infostore_sendLink" in window) {
            	register("OX_InfoStore_Send_Link", infostore_sendLink);
            }
            register("OX_InfoStore_Open_Attachment", openFileinInfoStore);  
            register("OX_InfoStore_Save_Attachment", saveFileinInfoStore);  
        }, 
        function() {
            if (infostoreRequest) {
                OXCache.unregister(infostoreRequest.uniqueName);
                infostoreRequest=null;
            }
            if (bInfoSplitLoaded) { 
		        gridInfoSplit.disable();
		        bInfoSplitLoaded = false;
		    }
            infostoreFolderPath.clear();
            unregister('OX_InfoStore_Delete', deleteItems);
            unregister('OX_InfoStore_Edit', editItem);
            unregister('OX_InfoStore_Lock', lockItem);
            unregister('OX_InfoStore_Unlock', lockItem); 
            unregister('OX_Add_Flag', setTagInfoStore);
            unregister("OX_New_Search", searchInfoItem);
            unregister("OX_Delete_Search", deleteSearchInfoItem);
            unregister("OX_Print",infostore_print);
            unregister("OX_InfoStore_Send_Attachment", infostore_sendAttachment);
            if ("infostore_sendLink" in window) {
            	unregister("OX_InfoStore_Send_Link", infostore_sendLink);
            }
            unregister("OX_InfoStore_Open_Attachment", openFileinInfoStore);
            unregister("OX_InfoStore_Save_Attachment", saveFileinInfoStore);
            triggerEvent('OX_Delete_Search');
        },
        function() {
            hideNode("infostore_split"); 
            $("infostore_split").style.display="none";
        },
        function(changeFolder) {  	
        	if (changeFolder != undefined) {
        	    triggerEvent('OX_Delete_Search');
        		loadLiveGridInfoSplit();
        		if (gridInfoSplit) {
                    infostore_setFocus(gridInfoSplit);                    
                }                
        	}   
        }
);
  
registerView("infostore/split/overview",
        function() {
            $("tab_infodetail1").style.display="block";
            $("panel_infodetail1").className="tabbing_tab_active";
        }, 
        null,
        null,
        function() {    
            $("tab_infodetail1").style.display="none";
            $("panel_infodetail1").className="tabbing_tab_inactive";
        }
);

registerView("infostore/split/version",
		function() {
			$("tab_infodetail2").style.display="block";
			$("panel_infodetail2").className="tabbing_tab_active";
		}, 
		function() { 
			function clickVersionInformation() {				
				if(gridVersionsInfoSplit && gridVersionsInfoSplit.selection && gridVersionsInfoSplit.selection.count == 1)			
					gridVersionsInfoSplit.selection.click(gridVersionsInfoSplit.selection.anchor);	
			}
			loadDetailDocumentVersions("version", clickVersionInformation);
			if (bDetailVersionLoaded) {
				getVersions();
			}				
			register('OX_InfoStore_Version_Delete', deleteDetailVersion);
			register('OX_InfoStore_Version_Current', setCurrentVersion);	
			register('OX_Refresh', getVersions);				
		},
		function() {
			if (bDetailVersionLoaded) {   
                gridVersionsInfoSplit.disable();
                bDetailVersionLoaded = false;
            }
			unregister('OX_InfoStore_Version_Delete', deleteDetailVersion);
			unregister('OX_InfoStore_Version_Current', setCurrentVersion);		
			unregister('OX_Refresh', getVersions);							
		},
		function() {
			$("tab_infodetail2").style.display="none";
			$("panel_infodetail2").className="tabbing_tab_inactive";
		}
);

function infostore_setFocus(grid) {
    if (grid && grid.collection && infostoreSelection.count.length) {
        var index = grid.collection.getIndex(infostoreSelection.getSelected()[0]);
        grid.focus = index ? index-1 : 0;
        grid.showFocus();
    }
}

function openFileinInfoStore (files) {
    // loop over objects
    var i = 0, $i = files.length, obj;
    for (; i < $i; i++) {
        obj = {
            id: files[i].id,
            filename: files[i].filename
        };
        if (ox.browser.Chrome) {
            // download (Chrome)
            ox.api.infostore.download(obj);
        } else {
            // open in window
            ox.api.infostore.open(obj);
        }
    }
}

function saveFileinInfoStore (files) {
    // loop over objects
    var i = 0, $i = files.length, obj;
    for (; i < $i; i++) {
        obj = {
            id: files[i].id,
            filename: files[i].filename
        };
        // download
        ox.api.infostore.download(obj);
    }
}

function jumpToInfoStoreConfiguration(divId) {
	if(divId && $(divId))
		$(divId).style.display = 'none';
	triggerEvent("OX_Switch_View","configuration/infostore/preferences");
}

function infostore_sendAttachment(bSendAsLink) {	
	function cb_openWindow(arg) {	
		var aInfoMailObj = new Array();
		var hasLink = false;
		for(var indx=0;indx < arg.length;indx++) {
			var obj = arg[indx].data;
			if (obj.file_size <= 0) {
				hasLink=true;
			}
			var oInfoMailObj = new Object();
			oInfoMailObj["filename"] = obj.filename;			
			oInfoMailObj["size"]= obj.file_size;		
			oInfoMailObj["content_type"]= obj.file_mimetype;			
			oInfoMailObj["content"]= null;
			oInfoMailObj["disk"]= null;
			oInfoMailObj["id"] = obj.id;
			oInfoMailObj["selected"] = false;
			oInfoMailObj["msgref"] = null;
			oInfoMailObj["infostore"] = true;
			oInfoMailObj["aslink"] = (bSendAsLink!=undefined && bSendAsLink);	
			aInfoMailObj.push(oInfoMailObj);
		}
		
		function cbyes() {
		    // compose new mail
		    ox.api.mail.compose({
		        data: {
		            aInfoMailAttachmentFile: aInfoMailObj
		        }
		    });
		}
		
		if (hasLink) {
			newConfirm(_("Send Attachment"),
				_("This object does not contain a file, would you like to send the link?"),
				AlertPopup.YESNO,null,null, function() { infostore_sendLink(arg) },
				null);
		} else {
			cbyes();
		}
	}
	doAjaxGetInfoItemMulti(oLastSelectedInfoObject,cb_openWindow);
}

function doAjaxGetInfoItemMulti(aItems, callback) {
	var aRequestes = new Array();
	for (var nindx=0;nindx<aItems.length;nindx++) {
		var oReqObj = new Object();
		oReqObj["module"] = "infostore";
		oReqObj["action"] = "get";
		oReqObj["folder"] = aItems[nindx].folder;
		oReqObj["id"] = aItems[nindx].id;		
		aRequestes.push(oReqObj);
	}
	var multJSON = new JSON();
	multJSON.put(AjaxRoot + "/multiple?session=" + session,aRequestes,null,callback);
}

function reloadInfoStoretDetailView() {
	triggerEvent("OX_Switch_View", "infostore/split/overview");
}

function infostore_print() {	
    if (!infostoreSelection || activemodule != "infostore") {
        return;
        
    } else if (infostoreSelection.count > 1) {    	
        if (currentpath2[1] == "split" && gridInfoSplit) {
            globalprint.printLiveGrid(gridInfoSplit)
        } else if (gridInfoList) {
            globalprint.printLiveGrid(gridInfoList);
        }
        
    } else {
    	if (!aPrintDetailInfoStore) return;
        
        /* detail print */
        var aPrintData = new Array();
        var detailInfoPrint = new Print(aPrintDetailInfoStore.title);
        
        aPrintData.push(Print.createTitle(aPrintDetailInfoStore.title || ""));
        aPrintData.push(Print.createLine("5px"));
        aPrintData.push(Print.createEmpty(true));
        
        if (aPrintDetailInfoStore.filename && aPrintDetailInfoStore.filename.length > 0) {
            aPrintData.push(Print.createContent(_("Document:"), aPrintDetailInfoStore.filename));
        }
        
        if (aPrintDetailInfoStore.created_by) {
	        var aTMPusrArray2 = new Array();
	        aTMPusrArray2[0]  = aPrintDetailInfoStore.created_by;
	        internalCache.getUsers(aTMPusrArray2, function (oparam){
	            aPrintData.push(Print.createContent(_("Created By:"), oparam[aTMPusrArray2[0]].display_name));        
	        });
	    }
	    
	    if (aPrintDetailInfoStore.creation_date) {                               
	        aPrintData.push(Print.createContent(_("Created on:"), formatDate(aPrintDetailInfoStore.creation_date, "datetime")));
        }
        
        if (aPrintDetailInfoStore.modified_by) {
	        var aTMPusrArray = new Array();
	        aTMPusrArray[0]  = aPrintDetailInfoStore.modified_by;
	        internalCache.getUsers(aTMPusrArray, function (oparam) {
	            aPrintData.push(Print.createContent(_("Modified By:"), oparam[aTMPusrArray[0]].display_name));     
	        });
	    }
	    
	    if (aPrintDetailInfoStore.last_modified) {                               
	        aPrintData.push(Print.createContent(_("Last modified:"), formatDate(aPrintDetailInfoStore.last_modified, "datetime")));
	    }
        
        aPrintData.push(Print.createEmpty(true));        
	    if (aPrintDetailInfoStore.description) {
	        aPrintData.push(Print.createContent(_("Comment:"), aPrintDetailInfoStore.description));
	    }
        
        detailInfoPrint.printDetail(aPrintData);
    }	
}

function checkLockUnLock(selected) {
	var countlocked    = 0;
	var countunlocked  = 0;	
	var counteditlocked= 0;
	var uid = configGetKey("identifier");

    if (!checkLockUnLock.callbacks) checkLockUnLock.callbacks = [];
    var lock = checkLockUnLock.join.add();
    var collection = { objects : selected , columns : ["created_by","modified_by","locked_until"] };
    OXCache.newRequest(null, "infostore", collection, null, function(daten) {
        for (var i = 0; i < daten.objects.length; i++) {
            if (daten.objects[i]["locked_until"] != 0) { 
                if (daten.objects[i]["modified_by"] == uid) {
                    countunlocked++;
                    counteditlocked++;
                } else if (daten.objects[i]["created_by"] == uid) {
                    countunlocked++;
                }
            } else {
                countlocked++;
            }
        }
        triggerEvent("OX_Lockable", countlocked, countunlocked, counteditlocked);
        ox.ToolBarController.processSelection("lockable", false, selected, true);
        lock();
    }, false);
}
checkLockUnLock.join = new Join(function() {
        for (var i = 0; i < checkLockUnLock.callbacks.length; i++) {
            checkLockUnLock.callbacks[i]();
        }
        checkLockUnLock.callbacks = null;
});
checkLockUnLock.callbacks = null;
checkLockUnLock.wait = function(callback) {
    if (this.callbacks) this.callbacks.push(callback); else callback();
};

function openNewInfoPopup(module,folder) {
	if (module != "infostore")
		return;
		
	if (editInfoItemId != -1) {
	    // edit item
	    ox.api.infostore.edit({
	        params: {
	            id: editInfoItemId.id,
	            folder: editInfoItemId.folder_id
	        }
	    });
	} else {
	    // compose item
	    ox.api.infostore.compose({
	        params: {
	            folder: folder
	        }
	    });
	}
	
	editInfoItemId = -1;	
	//propertiesPopUp.focus();
}

//function closeInfoPopUp() {
////	propertiesPopUp.close();
//}

function callback_error(arg) {
	newServerError(arg);
}

function infostore_HeaderUpdate(data) {
	infostoreFolderPath.additionalNode=document.createTextNode(" ("+ data.objects.length + ")");
	infostoreFolderPath.drawDOMNode(currentpath2[1] == "split" ? "infostoreHsplitHeaderOwner" : "infostoreListHeaderOwner", activefolder);
}

fileloaded();