/**
 * Execute when the DOM is fully loaded
 */
$(document).ready(function() {
	// Load utility scripts (if any)
});
/**
 * Constructor
 * 
 * @return Nothing
 */
var kvmPlugin = function() {
};
/**
 * Configure self-service page
 */
kvmPlugin.prototype.loadConfigPage = function(tabId) {	
	var configAccordion = $('
');
	
	// Create accordion panel for user
	var userSection = $('
');
	var userLnk = $('').click(function () {
		// Do not load panel again if it is already loaded
		if ($('#kvmConfigUser').find('.dataTables_wrapper').length)
			return;
		else
			$('#kvmConfigUser').append(createLoader(''));
		
		// Get user data
		loadUserPanel('kvmConfigUser');
	});
	
	// Create accordion panel for profiles
	var profileSection = $('
');
	profileSection.append(createInfoBar('Create, edit, and delete virtual machine profiles used in the self-service portal'));
	var profileLnk = $('').click(function () {
		
	});
	
	// Create accordion panel for nodes
	var nodeSection = $('
');
	nodeSection.append(createInfoBar('Modify node attributes'));
	var nodeLnk = $('').click(function () {
		
	});
	
	configAccordion.append(userLnk, userSection, profileLnk, profileSection, nodeLnk, nodeSection);
	$('#' + tabId).append(configAccordion);
	configAccordion.accordion();
	
	userLnk.trigger('click');
};
/**
 * Clone node (service page)
 * 
 * @param node
 * 			Node to clone
 * @return Nothing
 */
kvmPlugin.prototype.serviceClone = function(node) {
	openDialog('info', 'Not yet supported');
};
/**
 * Load provision page (service page)
 * 
 * @param tabId
 * 			Tab ID where page will reside
 * @return Nothing
 */
kvmPlugin.prototype.loadServiceProvisionPage = function(tabId) {
	$('#' + tabId).append(createInfoBar('Not yet supported'));
};
/**
 * Show node inventory (service page)
 * 
 * @param data
 *            Data from HTTP request
 * @return Nothing
 */
kvmPlugin.prototype.loadServiceInventory = function(data) {
	
};
/**
 * Load node inventory
 * 
 * @param data
 *            Data from HTTP request
 * @return Nothing
 */
kvmPlugin.prototype.loadInventory = function(data) {
	var args = data.msg.split(',');
	var tabId = args[0].replace('out=', '');
	var node = args[1].replace('node=', '');
	
	// Get node inventory
	var inv = data.rsp;
	// Remove loader
	$('#' + tabId).find('img').remove();
	// Create division to hold inventory
	var invDiv = $('
');
	
	// Create a fieldset
	var fieldSet = $(' ');
	var legend = $('Hardware ');
	fieldSet.append(legend);
	
	var oList = $(' ');
	fieldSet.append(oList);
	invDiv.append(fieldSet);
	// Loop through each line
	var item;
	for (var k = 0; k < inv.length; k++) {
		// Remove node name
		var attr = inv[k].replace(node + ': ', '');
		attr = jQuery.trim(attr);
		// Append attribute to list
		item = $(' ');
		item.append(attr);
		oList.append(item);
	}
	// Append to inventory form
	$('#' + tabId).append(invDiv);
};
/**
 * Load clone page
 * 
 * @param node
 *            Source node to clone
 * @return Nothing
 */
kvmPlugin.prototype.loadClonePage = function(node) {
	// Get nodes tab
	var tab = getNodesTab();
	var newTabId = node + 'CloneTab';
	// If there is no existing clone tab
	if (!$('#' + newTabId).length) {
		// Create info bar
		var infoBar = createInfoBar('Not yet supported');
		// Create clone form
		var cloneForm = $('
');
		cloneForm.append(infoBar);
		// Add clone tab
		tab.add(newTabId, 'Clone', cloneForm, true);
	}
	
	tab.select(newTabId);
};
/**
 * Load provision page
 * 
 * @param tabId
 *            The provision tab ID
 * @return Nothing
 */
kvmPlugin.prototype.loadProvisionPage = function(tabId) {
	// Get OS image names
	$.ajax( {
		url : 'lib/cmd.php',
		dataType : 'json',
		data : {
			cmd : 'tabdump',
			tgt : '',
			args : 'osimage',
			msg : ''
		},
		success : setOSImageCookies
	});
	// Get groups
	$.ajax( {
		url : 'lib/cmd.php',
		dataType : 'json',
		data : {
			cmd : 'extnoderange',
			tgt : '/.*',
			args : 'subgroups',
			msg : ''
		},
		success : setGroupsCookies
	});
	// Create provision form
	var provForm = $('
');
	// Create info bar
	var infoBar = createInfoBar('Provision an KVM virtual machine.');
	provForm.append(infoBar);
	// Append to provision tab
	$('#' + tabId).append(provForm);
	
	// Create VM fieldset
	var vmFS = $(' ');
	var vmLegend = $('Virtual Machine ');
	vmFS.append(vmLegend);
	
	var vmAttr = $('
');
	vmFS.append($(''));
	vmFS.append(vmAttr);
	
	// Create hardware fieldset
	var hwFS = $(' ');
	var hwLegend = $('Hardware ');
	hwFS.append(hwLegend);
	
	var hwAttr = $('
');
	hwFS.append($(''));
	hwFS.append(hwAttr);
	
	// Create image fieldset
	var imgFS = $(' ');
	var imgLegend = $('Image ');
	imgFS.append(imgLegend);
	
	var imgAttr = $('
');
	imgFS.append($(''));
	imgFS.append(imgAttr);
	
	provForm.append(vmFS, hwFS, imgFS);
	
	// Create hypervisor input
	var host = $('
');
	var hostLabel = $('Host: ');
	host.append(hostLabel);
	var hostInput = $(' ');
	host.append(hostInput);
	vmAttr.append(host);
	
	// Create group input
	var group = $('
');
	var groupLabel = $('Group: ');
	group.append(groupLabel);
	// Turn on auto complete for group
	var groupNames = $.cookie('groups');
	if (groupNames) {
		// Split group names into an array
		var tmp = groupNames.split(',');
		// Create drop down for groups
		var groupSelect = $(' ');
		groupSelect.append(' ');
		for ( var i in tmp) {
			// Add group into drop down
			var opt = $('' + tmp[i] + ' ');
			groupSelect.append(opt);
		}
		group.append(groupSelect);
	} else {
		// If no groups are cookied
		var groupInput = $(' ');
		group.append(groupInput);
	}
	vmAttr.append(group);
	// Create node input
	var node = $('
');
	var nodeLabel = $('VM name: ');
	var nodeInput = $(' ');
	node.append(nodeLabel);
	node.append(nodeInput);
	vmAttr.append(node);
	// Create memory input
	var memory = $('
');
	var memoryLabel = $('Memory: ');
	var memoryInput = $(' ');
	memory.append(memoryLabel);
	memory.append(memoryInput);
	hwAttr.append(memory);
	
	// Create processor dropdown
	var cpu = $('
');
	var cpuLabel = $('Processor: ');
	var cpuSelect = $(' ');
	cpuSelect.append('1 '
		+ '2 '
		+ '3 '
		+ '4 '
		+ '5 '
		+ '6 '
		+ '7 '
		+ '8 '
	);
	cpu.append(cpuLabel);
	cpu.append(cpuSelect);
	hwAttr.append(cpu);
	
	// Create NIC dropdown
	var nic = $('
');
	var nicLabel = $('NIC: ');
	var nicInput = $(' ');
	nic.append(nicLabel);
	nic.append(nicInput);
	hwAttr.append(nic);
	
	// Create disk input
	var disk = $('
');
	var diskLabel = $('Disk size: ');
	var diskInput = $(' ');
	var diskSizeSelect = $(' ');
	diskSizeSelect.append('GB ' +
		'MB '
	);
	disk.append(diskLabel, diskInput, diskSizeSelect);
	hwAttr.append(disk);
	
	// Create disk storage input
	var storage = $('
');
	var storageLabel = $('Storage: ');
	var storageInput = $(' ');
	storage.append(storageLabel);
	storage.append(storageInput);
	hwAttr.append(storage);
	
	// Create operating system input
	var os = $('
');
	var osLabel = $('Operating system: ');
	var osInput = $(' ');
	osInput.one('focus', function() {
		var tmp = $.cookie('osvers');		
		if (tmp) {
			// Turn on auto complete
			$(this).autocomplete({
				source: tmp.split(',')
			});
		}
	});
	os.append(osLabel);
	os.append(osInput);
	imgAttr.append(os);
	
	// Create architecture input
	var arch = $('
');
	var archLabel = $('Architecture: ');
	var archInput = $(' ');
	archInput.one('focus', function() {
		var tmp = $.cookie('osarchs');
		if (tmp) {
			// Turn on auto complete
			$(this).autocomplete({
				source: tmp.split(',')
			});
		}
	});
	arch.append(archLabel);
	arch.append(archInput);
	imgAttr.append(arch);
	
	// Create profile input
	var profile = $('
');
	var profileLabel = $('Profile: ');
	var profileInput = $(' ');
	profileInput.one('focus', function() {
		var tmp = $.cookie('profiles');
		if (tmp) {
			// Turn on auto complete
			$(this).autocomplete({
				source: tmp.split(',')
			});
		}
	});
	profile.append(profileLabel);
	profile.append(profileInput);
	imgAttr.append(profile);
	
	// Create boot method dropdown
	var method = $('
');
	var methodLabel = $('Boot method: ');
	var methodSelect = $(' ');
	methodSelect.append(' '
		+ 'boot '
		+ 'install '
		+ 'iscsiboot '
		+ 'netboot '
		+ 'statelite '
	);
	method.append(methodLabel);
	method.append(methodSelect);
	imgAttr.append(method);
	/**
	 * Provision existing
	 */
	var provisionBtn = createButton('Provision');
	provisionBtn.bind('click', function(event) {
		// Remove any warning messages
		$(this).parents('.ui-tabs-panel').find('.ui-state-error').remove();
		var ready = true;
		
		// Get tab ID
		var tabId = $(this).parents('.ui-tabs-panel').attr('id');
				
		// Check if fields are properly filled in
		var inputs = $('#' + tabId + ' input:visible');
		for ( var i = 0; i < inputs.length; i++) {
			if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'storage') {
				inputs.eq(i).css('border', 'solid #FF0000 1px');
				ready = false;
			} else {
				inputs.eq(i).css('border', 'solid #BDBDBD 1px');
			}
		}
		
		var selects = $('#' + tabId + ' select:visible');
		for ( var i = 0; i < selects.length; i++) {
			if (!selects.eq(i).val()) {
				selects.eq(i).css('border', 'solid #FF0000 1px');
				ready = false;
			} else {
				selects.eq(i).css('border', 'solid #BDBDBD 1px');
			}
		}
		
		if (ready) {
			var inst = tabId.replace('kvmProvisionTab', '');
			
			// Prepend status bar
			var statBar = createStatusBar('kvmProvisionStatBar' + inst);
			statBar.append(createLoader(''));
			statBar.prependTo($('#' + tabId));
						
			var host = $('#' + tabId + ' input[name=host]').val();
			var group = $('#' + tabId + ' select[name=group]').val();
			var node = $('#' + tabId + ' input[name=node]').val();
			
			var memory = $('#' + tabId + ' input[name=memory]').val();
			var cpu = $('#' + tabId + ' select[name=cpu]').val();
			var nic = $('#' + tabId + ' input[name=nic]').val();
			var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val();
			var storage = $('#' + tabId + ' input[name=storage]').val();
			
			var os = $('#' + tabId + ' input[name=os]').val();
			var arch = $('#' + tabId + ' input[name=arch]').val();
			var profile = $('#' + tabId + ' input[name=profile]').val();
			var boot = $('#' + tabId + ' select[name=bootMethod]').val();
			
			/**
			 * (1) Define node
			 */
			var args = '-t;node;-o;' + node +
				';vmhost=' + host +
				';groups=' + group +
				';vmmemory=' + memory +
				';vmcpus=' + cpu +
				';vmnics=' + nic +
				';vmstorage=' + storage +
				';os=' + os +
				';arch=' + arch +
				';profile=' + profile +
				';netboot=xnba' +
				';nodetype=osi' +
				';serialport=0' +
				';serialspeed=115200' +
				';mgt=kvm';
			$.ajax( {
				url : 'lib/cmd.php',
				dataType : 'json',
				data : {
					cmd : 'chdef',
        			tgt : '',
        			args : args,
        			msg : 'cmd=chdef;out=' + inst
				},
				success : updateKVMProvisionStatus
			});
		} else {
			// Show warning message
			var warn = createWarnBar('Please provide a value for each missing field.');
			warn.prependTo($(this).parent().parent());
		}
	});
	provForm.append(provisionBtn);
};
/**
 * Load resources
 * 
 * @return Nothing
 */
kvmPlugin.prototype.loadResources = function() {
	// Get resource tab ID
	var tabId = 'kvmResourceTab';
	// Remove loader
	$('#' + tabId).find('img').remove();
	
	// Create info bar
	var infoBar = createInfoBar('Not yet supported');
	// Create resource form
	var resrcForm = $('
');
	resrcForm.append(infoBar);
	
	$('#' + tabId).append(resrcForm);
};
/**
 * Add node range
 */
kvmPlugin.prototype.addNode = function() {
	var dialog = $('
');
    var info = createInfoBar('Add a KVM node');
    dialog.append(info);
    
    // Create node inputs
    dialog.append($('Node: 
'));
	dialog.append($('VM host: 
'));
	dialog.append($('IP address: 
'));
	dialog.append($('Groups: 
'));
    
    dialog.dialog({
    	title: 'Add node',
        modal: true,
        width: 400,
        close: function(){$(this).remove();},
        buttons: {
            "OK" : function(){addKvmNode();},
            "Cancel": function(){$(this).dialog('close');}
        }
    });
};
/**
 * Add iDataPlex node range
 */
function addKvmNode(){
	var attr, args;
    var errorMessage = '';
        
    // Remove existing warnings
    $('#addKvm .ui-state-error').remove();
    
    // Return input border colors to normal
    $('#addKvm input').css('border', 'solid #BDBDBD 1px');
    
    // Check node attributes
    $('#addKvm input').each(function(){
        attr = $(this).val();
        if (!attr) {
            errorMessage = "Please provide a value for each missing field!";
            $(this).css('border', 'solid #FF0000 1px');
        }
    });
    
    // Show error message (if any)
    if (errorMessage) {
        $('#addKvm').prepend(createWarnBar(errorMessage));
        return;
    }
    
    // Create loader
    $('#addKvm').append(createLoader());
    
    // Change dialog buttons
    $('#addKvm').dialog('option', 'buttons', {
    	'Close':function(){
    		$('#addKvm').dialog('close');
    	}
    });
    
    // Generate chdef arguments
    args = '-t;node;-o;' + $('#addKvm input[name="node"]').val()
	    + ';ip=' + $('#addKvm input[name="ip"]').val()
	    + ';groups=' + $('#addKvm input[name="groups"]').val() 
	    + ';vmhost=' + $('#addKvm input[name="vmhost"]').val() 
	    + ';mgt=kvm;netboot=xnba;nodetype=osi;profile=compute';
    $.ajax({
        url : 'lib/cmd.php',
        dataType : 'json',
        data : {
            cmd : 'chdef',
            tgt : '',
            args : args,
            msg : ''
        },
        success: function(data) {
        	// Update /etc/hosts
        	$.ajax({
    			url : 'lib/cmd.php',
    			dataType : 'json',
    			data : {
    				cmd : 'makehosts',
    				tgt : '',
    				args : '',
    				msg : ''
    			}
    		});
        	
        	// Remove loader
            $('#addKvm img').remove();
            
            // Get return message
            var message = '';
            for (var i in data.rsp) {
                message += data.rsp[i] + ' ';
            }
            
            // Show return message
            if (message)
                $('#addKvm').prepend(createInfoBar(message));
        }
    });
}
/**
 * Update the provision node status
 * 
 * @param data
 *            Data returned from HTTP request
 * @return Nothing
 */
function updateKVMProvisionStatus(data) {
	// Get ajax response
	var rsp = data.rsp;
	var args = data.msg.split(';');
	// Get command invoked
	var cmd = args[0].replace('cmd=', '');
	// Get provision tab instance
	var inst = args[1].replace('out=', '');
	
	// Get provision tab and status bar ID
	var statBarId = 'kvmProvisionStatBar' + inst;
	var tabId = 'kvmProvisionTab' + inst;
	
	var node = $('#' + tabId + ' input[name=node]').val();
	
	/**
	 * (2) Create virtual machine
	 */
	if (cmd == 'chdef') {
		// Write ajax response to status bar
		var prg = writeRsp(rsp, '');	
		$('#' + statBarId).find('div').append(prg);
		// Get parameters
		var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val();
		
		// Begin installation
		$.ajax( {
			url : 'lib/cmd.php',
			dataType : 'json',
			data : {
				cmd : 'mkvm',
				tgt : '',
				args : node + ';-s;' + disk,
				msg : 'cmd=mkvm;out=' + inst
			},
			success : updateKVMProvisionStatus
		});
	} 
	
	/**
	 * (3) Prepare node for boot
	 */
	if (cmd == 'mkvm') {
		// Write ajax response to status bar
		var prg = writeRsp(rsp, '');	
		$('#' + statBarId).find('div').append(prg);
		
		// Get provision method
		var boot = $('#' + tabId + ' select[name=bootMethod]').val();
		
		// Prepare node for boot
		$.ajax( {
			url : 'lib/cmd.php',
			dataType : 'json',
			data : {
				cmd : 'nodeset',
				tgt : node,
				args : boot,
				msg : 'cmd=nodeset;out=' + inst
			},
			success : updateKVMProvisionStatus
		});
	}
	
	/**
	 * (4) Power on node
	 */
	if (cmd == 'nodeset') {
		var prg = writeRsp(rsp, '');	
		$('#' + statBarId).find('div').append(prg);
		
		// Prepare node for boot
		$.ajax( {
			url : 'lib/cmd.php',
			dataType : 'json',
			data : {
				cmd : 'rpower',
				tgt : node,
				args : 'on',
				msg : 'cmd=rpower;out=' + inst
			},
			success : updateKVMProvisionStatus
		});
	}
	
	/**
	 * (5) Done
	 */
	else if (cmd == 'rpower') {
		// Write ajax response to status bar
		var prg = writeRsp(rsp, '');	
		$('#' + statBarId).find('div').append(prg);
		$('#' + statBarId).find('img').remove();
		
		// If installation was successful
		if (prg.html().indexOf('Error') == -1) {
			$('#' + statBarId).find('div').append('It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install. ');
		}
	}
}