var oCi_import_data = null;
var importDataFolderTree = null;
var importFolderId = -1;
var importFolderDestination = null;

register("Loaded", function () {
	addOnClose($("window_import_status"), function() { oCi_import_data.closeWindow(); }); 
});

registerView("configuration/import",
	function () { 
		showNode("config_import"); 
		$("config_import").style.display="block";
        
        // toolbar
        if (!configToolbars.configImport) {
            configToolbars.configImport = temporary.configuration.newToolbar(
                _("Import"),
                [{
                    title: _("Import"),
                    id: "import",
                    buttons: [{
                        title: _("Import"),
                        id: "import",
                        icons: ["img/menu/img_import.gif"],
                        big: true,
                        event: "OX_SAVE_OBJECT"
                    }]
                }], "import"
            );
        }
        temporary.configuration.showToolbar(configToolbars.configImport);
    },
	function() { 		
		oCi_import_data = new Ci_import_data();
		oCi_import_data.createCombobox();
		if(!config.modules.calendar.module || !config.modules.tasks.module) {
			$("cs_import_ical").disabled = "disabled";
			$('cs_import_vcard').checked = true;
		} else {
			$('cs_import_ical').checked = true;
			if (importFolderDestination != null && importFolderDestination.module == "contacts"){
				$('cs_import_vcard').checked = true;
				oCi_import_data.combobox.disable();
				oCi_import_data.action="VCARD";
			} else if (importFolderDestination != null && importFolderDestination.module == "tasks"){
				oCi_import_data.combobox.setKey("tasks");
			}
		}
		oCi_import_data.form = $('form_config_import');
		oCi_import_data.form.file.value="";
		register("OX_SAVE_OBJECT",uploadImportData);
	},
	function() {
		unregister("OX_SAVE_OBJECT",uploadImportData);
		unregister("cb_importComboChanged",cb_importComboChanged);
		unregister('cb_importComboCSVChanged', cb_importComboCSVChanged);
	},
	function () {
		hideNode("config_import"); 
		$("config_import").style.display="none"; 
		oCi_import_data.closeWindow();
	},
	function () { }
);

function uploadImportData() {
	if(!oCi_import_data.process)
		oCi_import_data.uploadData();
}

function Ci_import_data() {
	this.action = "ICAL";
	this.folder = configGetKey("folder.calendar");
	this.combobox = null;
	this.process = false;
	$("fileImportInput").disabled = false;
	setConfigPath($("cimp_header"));	
}

function cb_importComboChanged() {
	if(oCi_import_data.action == "ICAL")
		oCi_import_data.changeStatus("ical");	
}

function cb_importComboCSVChanged() {
	if(oCi_import_data.action == "CSV" || oCi_import_data.action == "OUTLOOK_CSV")
		oCi_import_data.changeStatus("csv");	
}

Ci_import_data.prototype = {
	uploadData : function() {	
		this.form = $('form_config_import');
		this.uri = AjaxRoot + "/import?action="+this.action+"&session="+session+"&folder="+importFolderId //this.folder;	
		this.form.action = this.uri; 
		this.form.target="dlIframe"
		if(this.form.file.value=="") {
			triggerEvent("OX_New_Error", 4, _("Please select a file to import"));
		}
		else {
			this.process = true;
			this.form.submit();
			$("fileImportInput").disabled = true;
		}
	}, 
	createCombobox : function() {
		var cbText = new Array();
        cbText[0] = _("Appointments");
        cbText[1] = _("Tasks");
        cbText[2] = _("Comma Separated");
        cbText[3] = _("Outlook file");
		this.combobox = new ComboBox3(window, "import.combobox.module", "20em", 
			0, true, "cb_importComboChanged", null);
		this.combobox.addElement(cbText[0],"calendar");
		this.combobox.addElement(cbText[1],"tasks");
		this.combobox.getDomNode();
		if(!config.modules.calendar.module || !config.modules.tasks.module)
			this.combobox.disable();
		register('cb_importComboChanged', cb_importComboChanged);
		this.comboboxCSV = new ComboBox3(window, "import.combobox.csv", "20em", 
			0, true, "cb_importComboCSVChanged", null);
		this.comboboxCSV.addElement(cbText[2],"CSV");
		this.comboboxCSV.addElement(cbText[3],"OUTLOOK_CSV");
		this.comboboxCSV.getDomNode();
		this.comboboxCSV.disable();
		register('cb_importComboCSVChanged', cb_importComboCSVChanged);
		
		if (importFolderDestination != null) {
			setFolder(importFolderDestination.id);
		} else {
			setFolder(configGetKey("folder.calendar") || configGetKey("folder.contacts"));
		}
	},
	
	openWindow: function() {
	    ox.api.setModal(true);
		//showNode("modal-dialog");
		//$("modal-dialog").style.display="block";
		showNode("config_popups_win");
		$("config_popups_win").style.display="block";
		showNode("window_import_status");
		centerPopupWindow($("window_import_status"));
		$("window_import_status").style.display="block";
	}, 
	
	closeWindow: function() {
		hideNode("window_import_status");
		$("window_import_status").style.display="none";
		hideNode("config_popups_win");
		$("config_popups_win").style.display="none";
		ox.api.setModal(false);
		//hideNode("modal-dialog");
		var childs=	$("modal-dialog").childNodes;
		var closeall=true;
		for(var i=0;i<childs.length;i++) {
			if(childs[i].tagName && childs[i].tagName == "DIV") {
				if(childs[i].style.display && childs[i].style.display!= "none" ) {
					closeall=false;
				}
			}
		}
		if(closeall) {
		    ox.api.setModal(false);
			//$("modal-dialog").style.display="none";
		}
		$("cms_import_status").firstChild.data = "";
		$("cms_import_log").value = "";
		this.form.reset();
	},
	
	changeStatus : function(suffix) {
		var Self = this;
		switch(suffix) {
			case 'ical'		 	: 	Self.action = "ICAL";
									
									Self.combobox.enable();
									Self.comboboxCSV.disable();
													
									Self.folder  = configGetKey("folder."+Self.combobox.getKey());
									
									if (importFolderDestination == null || importFolderDestination.module == "contacts")
										setFolder(Self.folder);
									else
										setFolder(importFolderDestination.id);
									
									break;
				
			case 'vcard' 		: 	Self.action = "VCARD";
									Self.folder = configGetKey("folder.contacts");
									
									Self.combobox.disable();
									Self.comboboxCSV.disable();

									if (importFolderDestination == null || importFolderDestination.module != "contacts")
										setFolder(Self.folder);
									else
										setFolder(importFolderDestination.id);
									
									break;
			
			case 'csv' 			: Self.action = Self.comboboxCSV.getKey();
									Self.folder = configGetKey("folder.contacts");
									Self.comboboxCSV.enable();
									Self.combobox.disable();

									if (importFolderDestination == null || importFolderDestination.module != "contacts")
										setFolder(Self.folder);
									else
										setFolder(importFolderDestination.id);
									
									break;
		}
	}
}

function import_getWarningsAsString(warnings) {
    var retVal = [];
    for (var i = 0; i < warnings.length; i++) {
        //#. Format string for warnings. The difference to the default
        //#. is that it doesn't have "Error:" at the beginning.
        //#. %1$s is the error code.
        //#. %2$s is the formatted error message.
        //#. %3$s is the unique error ID.
        //#, c-format
        retVal.push(escapeHTML(formatError(warnings[i], "%2$s (%1$s, %3$s)"/*i18n*/)) + "\n");
    }
    return retVal.join();
}

function callback_import(arg) {
	var textM = "";
	oCi_import_data.process = false;
	$("fileImportInput").disabled = false;
	
	if (arg.error) {
		newServerError(arg);
	} else if (arg.data && arg.data.length != 0) {
		var successfullImported = 0;
		var importLog = "";
		
		for (var i=0; i<arg.data.length; i++) {
			if (arg.data[i].error) {
	            //#. Format string for warnings. The difference to the default
			    //#. is that it doesn't have "Error:" at the beginning.
                //#. %1$s is the error code.
                //#. %2$s is the formatted error message.
                //#. %3$s is the unique error ID.
                //#, c-format
				importLog += escapeHTML(formatError(arg.data[i], "%2$s (%1$s, %3$s)"/*i18n*/)) + "\n";
				if (arg.data[i].warnings && arg.data[i].warnings.length) {
					importLog += import_getWarningsAsString(arg.data[i].warnings);
				}
				if (arg.data[i].category && arg.data[i].category == 13){
				    successfullImported++;
				}
			} else if (arg.data[i].warnings && arg.data[i].warnings.length) {
                importLog += import_getWarningsAsString(arg.data[i].warnings);
            } else {
				successfullImported++;
			}
		}
		
		$("cms_import_log").value = importLog.length != 0 ? importLog : _("None");
		//#. %d is the number of successfully imported data records
		//#, c-format
		textM = format(_("Successfully imported: %d"), successfullImported);		
		oCi_import_data.openWindow();
	} else {
		oCi_import_data.closeWindow();
		triggerEvent("OX_New_Error", 4, _("Internal Error: The server didn't provide any data."));
	}
	$("cms_import_status").firstChild.data = textM;
}

function toggleConfigTree(){
	if (document.getElementsByName('cs_import_type')[0].checked == true){
		clickedItem = configGetKey("folder.calendar");
	} else {
		clickedItem = configGetKey("folder.contacts");
	}
	
	initImportTree();
	
	if ($("TreeDialogImportForlder").style.display == "none"){
		centerPopupWindow($("TreeDialogImportForlder"));
		$("TreeDialogImportForlder").style.display = "block";
		$("TreeDialogImportForlder").style.top = "230px";
		$("TreeDialogImportForlder").style.left = "420px";
	}else{
		$("TreeDialogImportForlder").style.display = "none";
	}
		
}

function initImportTree() {		
		
	importDataFolderTree = null;
	removeChildNodes($("folder_tree_info"));
	
	var type = "contacts";
	if (document.getElementsByName('cs_import_type')[0].checked == true){
		if (oCi_import_data.combobox.getKey() == "calendar"){
			type = "calendar";
		} else {
			type = "tasks";
		}
	}

	ox.api.ui.selectFolder({
    	type: type,
    	id: "select-folder-popup-" + type,
    	callback: folderConfigAction,
    	node: $('folder_tree_info')
    });

}


function cb_getpath(sPath) {
    var nodes = document.getElementsByName('importFolderInput');
    if (nodes && nodes.length > 0) {
        nodes[0].value = sPath;
    }
}

function setFolder(fId){
	importFolderId = fId;
	ox.api.folder.getPathString({
	    folder: fId,
	    success: cb_getpath
	});
}

function folderConfigAction (data) {
	importFolderDestination = data;
	toggleConfigTree();
	clickedItem = data.id;
	setFolder(clickedItem);
}

fileloaded();