/**
 * 
 * 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 ExecAfterUpload =  function (){};
var ExecErrorAfterUpload = null;

function attachmentDialog(sDialogNum, fkt_On_OK) {
    this.template_id = 'attachPopupTemplate';
    this.popup = $('attachPopupTemplate');
    this.popup.id = this.template_id + '_' + this.dialog_num;
    this.dialog_num = sDialogNum;
    this.att_server_rem = [];    
    this.callOnOK = fkt_On_OK;
    this.form_name = 'attFile_' + this.dialog_num;
    this.form =  document.attFile;
    this.form.name = this.form_name;
    
    //this.sel_files_area = $("selectedFilesArea");
    this.files_area_id = "selectedFilesArea" + '_' + this.dialog_num;
    //this.sel_files_area.id = this.files_area_id;
    this.live_grid_container = $("sel_files_area");
    this.file_storage = new Storage(0, [], "", 0, 0,  null, function(x){ return x[0];});
    this.file_input_count = 0; 
    this.attachmentsChanged = false;
    
    var Self = this;
    register("OX_Attachment_Dialog_Cancel", function(){Self.closePopup();});
    addOnClose (this.popup,function(){
          triggerEvent("OX_Attachment_Dialog_Cancel");
        });
    register("OX_Object_Add_Attachment", function(){Self.openPopup();});
    register("OX_Attachments_Add_File", function(){Self.addFile();});
    register("OX_Attachments_Remove_File", function(){Self.removeFile();});
    register("OX_Attachment_Dialog_OK", function(){Self.commitPopup();});
    
    this.all_input_fields = [];
    this.file_name_list = [];
    this.temp_list = [];
    
    this.last_input = null;
    
    this.curr_file_input_id;
    
    this.open = false;    
}

attachmentDialog.prototype = {
    attach_changed: function () {
        return (this.att_server_rem.length > 0 || this.file_input_count > 0 || this.attachmentsChanged);
    },
    do_post: function (obj,fn_exec_afterupload,sActionParam,sTargetParam,fn_error_exec_afterupload) {
        if(this.att_server_rem.length > 0) {
            var aAttIds = [];

            for (var indx2=0;indx2<this.att_server_rem.length;indx2++) {
                aAttIds.push(this.att_server_rem[indx2].attid);
            }

            var sAction = AjaxRoot + "/attachment?action=detach" + "&session="+session + "&attached=" 
                        + this.att_server_rem[0].item_id + "&module=" 
                                + this.att_server_rem[0].module + "&folder=" + (this.att_server_rem[0].folder || this.att_server_rem[0].folder_id);                                                 
            this.att_server_rem = [];    
            var attJson = new JSON();
            var Self = this;
            function cb_deleted(arg) {
                if (arg && arg.error) {
                    alert(arg.error);
                } else {
                    Self.post_new(obj,fn_exec_afterupload,sActionParam,sTargetParam,fn_error_exec_afterupload);
                }                
            }
            attJson.put(sAction,aAttIds,null,cb_deleted);
        } else {
            this.post_new(obj,fn_exec_afterupload,sActionParam,sTargetParam,fn_error_exec_afterupload);
        }
        return;
    },
    post_new: function (obj,fn_exec_afterupload,sActionParam,sTargetParam,fn_error_exec_afterupload) {
        ExecAfterUpload = fn_exec_afterupload;
        ExecErrorAfterUpload = fn_error_exec_afterupload;
        if(sActionParam) {
            this.form.action = sActionParam;
        } else {
            this.form.action = AjaxRoot + "/attachment?action=attach&session=" + session;
        }
        if (sTargetParam) {
            this.form.target = sTargetParam;
        }
        var  sObj = JSON.serialize(obj);
        if (this.file_input_count === 0) {
            var oNodeJson;
            if (this.form["json_0"] === undefined) {
                oNodeJson = newnode('input',0,{
                                        type:"hidden",
                                        name:'json_0'
                                        });                                
                this.form.appendChild(oNodeJson);
            }
            else {
                oNodeJson = this.form["json_0"];
            }
            oNodeJson.value = sObj;
        }        
        else {
            for (var nCount=0;nCount<this.file_input_count;nCount++) {
                if(this.form['json_'+nCount]) {
                    this.form['json_'+nCount].value = sObj;
                }
            }
        }
        this.attachmentsChanged = true;
        this.form.submit();
    },
    createFileInput: function () {
        var sId = 'file_' + (this.file_input_count);
        var oNode = newnode('input',0,{
                                        type:"file",
                                        size:"40",
                                        name:sId,
                                        id:sId,
                                        className:"inputElementAttachment"
                                        });
        var oNodeJson = newnode('input',0,{
                                        type:"hidden",
                                        name:'json_'+(this.file_input_count),
                                        id:'json_'+(this.file_input_count)
                                        });
        // auto-add file on change
        var self = this;
        jQuery(oNode).bind("change", function (e) {
            self.addFile();
        });
        this.last_input = oNode;
        var outerDiv1 = newnode("div");
        var outerDiv2 = newnode("div");        
        outerDiv1.appendChild(oNode);
        outerDiv2.appendChild(oNodeJson);
        this.form.appendChild(outerDiv1);
        this.form.appendChild(outerDiv2);
        this.all_input_fields.push(oNode);
        this.all_input_fields.push(oNodeJson);        
        return sId;
    },
    openPopup: function () {
        if(!this.open) {
            this.curr_file_input_id = this.createFileInput();
        }
        this.open = true;
        this.temp_list = [];
        if ($("modal-dialog")) {
            ox.api.setModal(true);
//            showNode("modal-dialog");
//            $("modal-dialog").style.display = "block";
        }
        centerPopupWindow(this.popup);
        this.popup.style.display = 'block';        
        //create
        if(this.live_grid === null || this.live_grid === undefined) {
            this.live_grid = new LiveGrid([ 
                {
                    text:" ",                
                    index: 1,    
                    style: {overflowX:"auto"},
                    set: function(div, text) {
                        text = text || "\u00a0";
                        if (div.firstChild) {
                            div.firstChild.data = text;
                        } else {
                            div.appendChild(document.createTextNode(text));
                        }
                    },                    
                    clear: LiveGrid.makeClear("")
                }
            ],new Selection());            
    
            this.live_grid.emptylivegridtext ="";
            this.live_grid.getHeader();        
            this.live_grid.getTable(this.live_grid_container);
            this.live_grid_container.style.overflowX = "auto";
            //this.live_grid_container.firstChild.style.width = "";            
            //this.live_grid_container.firstChild.style.overflowX = "auto";            
        } else {
            this.live_grid.enable(this.file_storage = new Storage(0, [], "", 0, 0,  null, function(x){ return x[0];}));
        }

    },
    closePopup: function () {
        //this.form.reset();
        //var oNode;
        //empty lg
        //removeChildren(this.sel_files_area);        
        /*
        while(oNode = this.all_input_fields.pop())
        {
            if(oNode)
            {
                this.form.removeChild(oNode);
            }
        }*/
        if ($("modal-dialog")) {
            ox.api.setModal(false);
//            hideNode("modal-dialog");
//            $("modal-dialog").style.display = "none";
        }
        this.popup.style.display = 'none';    
        /*
        this.file_input_count = 0;    
        */
        this.open = false;
        var aToDel = [];
        for (var indxTd in this.temp_list) {
            aToDel.push(this.temp_list[indxTd].id);
        }
        this.removeFiles(aToDel);
        this.temp_list = [];        
        this.live_grid.disable();
        if (this.last_input !== null) {
            this.form.removeChild(this.last_input.parentNode);
        }
        this.last_input = null;
        this.file_input_count++;
    },    
    commitPopup: function () {
        if ($("modal-dialog")) {
            ox.api.setModal(false);
//            hideNode("modal-dialog");
//            $("modal-dialog").style.display = "none";
        }
        this.popup.style.display = 'none';    
        this.file_name_list = this.file_name_list.concat(this.temp_list);
        this.callOnOK(this.file_name_list);    
        this.live_grid.disable();
    },
    showAttachedFiles: function () {
        return this.file_name_list;
    },
    addFile: function () {    
        //ie7 bugfix
        //var currFileInput = this.form.elements[this.curr_file_input_id];
        
        var currFileInput = document.getElementById(this.curr_file_input_id);
        
        if(currFileInput.value.length === 0) {
            return;
        }
        var fileName = separateFilenameFromPath(currFileInput.value);        
        var file = {id:fileName+'_'+this.file_input_count,filename:fileName};
        this.temp_list.push(file);
        
        //add file to lg
        var aFileObjects =  [[file.id,fileName]];
        this.file_storage.append(aFileObjects);
        this.live_grid.enable(this.file_storage);
        
        //update styles here (IE BUG FIX horizontal scroll bar)
        this.live_grid.rowTemplate.style.tableLayout = "auto";
        
        //this.sel_files_area.appendChild(newnode("option", 0,
        //    {value: file.id}, [document.createTextNode(fileName)]));

        currFileInput.style.display = "none";
        
        this.file_input_count++;
        this.curr_file_input_id = this.createFileInput();            
    },
    removeFile: function() {    
        //var files = this.sel_files_area.childNodes;
//        var len = files.length;
//        var selected = [];
//        for (var i = 0; i < len; i++)
//            if (files[i].selected) selected.push(files[i].value);
        var aSelItems = this.live_grid.selection.getSelected();
        if(aSelItems.length > 0) {
            this.removeFiles(aSelItems);
        }
//        removSelected;
    },
    getLocalPath:function (sId) {
            sFileName = sId.split('_')[0]; 
            for(var nField=0;nField<this.all_input_fields.length;nField++) {
                if((this.all_input_fields[nField].name == 'file_' + sId.split('_')[1])) {
                    return this.all_input_fields[nField];
                }
            }
    },
    removeFiles:function (aFiles) {
        function removeFileNameFromString(sStr,sFileName) {
            sFileName += '; ';
            var sReturnStr = sStr.replace(sFileName,'');
            return sReturnStr;
        }
        var Self = this;
        function removeFileNameFromList(sId) {
            for (var indx in Self.file_name_list) {
                if (Self.file_name_list[indx].id == sId) {
                    Self.file_name_list.splice(indx,1);
                    break;
                }
            }
            for (var indx in Self.temp_list) {
                if (Self.temp_list[indx].id == sId) {
                    Self.temp_list.splice(indx,1);
                    break;
                }
            }
        }
        //aFiles
        //get files from lg
        //var options = this.sel_files_area.childNodes;
        if( this.live_grid && this.live_grid.storage !== undefined) {
            this.live_grid.deleteIDs(aFiles);
        }
        for (var nIndex=0;nIndex<aFiles.length;nIndex++) {
            var filename = aFiles[nIndex];
            //var len = options.length;
            //remove fildes from lg
            /*
            for (var i = 0; i < len; i++)
                if (options[i].value == filename) {
                    //this.sel_files_area.removeChild(options[i]);
                    break;
                }
*/
            var sFileName = expandFileNames(filename);
            removeFileNameFromList(filename);
            var aToRemoveArray = [];
            for(var nField in this.all_input_fields) {
                if(((this.all_input_fields[nField].name == 'file_' + expandIDS(filename))
                            || (this.all_input_fields[nField].name == 'json_' + expandIDS(filename))) 
                                            && this.all_input_fields[nField].name != 'json_0')
                {
                    this.form.removeChild(this.all_input_fields[nField].parentNode);
                    aToRemoveArray.push(nField);
                }
            }
            for (var nRemItem in aToRemoveArray) {
                this.all_input_fields.splice(aToRemoveArray[nRemItem],1);
            }
        }
    }
};

function expandIDS(sFileWithId) {
    var aTempArray = sFileWithId.split('_');
    return aTempArray[(aTempArray.length-1)];
}

function expandFileNames(sFileWithId) {
    var aTempArray = sFileWithId.split('_');
    var sFileName = "";
    for(var nIndxx=0;nIndxx<aTempArray.length-1;nIndxx++) {
        sFileName += aTempArray[nIndxx];
        if(nIndxx < aTempArray.length-2) {
            sFileName += "_";
        }
    }
    return sFileName;
}

/*
 * remove is possible in new/edit window only
 * */
function attachmentGrid(sContainerId,nId,nFolder,sModule,oDialog) {
    this.container = $(sContainerId);
    this.containerHeader = $(sContainerId + "Header");
    this.module  = sModule;
    this.nItemId = nId;
    this.folder = nFolder;    
    this.liveGrid = null;
    this.viewGrid();
    this.attachmentStorage;// = new Storage(0, []);
    this.bDetailAttachmentsLoaded = false;
    
    this.selection_dialog = (oDialog)?oDialog:false;
    
    this.timestamp = 0;
    
    this.addData = [];
    this.selectedRtfFlag = false;
    this.selectedId = null;
    this.selectedFilename = null;    
    
    this.numberOfAttachments = 0;
    
    Self = this;
    this.openAttachedFile = function () {
                if(Self.selectedRtfFlag) {
                    return;
                }
                var sURL = 
                AjaxRoot + "/attachment/" + Self.selectedFilename + "?action=document&session="
                    + session + "&attached=" + Self.nItemId  + "&module=" + Self.module + "&folder="
                    + activefolder + "&id=" + Self.selectedId;
                newWindow(sURL, getWindowOptions(null, null, "scrollbars=yes"));
    };
    this.saveAttachedFile = function () {

                if(Self.selectedRtfFlag) {
                    return;
                }
                var sContentType = 'application%2Foctet-stream';    
                var sURL = 
                AjaxRoot + "/attachment/" + Self.selectedFilename + "?action=document&session="
                    + session + "&attached=" + Self.nItemId  + "&module=" + Self.module + "&folder="
                    + activefolder + "&id=" + Self.selectedId + '&content_type=' +sContentType;
                if (IE6) {
                    newWindow(sURL, getWindowOptions());
                } else {
                    var frame = $ALL("dlIframe") ? getFrameElement('dlIframe') : parent.frames['dlIframe'];
                    frame.location.href = sURL;
                }
    };
    this.saveAttachInInfoStore = function () {
        if (Self.selectedRtfFlag) {
            return;
        }
        if (activemodule === "mail") {
            return;
        }
        var nNumModule = -1;
        switch (activemodule) {
            case "calendar":     nNumModule = 1;
                                break;
            case "tasks":     nNumModule = 4;
                                break;
            case "contacts":     nNumModule = 7;
                                break;                                                                
        }
        
        // use new api
        ox.api.infostore.compose({
            params: {
                attachmodule: nNumModule,
                filename: Self.selectedFilename,
                attid: Self.selectedId,
                attobjid: Self.nItemId,
                attobjfolder: Self.folder || Self.folder_id,
                folder: configGetKey("folder.infostore")
            },
            id: [ Self.selectedId, Self.nItemId, (Self.folder || Self.folder_id)]
        });
    };
    
    var Self = this;
    this.remAttachedFile  = function () {
        if(Self.selectedRtfFlag) return;        
        function cbyes() {
            Self.remove(Self.liveGrid.selection.getSelected(), function() {
                Self.updateGrid(Self.selection_dialog.file_name_list);
            });                                        
        }
        newConfirm(_("Delete Attachment"),_('Are you sure you want to delete the selected attachment?'),AlertPopup.YESNO,null,null,cbyes,null);
                                        
    };
                                        
    register("OX_Attachment_Open", this.openAttachedFile);        
    register("OX_Attachment_Save", this.saveAttachedFile);        
    register("OX_Attachment_SaveInfoStore", this.saveAttachInInfoStore);    
    
    if(this.selection_dialog) {
        register("OX_Object_Attachment_Delete", this.remAttachedFile);
    }
}

attachmentGrid.prototype = {
updateGrid: function (data) {    
    var aNewData = [];
    for(var indx in data) {
        var bFound = false;
        for(var indx2=0;indx2<this.addData.length;indx2++) {    
            if (data[indx].id == this.addData[indx2].id) {
                bFound = true;
                break;
            }
        }
        if(!bFound) {
            aNewData.push(data[indx]);
        }
    }    
    for(var indx2=0;indx2<this.addData.length;indx2++) {
        var bFound = false;
        for (var indx in data) {
            if (data[indx].id == this.addData[indx2].id) {
                bFound = true;
                break;                
            }
        }
        if(!bFound) {
            //IE7 bugfix
            //this.attachmentStorage.remove(this.attachmentStorage.ids.indexOf(this.addData[indx2].id));
            var indexToDelete = -1;
            var aIds = this.attachmentStorage.ids;
            for (var i = 0; i < aIds.length; i++) {
                if (aIds[i] == this.addData[indx2].id) {
                    this.liveGrid.deleteIDs([this.addData[indx2].id]);
                    indexToDelete = i; 
                }
            }
//            if(indexToDelete != -1)
//                this.attachmentStorage.remove(indexToDelete);
            this.addData.splice(indx2,1);
        }
    }
    this.addData = this.addData.concat(aNewData);
    var aNewObj =  [];
    for (var i in aNewData) {
        sFileName = aNewData[i].filename;
        aNewObj.push(new Array(aNewData[i].id,sFileName,'','',''));
        this.numberOfAttachments++;
        triggerEvent("OX_Attachments_Changed_InGrid",this.numberOfAttachments);
    }
    if(aNewObj.length == 0) {
        triggerEvent("SubSelected", 0);
    } else {
        this.attachmentStorage.append(aNewObj);
    }
    this.enableGrid();

},
remove: function (ids, callback) {
    var local = [], remote = [];
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        if (typeof id === "string" && id.indexOf("_") >= 0) {
            local.push(id);
        } else {
            remote.push(id);
            this.selection_dialog.att_server_rem.push({
                attid: id, item_id: this.nItemId, module: this.module,
                folder: this.folder || this.folder_id
            });
        }    
    }
    if (local.length) {
        this.selection_dialog.removeFiles(local);
    }
    if (remote.length) {
        this.attachmentStorage.removeIDs(remote);
    }
    this.numberOfAttachments -= ids.length;        
    triggerEvent("OX_Attachments_Changed_InGrid",this.numberOfAttachments);
    if (callback) {
        callback();
    }
},
enableGrid: function () {
    this.liveGrid.enable(this.attachmentStorage);        
    register("OX_Attachment_Open", this.openAttachedFile);        
    register("OX_Attachment_Save", this.saveAttachedFile);    
    register("OX_Attachment_SaveInfoStore", this.saveAttachInInfoStore);        
},
disableGrid: function () {
        this.liveGrid.disable();
        unregister("OX_Attachment_Open", this.openAttachedFile);        
        unregister("OX_Attachment_Save", this.saveAttachedFile);
        unregister("OX_Attachment_SaveInfoStore", this.saveAttachInInfoStore);
},
getAttachments: function (nId,nFolder,fn_update_opt) {
    var  Self = this;    
    this.attachmentStorage = new Storage(0, []);
    if (this.nItemId === false) {
        return;
    }
    function cb_attachments(arg) {
        var aData = [];
        Self.numberOfAttachments = 0;
        //check rtf_flags here
        for (var indx in arg.data) {
            aData.push(arg.data[indx]);
            Self.numberOfAttachments++;        
        }
        
        triggerEvent("OX_Attachments_Changed_InGrid",Self.numberOfAttachments);
        Self.attachmentStorage.append(aData);
        Self.attachmentStorage.timestamp = arg.timestamp;
        Self.liveGrid.enable(Self.attachmentStorage);
        Self.bDetailAttachmentsLoaded = true; 
        if(fn_update_opt)
            fn_update_opt();            
    }
    if(nId != 0 && nId !== undefined &&  nFolder != 0 && nFolder !== undefined) {
        this.nItemId = nId;
        this.folder = nFolder;        
    }        
    this.doAjaxFetchAllAttachments(cb_attachments);
},
viewGrid: function () {
        var Self = this;
        var clear = LiveGrid.makeClear("...");
        function setAttachmentsTest1 (div, text){
            removeChildNodes(div);
            if (text[5]) {
                div.style.fontStyle = "italic";
            } else {
                div.style.fontStyle = "";
            }
            div.appendChild(document.createTextNode(text[1]));        
        }
        function setAttachmentsTest2 (div, text){
            removeChildNodes(div);
            if (text[5]) {
                div.style.fontStyle = "italic";
            } else {
                div.style.fontStyle = "";
            }
            div.appendChild(document.createTextNode(text[2]));        
        }    
        function setAttachmentsTest3 (div, text){
            removeChildNodes(div);
            if (text[5]) {
                div.style.fontStyle = "italic";
            } else {
                div.style.fontStyle = "";
            }
            div.appendChild(document.createTextNode( text[3] && text[3].length != 0 ? bytesToString(text[3]) : "") );        
        }            
        function setAttachmentsTest4 (div, text){
            removeChildNodes(div);
            if (text[5]) {
                div.style.fontStyle = "italic";
            } else {
                div.style.fontStyle = "";
            }
            if (text[4].length==0) {
                div.appendChild(document.createTextNode(""));
            } else {
                div.appendChild(document.createTextNode(formatDate(text[4], "date")));
            }
        }                                
        this.liveGrid = new LiveGrid([ 
            {
                text: "File name", /*i18n*/
                i18n: true,
                sortable: true,
                set: setAttachmentsTest1,
                clear: clear
            }, {
                text: "Mime type", /*i18n*/
                i18n: true,                
                sortable: true,
                width: "20%",
                set: setAttachmentsTest2,
                clear: clear
            }, {
                text: "Size", /*i18n*/
                i18n: true,                
                sortable: true,
                width: "15%",
                set: setAttachmentsTest3,
                clear: clear
            }, {
                text: "Last modified", /*i18n*/
                i18n: true,                    
                sortable: true,
                width: "15%",
                set: setAttachmentsTest4,
                clear: clear
            }
        ], new Selection());
        this.liveGrid.emptylivegridtext="No Attachments available";/*i18n*/
        this.containerHeader.appendChild(this.liveGrid.getHeader());
        this.liveGrid.getTable(this.container);
                
        this.liveGrid.events.register("Activated", function(ids){
            if (!ids || ids == 0) {
                return;
            }
            (menucheckRight("WRITE")) ? triggerEvent("OX_Object_Delete_Attachment") :
                triggerEvent("OX_New_Error", 4, _("You're not allowed to delete this attachment!"));
        });
    
        var aIds = Self.liveGrid.selection.getSelected();
        var Self = this;        
        function fn_triggerSubSel(ids){
            triggerEvent("SelectedAttachment",ids);
            ox.ToolBarController.processSelection("attachments", false,
                Self.liveGrid.selection.getSelected(), true);
            if (ids == 1) {                
                var aIDS = Self.liveGrid.getSelectedIDs();
                Self.selectedId = aIDS[0];
                Self.selectedFilename = Self.liveGrid.storage.data.get(Self.selectedId)[1];        
                Self.selectedRtfFlag = !(Self.liveGrid.storage.data.get(Self.selectedId)[5] == false);
                if(Self.liveGrid.storage.data.get(Self.selectedId)[5] === undefined) {
                    Self.selectedRtfFlag = false;
                }
                triggerEvent("SubSelected", ids,Self.selectedRtfFlag);                
            }          

        }
        this.liveGrid.events.register("Selected", fn_triggerSubSel);
},
doAjaxFetchAllAttachments:function (cb)
{
    json.get(AjaxRoot + "/attachment?action=all&session=" + session + "&folder=" +
            (this.folder || this.folder_id) + "&attached=" + this.nItemId + "&module="+this.module+"&" + 
            "columns=1%2C803%2C805%2C804%2C4%2C806&sort=803&order=asc", null,cb);        
}
}

function callback_attach(cb) {
    if(typeof savePending != "undefined" && savePending) {
        savePending = false;
    }
    if (!cb.error) {
        ExecAfterUpload();    
    }
    else {
        //triggerEvent("OX_New_Error", 4, cb.toString());
    }
}

function callback_document(cb) {
    if(typeof savePending != "undefined" && savePending) {
        savePending = false;
    }
    if (cb.error) {
        newServerError(cb);
    }
}
function callback_error(arg)
{
    if(typeof savePending != "undefined" && savePending) {
        savePending = false;
    }
    if(ExecErrorAfterUpload && typeof ExecErrorAfterUpload != "undefined") {
        ExecErrorAfterUpload(arg);
    } else {
        newServerError(arg);
    }
}
fileloaded();


/* 
 * +++++++++++++++++
 * Infostore Attachment Load 
 * +++++++++++++++++
 */

function infostoreDialog(number, callback) {
	var Self = this;
    this.popup = $('attachInfostorePopupTemplate');
    this.open = false;
    this.attachLiveGrid;
    this.gridSelectedElements = new Selection2();
    this.gridSelectedElements.oldToggle = this.gridSelectedElements.toggle;
    // overwrite toggle to prevent selection of non files
    this.gridSelectedElements.toggle = function(index) {
        var data = Self.attachLiveGrid.collection.objects;
        if (data && data[index] && !data[index].filename) {
            return false;
        } else {
            this.oldToggle(index);
        }
    }
    
    this.gridAddedElements = $("selectedFilesInfostore");
    this.miniGrid;
    this.file_storage;
    this.callback = callback || jQuery.noop;
    
    register("OX_AttachInfostore_Dialog_Cancel", function(){Self.closePopup();});
    addOnClose (this.popup,function(){
          triggerEvent("OX_AttachInfostore_Dialog_Cancel");
        });
    register("OX_Object_Add_Attachment_Infostore", function(){Self.openPopup();});
    register("OX_AttachInfostore_OK", function(){ Self.commitPopup(); });
}

infostoreDialog.prototype = {
	commitPopup: function () {
		var Self = this, attachments = [];
    	// get selected files from the top grid 
    	if (this.gridSelectedElements.count > 0){
    		jQuery(this.gridSelectedElements.getSelected()).each(function(index) {
    			var file = jQuery(this)[0];
    			// pre-fill object for callback
    			attachments.push({ id: file.id, filename: file.title, size: null, 
    			        content_type: file.file_mimetype || null, msgref: null, 
    			        selected: false, infostore: true });
    		});
    	}
        // trigger callback with infostore objects
        Self.callback(attachments);
    	Self.closePopup();
	},
    openPopup: function () {
    	this.loadFolderTree();
    	
    	// get the grid header and body div from the template
    	var gridHeader = $("attachInfostorGridHeader");
    	var gridContent = $("attachInfostorGridContent");
    	
    	// clear a old grid if available
    	if (this.attachLiveGrid) {
    		removeChildNodes(gridContent);
    		removeChildNodes(gridHeader);
    		this.attachLiveGrid = null;
    	}
    	
    	//fix some css
    	jQuery("#folder_tree_attachment #select-folder-popup-infostore").removeClass("oxStretch");
    	jQuery("#folder_tree_attachment #select-folder-popup-infostore").css("overflow", "visible");
    	
    	// create the grid
    	this.attachLiveGrid = new LiveGrid2([
            {
  				name : ["title"],
                i18n: "description", /*i18n context*/
  				text: "Title", /*i18n*/
  				sortable: true,
  				sort : "title",
  				set: LiveGrid.defaultSet,
  				clear: LiveGrid.makeClear("")
  			}, {
  				name : ["file_size", "file_mimetype", "filename"],
  				text: "Size", /*i18n*/
  				i18n: true,
  				sortable: true,
  				width: "20%",
  				sort : "file_size",
  				set: function (div, object) {
                    // mark non-files as greyed-out
                    jQuery(div).parent().css("color", object.filename ? "" : "silver");
                    // calculate size
  					var sDisplayString = object.file_size ? bytesToString(object.file_size) : "-";
  					if (div.firstChild) {
  						div.firstChild.data = sDisplayString;
  					} else {
  						div.appendChild(document.createTextNode(sDisplayString));
  					}
  				},
  				clear: LiveGrid.makeClear("")
  			}, {
  				name : ["created_by"],
  				text: "Created by", /*i18n*/
  				i18n: true,
  				sortable: true,
  				sort : "created_by",
  				width: "25%",			
  				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("")
  			}
  		], this.gridSelectedElements);
    	this.attachLiveGrid.module="infostore";

    	// add grid to header and body divs
    	gridHeader.appendChild(this.attachLiveGrid.getHeader());
    	this.attachLiveGrid.getTable(gridContent);
    	    	
    	// start the popup
	    if ($("modal-dialog")) {
	        ox.api.setModal(true);
	    }
		this.open = true;
		
		// center popup
    	centerPopupWindow(this.popup);
    	this.popup.style.display = 'block';
    	
    },
    closePopup: function () {
    	// disable the big grid
    	this.attachLiveGrid.disable();
        
    	// clode popup
    	this.open = false;
        if ($("modal-dialog")) {
            ox.api.setModal(false);
        }
        this.popup.style.display = 'none'; 
    },
    loadFolderTree: function() {
    	var Self = this;
    	
    	// load the folder and draw the grid
    	function loadFolderContent(data) {
        	var criteria= { "folder_id" : data.id };
        	Self.attachLiveGrid.disablehover=true;
        	Self.attachLiveGrid.enable(criteria,false);
        }
    	
    	// the left side folder tree
    	ox.api.ui.selectFolder({
        	type: "infostore",
        	id: "select-folder-popup-infostore",
        	root: "9",
        	open: ["9", "10", ox.api.config.get("folder.infostore")],
        	callback: loadFolderContent,
        	node: $('folder_tree_attachment')
        });
    }
}
