// create plugin namespace
var com_openexchange_publish = {};
com_openexchange_publish.targets = {};
com_openexchange_publish.modules = {};
com_openexchange_publish.folders = {};
com_openexchange_publish.currentModule;
com_openexchange_publish.currentDisplayName;

var selection = new Selection();
var storage = new Storage(0, []);

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


ox.JSON.get(AjaxRoot + "/templating?action=names&session=" + session,
     function(reply) {
		com_openexchange_publish.template_key = [""];
		com_openexchange_publish.template_value = [_("Please choose")];
			if(reply.data) {
				for(var i in reply.data) {
					com_openexchange_publish.template_key.push(reply.data[i]);
					com_openexchange_publish.template_value.push(reply.data[i]);
				}  					
				
			}

});

/* Widgets for form field */
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;
    },
    templateChooser: function(def) {
    	var field_template_chooser = new ox.UI.ComboBox(noI18n(def.displayName));
    	field_template_chooser.setEntries(com_openexchange_publish.template_key, com_openexchange_publish.template_value); 
    	//field_template_chooser.changed = changePort;
	    return field_template_chooser; 
    	
    }
};


/* functions for publications content in Tab */

com_openexchange_publish.getEntry = function(select, targets) {
	var targets = targets;
	var select = select;
	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 targets)) {
            var defs = targets[id].formDescription;
            for (var i = 0; i < defs.length; i++) {
                var def = defs[i];
                if(def.widget == "com.openexchange.templating.templateChooser") {
                	def.widget = "templateChooser";
                }
                	
                var widget = widgets[def.widget](def);
                this.addWidget(widget, def.name);
                if ("defaultValue" in def) {
                    widget.default_value = def.defaultValue;
                    widget.set(def.defaultValue);
                }
            }
        }
    };

    var defaultSet = entry.set;
    entry.set = function(value) {
        this.id = value.id;
        select.set(value.target);
        this.updateSelect();
        defaultSet.call(this, value[value.target]);
    };
    
    var defaultGet = entry.get;
    entry.get = function() {
        var id = select.get();
        if (!id) return;
        var value = {
            target: id,
            entityModule: tab.parent.folder.module,
            entity: { folder: tab.parent.folder.id }
        };
        value[value.target] = defaultGet.call(this);
        if (this.id) value.id = this.id;
        return value;
    };
    
    return entry;
};

// return grid
com_openexchange_publish.getGrid = function(configuration_page) {
	
	com_openexchange_publish.colums_view = [{
        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_publish.addCheckBox(data[0]));
            }
            div.firstChild.checked = data[2] || false;
        }
    }];
	
	com_openexchange_publish.colums_config = [{
	        text: _("Folder"),
	        index: 1,
	        clear: LiveGrid.makeClear(""),
	        set: function(div, pub) {
	    		var foldername = "";
	    		var folderpath = "";
	    		var folderid = (typeof pub != "undefined") ? pub.folder : com_openexchange_publish.selected_publish[1].folder;
	    		var cb_folderpath = function(folderpath) {
                    foldername = folderpath.slice(folderpath.lastIndexOf("/")+1, folderpath.length);
	    			folderpath = folderpath.slice(0,folderpath.lastIndexOf("/"));
	    			
	    			com_openexchange_publish.folders["id"+folderid] = [folderpath, foldername];

	    	    	if (div.firstChild)
	    	    		jQuery(div.firstChild).remove();
	    	    	
	    			jQuery('<span>').attr("title", folderpath)
	    			    .append(newtext(foldername)).appendTo(div);
	    			com_openexchange_publish.foldersLoaded = true;
	    	    	
	    		};
	    		ox.api.folder.getPathString({
	    		    folder: folderid,
	    		    success: cb_folderpath
	    		});
	    	}
		    },{
		        text: _("Module"),
		        index: 2,
		        clear: LiveGrid.makeClear(""),
		        set: LiveGrid.defaultSet
		    },{
		        text: _("Status"),
		        index: 4,
		        clear: LiveGrid.makeClear(""),
		        set: function(div, pub) {

	            var enabled_string = com_openexchange_publish.get_enabled_string(pub);
    	    	if (div.firstChild)
    	    		jQuery(div.firstChild).remove();
    	    	
    			jQuery('<span>').attr("class", enabled_string)
                    .append(newtext(enabled_string)).appendTo(div);
		    		
		    	}
		    }];

		if(configuration_page) {
			var grid = new LiveGrid(
					com_openexchange_publish.colums_config,
					new Selection()
				);
		} else {
			var grid = new LiveGrid(
					com_openexchange_publish.colums_view, 
					selection
				);
		}
	grid.emptylivegridtext = _("No publications added");
    return grid;
	
};

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

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

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

//Helper
com_openexchange_publish.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],
    					enabled:checkbox.checked , module: com_openexchange_publish.currentModule
                   };
                
                com_openexchange_publish.update_enabled(com_openexchange_publish.get_enabled_string(checkbox.checked) , com_openexchange_publish.currentDisplayName, data, false);

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



/*
 * 
 *  BEGIN Configuration view 
 *  
 *  */

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

com_openexchange_publish.node2 = new ox.Configuration.LeafNode("configuration/oxsocial/publications",_("Publications")); //Navigation Child

com_openexchange_publish.split = new ox.Configuration.VSplit(com_openexchange_publish.node2, _("Publications"), 0.28, false); //Section Headline

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

            	if(cb)cb();

            });
    };
    
    com_openexchange_publish.openFolder = function () {
        var id = com_openexchange_publish.selected_publish[1].folder;
        if (id !== undefined) {
            ox.UIController.setFolder({
                folder: id,
                module: "default"
            });
        }
   };
   
    com_openexchange_publish.oldWidget = false;
    
    /* view selected object */
    com_openexchange_publish.updatePubDetailView = function() {
    	var ids = com_openexchange_publish.split.list.selection.getSelected();
    	/* count the grid selections */
    	if (ids && ids.length == 1) {    		    		
    		com_openexchange_publish.selected_publish = com_openexchange_publish.allData["id"+ids[0]];
    		var enabled_string = (com_openexchange_publish.selected_publish[4])?_('enabled'):_('disabled');
            var enabled_state = (com_openexchange_publish.selected_publish[4])? ' checked':'';
            if (com_openexchange_publish.folders["id"+com_openexchange_publish.selected_publish[1].folder]) {
                content_string = "<div class='wrapper_detail_infos'>"+
    				            		"<h2>"+_('Detail information for publication')+"</h2>"+
    		      						"<div class='detail_info'>"+
    		      							"<label>"+_('Folder name')+"</label> <a class='linkInView' id='foldername_pub_"+com_openexchange_publish.selected_publish[1].folder+"'>"+com_openexchange_publish.folders["id"+com_openexchange_publish.selected_publish[1].folder][1]+"</a>"+
    		      						"</div>"+
    				            		"<div class='detail_info'>"+
    				            			"<label>"+_('Module')+"</label> "+com_openexchange_publish.selected_publish[2]+
    				            		"</div>"+
    				            		"<div class='detail_info'>"+
    				            			"<label>"+_('Publication status')+"</label> "+enabled_string+
    				            			"<input type='checkbox'" + enabled_state +
    				            			" class='t_checkbox' name='publish_"+com_openexchange_publish.selected_publish[0]+
    				            			"' id='publish_"+com_openexchange_publish.selected_publish[0]+"' value='true' />"+
    		      						"</div>"+
    		      						"<div class='detail_info'>"+    		      						
    		      							"<label>"+_('Folder path')+"</label> <a class='linkInView' id='foldername_pub2_"+com_openexchange_publish.selected_publish[1].folder+"'>"+com_openexchange_publish.folders["id"+com_openexchange_publish.selected_publish[1].folder][0]+"/"+com_openexchange_publish.folders["id"+com_openexchange_publish.selected_publish[1].folder][1]+"</a>"+
    		      						"</div>"+
    		      					"</div>";
            } else {
                content_string = "";
            }
		} else {
			if (ids && ids.length > 1) {
	    		var content_message = _('Please select only one Publication');
			} else {
	    		var content_message = _('No Publication selected');
			}
    		content_string = "<div class='wrapper_detail_infos'>"+
    		"<h2>"+_('Detail Information for Publication')+"</h2>"+
				"<div class='detail_info'>"+
				"<label>"+content_message+"</label>"+
				"</div>"+
			"</div>";
		}
    	
    	
		com_openexchange_publish.selected_publish = com_openexchange_publish.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_publish.oldWidget) {
        	com_openexchange_publish.split.deleteWidget(com_openexchange_publish.oldWidget);
        }
        com_openexchange_publish.oldWidget = entry;
        com_openexchange_publish.split.addWidget(entry, ox.Configuration.Group.NoField);
		   
        if (ids && ids.length == 1 && content_string) { 
			addDOMEvent(document.getElementById('foldername_pub_'+com_openexchange_publish.selected_publish[1].folder), "click", com_openexchange_publish.openFolder);
			addDOMEvent(document.getElementById('foldername_pub2_'+com_openexchange_publish.selected_publish[1].folder), "click", com_openexchange_publish.openFolder);
        }
		
    };

    com_openexchange_publish.split.save = function () {
        var final_state = com_openexchange_publish.get_enabled_string(jQuery('#publish_'+com_openexchange_publish.selected_publish[0])[0].checked);
    	var updatedfolder = com_openexchange_publish.folders["id"+com_openexchange_publish.selected_publish[1].folder][1];
		data = {	id:com_openexchange_publish.selected_publish[0],
					enabled:jQuery('#publish_'+com_openexchange_publish.selected_publish[0])[0].checked, module: com_openexchange_publish.selected_publish[2]
               };
        com_openexchange_publish.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 Publications')+"</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_publish.oldWidget = entry;
    com_openexchange_publish.split.addWidget(entry, ox.Configuration.Group.NoField);
    
};


/* END Configuration view */









// get modules
ox.JSON.get(AjaxRoot + "/publicationTargets/?action=all" +
    "&columns=id,displayName,icon,module,formDescription&session=" + session, 
    function(reply) {
        for (var i in reply.data) {
            var t = reply.data[i];
            var target = { id: t[0], displayName: t[1], icon: t[2],
                           module: t[3], formDescription: t[4] };
            com_openexchange_publish.targets[target.id] = target;
            var module = com_openexchange_publish.modules[target.module];
            if (!module) {
                module = com_openexchange_publish.modules[target.module] = {};
            }
            module[target.id] = target;
        }
    }
);



/*
 * 
 * Kontext Menu in sidepanel
 * 
 * */

// is active?
com_openexchange_publish.supportsFolder = function (folder) {
    return Boolean(
        com_openexchange_publish.modules && 
        folder && folder.module in com_openexchange_publish.modules && 
        folder.own_rights & (1 << 28)
    );
};

// add menu item
com_openexchange_publish.folderMenuItem = new MenuItem(_("Publish"), 
    function() { 
        setTabLists(fdpropsTabsList, fdpropsPanelsList,fdpropsEventList);
        ox.api.folder.viewProperties(this.getContext().data.id);
        temporary.folderTabs.showTab(com_openexchange_publish.tab);
    }
);

// set its "onShow" handler
com_openexchange_publish.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_publish.supportsFolder(data));
        }
    });
    return this.visible && this.enabled;
};

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



/*
 * 
 * Folder properties tab
 * 
 * */

tab.init = function() {

    var targets, modules, onInit;
    
    // copy
    targets = com_openexchange_publish.targets;
    modules = com_openexchange_publish.modules;
    
    // visible?
    for (var t in targets) {
        if (temporary.folderTabs.folder.module == targets[t].module) {
            tab.setVisible(true);
            break;
        }
    }
        
    var old_enter = temporary.folderTabs.enter;
    temporary.folderTabs.enter = function() {
        var pubActive = Boolean(
            modules && this.folder.module in modules && this.folder.own_rights & (1 << 28)
        );
        tab.setVisible(pubActive);
        old_enter.call(this);
        if (targets) initSelect(); else onInit = initSelect;
    };
    
    tab.list = com_openexchange_publish.getGrid(false);
    

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

    tab.load = function(cont) { load(selection.getSelected()[0], cont);};
    
    
    tab.leave = function() {
    	// temporary fix for bug #16710
        // @todo: needs to be re-viewed by vp
    	tab.list.selection.reset();
    	tab.cancelView();
    }
    
    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 + "/publications/?action=update&session=" +
                session, data, function(reply) {
                    load(data.id, function(data) {
                        storage.localUpdate([data.id], function(old) {
                            return [data.id, data.displayName];
                        });
                        cont(data);
                    });
                });
        } else {
            ox.JSON.put(AjaxRoot + "/publications/?action=new&session=" +
                session, data, function(reply) {
                    load(reply.data, function(data) {
                        storage.append([[data.id, data.displayName]]);
                        cont(data);
                    });
                });
        }
    };
    
    menuarrows[tab.viewID] = {};
    var menu = MenuNodes.createSmallButtonContext("publish.publications",
        _("Publications"));
    MenuNodes.createSmallButton(menu, "publish.publications.add", _("Add"),
        getFullImgSrc("img/menu/add_category.gif"),
        getFullImgSrc("img/menu/add_category_d.gif"),
        function() { tab.addNew({}); });
    MenuNodes.createSmallButton(menu, "publish.publications.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, "publish.publications");
    
    menuarrows[tab.viewID] = {};
    register("OX_SELECTED_ITEMS_CHANGED", function() {
        var deleteenabled = selection.count > 0;
        menuglobalzaehler = 0;
        menuarrows[tab.viewID]["publish.publications"] = [];
        menu_display_contents(tab.viewID, "publish.publications", true,
            "publish.publications.add");
        menu_display_contents(tab.viewID, "publish.publications", deleteenabled,
            "publish.publications.remove");
    });

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

    // Right panel
    var select = new ox.UI.ComboBox(_("Target"));
    select.changed = function() { entry.updateSelect(); };
    if (targets) initSelect(); else onInit = initSelect;
    function initSelect() {
        var module = com_openexchange_publish.tab.parent.folder.module;
        var ids = [], names = [];
        for (var i in targets) {
            var m = targets[i].module;
            if (m == module) {
                ids.push(i);
                names.push(targets[i].displayName);
            }
        }
        select.setEntries(ids, names);
        onInit = undefined;
        // Done!
//        if (com_openexchange_publish.tab.initSelectDone) {
//            com_openexchange_publish.tab.initSelectDone();
//        }
    }
    
    var entry = com_openexchange_publish.getEntry(select, targets);
    
    
    
    tab.addWidget(entry, ox.Configuration.Group.NoField);


// Option for sending an e-mail about this subscription
	var info_mail_button = new ox.UI.Button(_("Send E-Mail about this publication"));
	info_mail_button.click = function() {
	    // compose mail
	    var pub_url = entry.children[4].anchor.href;
	    ox.api.mail.compose({
	        params: {
	            subject: _("Publication") /*i18n*/
	        },
	        data: {
	            headers: {
                    "X-OX-PubURL": pub_url,
                    "X-OX-PubType": this.pubType
                },
	            aInfoMailAttachmentLink: [{
	                content_type: "text/plain",
	                content: pub_url
                }]
	        }
	    });
	}
	var on_off_switcher = { 
		get: function(data, value) {},
	    set: function(data) {
            info_mail_button.pubType = data.entityModule + "," + data.target;
			info_mail_button.setEnabled(! isEmpty(data));
		}
	};
	tab.addWidget(info_mail_button, on_off_switcher);


    var privacy = new ox.UI.Button("");
    privacy.addContent = function() {
    	this.text = newnode("div",{lineHeight:"1.2em",marginTop:"1.5em"});
    	this.text.appendChild(newnode("p", { fontWeight: "bold" }, 0, [ document.createTextNode(_("Attention"))]));
    	this.text.appendChild(newnode("p", 0, 0, [ document.createTextNode( _("The published data will be accessible to everyone on the Internet. Please consider, which data you want to publish.") )]));
    	
    	this.text.appendChild(newnode("p", { fontWeight: "bold" }, 0, [ document.createTextNode(_("Privacy Notice"))]));
    	var tmpText = _("When using this publish feature, you as the current owner of the data are responsible for being careful with privacy rules and for complying with legal obligations (Copyright, Privacy Laws).\n\nEspecially when publishing personal data you are the responsible party according to the Federal Data Protection Act (BDSG, Germany) or other Privacy Acts of your country.\n\nAccording to European and other national regulations you as the responsible party are in charge of data economy, and must not publish or forward personal data without the person’s consent.\n\nBeyond legal obligations, Open-Xchange would like to encourage extreme care when dealing with personal data. Please consider carefully where you store and to whom you forward personal data. Please ensure appropriate access protection, e.g. by proper password protection.");
    	var nText = String(tmpText).split("\n");
        for (var i in nText) {
        	this.text.appendChild(document.createTextNode(nText[i]));
        	this.text.appendChild(newnode("br"));
        }
    	this.node = this.parent.addRow(this.text,true);
        ox.UI.Widget.prototype.addContent.apply(this, arguments);
    };
    tab.addWidget(privacy, ox.Configuration.Group.NoField);
};