/**
 * 
 * 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) Open-Xchange Inc., 2006-2011
 * Mail: info@open-xchange.com 
 * 
 * @author Jan Finsel <jan.finsel@open-xchange.com>
 * 
 */

register("OX_Configuration_Loaded", function() {
	var configerrors=false;
	try {
		if (typeof(config.gui) == "string") {
			config.gui = eval("(" + config.gui + ")");
		}
	} catch (e) {
		delete(config.gui);
		//#. %s is the error message.
		//#, c-format
		alert(format(_("Syntax error in config: \n%s"), e.message));
	}
	if (!configContainsKey("identifier") || !configContainsKey("contact_id")) {
		 configerrors=true;
		 alert(_("Configuration damaged, please inform the administrator."));
	} 
	if (!configContainsKey("language")) {
			configSetKey("language","de_DE");
	}
	if (!configContainsKey("timezone")) {
		configSetKey("timezone","Europe/Berlin");
	}
	if (!configContainsKey("folder"))  {
		configSetKey("folder",{});	
	}	
 	if (!configContainsKey("modules.tasks.notifyNewModifiedDeleted")) {
		configSetKey("modules.tasks.notifyNewModifiedDeleted",false);
    }
    if (!configContainsKey("modules.tasks.notifyAcceptedDeclinedAsParticipant")) {
    	configSetKey("modules.tasks.notifyAcceptedDeclinedAsParticipant",true);
    }
	if(!configContainsKey("mail.deletemail")) {
		configSetKey("mail.deletemail",false);	
	}	
	if(!configContainsKey("gui.menu.menuiteration")) {
		configSetKey("gui.menu.menuiteration",2);
	}
	if(!configContainsKey("gui.mail.notifyacknoledge")) {
		configSetKey("gui.mail.notifyacknoledge",true);
	}
    if(!configContainsKey("gui.mail.showimage")) {
        configSetKey("gui.mail.showimage", true);
    }
	if(!configContainsKey("gui.mail.select_first_message")) {
        configSetKey("gui.mail.select_first_message",true);
    }
	if(!configContainsKey("mail.appendmailtext")) {
		configSetKey("mail.appendmailtext",true);
	}
	if(!configContainsKey("gui.mail.htmlmessage")) {
		configSetKey("gui.mail.htmlmessage",true);
	}
	if(!configContainsKey("mail.vcard")) {
		configSetKey("mail.vcard",false);
	}
	if(!configContainsKey("gui.mail.editor_featureset")) {
		configSetKey("gui.mail.editor_featureset", 2);
		configSetKey("mail.inlineattachments",true);
		configSetKey("mail.emoticons",true);
		configSetKey("mail.colorquoted",true);
	}
	if (!configContainsKey("gui.mail.showname")) {
	    configSetKey("gui.mail.showname", false);
	}
	if(!configContainsKey("gui.mail.formatmessage")) {
		configSetKey("gui.mail.formatmessage","ALTERNATIVE")
	} else if(configGetKey("gui.mail.formatmessage") == "text") {
		configSetKey("gui.mail.formatmessage","ALTERNATIVE")
	}
	if(!configContainsKey("gui.mail.autocomplete")) {
		configSetKey("gui.mail.autocomplete",true)
	}
	if(!configContainsKey("mail.forwardmessage")) {
		configSetKey("mail.forwardmessage","Inline");
	}
	if(!configContainsKey("mail.linewrap")) {
		configSetKey("mail.linewrap",70)
	}
	if(!configContainsKey("gui.calendar.interval")) {
		configSetKey("gui.calendar.interval",30);
	}
	if(!configContainsKey("gui.calendar.starttime")) {
		configSetKey("gui.calendar.starttime",8);
	}
	if(!configContainsKey("gui.calendar.endtime")) {
		configSetKey("gui.calendar.endtime",18);
	}
	if(!configContainsKey("gui.calendar.default_reminder")) {
		configSetKey("gui.calendar.default_reminder",15);
	}
	if(!configContainsKey("gui.calendar.teamview.workingTimeOnly")) {
        configSetKey("gui.calendar.teamview.workingTimeOnly", true);
    }
	
    if (!configContainsKey("gui.calendar.views")) {
        if (configContainsKey("gui.calendar.view")) {
            var view = configGetKey("gui.calendar.view");
            if (!view || typeof view != "object") {
                var match = /^calendar\/([^\/]+)\/([^\/]+)$/.exec(view)
                    || [, "calendar", "day"];
                view = { view: match[1], calendar: match[2], team: match[2],
                         list: match[2], shared: true };
            }
            if(!(   configGetKey("modules.calendar.calendar_freebusy")
                && configGetKey("modules.calendar.calendar_teamview")))
            {
                if (view.view == "team") view.view = "calendar";
            }
        } else {
            var view = { view: "calendar", calendar: "workweek", team: "workweek",
                         list: "weorkweek", shared: true };
        }
        configSetKey("gui.calendar.views", view);
        configSetKey("gui.calendar.view", getDefaultCalendarView());
    }
	if (!configContainsKey("gui.calendar.allfolders")) {
		configSetKey("gui.calendar.allfolders",true);
		configSetKey("modules.calendar.notifyAcceptedDeclinedAsCreator",true);
    	configSetKey("modules.tasks.notifyAcceptedDeclinedAsCreator",true);
	}
	if(!configContainsKey("gui.calendar.day.numberofappointments")) {
		configSetKey("gui.calendar.day.numberofappointments",4);
	}
	if(!configContainsKey("gui.calendar.workweek.numberofappointments")) {
		configSetKey("gui.calendar.workweek.numberofappointments",2);
	}
	if(!configContainsKey("gui.calendar.workweek.startday")) {
		configSetKey("gui.calendar.workweek.startday",1);
	}
	if(!configContainsKey("gui.calendar.workweek.countdays")) {
		configSetKey("gui.calendar.workweek.countdays",5);
	}
	if(!configContainsKey("gui.calendar.custom.countdays")) {
		configSetKey("gui.calendar.custom.countdays",3);
	}
	if(!configContainsKey("gui.calendar.custom.numberofappointments")) {
		configSetKey("gui.calendar.custom.numberofappointments",3);
	}
	if (!configContainsKey("modules.calendar.notifyNewModifiedDeleted")) {
        configSetKey("modules.calendar.notifyNewModifiedDeleted",false);
    } 
    if (!configContainsKey("modules.calendar.notifyAcceptedDeclinedAsParticipant")) {
        configSetKey("modules.calendar.notifyAcceptedDeclinedAsParticipant",true);
    }
	if(!configContainsKey("gui.contacts.view")) {
		configSetKey("gui.contacts.view","contacts/cards");
	}
	if(!configContainsKey("gui.infostore.view")) {
		configSetKey("gui.infostore.view","infostore/split");
	}
	if(!configContainsKey("gui.mail.view")) {
		configSetKey("gui.mail.view","mail/hsplit/unthreaded");
	}
	if(!configContainsKey("gui.mail.signatures")) {
		configSetKey("gui.mail.signatures",new Array());
	}
	if(!configContainsKey("reloadtimes")) {
		configSetKey("reloadtimes",[0]);		
	}
	if(!configContainsKey("gui.global.autorefresh")) {
		configSetKey("gui.global.autorefresh",10);
	} else {
		var isvalid=false;
		var myrel=configGetKey("reloadtimes");		
		for(var i=0;i<myrel.length;i++) {
			if(configGetKey("gui.global.autorefresh")*60000==myrel[i]) {
				isvalid=true;
				break;
			}
		}
		if(!isvalid) {
			configSetKey("gui.global.autorefresh",0);
		}
	}
	if(!configContainsKey("gui.effects.hover.portal")) {
		configSetKey("gui.effects.hover.portal",true);
	}
	if(!configContainsKey("gui.effects.hover.mail")) {
		configSetKey("gui.effects.hover.mail",false);
	}
	if(!configContainsKey("gui.effects.hover.calendar")) {
		configSetKey("gui.effects.hover.calendar",true);
	}
	if(!configContainsKey("gui.effects.hover.contacts")) {
		configSetKey("gui.effects.hover.contacts",true);
	}
	if(!configContainsKey("gui.effects.hover.tasks")) {
		configSetKey("gui.effects.hover.tasks",true);
	}
	if(!configContainsKey("gui.effects.hover.infostore")) {
		configSetKey("gui.effects.hover.infostore",true);
	}
	if(!configContainsKey("gui.effects.hover.speed")) {
		configSetKey("gui.effects.hover.speed",3);
	}
	if(!configContainsKey("gui.effects.global")) {
		configSetKey("gui.effects.global",false);
		configSetKey("gui.effects.fading",false);
	}
	if (!configContainsKey("gui.categories.local")) {
		configSetKey("gui.categories.local", []);
		ox.categories.utils.migrateTags();
	}
//	if (!configContainsKey("gui.FolderTreeState")) {
//		configSetKey("gui.FolderTreeState",new Object);
//	}			
	if (!configContainsKey("gui.contacts.gridsort") || !isNaN(configGetKey("gui.contacts.gridsort")))   {
		configSetKey("gui.contacts.gridsort","last_name");
	}
	if (!configContainsKey("gui.contacts.gridorder")) {
		configSetKey("gui.contacts.gridsort","asc");
	}			
	if (!configContainsKey("gui.contacts.cardsToViewPerColumn")) {
		configSetKey("gui.contacts.cardsToViewPerColumn","auto");
	}
	if (!configContainsKey("gui.tasks.view")) {
		configSetKey("gui.tasks.view","tasks/split");
	}
	if(!configContainsKey("gui.tasks.gridsort")) {
		configSetKey("gui.tasks.gridsort","200");
	}
	if(!configContainsKey("gui.tasks.gridorder")) {
		configSetKey("gui.tasks.gridsort","asc");
	}
	if(!configContainsKey("gui.tasks.interval")) {
		configSetKey("gui.tasks.interval",30);
	}
	if(!configContainsKey("gui.global.save")) {
		configSetKey("gui.global.save",1);
	}
	if(!configContainsKey("gui.global.confirmpopup")) {
		configSetKey("gui.global.confirmpopup",true);
	} else {
		var id=configGetKey("gui.global.save");
		if(id != 0 && id != 1 && id != 2) {
			configSetKey("gui.global.save",2);
		}
	}
	if(!configContainsKey("gui.portal.internalcontents")) {
		configSetKey("gui.portal.internalcontents",new Array());
	}
	if(!configContainsKey("gui.portal.externalcontents")) {
		configSetKey("gui.portal.externalcontents",new Array());
	}
	
	// embedded windows
	if (!configContainsKey("ui.global.windows.mode")) {
        configSetKey("ui.global.windows.mode", { value: "embedded", configurable: true });
    }
	
	// toolbar
    if (!configContainsKey("ui.global.toolbar.mode")) {
        configSetKey("ui.global.toolbar.mode", { value: "tabbased", configurable: true });
    }
	
	triggerEvent("OX_Configuration_Set_Empty");
});
registerModule("configuration", _("Configuration"), 100);
function configuration_changed() {
	for (var i in configuration_changed_fields) {
		if(configuration_changed_fields[i] === true) 
			return true;
	}
	return false;
}
var configuration_changed_fields=new Object();
var configuration_changed_outside=false;
configuration_changed_fields["timezone"]=false;
configuration_changed_fields["language"]=false;
configuration_changed_fields["gui"]=false;
configuration_changed_fields["mail"]=false;
configuration_changed_fields["folder"]=false;
configuration_changed_fields["calendarnotification"]=false;
configuration_changed_fields["tasknotification"]=false;
configuration_changed_fields["modules"]=false;

var lastViewed = "";
var changed = new Array();
var changed_inv = false;
var foldersChanged = 0;
var j = 0;
var configVisited = false;
var configToolbars = {};

(function() {
	register("Loaded", function() {});
})();

//because already defined in configtree.js
/*
registerView("configuration",
	function (){},
	function() { 
	},
	function() {		
	},
	function() {
	},
	null
);*/
register("OX_Configuration_GUI_Changed",function () {
	configuration_changed_fields["gui"]=true;
});

/**
 * Asks the user to save changes before leaving a configuration page.
 * If the changes need to be saved, the event OX_SAVE_OBJECT is triggered.
 * If the changes should be discarded, the event OX_Cancel_Object is triggered.
 * @param {Function} callback An optional callback which is called if the page
 * change is not cancelled.
 */
function configuration_askforSave(callback) {
    if(configuration_changed()) {
        newConfirm(_("Configuration changed"),
            _("Do you want to save your configuration?"),
            AlertPopup.YESNO, null, null,
            function() {
                triggerEvent("OX_SAVE_OBJECT");
                if (callback) callback();
            },
            function() {
                triggerEvent("OX_Cancel_Object");
                if (callback) callback();
            });     
    } else {
        if(callback) callback();
    }
}

register("OX_Save_Configuration",configuration_saveObject);
function configuration_saveObject(force,hidemessage,myok,myerror,optParam) {
    var showmessage=true;
    var openrequests=0;
    var iserror=false;
    var errormessage="";
    
    function successcb(r) {
        openrequests--;
        if(openrequests==0) {
            afterRequest();
        }
    }
    if(!myok) {
        myok=successcb;
    }
    
    function errorcb(result,status) {
        openrequests--;
        iserror=true;
        if(status != 200) {
            errormessage=_("The configuration could not be saved, because of the following error:") +
                //#. HTTP Errors from the server
                //#. %1$s is the numeric HTTP status code
                //#. %2$s is the corresponding HTTP status text
                //#, c-format
                format(_("Error: %1$s - %2$s"), status, result);
        }
        if (openrequests==0) {
            afterRequest();
        }
    }
	if(!myerror) {
		myerror=errorcb;
	}

	function afterRequest() {
		if (iserror) {
			if(!hidemessage) triggerEvent("OX_New_Error",errormessage);
		} else {
			if(!hidemessage) {
				triggerEvent("OX_New_Info",4,_("Your settings have been saved"));
			}
			if (!force) {
				if(activemodule=="configuration") {
					triggerEvent("OX_Configuration_Changed",currentpath2.join("/"));
				} else {
					triggerEvent("OX_Configuration_Changed","");
				}
			}
		}
	}
	
    var ro_ConfigSettings = [
        "addresses", "availableModules", "availableTimeZones", "contact_id",
        "context_id", "currentTime", "defaultaddress", "folder",
        "global_categories", "identifier", "maxUploadIdleTimeout",
        "mail.addresses", "mail.defaultaddress", "mail.folder",
        "mail.spambutton", "modules", "participants.showDialog",
        "participants.showWithoutEmail", "reloadtimes", "serverVersion",
        "spambutton", "ui"
    ];
	
	function saveConfigtoServer(path,params,success1,error1,myjson) {
		showmessage=true;
		var reqstring=AjaxRoot + "/config";
		var myparams;
		if (path && path != "") {
			reqstring=reqstring+"/"+path;
		}
		reqstring=reqstring+"?session="+session;
		if (params && params != "") {
			myparams=configGetKey(params);
		} else {
			myparams=clone(config);
		}
        // going to remove read-only settings
		for (i in ro_ConfigSettings) {			
			var splitkey = ro_ConfigSettings[i].split(".");			
			var tmp = myparams;
			for (var ia=0; ia<splitkey.length-1; ia++) {
		        if (tmp[splitkey[ia]] != undefined) {
		            tmp=tmp[splitkey[ia]];
		        } else {
		            break;
		        }
		    }		       	            
            if (!splitkey || !splitkey.length) continue;
            delete tmp[splitkey[splitkey.length-1]];
		}
		myjson.put(reqstring, myparams, null, success1, error1);
	}
	var myjson=new JSON();
	if(force) {
		for (var i in configuration_changed_fields) {
			configuration_changed_fields[i] = false;
		}
		saveConfigtoServer("","",myok,myerror,myjson);
		configuration_changed_outside=false;
	}
    if (temporary.folderTabs.viewModified()) {
        temporary.folderTabs.saveView(configuration_changed_fields.folder ?
            emptyFunction :
            function() {
        		ox.api.folder.refresh({ folders: [temporary.folderTabs.folder.id] });
                /*
        		oMain-FolderTree.cache.updateFolders(
                    [temporary.folderTabs.folder.id],
                    function() {
                        oMain-FolderTree.load_view(
                            oMain-FolderTree.cache.folders.root,
                            oMain-FolderTree.tree, true, false);
                    
        			});*/
            });
        showmessage = false;
    }
	if(configuration_changed_fields["folder"] == true) {
		saveFolder(optParam);
		configuration_changed_fields["folder"]=false;
		showmessage=false;
	}
	if(configuration_changed_fields["mail"] == true) {
		saveConfigtoServer("mail","mail",myok,myerror,myjson);
		openrequests++;
		configuration_changed_fields["mail"] = false;
	}
	if(configuration_changed_fields["timezone"] == true) {
		saveConfigtoServer("timezone","timezone",myok,myerror,myjson);
		openrequests++;
		configuration_changed_fields["timezone"] = false;
	}
	if(configuration_changed_fields["language"] == true) {
        saveConfigtoServer("language", "language", function() {
            (new JSON).get(AjaxRoot + "/config/availableTimeZones?session=" +
                session, null, function(tz) {
                    configSetKey("availableTimeZones", tz.data);
                    myok();
                    //workaround for foldertree updates after language changes
                    ox.api.cache.folder0.clear();
                    ox.api.cache.folder1.clear();
                    ox.api.cache.folderFlat.clear();
                    ox.api.folder.dispatcher.trigger("modify");
                    
                });
        }, myerror, myjson);
		openrequests++;
		configuration_changed_fields["language"] = false;
	}
	if(configuration_changed_fields["gui"] == true) {
		saveConfigtoServer("gui","gui",function(){
		    myok();
		    triggerEvent("OX_Calendar_Teamlist_Changed");}
		,myerror,myjson);
		
		openrequests++;
		configuration_changed_fields["gui"] = false;
	}
	if(configuration_changed_fields["ui"] == true) {
	    saveConfigtoServer("ui", "ui", myok, myerror, myjson);
        openrequests++;
        configuration_changed_fields["ui"] = false;
    }
	if (configuration_changed_fields["tasknotification"] == true) {		
        delete(config["tasknotification"]);
		// todo: each modules section should have an own area later!!
		configuration_changed_fields["modules"] = true;
		configuration_changed_fields["tasknotification"] = false;
	}
	if (configuration_changed_fields["calendarnotification"] == true) {
		delete(config["calendarnotification"]);
		// todo: each modules section should have an own area later!!
        configuration_changed_fields["modules"] = true;
		configuration_changed_fields["calendarnotification"] = false;
	}
	if(configuration_changed_fields["modules"] == true) {
		saveConfigtoServer("modules","modules",myok,myerror,myjson);
		openrequests++;
		configuration_changed_fields["modules"] = false;
	}
	if(openrequests==0 && showmessage) {
		afterRequest();
	}
}

function selectValue(rObj, setValue) {
	var fieldValue = new Array();
	var j;
	for (var i=0; i < rObj.length; i++) {
		if (rObj[i].value == setValue) {
			j = i;
			break;
		} else {
			j = 0;
		}
	}
	return j;
}

function cancelConfigGUI() {
	if (cloned != "") {
		config = new Object();
		config = copy(cloned);
	}
	changed = new Array();
}

function displaySignatureConfig(val) {
	 sig = document.getElementById("signaturetext");
	 sig.value = val;
}

var setConfigPath = function (domNode) {
    var node = ox.widgets.configTree.nodeIndex[currentpath2.join("/")];
    var path = _(node.name);
    while (node.parentNode) {
        node = node.parentNode;
        path = _(node.name) + " / " + path;
    }
    domNode.firstChild.nodeValue = path;
};

var deleteFolderConfig = function () {
    // get folder
    ox.api.folder.get({
        folder: configfolder,
        success: function (data) {
            if (ox.api.folder.can("delete", data)) removeFolder(configfolder);
        }
    });
};

fileloaded();