var cenAXUI = {
	configListTable: null,
	currentEditingTPX: null,
	currentEmulatedTPX: null,
	deletingTPXFilename: null,
	renamingTPXFilename: null,

	initAccordion: function () {
		$("#configAccordion").accordion({
			header: "h3",
			heightStyle: "content",
			beforeActivate: function () {
				var index = $("#configAccordion").accordion("option", "active");

				switch (index) {
					case 0:
						cenAXUI.switchConfigView("windowGroups");

						cenWgUI.loadWindowGroupList();
						break;
					case 1:
						cenAXUI.switchConfigView("emulators");
						break;
				};
			},
			activate: function () {
				var index = $("#configAccordion").accordion("option", "active");

				localStorage.setItem(cenAX.storagePrefix + '.configPane', index);
			}
		});

		var index = localStorage.getItem(cenAX.storagePrefix + '.configPane');

		index = index ? parseInt(index) : 0;

		$('#configAccordion').accordion("option", "active", index);
	},

	loadConfigs: function() {
	 	var allTPX = cenAX.allTPXFiles();

	 	if(allTPX.length == 0) {
		 	var tpx;

		 	tpx = new cenTPXSettings("unix");
		 	tpx.tpxSettings["title"] = "UNIX";
		 	tpx.filename = cenAX.tpxPrefix + ".0";
		 	tpx.save();

		 	tpx = new cenTPXSettings("ibm3270");
		 	tpx.tpxSettings['title'] = "IBM 3270"
		 	tpx.filename = cenAX.tpxPrefix + ".1";
		 	tpx.save();

/*
		 	tpx = new cenTPXSettings();
		 	tpx.tpxSettings['emulate'] = 22;
		 	tpx.tpxSettings['title'] = "IBM 5250"
		 	tpx.filename = cenAX.tpxPrefix + ".1";
		 	tpx.save();
*/

		 	allTPX = cenAX.allTPXFiles();
	 	}

	 	var configs = new Array();
	 	var configNames = new Object();
	 	
	 	for(var i in allTPX) {
		 	var tpx = allTPX[i];
		 	configs.push({ title: tpx.tpxSettings['title'], filename: tpx.filename});
		 	configNames[tpx.tpxSettings['title']] = tpx.filename;
	 	}
	 	
		if(this.configListTable == null) {
			this.configListTable = $('#configListTable').dataTable( {
		    	"bJQueryUI": true,
				"sScrollY": "400px",
				"bPaginate": false,
		        "bScrollCollapse": true,
		        "bFilter": false,
		        "bSort": false,
		        "bInfo": false,
		        "bProcessing": true,
		        "aaData": configs,
				"aoColumns": [
					{
						"mData": null,
						"sName": "",
					    "bSearchable": false,
					    "bSortable": false,
					    "fnRender": function (oObj) {
					       return "";
				    	},
				    },
				{ "mData": "title" }
		 	    ]	
				
			});
			
			$('#configListTable tbody tr').live('click', function () {
				 cenAXUI.configListTable.$('tr.row_selected').removeClass('row_selected');
				 cenAXUI.configListTable.$('tr.subHeadingHighlighted').removeClass('subHeadingHighlighted');
				 $(this).addClass('row_selected');
				 
		 		var nTds = $('td', this);
		 		var aPos = cenAXUI.configListTable.fnGetPosition( nTds[0] );
		 		var data = cenAXUI.configListTable.fnGetData( aPos[0] );
		 		
		 		cenAXUI.fillFormWithSelected();
			});

			$('#configListTable tbody tr').live('dblclick', function () {
		 		var nTds = $('td', this);
		 		var aPos = cenAXUI.configListTable.fnGetPosition( nTds[0] );
		 		var data = cenAXUI.configListTable.fnGetData( aPos[0] );
		 		
		 		console.log("Double Clicked on " + data['filename'] + "\n");
		 		cenAXUI.duplicateWithFilename(data['filename']);
			});
		} else {
			this.configListTable.fnClearTable();
			this.configListTable.fnAddData(configs,true);
		}
		
        $('.dataTables_scrollBody').css('height', '278px');
        
		cenAXUI._fillSelection("#startupConfigList",configNames);
	},

	selectedData:function() {
		var nTr  = $('tr.row_selected');
 		var nTds = $('td', nTr[0]);
 		var aPos = cenAXUI.configListTable.fnGetPosition( nTds[0] );
 		var data = cenAXUI.configListTable.fnGetData( aPos[0] );
 		return data;
	},

	duplicateConfig:function(filename) {
		var tpx = new cenTPXSettings();
		tpx.load(filename);
		
		var newTPX = tpx.copy();
		
		var newTitle = "Copy of " + tpx.tpxSettings['title'];
		var titleCount = 1;
		var allTitles = cenAX.allTPXTitles();
		var foundName = false;
		while(! foundName) {
		
			foundName = true;
			
			for(var index in allTitles) {
				if(newTitle == allTitles[index]) {
					newTitle = "Copy " + (titleCount++) + " of "  + tpx.tpxSettings['title'];
					foundName = false;
					break;
				}
			}
		}
		
		newTPX.filename = cenAX.uniqueTPXFilename();
		newTPX.tpxSettings['title'] = newTitle;
		newTPX.save();
		this.loadConfigs();
		this.highlightTPXFilename(newTPX.filename);
	},
	
	deleteConfig:function(filename) {
		if(cenAX.allTPXFilenames().length < 2) {
			
			return -1;
		}
		
		var data = cenAXUI.selectedData();
		var tpx  = cenAX.tpxWithFilename(data.filename);
		var confirmText = "Are you sure you want to delete '" + 
			tpx.tpxSettings['title'] + "' ?";
		
		$("#modalDeleteConfirmText").html(confirmText);
		
		cenAXUI.deletingTPXFilename = filename;
		
		$("#modalDeleteConfirm").dialog("option","buttons",[
		
			{ text:"OK", click: function() {
				$("#modalDeleteConfirm").dialog("close");
				cenAXUI._deleteConfig(cenAXUI.deletingTPXFilename);
			}},
		
			{ text:"Cancel", click: function() {
				$("#modalDeleteConfirm").dialog("close");
			}}
		]);

		$("#modalDeleteConfirm").dialog("open");

		return 0;
	},
	
	_deleteConfig:function(filename) {
		this.currentEditingTPX = null;
		cenAX.deleteTPXWithFilename(filename);
		this.loadConfigs();
		this.highlightTPXIndex(0);
		return 0;
	},

	fillFormWithSelected:function() {
		var data = this.selectedData();
		this.fillFormWithTPXFile(data.filename);
	},

	fillFormWithTPXFile:function(filename) {
		var tpx = new cenTPXSettings();
		tpx.load(filename);
		this.fillFormWithTPX(tpx);
	},
	
	fillFormWithTPX:function(tpx) {
	
		this.saveFormToCurrentTPX();
	
		this.currentEditingTPX = tpx;
		
		// Connection tab
		
		$("#host").val(tpx.tpxSettings['node']);

		if(tpx.tpxSettings['commtype'] == "4")
			$("#starttls").iCheck('check');
		else if (tpx.tpxSettings['commtype'] == "8")
			$("#ssl").iCheck('check');
		else if (tpx.tpxSettings["commtype"] == "5")
			$("#ssh").iCheck("check");
		else 
			$("#telnet").iCheck('check');

		if (tpx.tpxSettings["commtype"] == "5") {
			var keys = tpx.tpxSettings["secureKeys"];
			var pass = keys[tpx.tpxSettings["passwordHash"]];

			$("#port").val(tpx.tpxSettings['sshport']);
			$("#ssh_user").val(tpx.tpxSettings["user"]);
			$("#ssh_pass").val(pass);
		}
		else {
			$("#port").val(tpx.tpxSettings['port']);
		}
		
		// Window tab
		
		$("#title").val(tpx.tpxSettings['windowTitle']);

		if(tpx.tpxSettings['windowType'] == "1") {
			$("#tab").iCheck('check');
		} else {
			$("#window").iCheck('check');
		}
		
		// Emulation tab
		var emulate = parseInt(tpx.tpxSettings['emulate']);
		
		if(tpx.isEmulationUNIX()) {
			this.setupUNIX();

			$("#unix").iCheck('check');
			$('#configEmulationModel').val(emulate.toString(10));
		}
		else if (tpx.isEmulation3270()) {
			this.setup3270();

			$("#tn3270").iCheck('check');

			if(emulate < 24 || emulate > 27) {
				emulate = 24;
			}

			$("#configEmulationModel").val(emulate.toString(10));
		}
		else if(tpx.isEmulation5250()) {
			this.setup5250();
			$("#tn5250").iCheck('check');
			$("#configEmulationModel").val(emulate.toString(10));
		} else {
		
		}

		if (tpx.isEmulationUNIX()) {
			$("#termTypeString").val(tpx.tpxSettings["teltermtype"]);

			if (tpx.tpxSettings["bsdel"] == "1") {
				$("#bsSendsDel").iCheck("check");
			}

			if (tpx.tpxSettings["MBMode"] == "1") {
				$("#hostUTF8").iCheck("check");
			}

			if (tpx.tpxSettings["maskpar"] == "1") {
				$("#ignoreGraphicsParity").iCheck("check");
			}

			$("#unixRows").val(tpx.tpxSettings["lines"]);
			$("#unixCols").val(tpx.tpxSettings["col"]);
		}
		
		// Display tab
		$("#configCodepages").val(tpx.tpxSettings['cptrxin']);

		if (tpx.isEmulationUNIX()) {
			var vt100nrcsIndex = 0;

			if (tpx.tpxSettings["charset"])
				vt100nrcsIndex = parseInt(tpx.tpxSettings["charset"], 10);

			$("#vt100nrcs").val(cenAX.VT100_NRCS[vt100nrcsIndex]);
			$("#vt200mn").val(tpx.tpxSettings["cpdecmn"]);
		}
		
		this._setColorWellsFromAttribute();

		if (!tpx.isEmulationUNIX()) {
			$("#configDBCSFont").val(tpx.tpxSettings['DBCSFont']);
		}
	},
	
	saveFormToCurrentTPX:function() {
		if(!this.currentEditingTPX) {
			return -1;
		}

		var tpx = this.currentEditingTPX;
		
		// Connection tab
		
		tpx.tpxSettings['node'] = $("#host").val();

		if ($("#ssh").prop("checked")) {
			tpx.tpxSettings["sshport"] = $("#port").val();
		}
		else {
			tpx.tpxSettings["port"] = $("#port").val();
		}

		if($("#telnet").prop('checked')) {
			tpx.tpxSettings['commtype']	= '0';
		}
		else if ($("#ssh").prop('checked')) {
			var ident = tpx.tpxSettings["passwordHash"];
			var keys = tpx.tpxSettings["secureKeys"];

			if (!ident)
				ident = cenAX.genRandIdent();

			if (!keys)
				keys = {};

			keys[ident] = $("#ssh_pass").val();

			tpx.tpxSettings["user"] = $("#ssh_user").val();
			tpx.tpxSettings["passwordHash"] = ident;
			tpx.tpxSettings["secureKeys"] = keys;
			tpx.tpxSettings["commtype"] = "5";
		}
		else if ($('#starttls').prop('checked'))
			tpx.tpxSettings['commtype'] = '4';
		else if ($('#ssl').prop('checked'))
			tpx.tpxSettings['commtype'] = '8';

		// Emulation tab

		tpx.tpxSettings['emulate'] = $("#configEmulationModel").val();

		if (tpx.isEmulationUNIX()) {
			tpx.tpxSettings["teltermtype"] = $("#termTypeString").val();
			tpx.tpxSettings["bsdel"] = $("#bsSendsDel").prop("checked");
			tpx.tpxSettings["MBMode"] = $("#hostUTF8").prop("checked");
			tpx.tpxSettings["maskpar"] = $("#ignoreGraphicsParity").prop("checked");
		}
		
		// Display tab
		tpx.tpxSettings['cptrxin'] = $("#configCodepages").val();

		if (tpx.isEmulationUNIX()) {
			var vt100nrcsValue = $("#vt100nrcs").val();	

			tpx.tpxSettings["charset"] = cenAX.VT100_NRCS.indexOf(vt100nrcsValue);
			tpx.tpxSettings["cpdecmn"] = $("#vt200mn").val();

			var rows = $("#unixRows").val();
			var cols = $("#unixCols").val();

			if (!rows || rows == "" || !rows.match(/^[0-9]+$/)) {
				rows = 25;
				$("#unixRows").val(rows);
				return -1;
			}

			if (!cols || cols == "" || !cols.match(/^[0-9]+$/)) {
				cols = 80;
				$("#unixCols").val(cols);
				return -1;
			}

			/* Cause the TE control to reload here, we need to resize. */
			if 	(
				cenAXUI.currentEditingTPX && cenAXUI.currentEmulatedTPX &&
				cenAXUI.currentEditingTPX.filename == cenAXUI.currentEmulatedTPX.filename &&
				(rows != tpx.tpxSettings["lines"] || cols != tpx.tpxSettings["col"])) {
				cenAX.hteConnection.init = false;
			}

			tpx.tpxSettings["lines"] = rows;
			tpx.tpxSettings["col"] = cols;
		}
		
		if (!tpx.isEmulationUNIX()) {
			tpx.tpxSettings['DBCSFont'] = $("#configDBCSFont").val();
		}
		
		// Window tab
		
		tpx.tpxSettings['windowTitle'] = $("#title").val();
		
		if($("#tab").prop('checked') == true) {
			tpx.tpxSettings['windowType']	= '1';
		} else {
			tpx.tpxSettings['windowType']	= '0';
		}

		tpx.save();
		
		return 0;
	},

	highlightTPXIndex:function(index) {
		var nTr  = cenAXUI.configListTable.$('tr');

		if(index < 0 || index > nTr.length-1) {
			return -1;
		}

		cenAXUI.configListTable.$('tr.row_selected').removeClass('row_selected');
		cenAXUI.configListTable.$('tr.subHeadingHighlighted').removeClass('subHeadingHighlighted');
		$(nTr[index]).addClass('row_selected');
		
		cenAXUI.fillFormWithSelected();
		return 0;
	},
	
	highlightTPXFilename:function(filename) {
		var nodes = cenAXUI.configListTable.fnGetNodes();
		for(var i in nodes) {
			var data = cenAXUI.configListTable.fnGetData(nodes[i]);
	 		if(data.filename == filename) {
				 cenAXUI.configListTable.$('tr.row_selected').removeClass('row_selected');
				 cenAXUI.configListTable.$('tr.subHeadingHighlighted').removeClass('subHeadingHighlighted');
				 $(nodes[i]).addClass('row_selected');
				 cenAXUI.fillFormWithSelected();
				 break;
	 		}
			
		}
	},
	
	selectTabIndex:function(index) {
		$( "#configDetailTabs" ).tabs('select', index);
	},
	
	selectTabNamed:function(name) {
		$( "#configDetailTabs" ).tabs('select', '#' + name);
	},
	
	isShowingSettings:function() {
		return ($("#controlFrame").is(":visible"));
	},
	
	toggleConfigView:function() {
		if(this.isShowingSettings()) {
			$("#controlFrame").hide();
			$("#uiTest").show();
		} else {

			if(arguments.length == 1) {
				highlightTPXFilename(arguments[0]);
			}

			$("#controlFrame").show();
			$("#uiTest").hide();
		}
	},

	switchConfigView: function (configView) {
		var view = configView + "ConfigView";

		if (view == "emulatorsConfigView") {
			$("#windowGroupsConfigView").hide(
				"slide",
				{ direction: "up" },
				50,
				function () {
					$("#emulatorsConfigView").show("slide", { direction: "down" }, 50);
				}
			);
		}
		else if (view == "windowGroupsConfigView") {
			$("#emulatorsConfigView").hide(
				"slide",
				{ direction: "down" },
				50,
				function () {
					$("#windowGroupsConfigView").show("slide", { direction: "up" }, 50);
				}
			);
		}
	},

	renameConfig:function(filename) {
		var tpx = new cenTPXSettings();
		tpx.load(filename);
		
		$("#modalRenameInput").val(tpx.tpxSettings['title']);
				
		cenAXUI.renamingTPXFilename = filename;

		$("#modalRename").dialog("option","buttons",[
		
			{ text:"OK", click: function() {
				cenAXUI._renameConfig(cenAXUI.renamingTPXFilename,$("#modalRenameInput").val());
				$("#modalRename").dialog("close");
			}},
		
			{ text:"Cancel", click: function() {
				$("#modalRename").dialog("close");
			}}
		]);
		
		$("#modalRename").dialog("open");
	},
	
	_renameConfig:function(filename, newName) {
		var tpx = new cenTPXSettings();
		tpx.load(filename);

		if(tpx.filename == this.currentEditingTPX.filename) {
			this.currentEditingTPX.tpxSettings['title'] = newName;
		}

		tpx.tpxSettings['title'] = newName;
		tpx.save();
		this.loadConfigs();
		this.highlightTPXFilename(filename);
	},
	
	setupHandlers:function() {

		var params = cenAX.getParams();
		
		$("#configDuplicate").click(function() {
			var tpxFilename = cenAXUI.selectedData().filename;
			cenAXUI.duplicateConfig(tpxFilename);
		});
		
		$("#configDelete").click(function() {
			var tpxFilename = cenAXUI.selectedData().filename;
			cenAXUI.deleteConfig(tpxFilename);
		});

		$("#configRename").click(function() {
			var tpxFilename = cenAXUI.selectedData().filename;
			cenAXUI.renameConfig(tpxFilename);
		});

		$("#configButtonOK").click(function() {
			if(cenAXUI.currentEditingTPX) {
				var activeConfig = localStorage.getItem("com.censoft.hte.activeConfig");

				if (cenAXUI.currentEditingTPX.filename &&
					activeConfig &&
					cenAXUI.currentEditingTPX.filename == activeConfig) {
					cenAXUI.saveFormToCurrentTPX();
					cenAXUI.currentEmulatedTPX = cenAXUI.currentEditingTPX;
					cenAXUI.currentEmulatedTPX.update();
				}

				cenAXUI.toggleConfigView();
			}

			$("#screen_frame").focus();
		});

		$("#configButtonCancel").click(function() {
			if(cenAXUI.currentEditingTPX) {
				var filename = cenAXUI.currentEditingTPX.filename;
				cenAXUI.currentEditingTPX = null;
				cenAXUI.highlightTPXFilename(filename);
				cenAXUI.toggleConfigView();
			}

			$("#screen_frame").focus();
		});

		$("#configButtonConnect").click(function() {
			if(cenAXUI.currentEditingTPX != null) {
				if(cenAXUI.currentEditingTPX.filename) {
					cenAXUI.saveFormToCurrentTPX();

					cenAXUI.currentEmulatedTPX = cenAXUI.currentEditingTPX;

					localStorage.setItem("com.censoft.hte.activeConfig", cenAXUI.currentEditingTPX.filename);

					cenAXUI.currentEmulatedTPX.connect(true);
					cenAXUI.toggleConfigView();
				}
			}

			$("#screen_frame").focus();
		});
	
		$(".cenToolbarConfigure").click(function() { 
			var activeConfig = localStorage.getItem("com.censoft.hte.activeConfig");

			cenAXUI.highlightTPXFilename(activeConfig);
			cenAXUI.toggleConfigView();
		});

		$(".cenToolbarColors").click(function() { 
			if(cenAXUI.isShowingSettings()) {
				cenAXUI.toggleConfigView();
			}
			cenAXUI.selectTabNamed("configDetailDisplay");
		});

		$(".cenToolbarHelp").click(function() { 
			window.open("http://www.censoft.com/help/ax5/","_blank")
		});

		$(".cenToolbarCopy").click(function() { 
		});

		$(".cenToolbarPaste").click(function() { 
		});

		$("#unix").on("ifChecked", function () {
			cenAXUI.setupUNIX();
		});

		$("#tn3270").on('ifChecked',function() { 
			cenAXUI.setup3270();
		});
		
		$("#tn5250").on('ifChecked',function() { 
			cenAXUI.setup5250();
		});
		
		cenAXUI._fillSelection("#configDBCSFont",cenAX.dbcsFonts);

		$(window).resize(function () {
			cenAXUI.sizeControlFrame();
		});
		 
		 var rgbTPX = new cenTPXSettings();
		 
		 for(i=0; i<rgbTPX.IBMRGBDefault.length; i++) {
			 var color = rgbTPX.IBMRGBDefault[i];
			 $("#foregroundcolor").append("<option value='" + color + "'>#" + color + "</option>");
			 $("#cursorColor").append("<option value='" + color + "'>#" + color + "</option>")
		 }

		 jQuery('#foregroundcolor').colourPicker({
		    ico:    'css/images/jquery.colourPicker.gif',
		    callback: function (rgbValue, index) {
				var foregroundColorName = cenAXUI._foregroundColorNameFromAttribute();

				index = (parseInt(index, 10) + 1).toString(10);
		
				cenAXUI.currentEditingTPX.tpxSettings[foregroundColorName] = index;
		   	},
		    title: false
		});

		$("#cursorColor").colourPicker({
			ico: "css/images/jquery.colourPicker.gif",
			title: false,
			callback: function (rgb, index) {

				cenAXUI.currentEditingTPX.tpxSettings["CursorColor"] = index.toString(10);

				if (cenAXUI.currentEditingTPX.filename == cenAXUI.currentEmulatedTPX.filename) {
					cenAX.hteConnection.init = false;
					cenAX.hteConnection.setTPXConfig(cenAXUI.currentEditingTPX.tpxSettings);
					cenAX.hteConnection.loadConfig(false, false);
				}
			}
		})
		
		$('#configAttributeList').change(function () {
			cenAXUI._setColorWellsFromAttribute();
		});

		$("#sshUsername").hide();
		$("#sshPassword").hide();	

		$("#ssh").on("ifChanged", function (e) {
			var config = cenAXUI.currentEditingTPX;
			var showLogin = e.currentTarget.checked;

			if (showLogin) {
				$("#sshUsername").show();
				$("#sshPassword").show();	

				$("#port").val(config.tpxSettings.sshport || 22);
			}
			else {
				$("#sshUsername").hide();
				$("#sshPassword").hide();	

				$("#port").val(config.tpxSettings.port || 23);
			}
		});
		
		$("#startupShowSettings").on('ifChecked',function() {
			localStorage.setItem(cenAX.storagePrefix + ".startupType","0")
			$("#startupConfigList").attr('disabled', true);
		});
		
		$("#startupUseConfig").on('ifChecked',function() {
			localStorage.setItem(cenAX.storagePrefix + ".startupType","1")
			$("#startupConfigList").attr('disabled', false);
			localStorage.setItem(cenAX.storagePrefix + ".startupConfig",$("#startupConfigList").val())
		});
		
		$('#startupConfigList').change(function () {
			localStorage.setItem(cenAX.storagePrefix + ".startupConfig",$("#startupConfigList").val())
		});

		if(typeof(params.loadConfigFilename) == 'string') {
			this.highlightTPXFilename(params.loadConfigFilename);
		} else {
			var activeConfig = localStorage.getItem("com.censoft.hte.activeConfig");

			if (activeConfig)
				this.highlightTPXFilename(activeConfig);
			else
				this.highlightTPXIndex(0);
		}		

		this.setStartupOptions();
	},
	
	duplicateWithFilename:function(filename) { 
		var launchURL = cenAX.baseURL() + "?loadConfigFilename=" + encodeURIComponent(filename) + "&addWindow=1";
		console.log("Launching " + launchURL);
		window.open(launchURL,"_blank","toolbar=no,menubar=no,resizable=yes,location=no,height=" + $(window).height() + ",width=" + $(window).width());
	},

	sizeControlFrame:function() {
	},

	connectWithTPXFilename:function(filename) {
		var tpx = new cenTPXSettings();

		tpx.load(filename);

		tpx.connect();

		cenAXUI.currentEmulatedTPX = tpx;
	},

	setStartupOptions:function()
	{
		var self = this;

		var needToShowSettings = false;

		var startupConfig = localStorage.getItem(cenAX.storagePrefix + ".startupConfig");
		var startupType = localStorage.getItem(cenAX.storagePrefix + ".startupType");
		var session = localStorage.getItem(cenAX.storagePrefix + ".sid");

		var tpx = new cenTPXSettings();

		tpx.load(startupConfig);

		if(!startupType || startupType == "0") {
			$("#startupShowSettings").iCheck('check');

			if (session) {
				tpx.attach(function () {
					localStorage.removeItem(cenAX.storagePrefix + ".sid");

					self.setStartupOptions();
				});
			}
			else {
				needToShowSettings = true;
			}
		} else {
			if(startupConfig) {
				tpx.connect(false, function () {
					localStorage.removeItem(cenAX.storagePrefix + ".sid");	

					self.setStartupOptions();
				});

				$("#startupConfigList").val(startupConfig);
			}

			$("#startupUseConfig").iCheck('check');
		}

		if(needToShowSettings) {
			this.toggleConfigView();
		}

		cenAXUI.currentEmulatedTPX = tpx;
	},

	_unixSelected:function()
	{
		var emulate = $("#configEmulationModel").val();
		return (emulate >= 0 && emulate <= 20) || (emulate >= 28 || emulate <= 30);
	},

	_3270Selected:function()
	{
		var emulate = $("#configEmulationModel").val();
		return (emulate >=24 && emulate <= 27);		
	},
	
	_setColorWellsFromAttribute:function()
	{
		var config = this.currentEditingTPX;

		var foregroundColorName = this._foregroundColorNameFromAttribute();
		var foregroundColorIndex = parseInt(config.tpxSettings[foregroundColorName], 10) - 1;

		var cursorColorIndex = parseInt(config.tpxSettings["CursorColor"], 10);

		$("input[name=foregroundColor]").css({ background: '#' + config.IBMRGBDefault[foregroundColorIndex] , color: '#' + config.IBMRGBDefault[foregroundColorIndex] });
		$("input[name=cursorColor]").css({ background: '#' + config.IBMRGBDefault[cursorColorIndex], color: '#' + config.IBMRGBDefault[cursorColorIndex] });
	},
	
	_foregroundColorNameFromAttribute:function()
	{
		if($('#configAttributeList').length) {
			var attributeIndex = parseInt($("#configAttributeList").val(), 10);
			if(this._unixSelected()) {
				switch (attributeIndex) {
		    		case 0:
		    			return "colorbg0";
		    		case 1:
		    			return "colorfg0";
		    		case 2:
		    			return "colorfg4";
		    	}
			} else if(this._3270Selected()) {
				return '3270colfg' + attributeIndex.toString(10);
			} else {
				return '5250colfg' + attributeIndex.toString(10);
			}
		}
		
		return "";
	},
	
	_fillSelection:function(selection, newOptions) {

		$(selection).empty();
		
		if(Object.prototype.toString.call( newOptions )  == "[object Array]") {

			$.each(newOptions, function(key,value) {
				$(selection).append($("<option></option>")
				.attr("value", value).text(value));
			});
		} else {
			$.each(newOptions, function(key, value) {
				$(selection).append($("<option></option>")
				.attr("value", value).text(key));
			});
		}
	},
	setupUNIX:function () {
		// connection tab
		$("#sshControls").show();
		$("#startTlsControls").hide();
		$("#sslControls").hide();

		// emulation tab
		cenAXUI._fillSelection("#configEmulationModel", {
			"ADM1":0,
			"ANSI":1,
			"AT386":2,
			"Mac":30,
			"Linux Console":11,
			"PCTERM":4,
			"SCOANSI":5,
			"TTY":6,
			"TV912":7,
			"TV925":8,
			"TV950":9,
			"VT100":10,
			"VT220":12,
			"VT220-7":13,
			"VT320":14,
			"VT320-7":15,
			"VT420":16,
			"ADDS Viewpoint":28,
			"WYSE50":17,
			"WYSE60":18,
			"WYSE60-25":19,
			"WYCOL":29,
			"IBM3101":3,
			"IBM3151":20,
		});

		$("#termTypeStringSection").show();
		$("#bsSendsDelSection").show();
		$("#hostUTF8Section").show();
		$("#ignoreGraphicsParitySection").show();

		// display tab
		$("#vt100nrcsSection").show();
		$("#vt200mnSection").show();
		$("#unixRowsSection").show();
		$("#unixColsSection").show();
		$("#dbcs").hide();

		var attributeNames = cenAX.attributeNamesUNIX();
		$("#configAttributeList").empty();
		for(i=0; i<attributeNames.length; i++) {
			$("#configAttributeList").append("<option value='" + i.toString(10) + "'>" + attributeNames[i] + "</option>");
		}

		cenAXUI._fillSelection("#configCodepages", cenAX.codepagesUNIX);
		cenAXUI._fillSelection("#vt100nrcs", cenAX.VT100_NRCS);
		cenAXUI._fillSelection("#vt200mn", cenAX.VT200_MULTINATIONAL);
	},
	setup3270:function() {
		// connection tab
		$("#sshControls").hide();
		$("#startTlsControls").show();
		$("#sslControls").show();

		// emulation tab
		var newOptions = { 
			"3278-2 (24x80)": "24",
			"3278-3 (32x80)": "25",
			"3278-4 (43x80)": "26",
			"3278-5 (27x132)": "27",
		};
		
		cenAXUI._fillSelection("#configEmulationModel", newOptions);

		$("#termTypeStringSection").hide();
		$("#bsSendsDelSection").hide();
		$("#hostUTF8Section").hide();
		$("#ignoreGraphicsParitySection").hide();

		// display tab
		$("#vt100nrcsSection").hide();
		$("#vt200mnSection").hide();
		$("#unixRowsSection").hide();
		$("#unixColsSection").hide();
		$("#dbcs").show();

		var attributeNames = cenAX.attributeNames3270();
		$("#configAttributeList").empty();
		for(i=0; i<attributeNames.length; i++) {
			$("#configAttributeList").append("<option value='" + i.toString(10) + "'>" + attributeNames[i] + "</option>");
		}
		
		cenAXUI._fillSelection("#configCodepages",cenAX.codepages3270);
	},
	setup5250:function() {
		// connection tab
		$("#sshControls").hide();
		$("#startTlsControls").show();
		$("#sslControls").show();

		// emulation tab
		var newOptions = { 
			"3179-2 (24x80)": "22",
			"3477-FC (27x132)": "23",
		};
		
		cenAXUI._fillSelection("#configEmulationModel", newOptions);

		$("#termTypeStringSection").hide();
		$("#bsSendsDelSection").hide();
		$("#hostUTF8Section").hide();
		$("#ignoreGraphicsParitySection").hide();
		$("#unixRowsSection").hide();
		$("#unixColsSection").hide();

		// display tab
		$("#vt100nrcsSection").hide();
		$("#vt200mnSection").hide();
		$("#dbcs").show();

		var attributeNames = cenAX.attributeNames5250();
		$("#configAttributeList").empty();
		for(i=0; i<attributeNames.length; i++) {
			$("#configAttributeList").append("<option value='" + i.toString(10) + "'>" + attributeNames[i] + "</option>");
		}

		cenAXUI._fillSelection("#configCodepages",cenAX.codepages5250);

	},

	handleDisconnect:function() {
	}
}

