// Javascript support for the TCO Calculator
var tco_isv_list = new Array();
// Move these here so we can override them in the templates if need be
var tco_warn_heading = 'Warning!';
var tco_warn_suffix = 'Please choose a less restrictive Edition that meets the requirements of your System Configuration';
var tco_warn_colour = '#CC0000';
var tco_norm_colour = '#000000';

function tco_clear_node(id) {
	var span = document.getElementById(id);
	if (span && span.hasChildNodes()) {
		for (var i = span.childNodes.length - 1; i>=0; i--) {
			span.removeChild(span.childNodes.item(i));
		}
	}
	return span;
}

function tco_replace_node(id, node) {
	var span = tco_clear_node(id);
	span.appendChild(node);
}

function tco_replace_text(id, value) {
	var span = tco_clear_node(id);
	span.appendChild(document.createTextNode(value));
}

var tco_display_result = {
	success:function(o){
		var table_node = tco_clear_node('tcotable');
		table_node.innerHTML = o.responseText;
		tco_hide_busy();
	},
	failure:function(o){
		tco_hide_busy();
	}
}

function tco_build_url() {
	var post_string = '';
	post_string += 'server_count=' + document.getElementById('tco_server_count').value;
	post_string += '&cpu_count=' + document.getElementById('tco_cpu_count').value;
	post_string += '&core_count=' + document.getElementById('tco_core_count').value;
	post_string += '&ram=' + document.getElementById('tco_ram').value;
	post_string += '&size=' + document.getElementById('tco_size').value;
	post_string += '&years=' + document.getElementById('tco_years').value;
	for (var i = 0; i < tco_isv_list.length; i++) {
		var opt = document.getElementById('tco_edition_' + tco_isv_list[i]);
		post_string += '&editions[]=' + opt.options[opt.selectedIndex].value;
	}
	return post_string;
}

function tco_base_url() {
	var baseURL = document.getElementById('baseURL').value;
	return baseURL;
}

function tco_get_result(e) {
	var post_string = tco_build_url();
	var table_url = '/table/?';
	var graph_node = document.getElementById('tco_graph_img');
	if (graph_node) {
		graph_node.src = tco_base_url() + '/graph/?' + post_string;
	}
	tco_show_busy();
	var tx = YAHOO.util.Connect.asyncRequest('GET', tco_base_url() + table_url + post_string, tco_display_result, null);
}

function tco_print_deferred() {
	var post_string = tco_build_url();
	window.open(tco_base_url() + '/print/?' + post_string, '_blank');
}

var tco_process_print = {
	success:function(o){
		// result is an XML list that we need to check for invalid editions
		tco_comparison_data = o.responseXML.getElementsByTagName('item');
		tco_validate_deferred(o.argument);
	},
	failure:function(o){
		tco_comparison_data = null;
	},
	argument:tco_print_deferred
}

function tco_print() {
	var post_string = tco_build_url();
	var ty = YAHOO.util.Connect.asyncRequest('POST', tco_base_url() + '/validate/', tco_process_print, post_string);
	return false; // Stops the page from reloading.
}

function tco_update_totals(e) {
	var servers = new Number(document.getElementById('tco_server_count').value);
	var cpus = new Number(document.getElementById('tco_cpu_count').value);
	var cores = new Number(document.getElementById('tco_core_count').value);
	var cpu_total = servers * cpus;
	var core_total = cpu_total * cores;
	tco_replace_text('tco_total_cpus', cpu_total);
	tco_replace_text('tco_total_cores', core_total);
	// Check the edition data
	tco_validate_deferred(tco_get_result);
}

// Grab everything we need and submit the form, putting the output
// into the editions page.
var tco_display_editions = {
	success:function(o){
		var edition_node = tco_clear_node('tco_editions');
		edition_node.innerHTML = o.responseText;
	},
	failure:function(o){
	}
}

function tco_get_editions(e) {
	var post_string = '';
	post_string += 'server_count=' + document.getElementById('tco_server_count').value;
	post_string += '&cpu_count=' + document.getElementById('tco_cpu_count').value;
	post_string += '&core_count=' + document.getElementById('tco_core_count').value;
	post_string += '&ram=' + document.getElementById('tco_ram').value;
	post_string += '&size=' + document.getElementById('tco_size').value;
	// Now we need to get the product lines and attach them.
	var product_lines = document.getElementById('tco_lines');
	var found = false;
	for (var i = 0; i < product_lines.options.length; i++) {
		if (product_lines.options[i].selected) {
			post_string += '&lines[]=' + product_lines.options[i].value;
			found=true;
		}
	}
	if (found) {
	  var tx = YAHOO.util.Connect.asyncRequest('POST', tco_base_url() + '/choices/', tco_display_editions, post_string);
	}
}

var tco_close_window = function() {
	this.hide();
}

var tco_warning_buttons = [ { text: 'Close', handler:tco_close_window } ];
var tco_warning_window = new YAHOO.widget.SimpleDialog('validWarn', {
					width: '20em',
					xy: [ 0, 0  ],
					modal: true,
					draggable: false });

var tco_busy = new YAHOO.widget.SimpleDialog('pleaseWait', {
	width: '20em',
	fixedcenter: true,
	modal: false,
	draggable: false
	});

function tco_show_busy()
{
	tco_busy.setBody('Calculating...');
	tco_busy.render(document.body);
	tco_busy.show();
}

function tco_hide_busy()
{
	tco_busy.hide();
}

function tco_highlight(node, high, low)
{
	node.style.color = high;
	for (var i = 0; i < node.options.length; i++) {
		if (i == node.selectedIndex) {
			node.options[i].style.color = high;
		} else {
			node.options[i].style.color = low;
		}
	}
}

var tco_comparison_data = null;

function tco_validate_deferred(callback)
{
	if (tco_comparison_data == null) {
		tco_validate_editions();
		return;
	}
	var tco_servers = document.getElementById('tco_server_count');
	var servers = new Number(tco_servers.value);
	var cpus = new Number(document.getElementById('tco_cpu_count').value);
	cpus *= servers;
	var cores = new Number(document.getElementById('tco_core_count').value);
	cores *= cpus;
	var ram = new Number(document.getElementById('tco_ram').value);
	var size = new Number(document.getElementById('tco_size').value);
	var offsets = YAHOO.util.Dom.getRegion(tco_servers);
	var ok = true;
	for (var i = 0; i < tco_comparison_data.length; i++) {
		var item = tco_comparison_data.item(i);
		var select_box = document.getElementById('tco_edition_' + item.getAttribute('line'));
		var max_servers = new Number(item.getAttribute('servers'));
		var max_cpus = new Number(item.getAttribute('cpus'));
		var max_cores = new Number(item.getAttribute('cores'));
		var max_ram = new Number(item.getAttribute('ram'));
		var max_size = new Number(item.getAttribute('size'));
		if ((max_servers > 0 && servers > max_servers)
		|| (max_cpus > 0 && cpus > max_cpus)
		|| (max_cores > 0 && cores > max_cores)
		|| (max_ram > 0 && ram > max_ram)
		|| (max_size > 0 && size > max_size) ) {
			// Display the warning.
			tco_warning_window.setHeader(tco_warn_heading);
			// Determine what is wrong so we can customise the error message.
			var details = 'For <b>' + item.getAttribute('isv') + '</b>, the <b>' + item.firstChild.data + '</b> has the following License Restrictions:<ul>';
			var max_servers = new Number(item.getAttribute('servers'));
			var max_cpus = new Number(item.getAttribute('cpus'));
			var max_cores = new Number(item.getAttribute('cores'));
			var max_ram = new Number(item.getAttribute('ram'));
			var max_size = new Number(item.getAttribute('size'));
			if (max_servers > 0) {
				details += '<li>' + max_servers + ' Servers</li>';
			}
			if (max_cpus > 0) {
				details += '<li>' + max_cpus + ' CPUs</li>';
			}
			if (max_cores > 0) {
				details += '<li>' + max_cores + ' Cores</li>';
			}
			if (max_ram > 0) {
				details += '<li>' + max_ram + 'GB RAM</li>';
			}
			if (max_size > 0) {
				details += '<li>' + max_size + 'GB Database Size</li>';
			}
			tco_warning_window.setBody(details + '</ul>' + tco_warn_suffix);
			tco_warning_window.cfg.setProperty('icon', YAHOO.widget.SimpleDialog.ICON_WARN);
			tco_warning_window.cfg.queueProperty('buttons', tco_warning_buttons);
			tco_warning_window.cfg.queueProperty('xy',  [ offsets.right + 5, offsets.top - 30 ]);
			tco_warning_window.render(document.body);
			tco_warning_window.show();
			// Set the colour to warning.
			tco_highlight(select_box, tco_warn_colour, tco_norm_colour);
			ok = false;
		} else {
			// Clear the colour
			tco_highlight(select_box, tco_norm_colour, tco_norm_colour);
		}
	}
	if (ok) {
		callback();
	}
}

var tco_process_validate = {
	success:function(o){
		// result is an XML list that we need to check for invalid editions
		tco_comparison_data = o.responseXML.getElementsByTagName('item');
		tco_validate_deferred(o.argument);
	},
	failure:function(o){
		tco_comparison_data = null;
	},
	argument:tco_get_result
}

function tco_validate_editions(e) {
	var post_string = tco_build_url();
	var ty = YAHOO.util.Connect.asyncRequest('POST', tco_base_url() + '/validate/', tco_process_validate, post_string);
	// call the main result getter as well
}

function tco_reset_position() {
	tco_get_result();
	self.scrollTo(0,0);
}

var tco_process_calculate = {
	success:function(o){
		tco_comparison_data = o.responseXML.getElementsByTagName('item');
		tco_validate_deferred(o.argument);
	},
	failure:function(o){
		tco_comparison_data = null;
	},
	argument:tco_reset_position
}

function tco_recalc(e) {
	if (tco_customize('')) {
		var post_string = tco_build_url();
		var ty = YAHOO.util.Connect.asyncRequest('POST', tco_base_url() + '/validate/', tco_process_calculate, post_string);
	}
}

function tco_customize(target) {
	var hash_string;
	try {
		hash_string = document.getElementById('tco_hash_value').value;
	}
	catch (e) {
		hash_string = '';
	}

	if (hash_string) {
		return true;
	} else {
		window.location.href = tco_base_url() + '/customize/?' + tco_build_url() + '&target=' + target + '#' + target;
		return false;
	}
}

function tco_check_load() {
	try {
		var target = window.location.href.match(/target=([^#&]*)/i);
		if (target) {
			window.location.href = '#' + target[1];
		} else if (target = document.getElementById('tco_target')) {
			window.location.href = '#' + target.value;
		}
	}
	catch (e) {
	}
}

var mozilla = true;
if (navigator.userAgent.indexOf('MSIE') != -1) {
	mozilla = false;
}

if (mozilla) {
	window.addEventListener('load', tco_check_load, false);
} else {
	window.attachEvent('onload', tco_check_load);
}
