/*
Copyright (c) 2008, Netmon Inc. All Rights Reserved
Author: $Author: xavier $
($Id: setup_wizard.js 5486 2010-02-16 15:56:22Z xavier $)
*/

// Global var declarations
var network_ranges = [];

var active_node = null;

var ip_regex   = /(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/;

var port_regex = /([0-9]{1,5})/

// Navigation tree
var nav_panel = new Ext.tree.TreePanel({
	title: "Configuration",
	region: 'west',
	split: true,
	width: 200,
	collapsible: true,
	frame: true,
	animate:true
});


// Root node
var root = new Ext.tree.TreeNode({
    text: 'Wizards',
    draggable:false,
    id:'source'
});
nav_panel.setRootNode(root);


// Container for the wizard panels
var main_container = new Ext.Panel({
	id: 'main_container',
	region: 'center',
	frame: true,
	title: "Wizard Viewer",
	split: true
});


// Setup wizard Ext window
var main_window = new Ext.Window({
	title: 'Netmon Deployment Wizard',
	closable: false,
	width: 640,
	height: 480,
	plain: true,
	modal: true,
	layout: 'border',
	items: [nav_panel, main_container]
});


// Displays the admin account creation form
ajax_admin_account_form = function() {
	
	set_info = new Ext.form.FieldSet({
		title: 'Contact Information',
		defaultType: 'textfield',
		defaults: {width: 230},
		autoHeight:true,
		items: [
			{ fieldLabel: 'First Name',    name: 'first_name', allowBlank: false },
			{ fieldLabel: 'Last Name',     name: 'last_name',   allowBlank: false },
			{ fieldLabel: 'Email Address', name: 'email', allowBlank: false, vtype: 'email' },
			{ name: 'sub_account_group[]', xtype: 'hidden', value: '1'}
		]
	});
	
	set_credentials = new Ext.form.FieldSet({
		title: 'Credentials',
		defaultType: 'textfield',
		defaults: {width: 230},
		autoHeight:true,
		items: [
			{ fieldLabel: 'Username', name: 'username', allowBlank: false },
			{ fieldLabel: 'Password', name: 'passwd', allowBlank: false, inputType: 'password' }
		]
	});

	var form = new Ext.FormPanel({
		url: '?module=core&action=setup_wizard_proxy&hook=admin_account_processor&root_tpl=blank',
		id: 'admin_account_form',
		method: 'POST',
		defaultType: 'textfield',
		bodyStyle:'padding:5px 5px 0',
		width: 400,
		collapsed: false,
		
		frame: true,
		items: [set_info, set_credentials],
		buttons: [
			{formBind: true, text: 'Next Step', type: 'submit', handler: account_processor}
		]
	});

	return wizard_load(form, "Create Administrator Account");
}

// Loads components in a new Wizard Panel
wizard_load = function(components, title) {

	if (Ext.getCmp('wizard_container')) {
		Ext.getCmp('wizard_container').destroy();
	}

	wizard_container = new Ext.Panel({
		id: 'wizard_container',
		frame: true,
		items: components
	});
	
	main_container.add(wizard_container);
	main_container.setTitle(title);
	main_container.doLayout();
	return true;
}

// Submits the admin account form
account_processor = function() {
	form = Ext.getCmp('admin_account_form').form;
	if (!form.isValid()) {
		Ext.MessageBox.alert('Error', 'You must provide valid values for every field in this form');
		return;
	}
	
	ret = form.submit({ 
		waitMsg: 'Saving...',
		reset: false,
		failure: function(formObj, action) {
			console.log(action.result);
			Ext.MessageBox.alert('Submission Error', action.result.errorInfo);
		},
		success: function(formObj, action) {
			console.log(action.response);
			next_step();
		}
	});
}

// Prepends the latest range entered to the ranges panel.
ajax_update_network_ranges = function(values) {
	tpl = new Ext.XTemplate(
			'{label} ({network} to {broadcast}) ',
			'<tpl if="enable_portscan == \'true\'">',
				'<span class="green">Portscan</span> ',
			'</tpl>',
			'<tpl if="enable_snmp_discovery == \'true\'">',
				'<span class="green">SNMP</span> ',
			'</tpl>',
			'<hr />');		
	panel = Ext.getCmp('network_ranges_list');
	if (network_ranges.length < 1) {
		panel.hide();
	} else {
		panel.show();
		tpl.insertFirst(panel.body, values);
		panel.doLayout();
		panel.body.highlight('#aaaaaa', {block:true});
	}
}


// AJAX Call that processes the creation of a new network range
ajax_add_network_range = function() {
	
	form_panel = Ext.getCmp('network_ranges_form');
	form =form_panel.getForm();
	if (!form.isValid()) {
		Ext.MessageBox.alert('Error', 'Some fields in this form contain incorrect values');
		return;
	}
	
	//console.log(form_panel);
	vals = form.getValues();
	if (!vals['enable_snmp_discovery']) {
		vals['enable_snmp_discovery'] = 'false';
	} else {
		vals['enable_snmp_discovery'] = 'true';
	}
			
	if (!vals['enable_portscan']) {
		vals['enable_portscan'] = 'false';
	} else {
		vals['enable_portscan'] = 'true';
	}
	
	
	ret = form.submit({ 
		waitMsg: 'Saving...',
		reset: false,
		failure: function(formObj, action) {
			Ext.MessageBox.alert('Submission Error', action.result.errorInfo);
		},
		success: function(formObj, action) {
			console.log(action.result);
			
			
			
			network_ranges.push(vals);
			ajax_update_network_ranges(vals);
			form.reset();
		}
	});
}

// Displays the Network Ranges Creation Form
ajax_network_ranges_form = function() {
	
	set_range = new Ext.form.FieldSet({
		title: 'Network Range',
		defaultType: 'textfield',
		defaults: {width: 230},
		autoHeight:true,
		items: [
			{ fieldLabel: 'Label (e.g. VLAN1)',  name: 'label', allowBlank: false, tabIndex: 1 },
			{ fieldLabel: 'Starting IP Address', name: 'network',    allowBlank: false, regex: ip_regex, regexText: "Invalid IP Address", tabIndex: 2 },
			{ fieldLabel: 'Ending IP Address',   name: 'broadcast',  allowBlank: false, regex: ip_regex, regexText: "Invalid IP Address", tabIndex: 3 }
		]
	});
	
	
	set_options = new Ext.form.FieldSet({
		title: 'Auto-Discovery Options',
		autoHeight: true,
		items:[{
	        layout:"column",
	        items:[{
	            columnWidth:0.5,
	            items:[{
	                xtype:"checkbox",
	                fieldLabel:"portscan",
	                boxLabel:"Port Scanning",
	                name:"enable_portscan",
	                inputValue:"true",
	                tabIndex: 4
	              }]
	          },{
	            columnWidth:0.5,
	            items:[{
	                xtype:"checkbox",
	                fieldLabel:"snmp",
	                boxLabel:"SNMP Discovery",
	                name:"enable_snmp_discovery",
	                inputValue:"true",
	                tabIndex: 5
	              }]
	          }]
      	}]
	});
	
	
	form = new Ext.FormPanel({
		url: '?module=core&action=setup_wizard_proxy&hook=network_ranges_processor&root_tpl=blank',
		id: 'network_ranges_form',
		method: 'POST',
		defaultType: 'textfield',
		//bodyStyle:'padding:5px 5px 0',
		width: 400,
		autoHeight: true,
		collapsed: false,
		
		frame: true,
		items: [set_range, set_options],
		buttons: [
			{text: 'Add Range', type: 'submit', handler: ajax_add_network_range},
			{formBind: true, text: 'Next Step', handler: next_step}
		]
	});
	
	
	
	range_panel = new Ext.Panel({
		title: "Network Ranges",
		id: 'network_ranges_list',
		height: 120,
		//autoHeight: true,
		//frame: true,
		autoScroll: true
	});
	
	wizard_load([form, range_panel], "Configure Network Ranges");
	ajax_update_network_ranges();
}


// Displays the SNMP Settings form
ajax_snmp_settings_form = function() {
	
	versionStore = new Ext.data.SimpleStore({
		fields: ['version'],
		data: [['1'], ['2c']]
	})
	
	
	set_options = new Ext.form.FieldSet({
		title: "SNMP Auto-Discovery Settings",
		defaultType: 'textfield',
		defaults: {width: 230},
		autoHeight:true,
		items: [
			{ fieldLabel: 'Community String',  name: 'community', value: 'public', allowBlank: false },
			{ fieldLabel: 'Scanning Port', name: 'port', value: '161', allowBlank: false, regex: port_regex, regexText: "You must specify a valid port number (1-65535)" },
			{ fieldLabel: 'SNMP Version',   
				name: 'snmpv',
				width: 60,
				allowBlank: false, 
				xtype: 'combo',
				readonly: true,
				editable: false,
				typeAhead: false,
				forceSelection: true,
				triggerAction: 'all',
				store: versionStore,
				displayField: 'version',
				valueField: 'version',
				mode: 'local',
				value: '1'
			}
		]
	});
	
	form = new Ext.FormPanel({
		url: '?module=core&action=setup_wizard_proxy&hook=snmp_settings_processor&root_tpl=blank',
		id: 'snmp_settings_form',
		method: 'POST',
		defaultType: 'textfield',
		//bodyStyle:'padding:5px 5px 0',
		width: 400,
		autoHeight: true,
		collapsed: false,
		
		frame: true,
		items: [set_options],
		buttons: [
			{formBind: true, text: 'Next Step', handler: ajax_snmp_settings_processor}
		]
	});
	
	wizard_load([form], "Configure SNMP Device Auto-Discovery");
	
}

// Registers the SNMP settings
ajax_snmp_settings_processor = function() {
	form_panel = Ext.getCmp('snmp_settings_form');
	form =form_panel.getForm();
	if (!form.isValid()) {
		Ext.MessageBox.alert('Error', 'Some fields in this form contain incorrect values');
		return;
	}	
	
	ret = form.submit({ 
		waitMsg: 'Saving...',
		reset: false,
		failure: function(formObj, action) {
			Ext.MessageBox.alert('Submission Error', action.result.errorInfo);
		},
		success: function(formObj, action) {
			console.log(action.result);
			next_step();
		}
	});
	
}

// Load the diagnostic results through AJAX
ajax_load_diagnostic = function() {
	mirroring_panel = new Ext.Panel({
		title: "Port Mirroring",
		id: 'mirroring_diag',
		height: 120,
		autoScroll: true
	});
	
	update_panel = new Ext.Panel({
		title: "Netmon Update Service",
		id: 'update_diag',
		height: 120,
		autoScroll: true
	});
	
	confirm_panel = new Ext.Panel({
		title: "Configuration Status",
		id: 'config_panel',
		height: 120,
		autoScroll: true,
		buttons: [
			{formBind: true, text: 'Close Wizard', handler: next_step}
		]
	});
	
	wizard_load([mirroring_panel, update_panel, confirm_panel], "Deployment Diagnostics");
	
	mirroring_panel.load({
		url: '/?module=core&action=setup_wizard_proxy&hook=detect_port_mirroring&root_tpl=blank',
		text: 'Sampling network traffic, please wait'
	});
	
	update_panel.load({
		url: '/?module=core&action=setup_wizard_proxy&hook=detect_rsync&root_tpl=blank',
		text: 'Contacting Netmon update service. Please wait.'
	});
	
	confirm_panel.load({
		url: '/?module=core&action=setup_wizard_proxy&hook=start_services&root_tpl=blank',
		text: 'Starting Netmon services. Please wait...'
	});
	
	
	
}


// Disables network ranges tree node and moves on to the next node.
next_step = function() {
	if (null == active_node) {
		active_node = root.firstChild;
	} else {
		active_node.disable();
		
		if (active_node.isLast()) {
			main_window.close();
			window.location.reload(true)
			return;
		}
		
		
		active_node = active_node.nextSibling;
	}
		
	active_node.enable();
	nav_panel.getSelectionModel().select(active_node);
	active_node.attributes.hook();
}

// Create leaf nodes
root.appendChild([
	new Ext.tree.TreeNode({
		text: 'Administrator Account', 
		id: 'account_node', 
		//listeners: { 'click': ajax_admin_account_form },
		hook: ajax_admin_account_form
	}),
	
	new Ext.tree.TreeNode({
		text: 'Network Ranges',
		id: 'network_ranges',
		disabled: true,
		//listeners: { 'click': ajax_network_ranges_form },
		hook: ajax_network_ranges_form
	}),
	
	new Ext.tree.TreeNode({
		text: 'SNMP Auto-Discovery',
		id: 'snmp_autodiscovery',
		disabled: true,
		//listeners: {'click' : ajax_snmp_settings_form },
		hook: ajax_snmp_settings_form
	}),
	
	new Ext.tree.TreeNode({
		text: 'Deployment Diagnostic',
		id: 'diagnostic',
		disabled: true,
		//listeners: {'click' : ajax_load_diagnostic },
		hook: ajax_load_diagnostic
	})]
);

// Launcher
wizard_launch = function() {
	document.title = "First-time Installation Wizard";

	Ext.QuickTips.init();
	main_window.show();
	root.expand(false, false);
	next_step();
	
	//ajax_load_diagnostic();
	
	
	// Find out if we have users in the DB
	// If we do, call main_window.show()
	// Otherwise, return
};


