var tab = new temporary.VTab(_("Subscriptions"), newnode("span", 0, 0, [
    addTranslated(_("Subscriptions")),
    newnode("span", { background: "orange", marginLeft: "5px", padding: "2px",
                      MozBorderRadius: "2px", WebkitBorderRadius: "2px",
                      color:"white" }, 0, [ addTranslated(_("New")) ])
]), 0.2);
temporary.folderTabs.addTab(tab);

var sourceTargetMappings = {
    "com.openexchange.subscribe.microformats.infostore.http":
        ["com.openexchange.publish.microformats.infostore.online"],
    "com.openexchange.subscribe.microformats.contacts.http":
        ["com.openexchange.publish.microformats.contacts.online"]
};

var targetSourceMapping = {};

var widgets = {
    input: function(def) { return new ox.UI.Input(noI18n(def.displayName)); },
    password: function(def) {
        return new ox.UI.Password(noI18n(def.displayName));
    },
    checkbox: function(def) {
        return new ox.UI.CheckBox(noI18n(def.displayName));
    },
    text: function(def) { return new ox.UI.Text(noI18n(def.displayName)); },
    link: function(def) {
        var link = new ox.UI.Widget();
        link.default_value = "";
        link.addContent = function() {
            this.anchor = newnode("a", 0,
                { href: this.default_value, target: "_blank" },
                [document.createTextNode(this.default_value)]);
            this.node = this.parent.addCells(noI18n(def.displayName),
                                             this.anchor);
            ox.UI.Widget.prototype.addContent.apply(this, arguments);
        };
        link.set = function(value) {
            this.anchor.href = value;
            this.anchor.firstChild.data = value;
        };
        link.get = function() { return this.anchor.firstChild.data; };
        return link;
    }
};

//create plugin namespace
var com_openexchange_subscribe = {};
com_openexchange_subscribe.sources = {};
com_openexchange_subscribe.modules = {};
com_openexchange_subscribe.mailHead = {};
com_openexchange_subscribe.folders = {};
com_openexchange_subscribe.currentSource;
com_openexchange_subscribe.currentDisplayName;
com_openexchange_subscribe.tab = tab;
var addedSubscription = null;
var selection = new Selection();
var storage = new Storage(0, []);

com_openexchange_subscribe.fnButton = function (button, fn_click){
	 var node = newnode("div",{flt:"left", width:"14em"},{ className:"fakeButton background-color-default cursorPointer whiteground"},[newnode("div",{},{className:"fakeButtonBottom"},[newnode("div",{},{className:"fakeButtonLeft"},[newnode("div",{},{className:"fakeButtonRight"},[
         newnode("div",{},{className:"fakeButtonTopLeft"},[newnode("div",{},{className:"fakeButtonTopRight"},[newnode("div",{},{className:"fakeButtonBottomLeft"},[newnode("div",{},{className:"fakeButtonBottomRight"},[button])])])])
      ])])])]);
	 
	if(fn_click)
		addDOMEvent(node, "click", fn_click);
	return node;
};

/* My OX Social overview in Configuration */

new ox.Configuration.InnerNode("configuration/oxsocial", _("My OX Social"));

com_openexchange_subscribe.node2 = new ox.Configuration.LeafNode("configuration/oxsocial/subscription",_("Subscriptions"));
  
com_openexchange_subscribe.split = new ox.Configuration.VSplit(com_openexchange_subscribe.node2, _("Subscriptions"), 0.28, false); //Section Headline

com_openexchange_subscribe.split.init = function() {
	com_openexchange_subscribe.split.list = com_openexchange_subscribe.getGrid(true);
    
	com_openexchange_subscribe.split.enableList = function(cb) {
    	ox.JSON.get(AjaxRoot + "/subscriptions?action=all&session=" + session,
            function(reply) {
                storage.remove(0, storage.ids.length);
                storage.append(reply.data);
                com_openexchange_subscribe.split.list.enable(storage);
                com_openexchange_subscribe.split.list.events.register("Selected", com_openexchange_subscribe.updatePubDetailView);
                com_openexchange_subscribe.allData = {};
                jQuery.each(reply.data, function(i, val) {
                	com_openexchange_subscribe.allData["id"+val[0]] = val;
                });
            	if(cb)cb();

            });
    };
    
    com_openexchange_subscribe.openFolder = function () {
        var id = com_openexchange_subscribe.selected_subscribe[1];
        if (id !== undefined) {
            ox.UIController.setFolder({
                folder: id,
                module: "default"
            });
        }
    };

    com_openexchange_subscribe.oldWidget = false;
    
    
    /* view selected object */
    com_openexchange_subscribe.updatePubDetailView = function() {
    	var ids = com_openexchange_subscribe.split.list.selection.getSelected();
		
    	if (ids && ids.length == 1) {  
    		com_openexchange_subscribe.selected_subscribe = com_openexchange_subscribe.allData["id"+ids[0]];
            var enabled_string = (com_openexchange_subscribe.selected_subscribe[4])?_('enabled'):_('disabled');
            var enabled_state = (com_openexchange_subscribe.selected_subscribe[4])? ' checked':'';
            if (com_openexchange_subscribe.folders["id"+com_openexchange_subscribe.selected_subscribe[1]]) {
        		var content_string = "<div class='wrapper_detail_infos'>"+
            		"<h2>"+_('Detail information for subscription')+"</h2>"+
        				"<div class='detail_info'>"+
        					"<label>"+_('Folder name')+"</label> <a class='linkInView' id='foldername_"+com_openexchange_subscribe.selected_subscribe[1]+"'>"+com_openexchange_subscribe.folders["id"+com_openexchange_subscribe.selected_subscribe[1]][1]+"</a>"+
        				"</div>"+
            		"<div class='detail_info'>"+
            			"<label>"+_('Module')+"</label>"+com_openexchange_subscribe.selected_subscribe[2]+
            		"</div>"+
            		"<div class='detail_info'>"+
            			"<label>"+_('Subscription status')+"</label> "+enabled_string+
            			"<input type='checkbox'" + enabled_state +
            			" class='t_checkbox' name='subscribe_"+com_openexchange_subscribe.selected_subscribe[0]+
            			"' id='subscribe_"+com_openexchange_subscribe.selected_subscribe[0]+"' value='true' />"+
        				"</div>"+
        				"<div class='detail_info'>"+
        					"<label>"+_('Folder path')+"</label> <a class='linkInView' id='foldername2_"+com_openexchange_subscribe.selected_subscribe[1]+"'>"+com_openexchange_subscribe.folders["id"+com_openexchange_subscribe.selected_subscribe[1]][0]+"/"+com_openexchange_subscribe.folders["id"+com_openexchange_subscribe.selected_subscribe[1]][1]+"</a>"+
        				"</div>"+
        			"</div>";
            } else {
                var content_string = "";
            }
		} else {
			if (ids && ids.length > 1) {
	    		var content_message = _('Please select only one subscription');
			} else {
	    		var content_message = _('No subscription selected');
			}
    		var content_string = "<div class='wrapper_detail_infos'>"+
    		"<h2>"+_('Detail Information for Subscription')+"</h2>"+
				"<div class='detail_info'>"+
				"<label>"+content_message+"</label>"+
				"</div>"+
			"</div>";
		}
    		
	    //com_openexchange_subscribe.allData["id"+ids[0]];
    		
    		
        var entry = new ox.UI.Container();
        entry.addContent = function() {
            this.childWidth = this.parent.childWidth;
            
            
	        this.table = jQuery(content_string)[0];
            this.node = this.parent.addRow(this.table);
            
            
            ox.UI.Container.prototype.remove();
            ox.UI.Container.prototype.addContent.apply(this, arguments);
        };
        if(com_openexchange_subscribe.oldWidget) {
        	com_openexchange_subscribe.split.deleteWidget(com_openexchange_subscribe.oldWidget);
        }
        com_openexchange_subscribe.oldWidget = entry;
        com_openexchange_subscribe.split.addWidget(entry, ox.Configuration.Group.NoField);

        if (ids && ids.length == 1 && content_string) { 
			addDOMEvent(document.getElementById('foldername_'+com_openexchange_subscribe.selected_subscribe[1]), "click", com_openexchange_subscribe.openFolder);
			addDOMEvent(document.getElementById('foldername2_'+com_openexchange_subscribe.selected_subscribe[1]), "click", com_openexchange_subscribe.openFolder);
        }
		
    };

	com_openexchange_subscribe.split.save = function () {
        var final_state = com_openexchange_subscribe.get_enabled_string(jQuery('#subscribe_'+com_openexchange_subscribe.selected_subscribe[0])[0].checked);
    	var updatedfolder = com_openexchange_subscribe.folders["id"+com_openexchange_subscribe.selected_subscribe[1]][1];    	
		var data = {	id:com_openexchange_subscribe.selected_subscribe[0],folder:com_openexchange_subscribe.selected_subscribe[1],
					enabled:jQuery('#subscribe_'+com_openexchange_subscribe.selected_subscribe[0])[0].checked, source: com_openexchange_subscribe.selected_subscribe[2]	};
		data[com_openexchange_subscribe.selected_subscribe[2]] = {};
        
        com_openexchange_subscribe.update_enabled(final_state, updatedfolder, data, true);
	};

    var entry = new ox.UI.Container();
    entry.addContent = function() {
        this.childWidth = this.parent.childWidth;
        content_string = "<div class='wrapper_detail_infos'>"+
		"<h2>"+_('Overview Subscriptions')+"</h2>"+
		"</div>";
        this.table = jQuery(content_string)[0];
        this.node = this.parent.addRow(this.table);
        ox.UI.Container.prototype.addContent.apply(this, arguments);
    };
    com_openexchange_subscribe.oldWidget = entry;
    com_openexchange_subscribe.split.addWidget(entry, ox.Configuration.Group.NoField);
	
};

com_openexchange_subscribe.update_enabled = function (final_state, updatedfolder, data, refresh_storage) {
	ox.JSON.put(AjaxRoot + "/subscriptions/?action=update&session=" +
            session, data, function(reply) {
			if(refresh_storage) {
				com_openexchange_subscribe.get_data(data.id);
			}
            ox.Configuration.info(
                format(_("The subscription %s is now %s"), [updatedfolder, final_state]));
        });
};

//Helper
com_openexchange_subscribe.addCheckBox = function (accountId) {
    var checkbox = newnode("input", 0, { type: "checkbox" });
    addDOMEvent(checkbox, "click", (function() {
        return function() {
            if (typeof(selection.getSelected()[0]) != "undefined") {
                // talk with server
                var data = {	id:selection.getSelected()[0],folder:activefolder,
    					enabled:checkbox.checked , source: com_openexchange_subscribe.currentSource
                   };
                data[com_openexchange_subscribe.currentSource] = {};

                com_openexchange_subscribe.update_enabled(com_openexchange_subscribe.get_enabled_string(checkbox.checked) , com_openexchange_subscribe.currentDisplayName, data, false);

            }
        };
    })());
    return checkbox;
}

com_openexchange_subscribe.get_enabled_string = function(bool) {
	 return (bool)?_('enabled'):_('disabled');
};

com_openexchange_subscribe.get_data = function(id) {
    ox.JSON.get(AjaxRoot + "/subscriptions?action=get&id=" + id +
        "&session=" + session, function(reply) { 
    	com_openexchange_subscribe.split.enableList(com_openexchange_subscribe.updatePubDetailView);
    });
};


/*
 * 
 * Configuration View
 * */


//return grid
com_openexchange_subscribe.getGrid = function() {
	
	
	com_openexchange_subscribe.colums_config = [{
	        text: _("Folder"),
	        index: 1,
	        clear: LiveGrid.makeClear(""),
	        set: function(div, sub) {
	    		var foldername = "";
	    		var folderpath = "";
	    		var folderid = (typeof sub != "undefined") ? sub : com_openexchange_subscribe.selected_subscribe[1];
	    		var cb_folderpath = function(folderpath) {
	    		    foldername = folderpath.slice(folderpath.lastIndexOf("/")+1, folderpath.length);
	    			folderpath = folderpath.slice(0,folderpath.lastIndexOf("/"));
	    			
	    			com_openexchange_subscribe.folders["id"+folderid] = [folderpath, foldername];

	    	    	if (div.firstChild)
	    	    		jQuery(div.firstChild).remove();
	    	    	
	    			jQuery('<span>').attr("title", folderpath)
	    			    .append(newtext(foldername)).appendTo(div);
	    	    	
	    		};
	    		ox.api.folder.getPathString({
	    		    folder: folderid,
	    		    success: cb_folderpath
	    		});
	    	}
		    },{
		        text: _("Source"),
		        index: 2,
		        clear: LiveGrid.makeClear(""),
		        set: function(div, path) {
		    		var module = path.slice(path.lastIndexOf(".")+1, path.length);
		 	    	if (div.firstChild)
		 	    		jQuery(div.firstChild).remove();
		 	    	
		 			jQuery('<span class="grid_module"/>')
		 			  .append(newtext(module)).appendTo(div);
		    	}
		    },{
		        text: _("Status"),
		        index: 4,
		        clear: LiveGrid.makeClear(""),
		        set: function(div, sub) {

	            var enabled_string = sub ? _("enabled") : _("disabled");
	            var enabled_class = sub ? "enabled" : "disabled";
	 	    	if (div.firstChild)
	 	    		jQuery(div.firstChild).remove();
	 	    	
	 			jQuery('<span>').attr("class", enabled_class)
	 			   .append(newtext(enabled_string)).appendTo(div);
		    		
		    	}
		    }];

		var grid = new LiveGrid(
				com_openexchange_subscribe.colums_config,
				selection
			);
		
	grid.emptylivegridtext = _("No subscription added");
 return grid;
	
};



/*
 * Returns a table node for the mail Header with a subscribe button
 * @param view - {string} - mail view i.e hsplit or vsplit
 * 
 * */
com_openexchange_subscribe.getTable = function(view) {
	
	com_openexchange_subscribe.mailHead[view] = newnode("table",{ display: "none", padding: "0 0.5em" },{ id:"mail."+view+".detail.header.puburl" , border : "0", width:"100%", className:"smallpopupborderbottom border-color-design mail-imip-content" },[
		newnode("tbody",null,null,[
			newnode("tr",null,null,[
				newnode("td",{padding: "5px"},null,[
					newnode("img",{width:"16", height:"16", align:"absmiddle"},{ src : getFullImgSrc("img/dummy.gif") },[])
				]),
				newnode("td",{ width: "100%" },{className:"font-style-big-headline"},[
					addTranslated(_("This mail contains an URL to a publication."))]),
				newnode("td",null,null,[
					com_openexchange_subscribe.fnButton(addTranslated(_("Subscribe this publication...")), com_openexchange_subscribe.ox_subcribePubURL)
				])
			])
		])
	]);
	
	return com_openexchange_subscribe.mailHead[view];
}


/*
 * Automatic subscript an URL in a Publish E-Mail, US4127
 * @param mailmessage - {object} - currently opened message in hsplit or vsplit view
 * @param view - {string} - mail view i.e hsplit or vsplit
 * 
 * */
com_openexchange_subscribe.checkSubscribeButton = function (mailmessage, view) {
    
    var pubURL = mailmessage.headers["X-OX-PubURL"] || "";
	var pubType = /^(\w+),(.*)$/.exec(mailmessage.headers["X-OX-PubType"])
	           || [, "", ""];
	var pubSource = targetSourceMapping[pubType[2]];
	
	com_openexchange_subscribe.getModuleType = function() {
		return pubType[1];
	}
	
    com_openexchange_subscribe.ox_subcribePubURL = function(e) {
        
		if (pubURLFolderpopupFrame.style.display == "none") {

            var currentModuleType = com_openexchange_subscribe.getModuleType();
            removeChildNodes(pubURLFolderpopup);
                        
        	ox.api.ui.selectFolder({
            	type: currentModuleType,
            	callback: function (data) {
        	    
                    // callback for click in folder tree
                    pubURLFolderpopupFrame.style.display = "none";
                    removeDOMEvent(body, "click", bodyPubClick);

                    // set current folder
                    ox.api.ui.setFolder(data.id);
                    
                    //switch view to subscribe tab
                    setTabLists(fdpropsTabsList, fdpropsPanelsList, fdpropsEventList);
                    ox.api.folder.viewProperties(data.id);
                    temporary.folderTabs.showTab(com_openexchange_subscribe.tab);
                    addedSubscription = { source: pubSource };
                    addedSubscription[pubSource] = { url: pubURL };
                },
            	node: pubURLFolderpopup
            });
            
            pubURLFolderpopupFrame.style.display = "block";
            treePubURLOpened = true;
            addDOMEvent(body, "click", bodyPubClick);
        }
		
	};
	
	//check if table node in mail head already created
	if(!com_openexchange_subscribe.mailHead[view]) {
		com_openexchange_subscribe.getTable(view);
		$("mail." + view + ".detail.header.phishing_protection").parentNode.insertBefore(com_openexchange_subscribe.mailHead[view], $("mail." + view + ".detail.header.phishing_protection"));
	}
	
	var treePubURLOpened = false;
	function bodyPubClick() {
        if (treePubURLOpened) {
        	treePubURLOpened = false;
            return;
        }
        removeChildNodes(pubURLFolderpopup);
        pubURLFolderpopupFrame.style.display = "none";
        removeDOMEvent(body, "click", bodyPubClick);
    }
	
	var pubURLFolderpopupFrame = newnode("div",
        { position: "absolute", display: "none", zIndex: 21,
          height: "19em", width: "18em", top: "50px", right: "185px",
          overflow: "auto" },
        { className: "background-color-content smallpopupborder " +
                     "border-color-design" });
	
	var pubURLFolderpopupHead = newnode("div",
            { height: "auto", padding: "5px" },
            { className: "background-color-content " +
                         "border-color-design" });
	
	var pubURLFolderpopup = newnode("div",
            { height: "auto", width: "18em",
              overflow: "auto" },
            { className: "background-color-content " +
                         "border-color-design" });
	
	pubURLFolderpopupHead.appendChild(document.createTextNode("Subscribe into:"/*i18n*/));
	pubURLFolderpopupFrame.appendChild(pubURLFolderpopupHead);
	pubURLFolderpopupFrame.appendChild(pubURLFolderpopup);
	
	$("mail." + view).appendChild(pubURLFolderpopupFrame);
	
    addDOMEvent(pubURLFolderpopup, "click", function(e) {
        cancelBubbling(e);
    });
	
	
    // check if mail contains a publication URL 
    if (pubURL && pubSource) {
        com_openexchange_subscribe.mailHead[view].style.display = "";
    } else {
        com_openexchange_subscribe.mailHead[view].style.display = "none";
    }
};

//register to mail load, this will triggert every time a mail is opened
register("OX_Mail_load",com_openexchange_subscribe.checkSubscribeButton);

// get modules
ox.JSON.get(AjaxRoot + "/subscriptionSources/?action=all"
    + "&columns=id,displayName,icon,module,formDescription&session=" + session,
    function(reply) {
        for (var i in reply.data) {
            var s = reply.data[i];
            var source = { id: s[0], displayName: s[1], icon: s[2],
                           module: s[3], formDescription: s[4] };
            com_openexchange_subscribe.sources[source.id] = source;
            var map = sourceTargetMappings[source.id];
            for (var i = 0; map && i < map.length; i++) {
                targetSourceMapping[map[i]] = source.id;
            }
            var module = com_openexchange_subscribe.modules[source.module];
            if (!module) {
                module = com_openexchange_subscribe.modules[source.module] = {};
            }
            module[source.id] = source;
        }
});

//is active?
com_openexchange_subscribe.supportsFolder = function (folder) {
    return Boolean(
        com_openexchange_subscribe.modules && folder &&
        folder.module in com_openexchange_subscribe.modules && 
        folder.own_rights & (127 << 14)
    );
};

//add menu item
// onClick open the tab subscribe of the folder property
com_openexchange_subscribe.folderMenuItem = new MenuItem(_("Subscribe"), 
    function() {
        setTabLists(fdpropsTabsList, fdpropsPanelsList, fdpropsEventList);
        ox.api.folder.viewProperties(this.getContext().data.id);
        temporary.folderTabs.showTab(com_openexchange_subscribe.tab);
    }
);


//set its "onShow" handler
com_openexchange_subscribe.folderMenuItem.onShow = function() {
    var self = this;
    // default
    self.setVisible(false);
    // get folder (might be async)
    ox.api.folder.get({
        folder: this.getContext().data.id,
        success: function (data) {
            // support for this folder?
            self.setVisible(com_openexchange_subscribe.supportsFolder(data));
        }
    });
    return this.visible && this.enabled;
    
};

com_openexchange_subscribe.folderMenuItem.getAutoEnabled = function() {
    // get folder
    ox.api.folder.get({
        folder: this.getContext().data.id,
        success: function (data) {
            // support for this folder?
            cont(com_openexchange_subscribe.supportsFolder(data));
        }
    });
};

var folderTypeSeperator = new MenuSeparator();
globalContextMenus.newFolderType.addItem(folderTypeSeperator);

var abo_folder_menu = new PopupMenu();

var new_abo_folder = new MenuItem(_("Subscribe"), abo_folder_menu);

globalContextMenus.newFolderType.addItem(new_abo_folder);

/*
 * Listener for subscribe submenu opens in RMB Folder
 * append menuitems to the subscribe menuitem, with possible subscribe services (i.e. facebook or gmx.de)
 * */
new_abo_folder.onShow = function() {	
	var folder = ox.api.folder.get({
        folder: this.getContext().data.id,
        success: function (data) {
			abo_folder_menu.removeAllItems();
			var availableTypes = com_openexchange_subscribe.modules[data.module];
			
			var visible = !isEmpty(availableTypes);
			new_abo_folder.setVisible(visible);
			folderTypeSeperator.setVisible(visible);
			
			for (var i in availableTypes) (function(type) {
			    var def = availableTypes[type];
			    
			    var item = new MenuItem(noI18n(def.displayName),
			        function() { new_subscribed_folder(this.getContext().data, data.module, def.displayName); });
			    item.onShow = function() {
			        this.setEnabled(true);
			    };
			    abo_folder_menu.addItem(item);
			})(i);	
		}
	});	
}

/*
 * RMB for subscribe folder
 * Appends a submenu "subscribe" to the RMB Foldermenu
 * @param parentFolderNode - {node} - clicked folder
 * @param folderModule - {string} - module of the clicked folder (i.e. contacts)
 * @param folderTitle - {string} - name of the subscribe service (i.e. facebook or gmx.de)
 * 
 * */
var new_subscribed_folder = function (parentFolderNode, folderModule, folderTitle) {
	
    var parent = parentFolderNode.id;
    
    // create new folder
    ox.api.folder.create({
        // parent folder
        folder: parent,
        // folder data
        data: {
            module: folderModule,
            title: folderTitle,
            permissions: [{
                bits: 403710016, /* all admin */
                entity: configGetKey("identifier"),
                group: false 
            }]
        },
        // on success
        success: function (data) {
            // get current view
            var view = ox.widgets.sidepanelViewControl.activeView;
            if (view) {
                // repaint now
                view.paint();
                // is it a tree?
                if (view.nodeIndex !== undefined) {
                    // get parent folder's tree node
                    view.selection.clickQuiet(data.id);
                    view.get(parent).open();
                    ox.api.ui.setFolder(data.id);
                } else {
                    // a flat view
                	if(view.selection)
                		view.selection.clickQuiet(data.id);
                    ox.api.ui.setFolder(data.id);
                }
                
                setTabLists(fdpropsTabsList, fdpropsPanelsList, fdpropsEventList);
                ox.api.folder.viewProperties(data.id);
                temporary.folderTabs.showTab(com_openexchange_subscribe.tab);
                com_openexchange_subscribe.tab.addNew({});
                
                if(typeof com_openexchange_subscribe.tab.children[0].children[0].combobox != "undefined") {
                    com_openexchange_subscribe.tab.children[0].children[0].combobox.setValue(folderTitle);
                }
            }
        },
        error: function (error) {
            // replaced drawError, which is defined nowhere, by simple alert
            alert(_("Unable to create a new subscription folder."));
            return true; // prevent global error
        }
    });
};


globalContextMenus.extended_folder_menu.addItem(com_openexchange_subscribe.folderMenuItem);

/* Refresh Button for subscribe folder */
com_openexchange_subscribe.generate_refresh_button = function(modulename) {
	
	registerView(modulename,
		null,
		function() {
	    	com_openexchange_subscribe.func_button_refresh_subscription_folder(modulename);
		},
		null,
		null,
		function() {
	    	com_openexchange_subscribe.func_button_refresh_subscription_folder(modulename); 
		}
	);	
	
	// getting module edit tab
	var tab = ox.widgets.toolBar.tabs[modulename + "Edit"];
	// creatng a new section
	var section = ox.widgets.toolBar.sections[modulename+"Subscriptions"] = new ox.gui.PanelMenuSection(_("Subscriptions"));
	// adding new menu item to section
	section.add(new ox.gui.MenuItem({ id: modulename + "-refresh", 
	    title: _("Refresh"), action: function() { refreshFolder(); }, 
	    icons: [ "img/toolbar/tb_loading.gif" ] })
	);
	// adding section to tab
    tab.add(section);
};


/* Refresh Button for subscribe folder */

com_openexchange_subscribe.generate_refresh_button("contacts");
com_openexchange_subscribe.generate_refresh_button("infostore");
com_openexchange_subscribe.generate_refresh_button("calendar");

/*
 * test if this folder a subscribed folder, so enable refresh button in the toolbar
 * */
com_openexchange_subscribe.func_button_refresh_subscription_folder = function() {
	ox.api.folder.get({
	    folder: activefolder,
	    success: function(folder) {
	        var section = ox.widgets.toolBar.sections[activemodule+"Subscriptions"];
	        if (section != undefined) {
	            section.setVisible(folder && folder.subscriptionFlag);
	        }
	    }
	});
};

function refreshFolder(callback) {
    ox.JSON.get(AjaxRoot + "/subscriptions?action=refresh&folder=" + activefolder + "&session=" + session,
        function() {
            var module = activemodule;
            if (module == "calendar") {
                storageCache.update();
            } else {
                OXCache.newRequest(null, activemodule,
                    { criteria: { folder_id: activefolder } },
                    null, null, true);
            }
            storageCache.update();
            if(callback)
            	callback();
        });
}

tab.init = function() {
    var sources, modules, onInit;
    
    // copy
    sources = com_openexchange_subscribe.sources;
    modules = com_openexchange_subscribe.modules;
    
    // visible?
    for (var s in sources) {
        if (temporary.folderTabs.folder.module == sources[s].module) {
            tab.setVisible(true);
            break;
        }
    }
    
    var old_enter = temporary.folderTabs.enter;
    temporary.folderTabs.enter = function() {
        tab.setVisible(Boolean(modules && this.folder.module in modules &&
                               (this.folder.own_rights & (127 << 14)) >= (2 << 14)) &&
                               	computePerm(this.folder.own_rights,0) >= 2);
        old_enter.call(this);
        if (sources) initSelect(); else onInit = initSelect;
    };
    
    // Left panel
    var grid = new LiveGrid([{
        text: _("Name"),
        index: 1,
        clear: LiveGrid.makeClear(""),
        set: LiveGrid.defaultSet
    },
    // Enabled flag
    {
        text: _("Enabled")/* i18n */,
        width: "6em",
        clear: emptyFunction,
        set: function(div, data) {
            if (!div.firstChild) {
                div.appendChild(com_openexchange_subscribe.addCheckBox(data[0]));
            }
            div.firstChild.checked = data[2] || false;
        }
    }], selection);
    grid.emptylivegridtext = _("No subscriptions configured");
    tab.list = grid;
    

    com_openexchange_subscribe.updatePubDetailMenu = function() {
		var deleteenabled = selection.count > 0;
        menuglobalzaehler = 0;
        //menuarrows[tab.viewID]["subscribe.subscriptions"] = [];
        menu_display_contents(tab.viewID, "subscribe.subscriptions", true,
            "subscribe.subscriptions.add");
        menu_display_contents(tab.viewID, "subscribe.subscriptions", deleteenabled,
            "subscribe.subscriptions.remove");
    }
    
    tab.list.events.register("Selected", com_openexchange_subscribe.updatePubDetailMenu);
    
    
    var storage = new Storage(0, []);

    tab.enableList = function() {
        ox.JSON.get(AjaxRoot +
            "/subscriptions?action=all&columns=id,displayName,enabled,source&folder=" +
            this.parent.folder.id + "&entityModule=" +
            this.parent.folder.module + "&session=" + session,
            function(reply) {
                storage.remove(0, storage.ids.length);
                storage.append(reply.data);
                grid.enable(storage);
                if (addedSubscription) {
                    tab.addNew({});
                    tab.set(addedSubscription);
                    addedSubscription = null;
                } else if (reply.data.length < 1) {
                	tab.addNew({});
                } else {
                	grid.selection.click(0);
                }
            });
    };
        
    function load(id, cont) {
        ox.JSON.get(AjaxRoot + "/subscriptions?action=get&id=" + id +
            "&session=" + session, function(reply) { 
        		cont(reply.data); 
        		com_openexchange_subscribe.currentSource = reply.data.source;
        		com_openexchange_subscribe.currentDisplayName = reply.data.displayName;
        });
    }

    tab.load = function(cont) { load(selection.getSelected()[0], cont); };
    
    function refresh(id, callback) {
        ox.JSON.get(AjaxRoot + "/subscriptions?action=refresh&id=" + id +
            "&folder=" + tab.parent.folder.id + "&session=" + session,
            function() {
                var module = tab.parent.folder.module;
                if (module == "calendar") {
                    storageCache.update();
                } else {
                    OXCache.newRequest(null, tab.parent.folder.module,
                        { criteria: { folder_id: tab.parent.folder.id } },
                        null, null, true);
                }
                callback();
            });
    }
    
    
    tab.leave = function() {
    	// temporary fix for bug #16710
        // @todo: needs to be re-viewed by vp
    	grid.selection.reset();
    	tab.cancelView();
    	
    	//workaround for events unregister
    	if(typeof tab.list.selection.events.events.Selected != "undefined")
    		tab.list.selection.events.events.Selected = [];
    }
    
    tab.save = function(data, cont) {
    	// temporary fix for bug #16710
    	// @todo: needs to be re-viewed by vp
    	if (isEmpty(data)) {
    		return;
    	}
    	
        if ("id" in data) {
            ox.JSON.put(AjaxRoot + "/subscriptions/?action=update&session=" +
                session, data, function(reply) {
                    refresh(data.id, function() {
                        load(data.id, function(data) {
                            storage.localUpdate([data.id], function(old) {
                                return [data.id, data.displayName];
                            });
                            cont(data);
                        });
                    });
                });
        } else {
            ox.JSON.put(AjaxRoot + "/subscriptions/?action=new&session=" +
                session, data, function(reply) {
                    refresh(reply.data, function() {
                        load(reply.data, function(data) {
                            storage.append([[data.id, data.displayName]]);
                            cont(data);
                        });
                    });
                });
        }
    };
    
    //menuarrows[tab.viewID] = {};

    var menu = MenuNodes.createSmallButtonContext("subscribe.subscriptions",
        _("Subscriptions"));
    MenuNodes.createSmallButton(menu, "subscribe.subscriptions.add", _("Add"),
        getFullImgSrc("img/menu/add_category.gif"),
        getFullImgSrc("img/menu/add_category_d.gif"),
        function() { tab.addNew({}); });
    MenuNodes.createSmallButton(menu, "subscribe.subscriptions.remove", _("Remove"),
        getFullImgSrc("img/menu/remove_category.gif"),
        getFullImgSrc("img/menu/remove_category_d.gif"), confirmDelete);
    addMenuNode(menu.node, MenuNodes.FIXED, 31);
    changeDisplay(tab.viewID, "subscribe.subscriptions");
    

    //menuarrows[tab.viewID] = {};
    register("OX_SELECTED_ITEMS_CHANGED", function() {
    	window.setTimeout(function() {
    		
    	}, 100);        
    });
    

    function confirmDelete() {
        if (!selection.count) return;
        newConfirm(ngettext("Delete Subscription", "Delete Subscriptions",
                            selection.count),
            ngettext(
                "Are you sure you want to delete the selected subscription?",
                "Are you sure you want to delete the selected subscriptions?",
                selection.count),
            AlertPopup.YES | AlertPopup.NO, null, null, handleDelete);
    }
    function handleDelete() {
        var ids = selection.getSelected();
        ox.JSON.put(AjaxRoot + "/subscriptions?action=delete&session=" + session,
            ids, function(reply) { storage.removeIDs(ids); });
    }

    
    

    // Right panel
    var select = new ox.UI.ComboBox(_("Source"));
    select.changed = function() { entry.updateSelect(); };
    if (sources) initSelect(); else onInit = initSelect;
    function initSelect() {
        var module = tab.parent.folder.module;
        var ids = [], names = [];
        for (var i in sources) {
            var m = sources[i].module;
            if (m == module) {
                ids.push(i);
                names.push(sources[i].displayName);
            }
        }
        select.setEntries(ids, names);
        onInit = undefined;
    }
    
    var entry = new ox.UI.Container();
    entry.addContent = function(node_id) {
        this.childWidth = this.parent.childWidth;
        this.table = newnode("div");
        this.node = this.parent.addRow(this.table);
        ox.UI.Container.prototype.addContent.apply(this, arguments);
    };
    entry.addRow = ox.Configuration.VSplit.prototype.addRow;
    entry.addCells = ox.Configuration.VSplit.prototype.addCells;
    entry.addWidget(select);
    
    entry.updateSelect = function() {
        for (var i = this.children.length - 1; i > 0; i--) {
            this.deleteWidget(entry.children[i]);
        }
        var id = select.get();
        if (id && (id in sources)) {
            var defs = sources[id].formDescription;
            for (var i = 0; i < defs.length; i++) {
                var def = defs[i];
                var widget = widgets[def.widget](def);
                if ("defaultValue" in def)
                    widget.default_value = def.defaultValue;
                this.addWidget(widget, def.name);
            }
        }
    };
    var defaultSet = entry.set;
    entry.set = function(value) {
        this.id = value.id;
        select.set(value.source);
        this.updateSelect();
        defaultSet.call(this, value[value.source]);
    };
    var defaultGet = entry.get;
    entry.get = function() {
        var id = select.get();
        if (!id) return;
        var value = {
            source: id,
            folder: tab.parent.folder.id,
            entityModule: tab.parent.folder.module,
            entity: { folder: tab.parent.folder.id }
        };
        value[value.source] = defaultGet.call(this);
        if (this.id) value.id = this.id;
        return value;
    };
    tab.addWidget(entry, ox.Configuration.Group.NoField);
    var subscriptiondur = new ox.UI.Text("");
    subscriptiondur.addContent = function() {
    	this.text = newnode("div",{lineHeight:"1.2em",marginTop:"1.5em"});
    	this.text.innerHTML = _("<b>Approximate Duration for Subscriptions</b><br/><br/>Subscribing to contacts that are not delivered by another Open-Xchange Server (i.e. OXMF) may take some time. <br/>Importing 100 contacs from Xing takes about 5 minutes for example.<br/><br/>We are continually improving this functionality. Future releases will work significantly faster.");
        this.node = this.parent.addRow(this.text,true);
        ox.UI.Widget.prototype.addContent.apply(this, arguments);
    };
    tab.addWidget(subscriptiondur);
};

