/**
 * 
 * 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_Settings_Changed_Language",cs_changedLanguage);
register("OX_Configuration_Settings_Changed_Timezone",cs_changedTimezone);
register("OX_Configuration_Settings_Changed_UI", cs_changedUI);
register("OX_Configuration_Settings_Changed_GUI", cs_changedGui);
register("OX_Configuration_Settings_Changed_Mail",cs_changedMail);
register("OX_Configuration_Settings_Changed_Modules",cs_changedModules);
register("OX_Configuration_Settings_Changed_Calendar_Notification",cs_changedCalendarNotification);
register("OX_Configuration_Settings_Changed_Task_Notification",cs_changedTaskNotification);
register("OX_Configuration_Settings_Changed_Region_Date", cs_region_date_changed);
register("OX_Configuration_Settings_Changed_Tree", function() {
    configuration_changed_fields["modules"] = true;
});

function cs_changedMail() {
	configuration_changed_fields["mail"]=true;
}
function cs_changedModules() {
	configuration_changed_fields["modules"]=true;
}
function cs_changedUI() {
	configuration_changed_fields["ui"]=true;
}
function cs_changedGui() {
    configuration_changed_fields["gui"]=true;
}
function cs_changedTimezone() {
	configuration_changed_fields["timezone"]=true;
}
function cs_changedLanguage() {
	configuration_changed_fields["language"]=true;
}
function cs_changedCalendarNotification() {
	configuration_changed_fields["calendarnotification"]=true;
}
function cs_changedTaskNotification() {
	configuration_changed_fields["tasknotification"]=true;
}
function getBoolofInt(myint) {
	if(myint!=0) 
		return true;
	return false;
}
function getValueofRadioBox(nameofradios) {
	var allelements = document.getElementsByName(nameofradios);
	var returnvalue = 0;
	for (var i=0; i<allelements.length; i++) {
		if (allelements[i].checked) {
			return parseInt(allelements[i].value);
		} 
	}
}
function getStringofRadioBox(nameofradios) {
	var allelements = document.getElementsByName(nameofradios);
	var returnvalue = 0;
	for (var i=0; i<allelements.length; i++) {
		if (allelements[i].checked) {
			return allelements[i].value;
		} 
	}
}
function setIntofRadioBox(nameofradios,value){
	var allelements = document.getElementsByName(nameofradios);
	for (var i=0; i<allelements.length; i++) {
		if (parseInt(allelements[i].value) == value) {
			allelements[i].checked=true;
			break;
		} 
	}
}
function setValueofRadioBox(nameofradios,value) {
	if(value==true) { value=1; }
	if(value==false) { value=0; }
	var allelements = document.getElementsByName(nameofradios);
	for (var i=0; i<allelements.length; i++) {
		if (parseInt(allelements[i].value) == value) {
			allelements[i].checked=true;
			break;
		} 
	}
}
function setStringofRadioBox(nameofradios,value) {
	if(value==true) { value=1; }
	if(value==false) { value=0; }
	var allelements = document.getElementsByName(nameofradios);
	for (var i=0; i<allelements.length; i++) {
		if (allelements[i].value == value) {
			allelements[i].checked=true;
			break;
		} 
	}
}

var applyConfigurableFlag = function (selector, key) {
    // is configurable?
    var flag = configGetKey(key + ".configurable");
    // not defined?
    if (flag === null && configGetKey(key) !== null) {
        // make it configurable
        configSetKey(key + ".configurable", true);
    }
    if (flag === false) {
        jQuery(selector).hide();
    } else {
        jQuery(selector).show();
    }
};

registerView("configuration/settings",
	function() { 
		showNode("config"); 
		$("config").style.display="block";
        
        // toolbar
        if (!configToolbars.settings) {
            configToolbars.settings = temporary.configuration.newToolbar(
                _("Options"), [temporary.configuration.saveButton], "options");
        }
        temporary.configuration.showToolbar(configToolbars.settings);
        
        // configurable: embedded mode
        applyConfigurableFlag("#configurable-windows", "ui.global.windows.mode");
        // configurable: toolbar
        applyConfigurableFlag("#configurable-toolbar", "ui.global.toolbar.mode");
	},
		
	function() { 
 	    register("OX_SAVE_OBJECT",cs_saveConfiguration);
		register("OX_Cancel_Object",cs_cancelConfiguration);
		register("LanguageChanged",cs_changeHeader);
		//init config
		cs_enter(); 
        changeTab('tabConfiguration1', 'panelConfiguration1');
        $("panelConfiguration1").className="tabPanelFirstHi tabPanelHiColor background-color-content font-style-lable border-color-content-default";        
		cs_region_enter();
	},
	function() { 
		//configuration_askforSave();
 	    unregister("OX_SAVE_OBJECT",cs_saveConfiguration);
		unregister("OX_Cancel_Object",cs_cancelConfiguration);
		unregister("LanguageChanged",cs_changeHeader);
		cs_leave();
	},
	function() { 
		hideNode("config"); 
		$("config").style.display="none";
		$("tabConfiguration1").style.display="none";
		$("panelConfiguration1").className="tabPanelFirst tabPanelColors font-color-disabled background-color-additional-content border-color-design font-weight-default";
	
	},
	function() { 
		cs_enter();
		cs_region_enter(); 
	}
);

function cs_changeHeader() {
	if(currentpath2.join("/") == "configuration/settings") {
		setConfigPath($("cs_header"));
	}
}

var configSettingsTabsList = new Array('tabConfiguration1','tabConfiguration2');
var configSettingsPanelsList = new Array('panelConfiguration1','panelConfiguration2');
var configSettingsEventList = null;

var cc_actualTree = null;

function cs_saveConfiguration() {
	if(configuration_changed_fields["timezone"]) {
		configSetKey("timezone",cs_timezone.getKey());
	}
	if(configuration_changed_fields["language"]) {
		configSetKey("language",cs_language.getKey());
		setLanguage(configGetKey("language"));
		cs_region_enter();
	
				
	}
    if (configuration_changed_fields["modules"]) {
        if (cc_actualTree === null) {
            cc_actualTree = configGetKey("modules.folder.tree");
        }
        if (cc_actualTree !== null) {
            var selectedTree = cs_tree.getKey();
            if (selectedTree != cc_actualTree) {
                ox.JSON.put(AjaxRoot + "/config/modules/folder/tree?session=" +
                    session, selectedTree, function() {
                        actualTree = selectedTree;
                        ox.Configuration.info(_("The new folder tree setting will take effect after a new login."/*i18n*/));
                });
            }
        }
    }
    
    if (configuration_changed_fields["ui"]) {
        // windows
        configSetKey("ui.global.windows.mode.value", getStringofRadioBox("cs_windows"));
        // toolbar
        configSetKey("ui.global.toolbar.mode.value", getStringofRadioBox("cs_toolbar"));
    }
    
    if (configuration_changed_fields["gui"]) {
        
        // switch theme?
        var selectedTheme = cs_theme.getKey();
        if (configContainsKey(["modules", "themes", selectedTheme])) {
            var themeName = configGetKey("modules.themes")[selectedTheme];
            configSetKey("gui.theme", { name: themeName, path: selectedTheme });
            // switch!
            switchTheme(selectedTheme, themeName);
        }
        
		// langing page
		var selectedPage = cs_landingPage.getKey();
		if (selectedPage) {
			configSetKey("gui.global.landing_page", { module: selectedPage });
		}
		
		// expert tree?
		var useExpert = getValueofRadioBox("cs_expert");
		if (useExpert != configGetKey("gui.global.expert_tree")) {
		    configSetKey("gui.global.expert_tree", useExpert);
		    ox.UIController.setExpertTree(useExpert == 1 ? true : false);
		}

 		configSetKey("gui.global.save",getValueofRadioBox("cs_saveconfig"));
		configSetKey("gui.global.autorefresh",cs_autorefresh.getKey());
		configSetKey("gui.effects.fading",getBoolofInt(getValueofRadioBox("cs_enableeffects")));
		configSetKey("gui.effects.global",getBoolofInt(getValueofRadioBox("cs_enableeffects")));
		configSetKey("gui.effects.hover.portal",getBoolofInt(getValueofRadioBox("cs_enablehoverportal")));
		configSetKey("gui.effects.hover.mail",getBoolofInt(getValueofRadioBox("cs_enablehovermail")));
		configSetKey("gui.effects.hover.calendar",getBoolofInt(getValueofRadioBox("cs_enablehovercalendar")));
		configSetKey("gui.effects.hover.contacts",getBoolofInt(getValueofRadioBox("cs_enablehovercontacts")));
		configSetKey("gui.effects.hover.tasks",getBoolofInt(getValueofRadioBox("cs_enablehovertasks")));
		configSetKey("gui.effects.hover.infostore",getBoolofInt(getValueofRadioBox("cs_enablehoverinfostore")));
		configSetKey("gui.effects.hover.speed",getValueofRadioBox("cs_hoverspeed"));	
		configSetKey("gui.global.region.time.predefined",getValueofRadioBox("cs_time_predefined"));
		if(getValueofRadioBox("cs_time_predefined") == 0) {
			if($("cs_time_userdefined:0").checked) {
				configSetKey("gui.global.region.time.format", "hh:mm a");
				configSetKey("gui.global.region.time.format_hour", "hh a");
				configSetKey("gui.global.region.time.format_suffix", true);
			}
			else {				
				configSetKey("gui.global.region.time.format", "HH:mm");
				configSetKey("gui.global.region.time.format_hour", "HH:mm");
				configSetKey("gui.global.region.time.format_suffix", false);
			}
		}
		configSetKey("gui.global.region.date.predefined",getValueofRadioBox("cs_date_predefined"));
		if(getValueofRadioBox("cs_date_predefined") == 0) {
			configSetKey("gui.global.region.date.format_selected_index", cs_dateformat.getSelectedIndex());
			configSetKey("gui.global.region.date.separator", cs_date_separator.getKey());
			var current_date_separator = cs_date_separator.getKey();
			var current_date_format = cs_dateformat.getKey();
			if(current_date_separator && current_date_separator != "default") {
				current_date_format = current_date_format.replace(/\W/g,current_date_separator);
			}
			configSetKey("gui.global.region.date.format", current_date_format);
		}
	}
	triggerEvent("OX_Save_Configuration",false,false);
}

function cs_cancelConfiguration() {
	configuration_changed_fields["gui"]=false;
	configuration_changed_fields["language"]=false;
	configuration_changed_fields["timezone"]=false;
    configuration_changed_fields["modules"] = false;
	cs_enter();	
}

function cs_region_enter() {
	/* time format */
	if(configContainsKey("gui.global.region.time.predefined") && configGetKey("gui.global.region.time.predefined")==0) {
		$("cs_time_userdefined:0").disabled = false;
		$("cs_time_userdefined:1").disabled = false;
		$("cs_time_predefined:0").checked = true
		var current_time_format = configGetKey("gui.global.region.time.format");
	} else {
		$("cs_time_userdefined:0").disabled = true;
		$("cs_time_userdefined:1").disabled = true;
		$("cs_time_predefined:1").checked = true
		var current_time_format = expectI18n(_("HH:mm"));
	}
	if(current_time_format.indexOf("a") != -1) {
		$("cs_time_userdefined:0").checked = true;
	} else {
		$("cs_time_userdefined:1").checked = true;
	}
	$("cs_region_time_sample").value = formatDate(new Date(now()), "time");
	
	
	/* date format */
	if(configContainsKey("gui.global.region.date.predefined") && configGetKey("gui.global.region.date.predefined")==0) {
		$("cs_date_predefined:0").checked = true
		var triggerNoEvent = true;
		cs_dateformat.setSelectedIndex(configGetKey("gui.global.region.date.format_selected_index"),triggerNoEvent);
		cs_date_separator.setKey(configGetKey("gui.global.region.date.separator"),triggerNoEvent);
		cs_dateformat.enable();
		cs_date_separator.enable();
	} else {
		cs_dateformat.disable();
		cs_date_separator.disable();
		$("cs_date_predefined:1").checked = true
	}
	$("cs_region_date_sample").value = formatDate(new Date(now()), "date");
}

function cs_region_set_time_format() {
	if($("cs_time_predefined:0").checked == true) {
		$("cs_time_userdefined:0").disabled = false;
		$("cs_time_userdefined:1").disabled = false;	
		var current_time_format = ($("cs_time_userdefined:0").checked) ? "hh:mm a" : "HH:mm";
		
	} else {
		$("cs_time_userdefined:0").disabled = true;
		$("cs_time_userdefined:1").disabled = true;
		var current_time_format = _("HH:mm");
		if(current_time_format.indexOf("a") != -1) {
			$("cs_time_userdefined:0").checked = true;
		} else {
			$("cs_time_userdefined:1").checked = true;
		}
	}
	$("cs_region_time_sample").value = formatDateTime(current_time_format, new Date(now()));
}

function cs_region_set_date_format() {
	if($("cs_date_predefined:0").checked == true) {
		cs_dateformat.enable();
		cs_date_separator.enable();
		var current_date_format = cs_dateformat.getKey();	
		var current_date_separator = cs_date_separator.getKey();	
	} else {
		cs_dateformat.disable();
		cs_date_separator.disable();
		var current_date_format = _("yyyy-MM-dd");
		var current_date_separator = false;
	}
	if(current_date_separator && current_date_separator != "default") {
		current_date_format = current_date_format.replace(/\W/g,current_date_separator);
	}
	$("cs_region_date_sample").value = formatDateTime(current_date_format, new Date(now()));
}

function cs_region_date_changed() {
	triggerEvent('OX_Configuration_Settings_Changed_GUI');
	cs_region_set_date_format()
}

function cs_enter() {	
	if(!cs_init_bool) {
		cs_init();
		cs_init_bool=true;
	}
	if(configContainsKey("language")) {
		cs_language.setKey(configGetKey("language"));
		configuration_changed_fields["language"]=false;
	}	
	if(configContainsKey("timezone")) {
		cs_timezone.setKey(configGetKey("timezone"));
		configuration_changed_fields["timezone"]=false;
	}
    if (configContainsKey("modules.folder.tree")) {
        cs_tree.setKey(configGetKey("modules.folder.tree"));
        configuration_changed_fields["modules"] = false;
    } else {
        $("cs_tree").parentNode.parentNode.style.display = "none";
    }
	if(configContainsKey("gui.theme")) {
		cs_theme.setKey(configGetKey("gui.theme").path);
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.global.landing_page")) {
		cs_landingPage.setKey(configGetKey("gui.global.landing_page").module);
		configuration_changed_fields["gui"]=false;
	}
	
	// expert tree
    if (configContainsKey("gui.global.expert_tree")) {
        setIntofRadioBox("cs_expert", configGetKey("gui.global.expert_tree"));
        configuration_changed_fields["gui"] = false;
    }
    
    // embedded windows
    if (configContainsKey("ui.global.windows.mode.value")) {
        setStringofRadioBox("cs_windows", configGetKey("ui.global.windows.mode.value"));
        configuration_changed_fields["ui"] = false;
    }
    
    // toolbar
    if (configContainsKey("ui.global.toolbar.mode.value")) {
        setStringofRadioBox("cs_toolbar", configGetKey("ui.global.toolbar.mode.value"));
        configuration_changed_fields["ui"] = false;
    }
    
	cs_autorefresh.setKey(configGetKey("gui.global.autorefresh"));
	if (configContainsKey("gui.global.save")) {
		var id = configGetKey("gui.global.save");
		setIntofRadioBox("cs_saveconfig", id);
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.global")) {
		setIntofRadioBox("cs_enableeffects",configGetKey("gui.effects.global"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.portal")) {
		setIntofRadioBox("cs_enablehoverportal",configGetKey("gui.effects.hover.portal"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.mail")) {
		setIntofRadioBox("cs_enablehovermail",configGetKey("gui.effects.hover.mail"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.calendar")) {
		setIntofRadioBox("cs_enablehovercalendar",configGetKey("gui.effects.hover.calendar"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.contacts")) {
		setIntofRadioBox("cs_enablehovercontacts",configGetKey("gui.effects.hover.contacts"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.tasks")) {
		setIntofRadioBox("cs_enablehovertasks",configGetKey("gui.effects.hover.tasks"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.infostore")) {
		setIntofRadioBox("cs_enablehoverinfostore",configGetKey("gui.effects.hover.infostore"));
		configuration_changed_fields["gui"]=false;
	}
	if(configContainsKey("gui.effects.hover.speed")) {
		setIntofRadioBox("cs_hoverspeed",configGetKey("gui.effects.hover.speed"));
		configuration_changed_fields["gui"]=false;
	}
	setConfigPath($("cs_header"));
	setTabLists(configSettingsTabsList, configSettingsPanelsList, null);
} 

function cs_enableallhover() {
		setIntofRadioBox("cs_enablehoverportal",1);
		setIntofRadioBox("cs_enablehovermail",1);
		setIntofRadioBox("cs_enablehovercalendar",1);
		setIntofRadioBox("cs_enablehovercontacts",1);
		setIntofRadioBox("cs_enablehovertasks",1);
		setIntofRadioBox("cs_enablehoverinfostore",1);
		configuration_changed_fields["gui"]=true;
}

function cs_disableallhover() {
		setIntofRadioBox("cs_enablehoverportal",0);
		setIntofRadioBox("cs_enablehovermail",0);
		setIntofRadioBox("cs_enablehovercalendar",0);
		setIntofRadioBox("cs_enablehovercontacts",0);
		setIntofRadioBox("cs_enablehovertasks",0);
		setIntofRadioBox("cs_enablehoverinfostore",0);
		configuration_changed_fields["gui"]=true;
}

function cs_init() {
    if(!configGetKey("modules.portal.module")) { $("cs_portal_hover").style.display="none"; }
    if(!configGetKey("modules.mail.module")) { $("cs_mail_hover").style.display="none"; }
    if(!configGetKey("modules.calendar.module")) { $("cs_calendar_hover").style.display="none"; }
    if(!configGetKey("modules.contacts.module")) { $("cs_contacts_hover").style.display="none"; }
    if(!configGetKey("modules.tasks.module")) { $("cs_tasks_hover").style.display="none"; }
    if(!configGetKey("modules.infostore.module")) { $("cs_infostore_hover").style.display="none"; }
	
	var myarray=configGetKey("reloadtimes");
	cs_autorefresh = new ComboBox3(window, "cs_autorefresh", "15em", 0, true,"OX_Configuration_Settings_Changed_GUI", 3);
    cs_autorefresh.addElement(_("Never"), 0);
	if(configContainsKey("reloadtimes")) {
		for(var i=0;i<myarray.length;i++) {
			if(!myarray[i]== 0) {
				cs_autorefresh.addElement(getInterval(myarray[i]),
				                          myarray[i]/60000);
			}
		}
	}
	cs_autorefresh.getDomNode();
	
	cs_language = new ComboBox3(window, "cs_language", "15em", 0, true, "OX_Configuration_Settings_Changed_Language", 3);
	for(var i in corewindow.all_languages) {
	    if (!i) continue;
	    var lang = corewindow.all_languages[i];
	    if (typeof lang == "string") lang = noI18n(lang);
        cs_language.addElement(lang, i);
	}
	cs_language.getDomNode();
	
	cs_timezone = new ComboBox3(window, "cs_timezone", "25em", 1, true, "OX_Configuration_Settings_Changed_Timezone", 8);
    var timezones = configGetKey("availableTimeZones");
    var tzarray = [];
    for (var i in timezones) tzarray.push({key: i, value: timezones[i] });
    tzarray.sort(function(a, b) {
        return a.value < b.value ? -1 : a.value > b.value ? 1 : 0;
    });
    for(var i = 0; i < tzarray.length; i++) {
        cs_timezone.addElement(noI18n(tzarray[i].value), tzarray[i].key);
    }
	cs_timezone.getDomNode();
	
	cs_dateformat = new ComboBox3(window, "cs_dateformat", "9em", 0, true, "OX_Configuration_Settings_Changed_Region_Date", 8);
	cs_dateformat.addElement(_("M/d/yyyy"),   "M/d/yyyy");
	cs_dateformat.addElement(_("M/d/yy"),     "M/d/yy");
	cs_dateformat.addElement(_("MM/dd/yy"),   "MM/dd/yy");
	cs_dateformat.addElement(_("MM/dd/yyyy"), "MM/dd/yyyy");
	cs_dateformat.addElement(_("yy/MM/dd"),   "yy/MM/dd");
	cs_dateformat.addElement(_("dd/MM/yyyy"), "dd/MM/yyyy");
	cs_dateformat.addElement(_("dd/MM/yy"),   "dd/MM/yy");
	cs_dateformat.addElement(_("dd.MM.yyyy"), "dd.MM.yyyy");	
	cs_dateformat.addElement(_("dd.MM.yy"),   "dd.MM.yy");
	cs_dateformat.addElement(_("d.MM.yy"),    "d.MM.yy");
	cs_dateformat.addElement(_("d.M.yy"),     "d.M.yy");
	cs_dateformat.addElement(_("d.M.yyyy"),   "d.M.yyyy");
	cs_dateformat.addElement(pgettext("label", "yyyy-MM-dd"), "yyyy-MM-dd");
	cs_dateformat.addElement(_("dd-MMM-yy"),  "dd-MMM-yy");
	cs_dateformat.getDomNode();
	
	cs_date_separator = new ComboBox3(window, "cs_dateseparator", "9em", 0, true, "OX_Configuration_Settings_Changed_Region_Date", 3);
	cs_date_separator.addElement(_("default"), "default");
	cs_date_separator.addElement(noI18n("/"),  "/");
	cs_date_separator.addElement(noI18n("."),  ".");
	cs_date_separator.addElement(noI18n("-"),  "-");
	cs_date_separator.getDomNode();
    
    var themes = [];
    var themeconfig = configGetKey("modules.themes");
    if (themeconfig) {
    	for (i in themeconfig) {
    		themes.push({ name: themeconfig[i], path: i });
    	}
        themes.sort(function(a, b) { 
        	   return (a.name.toUpperCase() < b.name.toUpperCase() ? -1 : 1); 
        	});
    } else {
        themes.push({ name: _("Default"), path: "default" });
    }
    
	cs_theme = new ComboBox3(window, "cs_theme", "30em", 0, true, "OX_Configuration_Settings_Changed_GUI", 3);
	for(var i=0;i<themes.length;i++) {
        cs_theme.addElement(
            themes[i].name instanceof I18nString ? themes[i].name
                                                 : noI18n(themes[i].name),
            themes[i].path);	
	}	
    cs_theme.getDomNode();
    
    
	cs_landingPage = new ComboBox3(window, "cs_landing_page", "30em", 0, true, "OX_Configuration_Settings_Changed_GUI", 3);
	var modules = ox.api.ui.listModules();
	for(var i in modules) {
		if (modules[i].disabled == false && modules[i].name != "configuration") {
			cs_landingPage.addElement(modules[i].title, modules[i].name);
		}
	}	
	cs_landingPage.getDomNode();
	
	cs_tree = new ComboBox3(window, "cs_tree", "15em", 0, true,
	    "OX_Configuration_Settings_Changed_Tree", 2);
	cs_tree.addElement(_("Classic"), 0);
	cs_tree.addElement(_("New"), 1);
	cs_tree.getDomNode();
}

function cs_leave() { }
var cs_init_bool=false;
var cs_language;
var cs_autorefresh;
var cs_timezone;
var cs_theme;
var cs_landingPage;
var cs_dateformat;
var cs_date_separator;
var cs_tree;

fileloaded();