var oService;
var aCurrencyConversionIndexes = [];
var aOptions = [ "server_typeid", "vc_slots", "server_name", "dynamic_slots", "paymentterm", "locationid" ];
var sVoucherType = 'VoiceComm';

// Service Utils
function remove_row( sId, bNoError )
{
	var oNode = document.getElementById( sId );
	if ( null === oNode )
	{
		if ( ! bNoError )
		{
			alert( 'Failed to find row: ' + sId + '!' );
		}
		return false;
	}
	oNode.parentNode.removeChild( oNode );

	return true;
}

function display_price( sId, iPrice, sZero, bDiscount, sCurrency )
{
	var sVal;
	if ( iPrice > 0 )
	{
		sVal = ( bDiscount ) ? '-' : '';
		sVal += format_currency( iPrice, sCurrency );
	}
	else if ( 0 == sZero )
	{
		sVal = format_currency( 0, sCurrency );
	}
	else
	{
		sVal = sZero;
	}
	document.getElementById( sId ).innerHTML = sVal;

	return true;
}

function is_native_currency()
{
	return ( 'GBP' != sDefaultCurrency );
}

function format_currency( fAmount, sCurrency )
{
	if ( undefined === sCurrency )
	{
		sCurrency = sDefaultCurrency;
	}
	var sSymbol;
	var fValue;
	switch( sCurrency )
	{
	case 'EUR':
		sSymbol = '&euro;';
		fValue = Math.round( aCurrencyConversionIndexes["GBP-EUR"].convertForwards( fAmount ) ) / 100
		break;

	case 'USD':
		sSymbol = '&#36;';
		fValue = Math.round( aCurrencyConversionIndexes["GBP-USD"].convertForwards( fAmount ) ) / 100
		break;

	case 'GBP':
	default:
		sSymbol = '&pound;';
		fValue =  Math.round( fAmount ) / 100;
	}
	return sSymbol + fValue.toFixed(2);
}

function edit_option( sOption )
{
	// Show the Edit & hide the Display
	document.getElementById( 'game-cart-' + sOption + '-display' ).style.display = 'none';
	document.getElementById( 'game-cart-' + sOption + '-edit' ).style.display = '';

	// Update the Action
	var oAction = document.getElementById( 'game-cart-' + sOption + '-action' );
	oAction.onclick = function() { return save_option( sOption ) };
	oAction.innerHTML = '<img src="/images/icons/disk.png" alt="Save" /> Save';
	oAction.title = oAction.title.replace( 'Edit', 'Save' );

	// Set focus
	document.getElementById( sOption ).focus();

	return cancel_href();
}

function blur_option( oEvent, sOption, aAltOptions )
{
	// NOTE: Currently ( 2009-12-17 ) Chrome fires the blur on a select incorrectly
	// http://code.google.com/p/chromium/issues/detail?id=23499
	// fortunately the target is the select box itself so using blur_option instead of save_option fixes
	// the issue. This may need revision if they "fix" this at a later date
	var sTargetId = ( oEvent.srcElement ) ? oEvent.srcElement.id : oEvent.explicitOriginalTarget.id;

	if ( sOption == sTargetId )
	{
		// Matched the target so do nothing
		return true;
	}

	if ( 'undefined' != typeof( aAltOptions ) )
	{
		for ( var i in aAltOptions )
		{
			if ( sTargetId == aAltOptions[i] )
			{
				// Matched an alt Option do nothing
				return true;
			}
		}
	}

	// no match save
	return save_option( sOption );
}

function save_option( sOption )
{
	// Hide the Edit & show the Display
	document.getElementById( 'game-cart-' + sOption + '-display' ).style.display = '';
	document.getElementById( 'game-cart-' + sOption + '-edit').style.display = 'none';

	// Update the Action
	var oAction = document.getElementById( 'game-cart-' + sOption + '-action' );
	oAction.onclick = function () { return edit_option( sOption ) };
	oAction.innerHTML = '<img src="/images/icons/pencil.png" alt="Edit" /> Edit';
	oAction.title = oAction.title.replace( 'Save', 'Edit' );

	return cancel_href();
}

function update_option( sOption )
{
	// Update the display based on the selected value
	var oElement = document.getElementById( sOption );
	var oSpan = document.getElementById( 'game-cart-' + sOption + '-display' );
	var sValue = "";
	switch ( oElement.tagName.toLowerCase() )
	{
	case "select":
		oSpan.innerHTML = oElement[oElement.selectedIndex].text.replace( /(FREE|.\d+.\d+)$/, '' );
		sValue = oElement[oElement.selectedIndex].value;
		break;

	case "input":
		switch ( oElement.type.toLowerCase() )
		{
		case "text":
			oSpan.innerHTML = oElement.value;
			sValue = oElement.value;
			break;

		default:
			alert( "Unsupported input type: " + oElement.type );
			return undefined;
		}
		break;

	default:
		alert( "Unsupported element type: " + oElement.tagName );
		return undefined;
	}

	return sValue;
}

function select_value( sId )
{
	var oSelect = document.getElementById( sId );

	return oSelect[oSelect.selectedIndex].value;
}

function cancel_href()
{
	return false;
}

function update_voucher_code( bAuto )
{
	if ( bAuto && bAutoVoucher )
	{
		return false;
	}

	var oVoucherCode = document.getElementById('voucher');

	document.getElementById( 'game-cart-voucher-cost' ).innerHTML = '<span id="game-cart-voucher-cost-spinner"><img src="/images/icons/progress.gif" alt="Validating Voucher" class="middle" /> Validating</span>';

	if ( "" == oVoucherCode.value || "None" == oVoucherCode.value )
	{
		oService.setVoucher( 'none', false );
		oVoucherCode.value = 'None';
		set_voucher_info( '', 'hidden', '', false );
		update_option( 'voucher' );
		save_option( 'voucher' );

		check_auto_voucher();

		return update_price();
	}

	update_option( 'voucher' );

	var aProductIds = oService.productIds();
	var sVoucherCheckUrl = '/order/check-voucher/?voucher=' + oVoucherCode.value + '&ptype=' + sVoucherType + '&lid=' + oService.locationid + '&period=' + oService.payment_term;
	if ( 0 <= aProductIds.length )
	{
		sVoucherCheckUrl += '&pid=' + aProductIds.join( ',' );
	}

	utilsXmlRequest( 'voucher', sVoucherCheckUrl, apply_voucher_code );

	return true;
}

function apply_voucher_code()
{
	var oReq = utilsXmlReqObj( 'voucher' );
	if ( 4 == oReq.readyState )
	{
		// Done
		var oVoucherResult = utilsJson( oReq );

		if ( ! oVoucherResult )
		{
			// Change page issue in FF
			return false;
		}

		if ( oVoucherResult['error'] )
		{
			oService.setVoucher( 'none', false );
			update_price();
			set_voucher_info( '', 'invalid', oVoucherResult['error'], false );
			edit_option( 'voucher' );
			return false;
		}

		oService.setVoucher( oVoucherResult['type'], oVoucherResult['value'], oVoucherResult['exclusive'] );

		set_voucher_info(
			( oVoucherResult['message'] ) ? oVoucherResult['message'] : '',
			'valid',
			'Voucher code <b>' + document.getElementById( 'voucher' ).value + '</b> has been recorded against your session. Any purchases you make will use this code.',
			oVoucherResult['exclusive']
		);

		save_option( 'voucher' );

		return update_price();
	}

	return false;
}

var aPaymentTermText = [];
function set_voucher_info( sNotes, sClass, sContent, bExclusive )
{
	document.getElementById( 'voucher-notes' ).innerHTML = sNotes;
	document.getElementById( 'incoming-voucher' ).className = 'content p10 ' + sClass;
	document.getElementById( 'incoming-voucher-content' ).innerHTML = sContent;
	if ( bExclusive )
	{
		document.getElementById( 'period-note-exclusive' ).style.display = 'block';
		document.getElementById( 'period-note' ).style.display = 'none';
		var oPaymentTermOptions = document.getElementById( 'paymentterm' ).options;
		var bStore = ( 0 == aPaymentTermText.length ) ? true : false;
		for ( var i = oPaymentTermOptions.length - 1; i >= 0; i-- )
		{
			var oOption = oPaymentTermOptions[i];
			if ( bStore )
			{
				aPaymentTermText[i] = oOption.text;
			}
			oOption.text = oOption.text.replace( /\(.*?\)/, '' );
		}
		update_option( 'paymentterm' );
	}
	else
	{
		document.getElementById( 'period-note-exclusive' ).style.display = 'none';
		document.getElementById( 'period-note' ).style.display = 'block';
		if ( 0 != aPaymentTermText.length )
		{
			var oPaymentTermOptions = document.getElementById( 'paymentterm' ).options;
			for ( var i = oPaymentTermOptions.length - 1; i >= 0; i-- )
			{
				oPaymentTermOptions[i].text = aPaymentTermText[i];
			}
			update_option( 'paymentterm' );
		}
	}
}

// AJAX methods
var xmlHttpRequests = [];

// Create a new named XmlHttpRequest object
function utilsXmlHttpRequest( sName )
{
	if ( ! sName )
	{
		sName = 'generic';
	}

	if ( window.XMLHttpRequest )
	{
		xmlHttpRequests[sName] = new XMLHttpRequest();
		return xmlHttpRequests[sName];
	}
	else if ( window.ActiveXObject )
	{
		xmlHttpRequests[sName] = new ActiveXObject( "Microsoft.XMLHTTP" );
		return xmlHttpRequests[sName];
	}
	else
	{
		alert( 'XMLHttpRequest not available' );
		return undefined;
	}
}


// Do a XmlHttpRequest
function utilsXmlRequest( sName, sURL, fHandler )
{
	var oXmlHttp = new utilsXmlHttpRequest( sName );
	if ( ! oXmlHttp )
	{
		return undefined;
	}

	oXmlHttp.open( 'GET', sURL, true );

	if ( fHandler )
	{
		oXmlHttp.onreadystatechange = fHandler;
	}
	oXmlHttp.send( null );
	return oXmlHttp;
}

// Returns the specified XmlHttp Request Object
function utilsXmlReqObj( sName )
{
	return xmlHttpRequests[sName];
}

// Returns the JSON object for the passed in XmlHttp Request Object
function utilsJson( oXmlHttp )
{
	if ( ! oXmlHttp )
	{
		// Change page issue in FF
		return undefined;
	}

	try
	{
		oJSON = eval( '(' + oXmlHttp.responseText + ')' );
	}
	catch( Exception )
	{
		return { error: 'Invalid JSON response:\n' + oXmlHttp.responseText };
	}

	return oJSON;
}

function update_locationid()
{
	oService.setLocation( update_option( 'locationid' ) );
	document.getElementById( 'location-image' ).src = '/images/icons/country/' + aLocations[oService.locationid].country_code.toLowerCase() + '.png';

	check_auto_voucher();

	return update_price();
}

function check_auto_voucher()
{
	var oVoucherCode = document.getElementById('voucher');
	if ( ! bAutoVoucher && 'None' != oVoucherCode.value )
	{
		// Manually selected voucher
		return false;
	}

	var oVoucher = get_auto_voucher();
	if ( oVoucher )
	{
		// An automatic voucher is available
		oService.setVoucher( oVoucher.type, oVoucher.discount, oVoucher.exclusive );
		oVoucherCode.value = oVoucher.code;
		set_voucher_info(
			oVoucher.msg,
			'valid',
			'Your selections qualify for a discount, we have automatically set the voucher code <b>' + oVoucher.code + '</b> below.',
			oVoucher.exclusive 
		);
		update_option( 'voucher' );
		save_option( 'voucher' );
		bAutoVoucher = true;

		return update_price();
	}
	else if ( bAutoVoucher )
	{
		// Remove the current automatic voucher
		oService.setVoucher( 'none', false );
		oVoucherCode.value = 'None';
		set_voucher_info( '', 'hidden', '', false );
		update_option( 'voucher' );
		save_option( 'voucher' );
		bAutoVoucher = false;

		return update_price();
	}

	return false;
}

function get_auto_voucher()
{
	var iLocationId = oService.locationid;
	var aProductIds = oService.productIds();
	var iPeriod = oService.payment_term;
	if ( 0 == aProductIds.length )
	{
		// No product selected yet, ignore
		return false;
	}

	// look for the best value voucher which matches all selcted products
	var oBestVoucher = false;
	for ( var iVoucherId in aVouchers )
	{
		var oVoucher = aVouchers[iVoucherId];
		if ( oVoucher.validForProducts( sVoucherType, iLocationId, iPeriod, aProductIds ) )
		{
			if ( ! oBestVoucher )
			{
				oBestVoucher = oVoucher;
			}
			else
			{
				var fCurrentPrice = oService.cost();
				var oCurrentVoucher = oService.getVoucher();
				oService.setVoucher( oVoucher.type, oVoucher.discount, oVoucher.exclusive );
				var fNewPrice = oService.cost();
				// NOTE: we use >= not just > to ensure default prices are overiden
				if ( fCurrentPrice >= fNewPrice )
				{
					// Better price from this voucher
					oBestVoucher = oVoucher;
				}

				// Restore the old voucher details
				oService.setVoucher( oCurrentVoucher.type, oCurrentVoucher.discount, oCurrentVoucher.exclusive );
			}
		}
	}

	return oBestVoucher;
}

function update_paymentterm()
{
	oService.payment_term = update_option( 'paymentterm' );

	check_auto_voucher();

	return update_price();
}

function decodeEntities( sStr )
{
	var oTmpDiv = document.createElement( 'div' );
	oTmpDiv.innerHTML = sStr;
	return oTmpDiv.firstChild.nodeValue;
}

function gaTrack( oForm )
{
	_gaq.push(['pageTracker._linkByPost', oForm]);
	_gaq.push(['globalTracker._linkByPost', oForm]);
}

// Models

// dedicatedServer
function dedicatedServer( service_typeid, name, description, exvat, incvat, man_type, man_default, man_exvat, man_incvat )
{
	this.service_typeid = service_typeid;
	this.name = name;
	this.description = description;
	this.exvat = exvat;
	this.incvat = incvat;
	this.man_type = man_type;
	this.man_default = man_default;
	this.man_exvat = man_exvat;
	this.man_incvat = man_incvat;

	this.osid = 0;
	this.voice_comm = 0;
	this.payment_term = 0;

	this.oses = [];
	this.voice_comms = [];
	this.payment_terms = [];
}

dedicatedServer.prototype.addOs = function ( service_optionid, name, exvat, incvat, type )
{
	this.oses[service_optionid] = new os( service_optionid, name, exvat, incvat, type );
	if ( 0 == this.osid )
	{
		this.osid = service_optionid;
	}

	return true;
}

dedicatedServer.prototype.getOsByType = function ( sType )
{
	for ( var i in this.oses )
	{
		if ( sType == this.oses[i].type )
		{
			return this.oses[i].service_optionid;
		}
	}
	return this.osid;
}

dedicatedServer.prototype.addVoiceComms = function ( service_optionid, name, exvat, incvat, type, iSlots )
{
	this.voice_comms[service_optionid] = new voice_comm( service_optionid, name, exvat, incvat, type, iSlots );

	if ( 0 == this.voice_comm )
	{
		this.voice_comm = service_optionid;
	}

	return true;
}

dedicatedServer.prototype.getVoiceCommsByType = function ( sType )
{
	for ( var i in this.voice_comms )
	{
		if ( sType == this.voice_comms[i].type )
		{
			return this.voice_comms[i].service_optionid;
		}
	}

	return this.voice_comm;
}

dedicatedServer.prototype.addPaymentTerm = function ( payment_term, discount )
{
	this.payment_terms[payment_term] = new PaymentTerm( payment_term, discount );

	if ( 0 == this.payment_term )
	{
		this.payment_term = payment_term;
	}

	return true;
}

dedicatedServer.prototype.validPaymentTerm = function ( payment_term )
{
	for ( var i in this.payment_terms )
	{
		if ( payment_term == this.payment_terms[i].payment_term )
		{
			return true;
		}
	}
	return false;
}


// dedicated_os
function os( service_optionid, name, exvat, incvat, type )
{
	this.service_optionid = service_optionid;
	this.name = name;
	this.exvat = exvat;
	this.incvat = incvat;
	this.type = type;
}

// dedicatedService
function dedicatedService()
{
	this.service_typeid = 0;
	this.osid = 0;
	this.voice_comm = 0;
	this.managed = 1;
	this.payment_term = 12;
	this.service_type = undefined;
	this.sVoucherType = 'none';
	this.iVoucherValue = 0;
	this.bVoucherExclusive = false;
	this.locationid = 0;

	this.serviceTypes = []

	this.base_cost = 0;
	this.os_cost = 0;
	this.voice_comm_cost = 0;
	this.managed_cost = 0;
	this.discount = 0;
	this.discount_cost = 0;
	this.voucher_cost = 0;
}

dedicatedService.prototype.setVoucher = function( sType, iValue, bExclusive )
{
	this.sVoucherType = sType;
	this.iVoucherValue = iValue;
	this.bVoucherExclusive = bExclusive;
}

dedicatedService.prototype.getVoucher = function()
{
	return { type: this.sVoucherType, value: this.iVoucherValue, exclusive: this.bVoucherExclusive };
}

dedicatedService.prototype.addServiceType = function ( iServiceTypeId, sName, sDescription, iExVat, iIncVat, iManType, iManDefault, iManExVat, iManIncVat )
{
	this.serviceTypes[iServiceTypeId] = new dedicatedServer( iServiceTypeId, sName, sDescription, iExVat, iIncVat, iManType, iManDefault, iManExVat, iManIncVat );

	return true;
}

dedicatedService.prototype.addOs = function ( iServiceTypeId, iServiceOptionId, sName, iExVat, iIncVat, sType )
{
	this.serviceTypes[iServiceTypeId].addOs( iServiceOptionId, sName, iExVat, iIncVat, sType );

	return true;
}

dedicatedService.prototype.getOsType = function ( iServiceOptionId )
{
	return ( undefined == this.service_type ) ? '' : this.service_type.oses[this.osid].type;
}

dedicatedService.prototype.addVoiceComms = function ( iServiceTypeId, iServiceOptionId, sName, iExVat, iIncVat, iType, iSlots )
{
	this.serviceTypes[iServiceTypeId].addVoiceComms( iServiceOptionId, sName, iExVat, iIncVat, iType, iSlots );

	return true;
}

dedicatedService.prototype.getVoiceCommsType = function ( iServiceOptionId )
{
	return ( undefined == this.service_type ) ? 0 : this.service_type.voice_comms[this.voice_comm].type;
}

dedicatedService.prototype.addPaymentTerm = function ( iServiceTypeId, iPaymentPeriod, iDiscount )
{
	this.serviceTypes[iServiceTypeId].addPaymentTerm( iPaymentPeriod, iDiscount );

	return true;
}

dedicatedService.prototype.setServiceType = function ( iServiceTypeId )
{
	var sOsId = this.getOsType();
	var sVoiceCommsId = this.getVoiceCommsType();

	this.service_typeid = iServiceTypeId;
	this.service_type = this.serviceTypes[iServiceTypeId];

	// OS
	this.osid = this.service_type.getOsByType( sOsId );

	// Voice Comms
	this.voice_comm = this.service_type.getVoiceCommsByType( sVoiceCommsId );

	// Payment Term
	if ( 0 == this.payment_term || ! this.service_type.validPaymentTerm( this.payment_term ) )
	{
		this.payment_term = this.service_type.payment_term;
	}

	this.cost();

	return true;
}

dedicatedService.prototype.setOs = function ( iOsId )
{
	this.osid = iOsId;
	this.cost();

	return true;
}

dedicatedService.prototype.setVoiceComms = function ( iVoiceCommsId )
{
	this.voice_comm = iVoiceCommsId;
	this.cost();

	return true;
}

dedicatedService.prototype.setManaged = function ( bManaged )
{
	this.managed = bManaged;
	this.cost();

	return true;
}

dedicatedService.prototype.setLocation = function ( iLocationId )
{
	this.locationid = iLocationId;
	this.cost();

	return true;
}

dedicatedService.prototype.cost = function ()
{
	var oServiceType = this.service_type;
	this.base_cost = oServiceType.incvat;
	this.os_cost = oServiceType.oses[this.osid].incvat;
	this.voice_comm_cost = oServiceType.voice_comms[this.voice_comm].incvat;
	this.managed_cost = ( this.managed ) ? oServiceType.man_incvat : 0;

	// If a voucher is exclusive don't apply discounts
	var iTotalCost = ( this.base_cost + this.os_cost + this.managed_cost ) * this.payment_term;
	if ( this.bVoucherExclusive )
	{
		this.discount = 0;
		this.discount_cost = 0;
	}
	else
	{
		this.discount = oServiceType.payment_terms[this.payment_term].discount;
		this.discount_cost = iTotalCost * this.discount;
	}

	// Apply our voucher discount, if appropriate.
	switch ( this.sVoucherType )
	{
	case 'fixed':
		this.voucher_cost = this.iVoucherValue;
		var iTempCost = iTotalCost - this.discount_cost - this.voucher_cost;
		if ( 0 > iTempCost )
		{
			this.voucher_cost = this.voucher_cost + iTempCost;
		}
		break;

	case 'percentage':
		// NOTE: percentage's are of the base total prior to payment term discounts
		this.voucher_cost = iTotalCost * this.iVoucherValue;
		var iTempCost = iTotalCost - this.discount_cost - this.voucher_cost;
		if ( 0 > iTempCost )
		{
			this.voucher_cost = this.voucher_cost + iTempCost;
		}
		break;

	default:
		this.voucher_cost = 0;
		break;
	}

	return iTotalCost - this.discount_cost - this.voucher_cost;
}

dedicatedService.prototype.autoVoucher = function()
{
	// TODO: Implement
}

// dedicated_voice_comm
function voice_comm( service_optionid, name, exvat, incvat, type, iSlots )
{
	this.service_optionid = service_optionid;
	this.name = name;
	this.exvat = exvat;
	this.incvat = incvat;
	this.type = type;
	this.slots = iSlots;
}

// GamePackage
function GamePackage( name, gameid, modid, base_cost, public_cost, iServiceOptionId, customer_info, promote, default_modid, gameids, modids )
{
	this.name = name;
	this.gameid = gameid;
	this.modid = modid;
	this.base_cost = base_cost;
	this.public_cost = public_cost;
	this.optionid = iServiceOptionId;
	this.customer_info = customer_info;
	this.base_players = 0;
	this.promote = promote;
	this.description = "";
	this.image = "";
	this.default_modid = default_modid;
	this.gameids = gameids;
	this.modids = modids;
	this.price_bands = [];
	this.addons = [];
	this.aliases = [];
	this.games = [];
}

GamePackage.prototype.addGame = function( iModId, sName, sIcon )
{
	this.games.push( { modid: iModId, name: sName, icon: sIcon } );
}

GamePackage.prototype.addPriceBand = function( sOption, iMin, iMax, iInc, fCost )
{
	if ( ! this.price_bands[sOption] )
	{
		this.price_bands[sOption] = [];
	}

	this.price_bands[sOption].push( new PriceBand( iMin, iMax, iInc, fCost ) );

	if ( 'maxplayers' == sOption )
	{
		if ( iMin < this.base_players || 0 == this.base_players )
		{
			this.base_players = iMin;
		}
	}
}

GamePackage.prototype.add_addon = function( name, iServiceOptionId, addonid, cost, group )
{
	this.addons[addonid] = new game_addon( name, iServiceOptionId, addonid, cost, group );
}

GamePackage.prototype.remove_addon = function( addonid )
{
	for( i in this.addons )
	{
		addon = this.addons[ i ];
		if ( addon.addonid == addonid )
		{
			this.addons.splice( i, 1 );
		}
	}
}

GamePackage.prototype.add_alias = function( alias )
{
	this.aliases[this.aliases.length] = alias;
}

GamePackage.prototype.min_max = function( sOption )
{
	if ( ! this.price_bands[sOption] )
	{
		return [ 0, 0 ];
	}

	var iMin;
	var iMax;
	var udef;
	var aPriceBands = this.price_bands[sOption];
	for ( var i in aPriceBands )
	{
		var oPriceBand = aPriceBands[i];
		if ( iMin === udef || oPriceBand.min < iMin )
		{
			iMin = oPriceBand.min;
		}

		if ( iMax === udef || oPriceBand.max > iMax )
		{
			iMax = oPriceBand.max;
		}
	}

	return [ iMin, iMax ];
}

GamePackage.prototype.optionValues = function( sOption )
{
	if ( ! this.price_bands[sOption] )
	{
		return [];
	}

	var aPriceBands = this.price_bands[sOption];
	var aOptions = [];
	var bFirst = true;
	var fCost = 0;
	for ( var i in aPriceBands )
	{
		var oPriceBand = aPriceBands[i];
		for ( var j = oPriceBand.min, k = oPriceBand.max, l = oPriceBand.inc, c = oPriceBand.inc_cost; j <= k; j += l )
		{
			if ( ! bFirst )
			{
				fCost += oPriceBand.inc_cost;
			}
			aOptions.push( { value: j, cost: fCost } );
		}
		bFirst = false;
	}

	return aOptions;
}

GamePackage.prototype.cost = function( iPlayers )
{
	return this.base_cost + this.priceBandCost( 'maxplayers', iPlayers );
}

GamePackage.prototype.priceBandCost = function( sOption, iValue )
{
	var fCost = 0;
	var iMin = this.min_max( sOption )[0];
	var aPriceBands = this.price_bands[sOption];

	// NOTE: pricing is cumulative so if there is a band 5 - 10 and 11 - 20
	// the first 5 slots are charged at band 1 pricing and then the rest at band 2
	for ( var i in aPriceBands )
	{
		var oPriceBand = aPriceBands[i];
		if ( oPriceBand.min <= iValue )
		{
			var iMax = ( iValue < oPriceBand.max ) ? iValue : oPriceBand.max;
			var iRange = iMax - oPriceBand.min;
			if ( oPriceBand.min > iMin )
			{
				iRange += oPriceBand.inc;
			}
			fCost += ( ( iRange / oPriceBand.inc ) * oPriceBand.inc_cost );
		}
	}
	return fCost;
}

GamePackage.prototype.priceBandByMax = function( sOption, iValue )
{
	var aPriceBands = this.price_bands[sOption];
	var oLastBand;
	for ( var i in aPriceBands )
	{
		var oPriceBand = aPriceBands[i];
		if ( oPriceBand.max == iValue )
		{
			return oPriceBand;
		}
		if ( oPriceBand.max > iValue )
		{
			return oLastBand || oPriceBand;
		}
		oLastBand = oPriceBand;
	}

	return undefined;
}

// game_addon
function game_addon( name, iServiceOptionId, addonid, cost, group )
{
	this.name = name;
	this.optionid = iServiceOptionId;
	this.addonid = addonid;
	this.cost = cost;
	this.group = group;
}

// PriceBand
function PriceBand( iMin, iMax, iInc, fIncCost )
{
	this.min = iMin;
	this.max = iMax;
	this.inc = iInc;
	this.inc_cost = fIncCost;
}

// Game Service
function GameService( package_cost, debrand_cost, vc_server_cost, payment_terms, service_options )
{
	this.packages = [];
	this.options = [];
	this.optionDiscounts = [];
	this.bPublic = true;
	this.bDebranded = false;
	this.payment_term = 12;
	this.discount = 1;
	this.base_package = 0;
	this.locationid = 0;
	this.sVoucherType = 'none';
	this.iVoucherValue = 0;
	this.bVoucherExclusive = 0;
	this.vc_server_typeid = 0;
	this.vc_slots = 0;
	this.vc_server_type = undefined;
	this.vc_slot_option = undefined;

	this.package_cost = package_cost;
	this.debrand_cost = debrand_cost;
	this.vc_server_cost = vc_server_cost;
	this.payment_terms = payment_terms;
	this.payment_term = 1;
	this.service_options = service_options;

	this.public_cost = 0;
	this.debranded_cost = 0;
	this.discount_cost = 0;
	this.voucher_cost = 0;
	this.vc_cost = 0;
	this.vc_slots_cost = 0;
	this.extra_package_cost = 0;

	this.vcServerTypes = [];
}

GameService.prototype.setOption = function( sOption, iValue, iServiceOptionId )
{
	this.options[sOption] = { value: iValue, serviceoptionid: iServiceOptionId, cost: aGamePackages[iServiceOptionId].priceBandCost( sOption, iValue ) };
}

GameService.prototype.hasOption = function( sOption )
{
	return ( this.options[sOption] ) ? true : false;
}

GameService.prototype.getOptionCost = function( sOption )
{
	return ( this.options[sOption] ) ? this.options[sOption].cost : 0;
}

GameService.prototype.getOptionValue = function( sOption )
{
	return ( this.options[sOption] ) ? this.options[sOption].value : undefined;
}

GameService.prototype.removeServiceOptions = function( iServiceOptionId )
{
	var aOptions = this.options;
	var aNewOptions = [];
	for ( var i = aOptions.length - 1; i >= 0; i-- )
	{
		var oOption = aOptions[i];
		if ( oOption.seviceoptionid != iServiceOptionid )
		{
			aNewOptions.push( oOption );
		}
	}

	this.options = aNewOptions;
}

GameService.prototype.setLocation = function( iLocationId )
{
	this.locationid = iLocationId;

	return this.canOrder();
}

GameService.prototype.canOrder = function()
{
	// Check all packages are available in this new location
	var iLocationId = this.locationid;
	for ( var i in this.packages )
	{
		var oProduct = aProducts[this.packages[i].productid];
		if ( ! oProduct.canOrderIn( iLocationId ) )
		{
			return false;
		}
	}

	return true;
}

GameService.prototype.freeVcSlots = function()
{
	if ( 0 != this.vc_server_type_id )
	{
		switch ( this.vc_server_type.gameid )
		{
		case 158:
			// Mumble gets maxplayers free slots
			var iMaxPlayers = this.maxPlayers();
			return ( iMaxPlayers > this.vc_slots ) ? this.vc_slots : iMaxPlayers;

		case 55:
		case 182:
			// Teamspeak gets 25% free slots
			return this.vc_slots - parseInt( this.vc_slots / 1.25 );
		}
	}

	return 0;
}

GameService.prototype.vcIsTeamspeak = function()
{
	return ( 0 != this.vc_server_type_id && ( 55 == this.vc_server_type.gameid || 182 == this.vc_server_type.gameid ) ) ? true : false;
}

GameService.prototype.vcSlotsCost = function()
{
	var iPaidSlots = this.vc_slots - this.freeVcSlots();
	if ( 0 == iPaidSlots )
	{
		return 0;
	}
	
	return this.vc_slot_option.incvat * iPaidSlots;
}

GameService.prototype.setVcServerType = function ( iServiceOptionId )
{
	this.vc_server_typeid = parseInt( iServiceOptionId );
	this.vc_server_type = this.vcServerTypes[iServiceOptionId];
	this.setVcSlotsOption();

	return true;
}

GameService.prototype.addVcSlotOption = function ( iServiceOptionId, iMinSlots, iMaxSlots, iIncrement, iSlotExVat, iSlotIncVat )
{
	// New Style ignore the rest
	if ( this.vcServerTypes[iServiceOptionId] )
	{
		this.vcServerTypes[iServiceOptionId].slotOptions.push( new VoiceCommsSlotOption( iServiceOptionId, iMinSlots, iMaxSlots, iIncrement, iSlotExVat, iSlotIncVat ) );
		if ( iMinSlots < this.min_slots )
		{
			this.min_slots = iMinSlots;
		}
	}

	return true;
}

GameService.prototype.addVcServerType = function( iServiceOptionId, iGameId, sName, iExVat, iIncVat )
{
	this.vcServerTypes[iServiceOptionId] = new VoiceCommsServerType( iServiceOptionId, iGameId, sName, iExVat, iIncVat );

	return true;
}

GameService.prototype.setVcSlots = function( iSlots )
{
	this.vc_slots = parseInt( iSlots );
	this.setVcSlotsOption();

	return this.cost();
}

GameService.prototype.setVcSlotsOption = function()
{
	if ( 0 == this.vc_server_typeid )
	{
		return false;
	}

	var aPlayerOptions = this.vc_server_type.slotOptions;
	var iPaidSlots = this.vc_slots - this.freeVcSlots();
	this.vc_slot_option = undefined;
	for ( var i = 0; i < aPlayerOptions.length; i++ )
	{
		var oPlayerOption = aPlayerOptions[i];
		// NOTE: there are wholes in some allocations e.g. TS3 5 - 35, 50 - 75  so we dont check min_slots
		// this assumes that slots are in order
		if ( iPaidSlots <= oPlayerOption.max_slots )
		{
			this.vc_slot_option = oPlayerOption;
			return true;
		}
	}

	return false;
}

GameService.prototype.getVcSlots = function()
{
	if ( 0 == this.vc_server_typeid )
	{
		return [ 0 ];
	}

	var aSlots = [];
	var aPlayerOptions = this.vc_server_type.slotOptions;
	for ( var i = 0; i < aPlayerOptions.length; i++ )
	{
		var oPlayerOption = aPlayerOptions[i];
		for ( var j = oPlayerOption.min_slots; j <= oPlayerOption.max_slots; j += oPlayerOption.increment  )
		{
			aSlots.push( j );
		}
	}

	return aSlots;
}

GameService.prototype.setVoucher = function( sType, iValue, bExclusive )
{
	this.sVoucherType = sType;
	this.iVoucherValue = iValue;
	this.bVoucherExclusive = bExclusive;
}

GameService.prototype.getVoucher = function()
{
	return { type: this.sVoucherType, value: this.iVoucherValue, exclusive: this.bVoucherExclusive };
}

GameService.prototype.addPackage = function( iProductId, iServiceOptionId, players )
{
	this.packages.push( new game_service_game( iProductId, iServiceOptionId, players ) );
	this.packages[this.packages.length - 1].cost = aGamePackages[iServiceOptionId].cost( players );
	if ( 1 == this.packages.length )
	{
		this.base_package = iServiceOptionId;
	}

	// recalc costs
	this.cost();

	return true;
}

GameService.prototype.productIds = function()
{
	var aProductIds = [];
	for ( var i in this.packages )
	{
		var oPackage = this.packages[i];
		aProductIds.push( oPackage.productid );
	}

	return aProductIds;
}

GameService.prototype.removePackage = function( iServiceOptionId )
{
	for ( var i in this.packages )
	{
		if ( iServiceOptionId == this.packages[i].optionid )
		{
			this.packages.splice( i, 1 );
			if ( iServiceOptionId == this.base_package && 0 < this.packages.length )
			{
				// default the base_package
				this.base_package = this.packages[0].optionid;
			}

			// Remove any service options for this package
			this.removeServiceOptions( iServiceOptionId );

			// recalc costs
			this.cost();

			return true;
		}
	}


	return false;
}

GameService.prototype.hasPackage = function( iServiceOptionId )
{
	for ( var i in this.packages )
	{
		if ( iServiceOptionId == this.packages[i].optionid )
		{
			return true;
		}
	}
	return false;
}

GameService.prototype.getPackage = function( iServiceOptionId )
{
	for ( var i in this.packages )
	{
		if ( iServiceOptionId == this.packages[i].optionid )
		{
			return this.packages[i];
		}
	}
	return undefined;
}

GameService.prototype.getPackageIndex = function( iServiceOptionId )
{
	for ( var i in this.packages )
	{
		if ( iServiceOptionId == this.packages[i].optionid )
		{
			return i;
		}
	}
	return undefined;
}

GameService.prototype.getPackageAtIndex = function( iIndex )
{
	if ( iIndex > this.packages.length || 0 > iIndex )
	{
		return undefined;
	}

	return this.packages[iIndex];
}

GameService.prototype.noPackages = function()
{
	return this.packages.length;
}

GameService.prototype.hasPackages = function()
{
	return ( 0 == this.packages.length ) ? false : true;
}

GameService.prototype.togglePackageAddon = function( iServiceOptionId, iAddonId, bChecked )
{
	var oPackage = this.getPackage( iServiceOptionId );

	if ( undefined == oPackage )
	{
		return false;
	}

	if ( bChecked )
	{
		oPackage.remove_addon( iAddonId );
	}
	else
	{
		oPackage.add_addon( iAddonId );
	}

	// recalc costs
	this.cost();

	return true;
}

GameService.prototype.updatePackage = function( iServiceOptionId, sPlayers )
{
	for ( var i in this.packages )
	{
		if ( iServiceOptionId == this.packages[i].optionid )
		{
			this.packages[i].players = parseInt( sPlayers );

			this.cost();
			return true;
		}
	}

	return false;
}

GameService.prototype.add_option_discount = function( iServiceOptionId, payment_term, discount )
{
	if ( undefined == this.optionDiscounts[iServiceOptionId] )
	{
		this.optionDiscounts[iServiceOptionId] = [];
	}
	this.optionDiscounts[iServiceOptionId][payment_term] = discount;

	return true;
}

GameService.prototype.packageCost = function( iServiceOptionId )
{
	if ( this.base_package != iServiceOptionId )
	{
		// Just an extra package option
		 return this.package_cost;
	}

	// Base game
	return this.getPackage( iServiceOptionId ).cost;
}

GameService.prototype.cost = function()
{
	var iTotalCost = 0;

	// Get the new discount
	this.discount = this.payment_terms[this.payment_term].discount;

	// Service Multiplier
	var iPaymentTerm = this.payment_term;
	// JScript maths is a so round to 2dp
	var fServiceMultiplier = Math.round( ( 1 - this.discount ) * 100 ) / 100;

	for ( var i in this.packages )
	{
		var oGame = this.packages[i];
		var iServiceOptionId = oGame.optionid;
		var oServiceOption = this.service_options[iServiceOptionId];
		var fMultiplier = this.option_multiplier( oServiceOption.optionid, fServiceMultiplier );

		// Base price given the players
		oGame.cost = oServiceOption.cost( oGame.players );

		if ( this.bPublic )
		{
			// Public Cost
			oGame.cost += oServiceOption.public_cost;
		}

		if ( oGame.addons.length > 0 )
		{
			// Addon Costs
			var aAddonCosts = [];
			var oAddons = this.service_options[iServiceOptionId].addons;
			for ( var j in oGame.addons )
			{
				var iAddonId = oGame.addons[j].addonid;
				var oAddon = oServiceAddons[iAddonId];

				if ( aAddonCosts[addon.group] < oAddon.cost || ! aAddonCosts[addon.group] )
				{
					aAddonCosts[addon.group] = oAddon.cost;
				}
			}

			for ( var j in aAddonCosts )
			{
				oGame.cost += aAddonCosts[j];
			}
		}

		if ( iTotalCost < oGame.cost || ! iTotalCost )
		{
			// This is currently the "primary" package ( costs the most )
			this.public_cost = oServiceOption.public_cost;
			this.base_package = iServiceOptionId;
			iTotalCost = oGame.cost;

			// NOTE: Calculated bit by bit so we can have different multipliers
			this.discount_cost = iTotalCost * iPaymentTerm * fMultiplier;
		}
	}

	// Update based on the payment term
	iTotalCost *= iPaymentTerm;

	// Additional Game Cost
	if ( this.packages.length > 1 )
	{
		var fMultiplier = this.option_multiplier( 83, fServiceMultiplier );
		this.extra_package_cost = ( this.packages.length - 1 ) * this.package_cost;
		this.discount_cost += this.extra_package_cost * fMultiplier * iPaymentTerm;
		iTotalCost += this.extra_package_cost * iPaymentTerm;
	}
	else
	{
		this.extra_package_cost = 0;
	}

	// Debranded Cost
	if ( this.bDebranded )
	{
		var fMultiplier = this.option_multiplier( 34, fServiceMultiplier );
		this.debranded_cost = this.debrand_cost;
		this.discount_cost += this.debranded_cost * fMultiplier * iPaymentTerm;
		iTotalCost += this.debranded_cost * iPaymentTerm;
	}
	else
	{
		this.debranded_cost = 0;
	}

	// Voice Comms Cost
	if ( 0 != this.vc_server_typeid )
	{
		var fMultiplier = this.option_multiplier( this.vc_server_typeid, fServiceMultiplier );
		this.vc_cost = this.vc_server_cost;
		this.discount_cost += this.vc_cost * fMultiplier * iPaymentTerm;
		iTotalCost += this.vc_cost * iPaymentTerm;

		// Voice Comms Slots Cost
		var fMultiplier = this.option_multiplier( this.vc_server_typeid, fServiceMultiplier );
		this.vc_slots_cost = this.vcSlotsCost();
		this.discount_cost += this.vc_slots_cost * fMultiplier * iPaymentTerm;
		iTotalCost += this.vc_slots_cost * iPaymentTerm;
		this.vc_cost += this.vc_slots_cost;
	}
	else
	{
		this.vc_cost = 0;
		this.vc_slots_cost = 0;
	}

	// Options
	for ( var i in this.options )
	{
		iTotalCost += this.options[i].cost * iPaymentTerm;
		this.discount_cost += this.options[i].cost * fServiceMultiplier * iPaymentTerm;
	}

	// If a voucher is exclusive don't apply discounts
	if ( this.bVoucherExclusive )
	{
		this.discount_cost = 0;
		this.discount = 0;
	}

	// Apply our voucher discount, if appropriate.
	switch ( this.sVoucherType )
	{
	case 'fixed':
		this.voucher_cost = this.iVoucherValue;
		var iTempCost = iTotalCost - this.discount_cost - this.voucher_cost;
		if ( 0 > iTempCost )
		{
			this.voucher_cost = this.voucher_cost + iTempCost;
		}
		break;

	case 'percentage':
		// NOTE: percentage's are of the base total prior to payment term discounts
		this.voucher_cost = iTotalCost * this.iVoucherValue;
		var iTempCost = iTotalCost - this.discount_cost - this.voucher_cost;
		if ( 0 > iTempCost )
		{
			this.voucher_cost = this.voucher_cost + iTempCost;
		}
		break;

	default:
		this.voucher_cost = 0;
		break;
	}

	return iTotalCost - this.discount_cost - this.voucher_cost;
}

GameService.prototype.period_discount = function( iPaymentTerm )
{
	var fDiscount = this.payment_terms[iPaymentTerm].discount;

	// JScript maths is a so round to 2dp
	var fServiceMultiplier = Math.round( ( 1 - fDiscount ) * 100 ) / 100;
	var fPeriodDiscount = fServiceMultiplier;

	for ( var i in this.packages )
	{
		var fMultiplier = this.option_multiplier( this.packages[i].optionid, fServiceMultiplier, iPaymentTerm );
		if ( fMultiplier > fPeriodDiscount )
		{
			fPeriodDiscount = fMultiplier;
		}
	}

	return fMultiplier;
}

GameService.prototype.option_multiplier = function( iServiceOptionId, fMultiplier, iPaymentTerm )
{
	if ( undefined == iPaymentTerm )
	{
		iPaymentTerm = this.payment_term;
	}

	if ( undefined == this.optionDiscounts[iServiceOptionId] )
	{
		return fMultiplier;
	}
	else if ( undefined == this.optionDiscounts[iServiceOptionId][iPaymentTerm] )
	{
		return fMultiplier;
	}

	return Math.round( ( 1 - this.optionDiscounts[iServiceOptionId][iPaymentTerm] ) * 100 ) / 100;
}

GameService.prototype.base_players = function()
{
	var max_min = 0;

	for ( var i in this.packages )
	{
		var sMinMax = String( this.service_options[this.packages[i].optionid].min_max( 'maxplayers' ) );
		var aMinMax = sMinMax.split( "," );

		if ( aMinMax[0] > max_min )
		{
			max_min = aMinMax[0];
		}
	}
	return max_min;
}

GameService.prototype.maxPlayers = function()
{
	var iMaxPlayers = 0;
	for ( var i in this.packages )
	{
		var iPlayers = parseInt( this.packages[i].players );
		if ( iPlayers > iMaxPlayers )
		{
			iMaxPlayers = iPlayers;
		}
	}

	return iMaxPlayers;
}

// game_service_game
function game_service_game( iProductId, iServiceOptionId, sPlayers )
{
	this.addons = [];
	this.productid = iProductId;
	this.optionid = iServiceOptionId;
	this.players = parseInt( sPlayers );
	this.cost = 0;
}

game_service_game.prototype.add_addon = function( addonid )
{
	this.addons.push( new game_service_game_addon( this.optionid, addonid ) );
}

game_service_game.prototype.remove_addon = function( addonid )
{
	for( i in this.addons )
	{
		addon = this.addons[i];
		if ( addon.addonid == addonid )
		{
			this.addons.splice( i, 1 );
			return 1;
		}
	}

	return 0;
}

game_service_game.prototype.check_addon = function( addonid )
{
	for( i in this.addons )
	{
		if ( this.addons[i].addonid == addonid )
		{
			return 1;
		}
	}

	return 0;
}

// game_service_game_addon
function game_service_game_addon( iServiceOptionId, addonid )
{
	this.optionid = iServiceOptionId;
	this.addonid = addonid;
}

// gf_game
function gf_game( gameid, name )
{
	this.gameid = gameid;
	this.name = name;
	this.default_mod = 0;
	this.mods = [];
}

gf_game.prototype.add_mod = function( modid, name, version, default_mod )
{
	this.mods[modid] = new gf_game_mod( modid, name, version, default_mod );
	if ( default_mod )
	{
		this.default_mod = modid;
	}
}

gf_game.prototype.has_mod = function( modid )
{
	for ( var i = 0; i < this.mods.length; i++ )
	{
		if ( modid == this.mods[i].modid )
		{
			return true;
		}
	}

	return false;
}

gf_game.prototype.get_mod = function( modid )
{
	return this.mods[modid];
}

// gf_game_mod
function gf_game_mod( modid, name, version, default_mod )
{
	this.modid = modid;
	this.name = name;
	this.version = version;
	this.default_mod = default_mod;
}

gf_game_mod.prototype.get_name = function()
{
	var name = this.name;
	if ( 0 < this.version.length )
	{
		name = name + " ( " + this.version + " )";
	}

	return name;
}

// Location
function Location( locationid, name, country_code, country_name )
{
	this.locationid = locationid;
	this.name = name;
	this.country_code = country_code;
	this.country_name = country_name;
}

// Payment Term
function PaymentTerm( payment_term, discount )
{
	this.payment_term = payment_term;
	this.discount = discount;
}

// VoiceCommsServerType
function VoiceCommsServerType( iServiceOptionId, iGameId, sName, iExVat, iIncVat )
{
	this.service_optionid = iServiceOptionId;
	this.gameid = iGameId;
	this.name = sName;
	this.exvat = iExVat;
	this.incvat = iIncVat;
	this.slotOptions = [];
}

// VoiceCommsSlotOption
function VoiceCommsSlotOption( iServiceOptionId, iMinSlots, iMaxSlots, iIncrement, iSlotExVat, iSlotIncVat )
{
	this.service_optionid = iServiceOptionId;
	this.min_slots = iMinSlots;
	this.max_slots = iMaxSlots;
	this.increment = iIncrement;
	this.exvat = iSlotExVat;
	this.incvat = iSlotIncVat;
}

function VoiceCommsService( iServiceTypeId, sName, iExVat, iIncVat )
{
	this.service_typeid = iServiceTypeId;
	this.name = sName;
	this.exvat = iExVat;
	this.incvat = iIncVat;
	this.min_slots = 99999;

	this.productid = 0;
	this.server_typeid = 0;
	this.server_type = undefined;
	this.slot_option = undefined;
	this.slots = 0;
	this.available_slots = 0;
	this.payment_term = 12;
	this.bDynamicSlots = true;
	this.sVoucherType = 'none';
	this.iVoucherValue = 0;
	this.bVoucherExclusive = false;

	this.base_cost = 0;
	this.server_type_cost = 0;
	this.slots_cost = 0;
	this.discount = 0;
	this.discount_cost = 0;
	this.voucher_cost = 0;

	this.serverTypes = [];
	this.paymentTerms = [];
}

VoiceCommsService.prototype.setLocation = function( iLocationId )
{
	this.locationid = iLocationId;
}

VoiceCommsService.prototype.serviceOptionIds = function()
{
	var aServiceOptionIds = [];
	for ( var oPackage in this.packages )
	{
		aServiceOptionIds.push( oPackage.optionid );
	}

	return aServiceOptionIds;
}

VoiceCommsService.prototype.setProduct = function ( iProductId )
{
	this.productid = iProductId;
}

VoiceCommsService.prototype.productIds = function ()
{
	return [ this.productid ];
}

VoiceCommsService.prototype.setVoucher = function( sType, iValue, bExclusive )
{
	this.sVoucherType = sType;
	this.iVoucherValue = iValue;
	this.bVoucherExclusive = bExclusive;
}

VoiceCommsService.prototype.getVoucher = function()
{
	return { type: this.sVoucherType, value: this.iVoucherValue, exclusive: this.bVoucherExclusive };
}

VoiceCommsService.prototype.setServerType = function ( iServiceOptionId )
{
	this.server_typeid = iServiceOptionId;
	this.server_type = this.serverTypes[iServiceOptionId];
	this.setSlotsOption();

	return true;
}

VoiceCommsService.prototype.addSlotOption = function ( iServiceOptionId, iMinSlots, iMaxSlots, iIncrement, iSlotExVat, iSlotIncVat )
{
	// New Style ignore the rest
	if ( this.serverTypes[iServiceOptionId] )
	{
		this.serverTypes[iServiceOptionId].slotOptions.push( new VoiceCommsSlotOption( iServiceOptionId, iMinSlots, iMaxSlots, iIncrement, iSlotExVat, iSlotIncVat ) );
		if ( iMinSlots < this.min_slots )
		{
			this.min_slots = iMinSlots;
		}
	}

	return true;
}

VoiceCommsService.prototype.addServerType = function( iServiceOptionId, iGameId, sName, iExVat, iIncVat )
{
	this.serverTypes[iServiceOptionId] = new VoiceCommsServerType( iServiceOptionId, iGameId, sName, iExVat, iIncVat );

	return true;
}

VoiceCommsService.prototype.addPaymentTerm = function( iPaymentPeriod, iDiscount )
{
	this.paymentTerms[iPaymentPeriod] = new PaymentTerm( iPaymentPeriod, iDiscount );

	return true;
}

VoiceCommsService.prototype.setSlots = function( iSlots, iAvailableSlots )
{
	this.slots = iSlots;
	this.available_slots = iAvailableSlots;
	this.setSlotsOption();

	return this.cost();
}

VoiceCommsService.prototype.setSlotsOption = function()
{

	var aPlayerOptions = this.server_type.slotOptions;
	var iSlots = this.available_slots; // Pricing is based on the total available slots
	this.slot_option = undefined;
	for ( var i = 0; i < aPlayerOptions.length; i++ )
	{
		var oPlayerOption = aPlayerOptions[i];
		if ( iSlots >= oPlayerOption.min_slots && iSlots <= oPlayerOption.max_slots )
		{
			this.slot_option = oPlayerOption;
			return true;
		}
	}

	if ( 0 != iSlots )
	{
		alert( 'Failed to find slot option for: ' + iSlots + ' slots' );
	}

	return false;
}

VoiceCommsService.prototype.getSlots = function ()
{
	var aSlots = [];
	var aPlayerOptions = this.server_type.slotOptions;
	for ( var i = 0; i < aPlayerOptions.length; i++ )
	{
		var oPlayerOption = aPlayerOptions[i];
		for ( var j = oPlayerOption.min_slots; j <= oPlayerOption.max_slots; j += oPlayerOption.increment  )
		{
			aSlots.push( j );
		}
	}

	return aSlots;
}

VoiceCommsService.prototype.cost = function()
{
	// Base + slot cost
	this.base_cost = this.incvat;
	this.slots_cost = this.slots * this.slot_option.incvat;

	this.server_type_cost = this.server_type.incvat;

	// If a voucher is exclusive don't apply discounts
	var iTotalCost = ( this.base_cost + this.server_type_cost + this.slots_cost ) * this.payment_term;
	if ( this.bVoucherExclusive )
	{
		this.discount = 0;
		this.discount_cost = 0;
	}
	else
	{
		this.discount = this.paymentTerms[this.payment_term].discount;
		this.discount_cost = iTotalCost * this.discount;
	}

	// Apply our voucher discount, if appropriate.
	switch ( this.sVoucherType )
	{
	case 'fixed':
		this.voucher_cost = this.iVoucherValue;
		var iTempCost = iTotalCost - this.discount_cost - this.voucher_cost;
		if ( 0 > iTempCost )
		{
			this.voucher_cost = this.voucher_cost + iTempCost;
		}
		break;

	case 'percentage':
		// NOTE: percentage's are of the base total prior to payment term discounts
		this.voucher_cost = iTotalCost * this.iVoucherValue;
		var iTempCost = iTotalCost - this.discount_cost - this.voucher_cost;
		if ( 0 > iTempCost )
		{
			this.voucher_cost = this.voucher_cost + iTempCost;
		}
		break;

	default:
		this.voucher_cost = 0;
		break;
	}

	return iTotalCost - this.discount_cost - this.voucher_cost;
}

function ProductLocation( iLocationId, iProductStatusId, bHasStock, oProduct )
{
	this.locationid = iLocationId;
	this.productstatusid = iProductStatusId;
	this.has_stock = bHasStock;
	this.product = oProduct;
}

ProductLocation.prototype.canOrder = function()
{
	var sProductName = this.product.name;
	var sLocation = aLocations[this.locationid].name;
	switch( this.productstatusid )
	{
	case 1: // Created
		return { available: false, msg: 'Sorry ' + sProductName + ' isnt available in ' + sLocation + ' yet!' };

	case 2: // Coming Soon
		return { available: false, msg: sProductName + ' is coming soon to ' + sLocation + ', please check back regularly!' };

	case 3: // Pre-Order
		return { available: true, msg: sProductName + ' is on pre-order in ' + sLocation +', once available your server will be setup automatically.' };

	case 4: // New
	case 5: // Current
	case 6: // Updated
		return { available: true, msg: '' };

	case 7: // Deleted		
		return { available: false, msg: 'Sorry ' + sProductName + ' is no longer available in ' + sLocation + '!' };
	}

	return { available: false, msg: 'Sorry ' + sProductName + ' is not available in ' + sLocation + '!' };
}

// Server Product
function ServerProduct( iProductId, iServiceOptionId, sName, iModId, iGameId, sIcon, sGameName )
{
	this.productid = iProductId
	this.serviceoptionid = iServiceOptionId;
	this.name = sName;
	this.game_name = sGameName;
	this.modid = iModId;
	this.gameid = iGameId;
	this.icon = sIcon;
	this.games = [];
	this.locations = [];
	this.conflicts = [];
}

ServerProduct.prototype.canOrderIn = function( iLocationId )
{
	var oProductLocation = this.locations[iLocationId];
	if ( ! oProductLocation )
	{
		// No overrides for this location
		return true;
	}

	var oCanOrder = oProductLocation.canOrder();
	if ( oCanOrder.msg )
	{
		alert( oCanOrder.msg );
	}

	return oCanOrder.available;
}

ServerProduct.prototype.addConflict = function( iProductId )
{
	this.conflicts.push( iProductId );
}

ServerProduct.prototype.conflictsWith = function( aProductIds )
{
	var aConflicts = [];
	for ( var i in this.conflicts )
	{
		var iProductId = this.conflicts[i];
		for ( var j in aProductIds )
		{
			if ( iProductId == aProductIds[j] )
			{
				aConflicts.push( '* ' + decodeEntities( aProducts[aProductIds[j]].name ) );
			}
		}
	}

	if ( 0 != aConflicts.length )
	{
		alert(
			'Sorry ' + aProducts[this.productid].name + " can not be added as a swappable game as it conflicts with:\n" +
			aConflicts.join( "\n" ) + "\n\n" +
			"Don't worry though; if you would like a server for both these games you can simply order multiple servers."
		);
		return true;
	}

	return false;
}

ServerProduct.prototype.addLocation = function( iLocationId, iProductStatusId, bHasStock )
{
	this.locations[iLocationId] = new ProductLocation( iLocationId, iProductStatusId, bHasStock, this );
}

// Currency Conversion Index
function CurrencyConversionIndex( from, to, index )
{
	this.from = from;
	this.to = to;
	this.index = index;
}

CurrencyConversionIndex.prototype.convertForwards = function( amount )
{
	return amount * this.index;
}

CurrencyConversionIndex.prototype.convertBackwards = function( amount )
{
	return amount / this.index;
}

// Vouchers
function Voucher( iVoucherId, sName, sCode, sMsg, sType, fDiscount, bExclusive )
{
	this.voucherid = iVoucherId;
	this.name = sName;
	this.code = sCode;
	this.msg = sMsg;
	this.type = sType;
	this.discount = fDiscount;
	this.exclusive = bExclusive;
	this.validProducts = [];
}

Voucher.prototype.addValidProduct = function( sType, iProductId, iLocationId, iPeriod )
{
	this.validProducts.push( new ValidProduct( sType, iProductId, iLocationId, iPeriod ) );
}

Voucher.prototype.validForProducts = function( sType, iLocationId, iPeriod, aProductIds )
{
	for ( var i in aProductIds )
	{
		var iProductId = aProductIds[i];
		if ( ! this.validForProduct( sType, iLocationId, iPeriod, iProductId ) )
		{
			return false;
		}
	}

	return true;
}

Voucher.prototype.validForProduct = function( sType, iLocationId, iPeriod, iProductId )
{
	for ( var i in this.validProducts )
	{
		var oValidProduct = this.validProducts[i];
		if ( oValidProduct.validFor( sType, iLocationId, iPeriod, iProductId ) )
		{
			return true;
		}
	}

	// No match
	return false;
}

function ValidProduct( sType, iProductId, iLocationId, iPeriod )
{
	this.type = sType;
	this.productid = iProductId;
	this.locationid = iLocationId;
	this.period = iPeriod;
}

ValidProduct.prototype.validFor = function( sType, iLocationId, iPeriod, iProductId )
{
	//console.log( "validFor1: " + sType + ", " + iLocationId + ", " + iProductId + ", " + iPeriod );
	//console.log( "validFor2: " + this.type + ", " + this.locationid + ", " + this.productid + ", " + this.period );
	if (
		this.type != sType ||
		( iProductId != this.productid && 0 != this.productid ) ||
		( iLocationId != this.locationid && 0 != this.locationid ) ||
		( iPeriod != this.period && 0 != this.period )
	)
	{
		return false;
	}

	// Match on all conditions for this valid product
	return true;
}

// Help
// vim: set ts=4 sw=4 filetype=javascript:

var aHelp = [];
var reHelp = new RegExp();
reHelp.compile( "#help-(.*)" );
function help_load()
{
	var oLinks = document.getElementsByTagName( "a" );
	for ( var i in oLinks )
	{
		var oLink = oLinks[i];
		if ( oLink.href && null != oLink.href.match( reHelp ) )
		{
			var sHelpId = RegExp.$1;
			var oHelp = aHelp[sHelpId];
			if ( undefined === oHelp )
			{
				alert( "Missing help for '" + RegExp.$1 + "'" );
				return false;
			}
			oLink.onmouseover = function () { help_show( this ); };
			oLink.onmouseout = function () { UnTip(); };
			oLink.onclick = function () { return false; };
		}
	}

	return true;
}

function help_show( oSrc )
{
	oSrc.href.match( reHelp );
	var oHelp = aHelp[RegExp.$1];

	Tip(
		oHelp.body,
		WIDTH, 350,
		TITLE, oHelp.title,
		SHADOW, true,
		FADEIN, 300,
		FADEOUT, 300,
		STICKY, 1,
		CLOSEBTN, true,
		CLICKCLOSE, true,
		BGCOLOR, "#FFFFFF",
		SHADOWCOLOR, "#EEEEEE",
		BORDERCOLOR, "#248EBC",
		TITLEBGCOLOR, "#248EBC"
	);

	return false;
}

function help_add( sId, sTitle, sBody )
{
	aHelp[sId] = { title: sTitle, body: sBody };
}


// Tool Tips
/* This notice must be untouched at all times.
Copyright (c) 2002-2008 Walter Zorn. All rights reserved.

wz_tooltip.js	 v. 5.31

The latest version is available at
http://www.walterzorn.com
or http://www.devira.com
or http://www.walterzorn.de

Created 1.12.2002 by Walter Zorn (Web: http://www.walterzorn.com )
Last modified: 7.11.2008

Easy-to-use cross-browser tooltips.
Just include the script at the beginning of the <body> section, and invoke
Tip('Tooltip text') to show and UnTip() to hide the tooltip, from the desired
HTML eventhandlers. Example:
<a onmouseover="Tip('Some text')" onmouseout="UnTip()" href="index.htm">My home page</a>
No container DIV required.
By default, width and height of tooltips are automatically adapted to content.
Is even capable of dynamically converting arbitrary HTML elements to tooltips
by calling TagToTip('ID_of_HTML_element_to_be_converted') instead of Tip(),
which means you can put important, search-engine-relevant stuff into tooltips.
Appearance & behaviour of tooltips can be individually configured
via commands passed to Tip() or TagToTip().

Tab Width: 4
LICENSE: LGPL

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License (LGPL) as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

For more details on the GNU Lesser General Public License,
see http://www.gnu.org/copyleft/lesser.html
*/

var config = new Object();


//===================  GLOBAL TOOLTIP CONFIGURATION  =========================//
var tt_Debug	= true		// false or true - recommended: false once you release your page to the public
var tt_Enabled	= true		// Allows to (temporarily) suppress tooltips, e.g. by providing the user with a button that sets this global variable to false
var TagsToTip	= true		// false or true - if true, HTML elements to be converted to tooltips via TagToTip() are automatically hidden;
							// if false, you should hide those HTML elements yourself

// For each of the following config variables there exists a command, which is
// just the variablename in uppercase, to be passed to Tip() or TagToTip() to
// configure tooltips individually. Individual commands override global
// configuration. Order of commands is arbitrary.
// Example: onmouseover="Tip('Tooltip text', LEFT, true, BGCOLOR, '#FF9900', FADEIN, 400)"

config. Above			= false		// false or true - tooltip above mousepointer
config. BgColor			= '#E2E7FF'	// Background colour (HTML colour value, in quotes)
config. BgImg			= ''		// Path to background image, none if empty string ''
config. BorderColor		= '#003099'
config. BorderStyle		= 'solid'	// Any permitted CSS value, but I recommend 'solid', 'dotted' or 'dashed'
config. BorderWidth		= 1
config. CenterMouse		= false		// false or true - center the tip horizontally below (or above) the mousepointer
config. ClickClose		= false		// false or true - close tooltip if the user clicks somewhere
config. ClickSticky		= false		// false or true - make tooltip sticky if user left-clicks on the hovered element while the tooltip is active
config. CloseBtn		= false		// false or true - closebutton in titlebar
config. CloseBtnColors	= ['#990000', '#FFFFFF', '#DD3333', '#FFFFFF']	// [Background, text, hovered background, hovered text] - use empty strings '' to inherit title colours
config. CloseBtnText	= '&nbsp;X&nbsp;'	// Close button text (may also be an image tag)
config. CopyContent		= true		// When converting a HTML element to a tooltip, copy only the element's content, rather than converting the element by its own
config. Delay			= 400		// Time span in ms until tooltip shows up
config. Duration		= 0			// Time span in ms after which the tooltip disappears; 0 for infinite duration, < 0 for delay in ms _after_ the onmouseout until the tooltip disappears
config. Exclusive		= false		// false or true - no other tooltip can appear until the current one has actively been closed
config. FadeIn			= 100		// Fade-in duration in ms, e.g. 400; 0 for no animation
config. FadeOut			= 100
config. FadeInterval	= 30		// Duration of each fade step in ms (recommended: 30) - shorter is smoother but causes more CPU-load
config. Fix				= null		// Fixated position, two modes. Mode 1: x- an y-coordinates in brackets, e.g. [210, 480]. Mode 2: Show tooltip at a position related to an HTML element: [ID of HTML element, x-offset, y-offset from HTML element], e.g. ['SomeID', 10, 30]. Value null (default) for no fixated positioning.
config. FollowMouse		= true		// false or true - tooltip follows the mouse
config. FontColor		= '#000044'
config. FontFace		= 'Verdana,Geneva,sans-serif'
config. FontSize		= '8pt'		// E.g. '9pt' or '12px' - unit is mandatory
config. FontWeight		= 'normal'	// 'normal' or 'bold';
config. Height			= 0			// Tooltip height; 0 for automatic adaption to tooltip content, < 0 (e.g. -100) for a maximum for automatic adaption
config. JumpHorz		= false		// false or true - jump horizontally to other side of mouse if tooltip would extend past clientarea boundary
config. JumpVert		= true		// false or true - jump vertically		"
config. Left			= false		// false or true - tooltip on the left of the mouse
config. OffsetX			= 14		// Horizontal offset of left-top corner from mousepointer
config. OffsetY			= 8			// Vertical offset
config. Opacity			= 100		// Integer between 0 and 100 - opacity of tooltip in percent
config. Padding			= 3			// Spacing between border and content
config. Shadow			= false		// false or true
config. ShadowColor		= '#C0C0C0'
config. ShadowWidth		= 5
config. Sticky			= false		// false or true - fixate tip, ie. don't follow the mouse and don't hide on mouseout
config. TextAlign		= 'left'	// 'left', 'right' or 'justify'
config. Title			= ''		// Default title text applied to all tips (no default title: empty string '')
config. TitleAlign		= 'left'	// 'left' or 'right' - text alignment inside the title bar
config. TitleBgColor	= ''		// If empty string '', BorderColor will be used
config. TitleFontColor	= '#FFFFFF'	// Color of title text - if '', BgColor (of tooltip body) will be used
config. TitleFontFace	= ''		// If '' use FontFace (boldified)
config. TitleFontSize	= ''		// If '' use FontSize
config. TitlePadding	= 2
config. Width			= 0			// Tooltip width; 0 for automatic adaption to tooltip content; < -1 (e.g. -240) for a maximum width for that automatic adaption;
									// -1: tooltip width confined to the width required for the titlebar
//=======  END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW  ==============//




//=====================  PUBLIC  =============================================//
function Tip()
{
	tt_Tip(arguments, null);
}
function TagToTip()
{
	var t2t = tt_GetElt(arguments[0]);
	if(t2t)
		tt_Tip(arguments, t2t);
}
function UnTip()
{
	tt_OpReHref();
	if(tt_aV[DURATION] < 0 && (tt_iState & 0x2))
		tt_tDurt.Timer("tt_HideInit()", -tt_aV[DURATION], true);
	else if(!(tt_aV[STICKY] && (tt_iState & 0x2)))
		tt_HideInit();
}

//==================  PUBLIC PLUGIN API	 =====================================//
// Extension eventhandlers currently supported:
// OnLoadConfig, OnCreateContentString, OnSubDivsCreated, OnShow, OnMoveBefore,
// OnMoveAfter, OnHideInit, OnHide, OnKill

var tt_aElt = new Array(10), // Container DIV, outer title & body DIVs, inner title & body TDs, closebutton SPAN, shadow DIVs, and IFRAME to cover windowed elements in IE
tt_aV = new Array(),	// Caches and enumerates config data for currently active tooltip
tt_sContent,			// Inner tooltip text or HTML
tt_t2t, tt_t2tDad,		// Tag converted to tip, and its DOM parent element
tt_musX, tt_musY,
tt_over,
tt_x, tt_y, tt_w, tt_h; // Position, width and height of currently displayed tooltip

function tt_Extension()
{
	tt_ExtCmdEnum();
	tt_aExt[tt_aExt.length] = this;
	return this;
}
function tt_SetTipPos(x, y)
{
	var css = tt_aElt[0].style;

	tt_x = x;
	tt_y = y;
	css.left = x + "px";
	css.top = y + "px";
	if(tt_ie56)
	{
		var ifrm = tt_aElt[tt_aElt.length - 1];
		if(ifrm)
		{
			ifrm.style.left = css.left;
			ifrm.style.top = css.top;
		}
	}
}
function tt_HideInit()
{
	if(tt_iState)
	{
		tt_ExtCallFncs(0, "HideInit");
		tt_iState &= ~(0x4 | 0x8);
		if(tt_flagOpa && tt_aV[FADEOUT])
		{
			tt_tFade.EndTimer();
			if(tt_opa)
			{
				var n = Math.round(tt_aV[FADEOUT] / (tt_aV[FADEINTERVAL] * (tt_aV[OPACITY] / tt_opa)));
				tt_Fade(tt_opa, tt_opa, 0, n);
				return;
			}
		}
		tt_tHide.Timer("tt_Hide();", 1, false);
	}
}
function tt_Hide()
{
	if(tt_db && tt_iState)
	{
		tt_OpReHref();
		if(tt_iState & 0x2)
		{
			tt_aElt[0].style.visibility = "hidden";
			tt_ExtCallFncs(0, "Hide");
		}
		tt_tShow.EndTimer();
		tt_tHide.EndTimer();
		tt_tDurt.EndTimer();
		tt_tFade.EndTimer();
		if(!tt_op && !tt_ie)
		{
			tt_tWaitMov.EndTimer();
			tt_bWait = false;
		}
		if(tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY])
			tt_RemEvtFnc(document, "mouseup", tt_OnLClick);
		tt_ExtCallFncs(0, "Kill");
		// In case of a TagToTip tip, hide converted DOM node and
		// re-insert it into DOM
		if(tt_t2t && !tt_aV[COPYCONTENT])
			tt_UnEl2Tip();
		tt_iState = 0;
		tt_over = null;
		tt_ResetMainDiv();
		if(tt_aElt[tt_aElt.length - 1])
			tt_aElt[tt_aElt.length - 1].style.display = "none";
	}
}
function tt_GetElt(id)
{
	return(document.getElementById ? document.getElementById(id)
			: document.all ? document.all[id]
			: null);
}
function tt_GetDivW(el)
{
	return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0);
}
function tt_GetDivH(el)
{
	return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0);
}
function tt_GetScrollX()
{
	return(window.pageXOffset || (tt_db ? (tt_db.scrollLeft || 0) : 0));
}
function tt_GetScrollY()
{
	return(window.pageYOffset || (tt_db ? (tt_db.scrollTop || 0) : 0));
}
function tt_GetClientW()
{
	return tt_GetWndCliSiz("Width");
}
function tt_GetClientH()
{
	return tt_GetWndCliSiz("Height");
}
function tt_GetEvtX(e)
{
	return (e ? ((typeof(e.pageX) != tt_u) ? e.pageX : (e.clientX + tt_GetScrollX())) : 0);
}
function tt_GetEvtY(e)
{
	return (e ? ((typeof(e.pageY) != tt_u) ? e.pageY : (e.clientY + tt_GetScrollY())) : 0);
}
function tt_AddEvtFnc(el, sEvt, PFnc)
{
	if(el)
	{
		if(el.addEventListener)
			el.addEventListener(sEvt, PFnc, false);
		else
			el.attachEvent("on" + sEvt, PFnc);
	}
}
function tt_RemEvtFnc(el, sEvt, PFnc)
{
	if(el)
	{
		if(el.removeEventListener)
			el.removeEventListener(sEvt, PFnc, false);
		else
			el.detachEvent("on" + sEvt, PFnc);
	}
}
function tt_GetDad(el)
{
	return(el.parentNode || el.parentElement || el.offsetParent);
}
function tt_MovDomNode(el, dadFrom, dadTo)
{
	if(dadFrom)
		dadFrom.removeChild(el);
	if(dadTo)
		dadTo.appendChild(el);
}

//======================  PRIVATE  ===========================================//
var tt_aExt = new Array(),	// Array of extension objects

tt_db, tt_op, tt_ie, tt_ie56, tt_bBoxOld,	// Browser flags
tt_body,
tt_ovr_,				// HTML element the mouse is currently over
tt_flagOpa,				// Opacity support: 1=IE, 2=Khtml, 3=KHTML, 4=Moz, 5=W3C
tt_maxPosX, tt_maxPosY,
tt_iState = 0,			// Tooltip active |= 1, shown |= 2, move with mouse |= 4, exclusive |= 8
tt_opa,					// Currently applied opacity
tt_bJmpVert, tt_bJmpHorz,// Tip temporarily on other side of mouse
tt_elDeHref,			// The tag from which we've removed the href attribute
// Timer
tt_tShow = new Number(0), tt_tHide = new Number(0), tt_tDurt = new Number(0),
tt_tFade = new Number(0), tt_tWaitMov = new Number(0),
tt_bWait = false,
tt_u = "undefined";


function tt_Init()
{
	tt_MkCmdEnum();
	// Send old browsers instantly to hell
	if(!tt_Browser() || !tt_MkMainDiv())
		return;
	tt_IsW3cBox();
	tt_OpaSupport();
	tt_AddEvtFnc(document, "mousemove", tt_Move);
	// In Debug mode we search for TagToTip() calls in order to notify
	// the user if they've forgotten to set the TagsToTip config flag
	if(TagsToTip || tt_Debug)
		tt_SetOnloadFnc();
	// Ensure the tip be hidden when the page unloads
	tt_AddEvtFnc(window, "unload", tt_Hide);
}
// Creates command names by translating config variable names to upper case
function tt_MkCmdEnum()
{
	var n = 0;
	for(var i in config)
		eval("window." + i.toString().toUpperCase() + " = " + n++);
	tt_aV.length = n;
}
function tt_Browser()
{
	var n, nv, n6, w3c;

	n = navigator.userAgent.toLowerCase(),
	nv = navigator.appVersion;
	tt_op = (document.defaultView && typeof(eval("w" + "indow" + "." + "o" + "p" + "er" + "a")) != tt_u);
	tt_ie = n.indexOf("msie") != -1 && document.all && !tt_op;
	if(tt_ie)
	{
		var ieOld = (!document.compatMode || document.compatMode == "BackCompat");
		tt_db = !ieOld ? document.documentElement : (document.body || null);
		if(tt_db)
			tt_ie56 = parseFloat(nv.substring(nv.indexOf("MSIE") + 5)) >= 5.5
					&& typeof document.body.style.maxHeight == tt_u;
	}
	else
	{
		tt_db = document.documentElement || document.body ||
				(document.getElementsByTagName ? document.getElementsByTagName("body")[0]
				: null);
		if(!tt_op)
		{
			n6 = document.defaultView && typeof document.defaultView.getComputedStyle != tt_u;
			w3c = !n6 && document.getElementById;
		}
	}
	tt_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0]
				: (document.body || null));
	if(tt_ie || n6 || tt_op || w3c)
	{
		if(tt_body && tt_db)
		{
			if(document.attachEvent || document.addEventListener)
				return true;
		}
		else
			tt_Err("wz_tooltip.js must be included INSIDE the body section,"
					+ " immediately after the opening <body> tag.", false);
	}
	tt_db = null;
	return false;
}
function tt_MkMainDiv()
{
	// Create the tooltip DIV
	if(tt_body.insertAdjacentHTML)
		tt_body.insertAdjacentHTML("afterBegin", tt_MkMainDivHtm());
	else if(typeof tt_body.innerHTML != tt_u && document.createElement && tt_body.appendChild)
		tt_body.appendChild(tt_MkMainDivDom());
	if(window.tt_GetMainDivRefs /* FireFox Alzheimer */ && tt_GetMainDivRefs())
		return true;
	tt_db = null;
	return false;
}
function tt_MkMainDivHtm()
{
	return(
		'<div id="WzTtDiV"></div>' +
		(tt_ie56 ? ('<iframe id="WzTtIfRm" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>')
		: '')
	);
}
function tt_MkMainDivDom()
{
	var el = document.createElement("div");
	if(el)
		el.id = "WzTtDiV";
	return el;
}
function tt_GetMainDivRefs()
{
	tt_aElt[0] = tt_GetElt("WzTtDiV");
	if(tt_ie56 && tt_aElt[0])
	{
		tt_aElt[tt_aElt.length - 1] = tt_GetElt("WzTtIfRm");
		if(!tt_aElt[tt_aElt.length - 1])
			tt_aElt[0] = null;
	}
	if(tt_aElt[0])
	{
		var css = tt_aElt[0].style;

		css.visibility = "hidden";
		css.position = "absolute";
		css.overflow = "hidden";
		return true;
	}
	return false;
}
function tt_ResetMainDiv()
{
	tt_SetTipPos(0, 0);
	tt_aElt[0].innerHTML = "";
	tt_aElt[0].style.width = "0px";
	tt_h = 0;
}
function tt_IsW3cBox()
{
	var css = tt_aElt[0].style;

	css.padding = "10px";
	css.width = "40px";
	tt_bBoxOld = (tt_GetDivW(tt_aElt[0]) == 40);
	css.padding = "0px";
	tt_ResetMainDiv();
}
function tt_OpaSupport()
{
	var css = tt_body.style;

	tt_flagOpa = (typeof(css.KhtmlOpacity) != tt_u) ? 2
				: (typeof(css.KHTMLOpacity) != tt_u) ? 3
				: (typeof(css.MozOpacity) != tt_u) ? 4
				: (typeof(css.opacity) != tt_u) ? 5
				: (typeof(css.filter) != tt_u) ? 1
				: 0;
}
// Ported from http://dean.edwards.name/weblog/2006/06/again/
// (Dean Edwards et al.)
function tt_SetOnloadFnc()
{
	tt_AddEvtFnc(document, "DOMContentLoaded", tt_HideSrcTags);
	tt_AddEvtFnc(window, "load", tt_HideSrcTags);
	if(tt_body.attachEvent)
		tt_body.attachEvent("onreadystatechange",
			function() {
				if(tt_body.readyState == "complete")
					tt_HideSrcTags();
			} );
	if(/WebKit|KHTML/i.test(navigator.userAgent))
	{
		var t = setInterval(function() {
					if(/loaded|complete/.test(document.readyState))
					{
						clearInterval(t);
						tt_HideSrcTags();
					}
				}, 10);
	}
}
function tt_HideSrcTags()
{
	if(!window.tt_HideSrcTags || window.tt_HideSrcTags.done)
		return;
	window.tt_HideSrcTags.done = true;
	if(!tt_HideSrcTagsRecurs(tt_body))
		tt_Err("There are HTML elements to be converted to tooltips.\nIf you"
				+ " want these HTML elements to be automatically hidden, you"
				+ " must edit wz_tooltip.js, and set TagsToTip in the global"
				+ " tooltip configuration to true.", true);
}
function tt_HideSrcTagsRecurs(dad)
{
	var ovr, asT2t;
	// Walk the DOM tree for tags that have an onmouseover or onclick attribute
	// containing a TagToTip('...') call.
	// (.childNodes first since .children is bugous in Safari)
	var a = dad.childNodes || dad.children || null;

	for(var i = a ? a.length : 0; i;)
	{--i;
		if(!tt_HideSrcTagsRecurs(a[i]))
			return false;
		ovr = a[i].getAttribute ? (a[i].getAttribute("onmouseover") || a[i].getAttribute("onclick"))
				: (typeof a[i].onmouseover == "function") ? (a[i].onmouseover || a[i].onclick)
				: null;
		if(ovr)
		{
			asT2t = ovr.toString().match(/TagToTip\s*\(\s*'[^'.]+'\s*[\),]/);
			if(asT2t && asT2t.length)
			{
				if(!tt_HideSrcTag(asT2t[0]))
					return false;
			}
		}
	}
	return true;
}
function tt_HideSrcTag(sT2t)
{
	var id, el;

	// The ID passed to the found TagToTip() call identifies an HTML element
	// to be converted to a tooltip, so hide that element
	id = sT2t.replace(/.+'([^'.]+)'.+/, "$1");
	el = tt_GetElt(id);
	if(el)
	{
		if(tt_Debug && !TagsToTip)
			return false;
		else
			el.style.display = "none";
	}
	else
		tt_Err("Invalid ID\n'" + id + "'\npassed to TagToTip()."
				+ " There exists no HTML element with that ID.", true);
	return true;
}
function tt_Tip(arg, t2t)
{
	if(!tt_db || (tt_iState & 0x8))
		return;
	if(tt_iState)
		tt_Hide();
	if(!tt_Enabled)
		return;
	tt_t2t = t2t;
	if(!tt_ReadCmds(arg))
		return;
	tt_iState = 0x1 | 0x4;
	tt_AdaptConfig1();
	tt_MkTipContent(arg);
	tt_MkTipSubDivs();
	tt_FormatTip();
	tt_bJmpVert = false;
	tt_bJmpHorz = false;
	tt_maxPosX = tt_GetClientW() + tt_GetScrollX() - tt_w - 1;
	tt_maxPosY = tt_GetClientH() + tt_GetScrollY() - tt_h - 1;
	tt_AdaptConfig2();
	// Ensure the tip be shown and positioned before the first onmousemove
	tt_OverInit();
	tt_ShowInit();
	tt_Move();
}
function tt_ReadCmds(a)
{
	var i;

	// First load the global config values, to initialize also values
	// for which no command is passed
	i = 0;
	for(var j in config)
		tt_aV[i++] = config[j];
	// Then replace each cached config value for which a command is
	// passed (ensure the # of command args plus value args be even)
	if(a.length & 1)
	{
		for(i = a.length - 1; i > 0; i -= 2)
			tt_aV[a[i - 1]] = a[i];
		return true;
	}
	tt_Err("Incorrect call of Tip() or TagToTip().\n"
			+ "Each command must be followed by a value.", true);
	return false;
}
function tt_AdaptConfig1()
{
	tt_ExtCallFncs(0, "LoadConfig");
	// Inherit unspecified title formattings from body
	if(!tt_aV[TITLEBGCOLOR].length)
		tt_aV[TITLEBGCOLOR] = tt_aV[BORDERCOLOR];
	if(!tt_aV[TITLEFONTCOLOR].length)
		tt_aV[TITLEFONTCOLOR] = tt_aV[BGCOLOR];
	if(!tt_aV[TITLEFONTFACE].length)
		tt_aV[TITLEFONTFACE] = tt_aV[FONTFACE];
	if(!tt_aV[TITLEFONTSIZE].length)
		tt_aV[TITLEFONTSIZE] = tt_aV[FONTSIZE];
	if(tt_aV[CLOSEBTN])
	{
		// Use title colours for non-specified closebutton colours
		if(!tt_aV[CLOSEBTNCOLORS])
			tt_aV[CLOSEBTNCOLORS] = new Array("", "", "", "");
		for(var i = 4; i;)
		{--i;
			if(!tt_aV[CLOSEBTNCOLORS][i].length)
				tt_aV[CLOSEBTNCOLORS][i] = (i & 1) ? tt_aV[TITLEFONTCOLOR] : tt_aV[TITLEBGCOLOR];
		}
		// Enforce titlebar be shown
		if(!tt_aV[TITLE].length)
			tt_aV[TITLE] = " ";
	}
	// Circumvents broken display of images and fade-in flicker in Geckos < 1.8
	if(tt_aV[OPACITY] == 100 && typeof tt_aElt[0].style.MozOpacity != tt_u && !Array.every)
		tt_aV[OPACITY] = 99;
	// Smartly shorten the delay for fade-in tooltips
	if(tt_aV[FADEIN] && tt_flagOpa && tt_aV[DELAY] > 100)
		tt_aV[DELAY] = Math.max(tt_aV[DELAY] - tt_aV[FADEIN], 100);
}
function tt_AdaptConfig2()
{
	if(tt_aV[CENTERMOUSE])
	{
		tt_aV[OFFSETX] -= ((tt_w - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0)) >> 1);
		tt_aV[JUMPHORZ] = false;
	}
}
// Expose content globally so extensions can modify it
function tt_MkTipContent(a)
{
	if(tt_t2t)
	{
		if(tt_aV[COPYCONTENT])
			tt_sContent = tt_t2t.innerHTML;
		else
			tt_sContent = "";
	}
	else
		tt_sContent = a[0];
	tt_ExtCallFncs(0, "CreateContentString");
}
function tt_MkTipSubDivs()
{
	var sCss = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:auto;',
	sTbTrTd = ' cellspacing="0" cellpadding="0" border="0" style="' + sCss + '"><tbody style="' + sCss + '"><tr><td ';

	tt_aElt[0].style.width = tt_GetClientW() + "px";
	tt_aElt[0].innerHTML =
		(''
		+ (tt_aV[TITLE].length ?
			('<div id="WzTiTl" style="position:relative;z-index:1;">'
			+ '<table id="WzTiTlTb"' + sTbTrTd + 'id="WzTiTlI" style="' + sCss + '">'
			+ tt_aV[TITLE]
			+ '</td>'
			+ (tt_aV[CLOSEBTN] ?
				('<td align="right" style="' + sCss
				+ 'text-align:right;">'
				+ '<span id="WzClOsE" style="position:relative;left:2px;padding-left:2px;padding-right:2px;'
				+ 'cursor:' + (tt_ie ? 'hand' : 'pointer')
				+ ';" onmouseover="tt_OnCloseBtnOver(1)" onmouseout="tt_OnCloseBtnOver(0)" onclick="tt_HideInit()">'
				+ tt_aV[CLOSEBTNTEXT]
				+ '</span></td>')
				: '')
			+ '</tr></tbody></table></div>')
			: '')
		+ '<div id="WzBoDy" style="position:relative;z-index:0;">'
		+ '<table' + sTbTrTd + 'id="WzBoDyI" style="' + sCss + '">'
		+ tt_sContent
		+ '</td></tr></tbody></table></div>'
		+ (tt_aV[SHADOW]
			? ('<div id="WzTtShDwR" style="position:absolute;overflow:hidden;"></div>'
				+ '<div id="WzTtShDwB" style="position:relative;overflow:hidden;"></div>')
			: '')
		);
	tt_GetSubDivRefs();
	// Convert DOM node to tip
	if(tt_t2t && !tt_aV[COPYCONTENT])
		tt_El2Tip();
	tt_ExtCallFncs(0, "SubDivsCreated");
}
function tt_GetSubDivRefs()
{
	var aId = new Array("WzTiTl", "WzTiTlTb", "WzTiTlI", "WzClOsE", "WzBoDy", "WzBoDyI", "WzTtShDwB", "WzTtShDwR");

	for(var i = aId.length; i; --i)
		tt_aElt[i] = tt_GetElt(aId[i - 1]);
}
function tt_FormatTip()
{
	var css, w, h, pad = tt_aV[PADDING], padT, wBrd = tt_aV[BORDERWIDTH],
	iOffY, iOffSh, iAdd = (pad + wBrd) << 1;

	//--------- Title DIV ----------
	if(tt_aV[TITLE].length)
	{
		padT = tt_aV[TITLEPADDING];
		css = tt_aElt[1].style;
		css.background = tt_aV[TITLEBGCOLOR];
		css.paddingTop = css.paddingBottom = padT + "px";
		css.paddingLeft = css.paddingRight = (padT + 2) + "px";
		css = tt_aElt[3].style;
		css.color = tt_aV[TITLEFONTCOLOR];
		if(tt_aV[WIDTH] == -1)
			css.whiteSpace = "nowrap";
		css.fontFamily = tt_aV[TITLEFONTFACE];
		css.fontSize = tt_aV[TITLEFONTSIZE];
		css.fontWeight = "bold";
		css.textAlign = tt_aV[TITLEALIGN];
		// Close button DIV
		if(tt_aElt[4])
		{
			css = tt_aElt[4].style;
			css.background = tt_aV[CLOSEBTNCOLORS][0];
			css.color = tt_aV[CLOSEBTNCOLORS][1];
			css.fontFamily = tt_aV[TITLEFONTFACE];
			css.fontSize = tt_aV[TITLEFONTSIZE];
			css.fontWeight = "bold";
		}
		if(tt_aV[WIDTH] > 0)
			tt_w = tt_aV[WIDTH];
		else
		{
			tt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]);
			// Some spacing between title DIV and closebutton
			if(tt_aElt[4])
				tt_w += pad;
			// Restrict auto width to max width
			if(tt_aV[WIDTH] < -1 && tt_w > -tt_aV[WIDTH])
				tt_w = -tt_aV[WIDTH];
		}
		// Ensure the top border of the body DIV be covered by the title DIV
		iOffY = -wBrd;
	}
	else
	{
		tt_w = 0;
		iOffY = 0;
	}

	//-------- Body DIV ------------
	css = tt_aElt[5].style;
	css.top = iOffY + "px";
	if(wBrd)
	{
		css.borderColor = tt_aV[BORDERCOLOR];
		css.borderStyle = tt_aV[BORDERSTYLE];
		css.borderWidth = wBrd + "px";
	}
	if(tt_aV[BGCOLOR].length)
		css.background = tt_aV[BGCOLOR];
	if(tt_aV[BGIMG].length)
		css.backgroundImage = "url(" + tt_aV[BGIMG] + ")";
	css.padding = pad + "px";
	css.textAlign = tt_aV[TEXTALIGN];
	if(tt_aV[HEIGHT])
	{
		css.overflow = "auto";
		if(tt_aV[HEIGHT] > 0)
			css.height = (tt_aV[HEIGHT] + iAdd) + "px";
		else
			tt_h = iAdd - tt_aV[HEIGHT];
	}
	// TD inside body DIV
	css = tt_aElt[6].style;
	css.color = tt_aV[FONTCOLOR];
	css.fontFamily = tt_aV[FONTFACE];
	css.fontSize = tt_aV[FONTSIZE];
	css.fontWeight = tt_aV[FONTWEIGHT];
	css.textAlign = tt_aV[TEXTALIGN];
	if(tt_aV[WIDTH] > 0)
		w = tt_aV[WIDTH];
	// Width like title (if existent)
	else if(tt_aV[WIDTH] == -1 && tt_w)
		w = tt_w;
	else
	{
		// Measure width of the body's inner TD, as some browsers would expand
		// the container and outer body DIV to 100%
		w = tt_GetDivW(tt_aElt[6]);
		// Restrict auto width to max width
		if(tt_aV[WIDTH] < -1 && w > -tt_aV[WIDTH])
			w = -tt_aV[WIDTH];
	}
	if(w > tt_w)
		tt_w = w;
	tt_w += iAdd;

	//--------- Shadow DIVs ------------
	if(tt_aV[SHADOW])
	{
		tt_w += tt_aV[SHADOWWIDTH];
		iOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3);
		// Bottom shadow
		css = tt_aElt[7].style;
		css.top = iOffY + "px";
		css.left = iOffSh + "px";
		css.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + "px";
		css.height = tt_aV[SHADOWWIDTH] + "px";
		css.background = tt_aV[SHADOWCOLOR];
		// Right shadow
		css = tt_aElt[8].style;
		css.top = iOffSh + "px";
		css.left = (tt_w - tt_aV[SHADOWWIDTH]) + "px";
		css.width = tt_aV[SHADOWWIDTH] + "px";
		css.background = tt_aV[SHADOWCOLOR];
	}
	else
		iOffSh = 0;

	//-------- Container DIV -------
	tt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]);
	tt_FixSize(iOffY, iOffSh);
}
// Fixate the size so it can't dynamically change while the tooltip is moving.
function tt_FixSize(iOffY, iOffSh)
{
	var wIn, wOut, h, add, pad = tt_aV[PADDING], wBrd = tt_aV[BORDERWIDTH], i;

	tt_aElt[0].style.width = tt_w + "px";
	tt_aElt[0].style.pixelWidth = tt_w;
	wOut = tt_w - ((tt_aV[SHADOW]) ? tt_aV[SHADOWWIDTH] : 0);
	// Body
	wIn = wOut;
	if(!tt_bBoxOld)
		wIn -= (pad + wBrd) << 1;
	tt_aElt[5].style.width = wIn + "px";
	// Title
	if(tt_aElt[1])
	{
		wIn = wOut - ((tt_aV[TITLEPADDING] + 2) << 1);
		if(!tt_bBoxOld)
			wOut = wIn;
		tt_aElt[1].style.width = wOut + "px";
		tt_aElt[2].style.width = wIn + "px";
	}
	// Max height specified
	if(tt_h)
	{
		h = tt_GetDivH(tt_aElt[5]);
		if(h > tt_h)
		{
			if(!tt_bBoxOld)
				tt_h -= (pad + wBrd) << 1;
			tt_aElt[5].style.height = tt_h + "px";
		}
	}
	tt_h = tt_GetDivH(tt_aElt[0]) + iOffY;
	// Right shadow
	if(tt_aElt[8])
		tt_aElt[8].style.height = (tt_h - iOffSh) + "px";
	i = tt_aElt.length - 1;
	if(tt_aElt[i])
	{
		tt_aElt[i].style.width = tt_w + "px";
		tt_aElt[i].style.height = tt_h + "px";
	}
}
function tt_DeAlt(el)
{
	var aKid;

	if(el)
	{
		if(el.alt)
			el.alt = "";
		if(el.title)
			el.title = "";
		aKid = el.childNodes || el.children || null;
		if(aKid)
		{
			for(var i = aKid.length; i;)
				tt_DeAlt(aKid[--i]);
		}
	}
}
// This hack removes the native tooltips over links in Opera
function tt_OpDeHref(el)
{
	if(!tt_op)
		return;
	if(tt_elDeHref)
		tt_OpReHref();
	while(el)
	{
		if(el.hasAttribute && el.hasAttribute("href"))
		{
			el.t_href = el.getAttribute("href");
			el.t_stats = window.status;
			el.removeAttribute("href");
			el.style.cursor = "hand";
			tt_AddEvtFnc(el, "mousedown", tt_OpReHref);
			window.status = el.t_href;
			tt_elDeHref = el;
			break;
		}
		el = tt_GetDad(el);
	}
}
function tt_OpReHref()
{
	if(tt_elDeHref)
	{
		tt_elDeHref.setAttribute("href", tt_elDeHref.t_href);
		tt_RemEvtFnc(tt_elDeHref, "mousedown", tt_OpReHref);
		window.status = tt_elDeHref.t_stats;
		tt_elDeHref = null;
	}
}
function tt_El2Tip()
{
	var css = tt_t2t.style;

	// Store previous positioning
	tt_t2t.t_cp = css.position;
	tt_t2t.t_cl = css.left;
	tt_t2t.t_ct = css.top;
	tt_t2t.t_cd = css.display;
	// Store the tag's parent element so we can restore that DOM branch
	// when the tooltip is being hidden
	tt_t2tDad = tt_GetDad(tt_t2t);
	tt_MovDomNode(tt_t2t, tt_t2tDad, tt_aElt[6]);
	css.display = "block";
	css.position = "static";
	css.left = css.top = css.marginLeft = css.marginTop = "0px";
}
function tt_UnEl2Tip()
{
	// Restore positioning and display
	var css = tt_t2t.style;

	css.display = tt_t2t.t_cd;
	tt_MovDomNode(tt_t2t, tt_GetDad(tt_t2t), tt_t2tDad);
	css.position = tt_t2t.t_cp;
	css.left = tt_t2t.t_cl;
	css.top = tt_t2t.t_ct;
	tt_t2tDad = null;
}
function tt_OverInit()
{
	if(window.event)
		tt_over = window.event.target || window.event.srcElement;
	else
		tt_over = tt_ovr_;
	tt_DeAlt(tt_over);
	tt_OpDeHref(tt_over);
}
function tt_ShowInit()
{
	tt_tShow.Timer("tt_Show()", tt_aV[DELAY], true);
	if(tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY])
		tt_AddEvtFnc(document, "mouseup", tt_OnLClick);
}
function tt_Show()
{
	var css = tt_aElt[0].style;

	// Override the z-index of the topmost wz_dragdrop.js D&D item
	css.zIndex = Math.max((window.dd && dd.z) ? (dd.z + 2) : 0, 1010);
	if(tt_aV[STICKY] || !tt_aV[FOLLOWMOUSE])
		tt_iState &= ~0x4;
	if(tt_aV[EXCLUSIVE])
		tt_iState |= 0x8;
	if(tt_aV[DURATION] > 0)
		tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true);
	tt_ExtCallFncs(0, "Show")
	css.visibility = "visible";
	tt_iState |= 0x2;
	if(tt_aV[FADEIN])
		tt_Fade(0, 0, tt_aV[OPACITY], Math.round(tt_aV[FADEIN] / tt_aV[FADEINTERVAL]));
	tt_ShowIfrm();
}
function tt_ShowIfrm()
{
	if(tt_ie56)
	{
		var ifrm = tt_aElt[tt_aElt.length - 1];
		if(ifrm)
		{
			var css = ifrm.style;
			css.zIndex = tt_aElt[0].style.zIndex - 1;
			css.display = "block";
		}
	}
}
function tt_Move(e)
{
	if(e)
		tt_ovr_ = e.target || e.srcElement;
	e = e || window.event;
	if(e)
	{
		tt_musX = tt_GetEvtX(e);
		tt_musY = tt_GetEvtY(e);
	}
	if(tt_iState & 0x4)
	{
		// Prevent jam of mousemove events
		if(!tt_op && !tt_ie)
		{
			if(tt_bWait)
				return;
			tt_bWait = true;
			tt_tWaitMov.Timer("tt_bWait = false;", 1, true);
		}
		if(tt_aV[FIX])
		{
			tt_iState &= ~0x4;
			tt_PosFix();
		}
		else if(!tt_ExtCallFncs(e, "MoveBefore"))
			tt_SetTipPos(tt_Pos(0), tt_Pos(1));
		tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter")
	}
}
function tt_Pos(iDim)
{
	var iX, bJmpMod, cmdAlt, cmdOff, cx, iMax, iScrl, iMus, bJmp;

	// Map values according to dimension to calculate
	if(iDim)
	{
		bJmpMod = tt_aV[JUMPVERT];
		cmdAlt = ABOVE;
		cmdOff = OFFSETY;
		cx = tt_h;
		iMax = tt_maxPosY;
		iScrl = tt_GetScrollY();
		iMus = tt_musY;
		bJmp = tt_bJmpVert;
	}
	else
	{
		bJmpMod = tt_aV[JUMPHORZ];
		cmdAlt = LEFT;
		cmdOff = OFFSETX;
		cx = tt_w;
		iMax = tt_maxPosX;
		iScrl = tt_GetScrollX();
		iMus = tt_musX;
		bJmp = tt_bJmpHorz;
	}
	if(bJmpMod)
	{
		if(tt_aV[cmdAlt] && (!bJmp || tt_CalcPosAlt(iDim) >= iScrl + 16))
			iX = tt_PosAlt(iDim);
		else if(!tt_aV[cmdAlt] && bJmp && tt_CalcPosDef(iDim) > iMax - 16)
			iX = tt_PosAlt(iDim);
		else
			iX = tt_PosDef(iDim);
	}
	else
	{
		iX = iMus;
		if(tt_aV[cmdAlt])
			iX -= cx + tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
		else
			iX += tt_aV[cmdOff];
	}
	// Prevent tip from extending past clientarea boundary
	if(iX > iMax)
		iX = bJmpMod ? tt_PosAlt(iDim) : iMax;
	// In case of insufficient space on both sides, ensure the left/upper part
	// of the tip be visible
	if(iX < iScrl)
		iX = bJmpMod ? tt_PosDef(iDim) : iScrl;
	return iX;
}
function tt_PosDef(iDim)
{
	if(iDim)
		tt_bJmpVert = tt_aV[ABOVE];
	else
		tt_bJmpHorz = tt_aV[LEFT];
	return tt_CalcPosDef(iDim);
}
function tt_PosAlt(iDim)
{
	if(iDim)
		tt_bJmpVert = !tt_aV[ABOVE];
	else
		tt_bJmpHorz = !tt_aV[LEFT];
	return tt_CalcPosAlt(iDim);
}
function tt_CalcPosDef(iDim)
{
	return iDim ? (tt_musY + tt_aV[OFFSETY]) : (tt_musX + tt_aV[OFFSETX]);
}
function tt_CalcPosAlt(iDim)
{
	var cmdOff = iDim ? OFFSETY : OFFSETX;
	var dx = tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0);
	if(tt_aV[cmdOff] > 0 && dx <= 0)
		dx = 1;
	return((iDim ? (tt_musY - tt_h) : (tt_musX - tt_w)) - dx);
}
function tt_PosFix()
{
	var iX, iY;

	if(typeof(tt_aV[FIX][0]) == "number")
	{
		iX = tt_aV[FIX][0];
		iY = tt_aV[FIX][1];
	}
	else
	{
		if(typeof(tt_aV[FIX][0]) == "string")
			el = tt_GetElt(tt_aV[FIX][0]);
		// First slot in array is direct reference to HTML element
		else
			el = tt_aV[FIX][0];
		iX = tt_aV[FIX][1];
		iY = tt_aV[FIX][2];
		// By default, vert pos is related to bottom edge of HTML element
		if(!tt_aV[ABOVE] && el)
			iY += tt_GetDivH(el);
		for(; el; el = el.offsetParent)
		{
			iX += el.offsetLeft || 0;
			iY += el.offsetTop || 0;
		}
	}
	// For a fixed tip positioned above the mouse, use the bottom edge as anchor
	// (recommended by Christophe Rebeschini, 31.1.2008)
	if(tt_aV[ABOVE])
		iY -= tt_h;
	tt_SetTipPos(iX, iY);
}
function tt_Fade(a, now, z, n)
{
	if(n)
	{
		now += Math.round((z - now) / n);
		if((z > a) ? (now >= z) : (now <= z))
			now = z;
		else
			tt_tFade.Timer(
				"tt_Fade("
				+ a + "," + now + "," + z + "," + (n - 1)
				+ ")",
				tt_aV[FADEINTERVAL],
				true
			);
	}
	now ? tt_SetTipOpa(now) : tt_Hide();
}
function tt_SetTipOpa(opa)
{
	// To circumvent the opacity nesting flaws of IE, we set the opacity
	// for each sub-DIV separately, rather than for the container DIV.
	tt_SetOpa(tt_aElt[5], opa);
	if(tt_aElt[1])
		tt_SetOpa(tt_aElt[1], opa);
	if(tt_aV[SHADOW])
	{
		opa = Math.round(opa * 0.8);
		tt_SetOpa(tt_aElt[7], opa);
		tt_SetOpa(tt_aElt[8], opa);
	}
}
function tt_OnCloseBtnOver(iOver)
{
	var css = tt_aElt[4].style;

	iOver <<= 1;
	css.background = tt_aV[CLOSEBTNCOLORS][iOver];
	css.color = tt_aV[CLOSEBTNCOLORS][iOver + 1];
}
function tt_OnLClick(e)
{
	//  Ignore right-clicks
	e = e || window.event;
	if(!((e.button && e.button & 2) || (e.which && e.which == 3)))
	{
		if(tt_aV[CLICKSTICKY] && (tt_iState & 0x4))
		{
			tt_aV[STICKY] = true;
			tt_iState &= ~0x4;
		}
		else if(tt_aV[CLICKCLOSE])
			tt_HideInit();
	}
}
function tt_Int(x)
{
	var y;

	return(isNaN(y = parseInt(x)) ? 0 : y);
}
Number.prototype.Timer = function(s, iT, bUrge)
{
	if(!this.value || bUrge)
		this.value = window.setTimeout(s, iT);
}
Number.prototype.EndTimer = function()
{
	if(this.value)
	{
		window.clearTimeout(this.value);
		this.value = 0;
	}
}
function tt_GetWndCliSiz(s)
{
	var db, y = window["inner" + s], sC = "client" + s, sN = "number";
	if(typeof y == sN)
	{
		var y2;
		return(
			// Gecko or Opera with scrollbar
			// ... quirks mode
			((db = document.body) && typeof(y2 = db[sC]) == sN && y2 &&  y2 <= y) ? y2 
			// ... strict mode
			: ((db = document.documentElement) && typeof(y2 = db[sC]) == sN && y2 && y2 <= y) ? y2
			// No scrollbar, or clientarea size == 0, or other browser (KHTML etc.)
			: y
		);
	}
	// IE
	return(
		// document.documentElement.client+s functional, returns > 0
		((db = document.documentElement) && (y = db[sC])) ? y
		// ... not functional, in which case document.body.client+s 
		// is the clientarea size, fortunately
		: document.body[sC]
	);
}
function tt_SetOpa(el, opa)
{
	var css = el.style;

	tt_opa = opa;
	if(tt_flagOpa == 1)
	{
		if(opa < 100)
		{
			// Hacks for bugs of IE:
			// 1.) Once a CSS filter has been applied, fonts are no longer
			// anti-aliased, so we store the previous 'non-filter' to be
			// able to restore it
			if(typeof(el.filtNo) == tt_u)
				el.filtNo = css.filter;
			// 2.) A DIV cannot be made visible in a single step if an
			// opacity < 100 has been applied while the DIV was hidden
			var bVis = css.visibility != "hidden";
			// 3.) In IE6, applying an opacity < 100 has no effect if the
			//	   element has no layout (position, size, zoom, ...)
			css.zoom = "100%";
			if(!bVis)
				css.visibility = "visible";
			css.filter = "alpha(opacity=" + opa + ")";
			if(!bVis)
				css.visibility = "hidden";
		}
		else if(typeof(el.filtNo) != tt_u)
			// Restore 'non-filter'
			css.filter = el.filtNo;
	}
	else
	{
		opa /= 100.0;
		switch(tt_flagOpa)
		{
		case 2:
			css.KhtmlOpacity = opa; break;
		case 3:
			css.KHTMLOpacity = opa; break;
		case 4:
			css.MozOpacity = opa; break;
		case 5:
			css.opacity = opa; break;
		}
	}
}
function tt_Err(sErr, bIfDebug)
{
	if(tt_Debug || !bIfDebug)
		alert("Tooltip Script Error Message:\n\n" + sErr);
}

//============  EXTENSION (PLUGIN) MANAGER  ===============//
function tt_ExtCmdEnum()
{
	var s;

	// Add new command(s) to the commands enum
	for(var i in config)
	{
		s = "window." + i.toString().toUpperCase();
		if(eval("typeof(" + s + ") == tt_u"))
		{
			eval(s + " = " + tt_aV.length);
			tt_aV[tt_aV.length] = null;
		}
	}
}
function tt_ExtCallFncs(arg, sFnc)
{
	var b = false;
	for(var i = tt_aExt.length; i;)
	{--i;
		var fnc = tt_aExt[i]["On" + sFnc];
		// Call the method the extension has defined for this event
		if(fnc && fnc(arg))
			b = true;
	}
	return b;
}

tt_Init();

 // Help info for order-game-server
help_add( 'gameserver-swappable', 'What are Swappable Games?', 'Swappable games enable you to change the game your server runs at any time.<br \/>\n<br \/>\n<b>Note<\/b>: This does not allow you to run multiple servers. If you want to run multiple servers you will need to order more than one server or look at our dedicated servers.' );
help_add( 'gameserver-default_mod', 'What is the Default Game?', 'The default game is the game which your server will run when it is first setup. You can still swap between any of the games ordered using Clanforge&trade; once it is running.' );
help_add( 'gameserver-server_name', 'What is the Server Name?', 'The server name is the name which your server will display as in the server list when it is first setup. You can change this at any time using Clanforge&trade; once it is running.' );
help_add( 'gameserver-public', 'What is the Server Type?', 'The server type is either Public or Private.\n<ul class="tip">\n<li>Public servers are not passworded by default but a password can be set at any time.<li>\n<li>Private servers are passworded so players must know the password to join your server<\/li>\n<\/ul>' );
help_add( 'gameserver-branding', 'What is Branding?', 'The Branding option determines if you can freely change various aspects of your server.<br \/>\nThese aspects include:-\n<ul class="tip">\n<li>Server Name (must include Multiplay.co.uk for branded servers)<\/li>\n<li>Server Banners (fixed for branded servers)<\/li>\n<li>Server Graphics (fixed for branded servers)<\/li>\n<\/ul>\n\nIf you choose the debranded option then you can change all of these items at any time.' );
help_add( 'gameserver-voicecomms', 'What are the Voice Comms Options?', 'The Voice Comms options allow you to select a voice comms server to setup with game server.<br \/>\n<br \/>\nThere are three options:-\n<ul>\n<li class="m0">Mumble - FREE up to game server slots, then 50% Off additional slots<\/li>\n<li class="m0">Ventrilo - 50% Off<\/li>\n<li class="m0">Teamspeak 2 - 50% Off (including 25% Free slotSCALE slots)<\/li>\n<\/ul>' );
help_add( 'order-location', 'What is Location?', 'Location determines where your server will be physically setup.<br \/>\n\nBy default this is automatic which will try to choose the datacenter closest to your location so you get the best ping to your server.<br \/>\n\nYou may wish to change this if most of your clan mates play from another country.<br \/>' );
help_add( 'order-paymentterm', 'What is the Renewal Period?', 'The renewal period determines how many months you pay for initially and each time your server is renewed.<br \/>\n<br \/>\nThe longer the term you pay for in advance the higher the discount.' );
help_add( 'voicecomms-server-type', 'What is the Server Type?', 'The Server Type determines whether you wish to use Ventrillo or Teamspeak 2. This can be changed in Clanforge&trade; at any time.' );
help_add( 'voicecomms-player-slots', 'What are Voice Comms Player Slots?', 'The Voice Comms player slots is the maximum number of people that can connect to your Voice Comms server at any one time.' );
help_add( 'voicecomms-slotscale', 'What is slotSCALE?', 'slotSCALE is an advanced technology developed by Multiplay to enable you to use up to 125% of the slots that you pay for. It dynamically adjusts the size of the server on the fly so there are always slots available for players to join up to the 125% limit.' );
help_add( 'dedicated-server-type', 'What is the Server Type?', 'The Server Type determines which type of machine you order to run your game servers on.' );
help_add( 'dedicated-os', 'What is the Operating System?', 'The Operating System is the software which runs your dedicated server and allows you to run servers.<br \/>\nNote: Some game servers run better on certain Operating Systems so ensure you select the best one for the games you want to play.' );
help_add( 'dedicated-voicecomms', 'What is the Voice Comms Server?', 'Each Multiplay dedicated server comes with the ablity to have a FREE Voice Comms server hosted on one of our dedicated Voice Comms machines, ensuring all of the power of your dedicated server is available to run your game servers.' );
help_add( 'dedicated-managed', 'What does Managed Mean?', 'A Managed dedicated server is one that uses Multiplay&#039;s Clanforge&trade; control panel to create, update and run all your game servers on your dedicated server.' );
help_add( 'voicecomms-server_name', 'What is the Server Name?', 'The server name is the name which your server will display as in the server list when its first setup. You can change this at any time using Clanforge&trade; once it is running.' );
help_add( 'order-voucher', 'What is a Voucher or Referral Code?', 'From time to time we run promotions which may require you to enter a code to get an extra discount on your order.\n\nAlternatively if you have a Multiplay Game Server you can setup referral codes for your friends to enter here, which could save both of you money!\n\nEither way, if you have a code, pop it in this box (if it&#039;s not there already) and enjoy an additional discount!' );
help_add( 'gameserver-max_memory', 'What does the Memory Option mean?', 'Larger amounts of memory can help your server run more smoothly with large amounts of players, large maps \/ worlds or many server addons<br \/>\n<br \/>\nBy default the minimum amount of memory required for the amount of players is selected.<br \/>\n<br \/>\nYou may wish to increase this if you know that your server will run large maps, many server addons or because you want better performance<br \/>' );
  

// Base Init
var aCurrencyConversionIndexes = [];
var aLocations = [];
var aVouchers = [];

var sDefaultCurrency = 'USD';
aCurrencyConversionIndexes["GBP-EUR"] = new CurrencyConversionIndex( "GBP", "EUR", 1.15 );
aCurrencyConversionIndexes["GBP-USD"] = new CurrencyConversionIndex( "GBP", "USD", 1.6 );
aCurrencyConversionIndexes["GBP-GBP"] = new CurrencyConversionIndex( "GBP", "GBP", 1 );
aLocations[8] = new Location( 8, 'Amsterdam', 'NL', 'Netherlands' );
aLocations[29] = new Location( 29, 'Atlanta - Georgia', 'US', 'US' );
aLocations[16] = new Location( 16, 'Chicago - Illinois', 'US', 'US' );
aLocations[17] = new Location( 17, 'Frankfurt', 'DE', 'Germany' );
aLocations[12] = new Location( 12, 'Herndon - Virginia', 'US', 'US' );
aLocations[18] = new Location( 18, 'Hudiksvall', 'SE', 'Sweden' );
aLocations[3] = new Location( 3, 'London', 'GB', 'UK' );
aLocations[6] = new Location( 6, 'Los Angeles - California', 'US', 'US' );
aLocations[24] = new Location( 24, 'Milan', 'IT', 'Italy' );
aLocations[21] = new Location( 21, 'Moscow', 'RU', 'Russia' );
aLocations[27] = new Location( 27, 'New York - New York', 'US', 'US' );
aLocations[19] = new Location( 19, 'Paris', 'FR', 'France' );
aLocations[13] = new Location( 13, 'San Antonio - Texas', 'US', 'US' );
aLocations[28] = new Location( 28, 'Seattle - Washington', 'US', 'US' );
aLocations[32] = new Location( 32, 'Singapore', 'SG', 'Singapore' );
aLocations[22] = new Location( 22, 'St. Louis - Missouri', 'US', 'US' );
aLocations[23] = new Location( 23, 'Sydney', 'AU', 'Australia' );
aLocations[25] = new Location( 25, 'Toronto', 'CA', 'Canada' );
aVouchers[416] = new Voucher( 416, "50% Off voice comms!", 'vc50pctoff', "A massive 50% off all Voice Comms servers!<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.50, 1 );
aVouchers[416].addValidProduct( 'VoiceComm', 0, 0, 0 );
aVouchers[1141] = new Voucher( 1141, "25% Off Minecraft", 'mc25pct', "25% off new orders- sssssssssssssssssshhh *boom*<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.25, 1 );
aVouchers[1141].addValidProduct( 'Clanserver', 65, 0, 12 );
aVouchers[1141].addValidProduct( 'Clanserver', 65, 0, 3 );
aVouchers[1141].addValidProduct( 'Clanserver', 65, 0, 6 );
aVouchers[2364] = new Voucher( 2364, "$1\/slot for US BF3 Orders!", 'bf3usa', "To celebrate the launch of Battlefield 3 servers, we are offering pre-orders in the US for just $1 per slot!<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.38, 1 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 13, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 25, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 28, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 29, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 6, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 16, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 29, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 27, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 12, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 22, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 27, 0 );
aVouchers[2364].addValidProduct( 'Clanserver', 69, 28, 0 );
aVouchers[2448] = new Voucher( 2448, "10% off BF3 Servers for 1 month", 'bf3-1month', "For all pre-orders we are offering 10% off for one month. Order for longer to get a larger discount!<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.10, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 17, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 21, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 3, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 18, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 32, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 23, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 8, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 19, 1 );
aVouchers[2448].addValidProduct( 'Clanserver', 69, 24, 1 );
aVouchers[2449] = new Voucher( 2449, "20% off BF3 Servers for 3 months", 'bf3-3month', "For all pre-orders we are offering 20% off for 3 months. Order for longer to get a larger discount!<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.20, 1 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 3, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 18, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 23, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 8, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 19, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 24, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 32, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 17, 3 );
aVouchers[2449].addValidProduct( 'Clanserver', 69, 21, 3 );
aVouchers[2450] = new Voucher( 2450, "25% off BF3 Servers for 6 months", 'bf3-6month', "For all pre-orders we are offering 25% off for 6 months. Order for longer to get a larger discount!<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.25, 1 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 18, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 23, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 32, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 8, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 19, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 24, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 17, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 21, 6 );
aVouchers[2450].addValidProduct( 'Clanserver', 69, 3, 6 );
aVouchers[2451] = new Voucher( 2451, "30% off BF3 Servers for 12 months", 'bf3-12month', "For all pre-orders we are offering a massive 30% off for 12 months!<br \/>This voucher overrides any discount for payment period.", 'percentage', 0.30, 1 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 8, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 19, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 24, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 17, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 21, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 32, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 3, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 18, 12 );
aVouchers[2451].addValidProduct( 'Clanserver', 69, 23, 12 );
var bAutoVoucher = false;

// Voice Comms Service Init
oService = new VoiceCommsService( 11, 'Voice Comm Server', 0.00, 0.00 );
oService.addServerType( 409, '158', 'Mumble', 0.0000, 0.0000 );
oService.addServerType( 413, '182', 'Teamspeak 3', 0.0000, 0.0000 );
oService.addServerType( 61, '50', 'Ventrilo', 0.0000, 0.0000 );
oService.addServerType( 60, '55', 'Teamspeak 2', 0.0000, 0.0000 );
oService.addSlotOption( 60, 10, 35, 5, 22.9167, 27.5000 );
oService.addSlotOption( 413, 10, 35, 5, 22.9167, 27.5000 );
oService.addSlotOption( 61, 10, 35, 5, 20.8333, 25.0000 );
oService.addSlotOption( 62, 10, 128, 1, 20.8333, 25.0000 );
oService.addSlotOption( 409, 10, 20, 5, 9.1667, 11.0000 );
oService.addSlotOption( 409, 25, 30, 5, 7.5000, 9.0000 );
oService.addSlotOption( 409, 35, 50, 15, 7.5000, 9.0000 );
oService.addSlotOption( 60, 50, 75, 25, 20.8333, 25.0000 );
oService.addSlotOption( 413, 50, 75, 25, 20.8333, 25.0000 );
oService.addSlotOption( 61, 50, 75, 25, 18.3333, 22.0000 );
oService.addSlotOption( 409, 75, 100, 25, 7.5000, 9.0000 );
oService.addSlotOption( 60, 100, 100, 1, 19.7917, 23.7500 );
oService.addSlotOption( 413, 100, 100, 1, 19.7917, 23.7500 );
oService.addSlotOption( 61, 100, 100, 1, 16.6667, 20.0000 );
oService.addSlotOption( 60, 150, 150, 1, 18.7500, 22.5000 );
oService.addSlotOption( 413, 150, 150, 1, 18.7500, 22.5000 );
oService.addSlotOption( 61, 150, 150, 1, 15.8333, 19.0000 );
oService.addSlotOption( 409, 150, 400, 50, 6.6667, 8.0000 );
oService.addSlotOption( 60, 200, 400, 50, 17.7083, 21.2500 );
oService.addSlotOption( 413, 200, 400, 50, 17.7083, 21.2500 );
oService.addSlotOption( 61, 200, 400, 50, 15.0000, 18.0000 );
oService.addPaymentTerm( 1, 0.00 );
oService.addPaymentTerm( 3, 0.10 );
oService.addPaymentTerm( 12, 0.20 );
oService.addPaymentTerm( 6, 0.15 );

function sortTypeByName( a, b )
{
	if ( a.name == b.name )
	{
		return 0;
	}
	return ( a.name > b.name ) ? -1 : 1;
}

function init_page( iProductId, iServiceOptionId, iSlots )
{
	// Avoid FireFox Gayness
	document.getElementById( "actionForm" ).reset();

	// Populate server_typeid select box
	var oServerTypeSelect = document.getElementById( "server_typeid" );
	var j = 0;
	var aSortedTypes = oService.serverTypes.slice(); // Create a copy as serverTypes order is important
	aSortedTypes.sort( sortTypeByName );
	for ( var i in aSortedTypes )
	{
		var oServerType = aSortedTypes[i];
		var bSelected = ( iServiceOptionId == oServerType.service_optionid ) ? true : false;
		oServerTypeSelect[j++] = new Option( oServerType.name, oServerType.service_optionid, bSelected, bSelected );
	}

	// Setup Type
	update_server_typeid( iSlots );

	// Setup slotSCALE
	update_vc_slots();

	// Default to London
	update_locationid();

	// Set the Payment Term
	update_paymentterm();

	// Validate the voucher code
	update_voucher_code( true );

	// Load help
	help_load();

	return true;
} 

function update_server_typeid( iSlotsWanted )
{
	// Update the Type
	var iServiceOptionId = parseInt( select_value( "server_typeid" ) );
	oService.setServerType( iServiceOptionId );

	// Populate vc_slots select box
	var oMaxClients = document.getElementById( "vc_slots" );
	var iSlotsSelected = ( iSlotsWanted ) ? iSlotsWanted : oService.available_slots;
	var aSlots = oService.getSlots();
	var j = 0;

	for ( var i = 0; i < aSlots.length; i++ )
	{
		var iSlots = aSlots[i];
		var bSelected = ( iSlotsSelected == iSlots ) ? true : false;
		oMaxClients.options[j++] = new Option( iSlots + " Slots", iSlots, bSelected, bSelected );
	}

	// Remove overflow
	while ( oMaxClients.options.length > j )
	{
		oMaxClients.options[j] = null;
	}

	update_option( "server_typeid" );

	// Server Type details
	var oIcon = document.getElementById( "game-cart-server_typeid-icon" );
	var iProductId = 0;
	// TODO: remove the hard coding for setProduct calls
	switch ( iServiceOptionId )
	{
	case 60:
		// TeamSpeak
		set_slot_scale( true );

		// TODO: pull from DB
		oIcon.src = "/images/icons/games/ts_on.png";
		oIcon.title = "Teamspeak 2";
		oService.setProduct( 2 );

		break;

	case 413:
		// TeamSpeak 3
		set_slot_scale( true );

		// TODO: pull from DB
		oIcon.src = "/images/icons/games/ts3_on.png";
		oIcon.title = "Teamspeak 3";
		oService.setProduct( 4 );

		break;

	case 61:
		// Ventrilo
		set_slot_scale( false );

		// TODO: pull from DB
		oIcon.src = "/images/icons/games/ven_on.png";
		oIcon.title = "Ventrilo";
		oService.setProduct( 1 );

		break;

	case 409:
		// Mumble
		set_slot_scale( false );

		// TODO: pull from DB
		oIcon.src = "/images/icons/games/mumble_on.png";
		oIcon.title = "Mumble";
		oService.setProduct( 3 );

		break;

	default:
		alert( "Unknown service type:" + iServiceOptionId );

		return false;
	}
	update_vc_slots();

	check_auto_voucher();

	return update_price();
}

function set_slot_scale( bEnabled )
{
	var oDynamicSlotsDisplay = document.getElementById( "game-cart-dynamic_slots-display" );
	var oDynamicSlotsAction = document.getElementById( "game-cart-dynamic_slots-action" );
	var oDynamicSlotsSelect = document.getElementById( "dynamic_slots" );
	if ( bEnabled )
	{
		oDynamicSlotsDisplay.href = "";
		oDynamicSlotsDisplay.className = "disabled";
		oDynamicSlotsDisplay.onclick = function () { return false };
		oDynamicSlotsAction.style.display = "none";
		oDynamicSlotsSelect.selectedIndex = 0;
	}
	else
	{
		oDynamicSlotsDisplay.href = "";
		oDynamicSlotsDisplay.className = "disabled";
		oDynamicSlotsDisplay.onclick = function () { return false };
		oDynamicSlotsDisplay.innerHTML = "Not Available";
		oDynamicSlotsAction.style.display = "none";
		oDynamicSlotsSelect.selectedIndex = 1;
	}

	update_option( "dynamic_slots" );

	oService.bDynamicSlots = bEnabled;

	return true;
}

function update_vc_slots()
{
	var iAvailableSlots = update_option( "vc_slots" );
	var iDynamicSlots = select_value( "dynamic_slots" );
	var oSlotsDisplay = document.getElementById( "game-cart-vc_slots-display" );
	var oFreeEdit = document.getElementById( "game-cart-vc_slots-free" );
	var oMaxClientsReal = document.getElementById( "vc_slots_real" );

	if ( oService.bDynamicSlots )
	{
		var iFreeSlots = iAvailableSlots - parseInt( iAvailableSlots / 1.25 );
		var iSlots = iAvailableSlots - iFreeSlots;
		var sFreeSlots = " ( includes " + iFreeSlots + " FREE slotSCALE Slots )";
		oSlotsDisplay.innerHTML = iAvailableSlots + " Slots" + sFreeSlots;
		oFreeEdit.innerHTML = sFreeSlots;
		oService.setSlots( iSlots, iAvailableSlots );
		oMaxClientsReal.value = iSlots;
	}
	else
	{
		oSlotsDisplay.innerHTML = iAvailableSlots + " Slots";
		oFreeEdit.innerHTML = "";
		oService.setSlots( iAvailableSlots, iAvailableSlots );
		oMaxClientsReal.value = iAvailableSlots;
	}

	return update_price();
}

function update_dynamic_slots()
{
	oService.bDynamicSlots = ( "1" == update_option( "dynamic_slots" ) ) ? true : false;

	// Update Slots
	update_vc_slots();

	return update_price();
}

function update_server_name()
{
	update_option( 'server_name' );

	return update_price();
}

function update_price()
{
	var iTotalCost = oService.cost();
	var iBaseCost = iTotalCost + oService.discount_cost;

	document.getElementById( "running_total" ).innerHTML = format_currency( iTotalCost );
	document.getElementById( "est-eur" ).innerHTML = format_currency( iTotalCost, 'EUR' );
	document.getElementById( "est-usd" ).innerHTML = format_currency( iTotalCost, 'USD' );
	if ( is_native_currency() )
	{
		document.getElementById( "game-cart-cost-billable" ).style.display = '';
		document.getElementById( "amount-gbp" ).innerHTML = format_currency( iTotalCost, 'GBP' );
	}

	// Server Type
	display_price( "game-cart-server_typeid-cost", oService.base_cost, "FREE" );

	// Slots
	display_price( "game-cart-vc_slots-cost", oService.slots_cost, "FREE" );

	// Discount
	display_price( "game-cart-paymentterm-cost", oService.discount_cost, 0, true );

	// Payment Term
	if ( oService.payment_term > 1 )
	{
		document.getElementById( "total_text" ).innerHTML = oService.payment_term + " Month Prepay Total " + ( ( is_native_currency() ) ? ' (approx) <span class="sup">(1)</span>' : '' );
		document.getElementById( "em_monthly" ).innerHTML = format_currency( iTotalCost / oService.payment_term );
	}
	else
	{
		document.getElementById( "total_text" ).innerHTML = "Monthly Total " + ( ( is_native_currency() ) ? ' (approx) <span class="sup">(1)</span>' : '' );
	}

	document.getElementById( "checkout_total" ).innerHTML = format_currency( iTotalCost );

	// Discount
	document.getElementById( "game-cart-cost-equiv" ).style.display = ( oService.discount_cost > 0 || oService.payment_term > 1 ) ? "" : "none";

	// Voucher
	display_price( "game-cart-voucher-cost",  oService.voucher_cost, 0, true );

	// TODO: Add Update of swappable-cost-bottom, swappable-cost-top?

	return true;
}

function checkout()
{
	// Check we have no outstanding edits
	for ( var i in aOptions )
	{
		if ( "" == document.getElementById( 'game-cart-' + aOptions[i] + '-edit' ).style.display )
		{
			// Item is still being edited, warn and abort
			alert( "Please confirm your edit before proceeding!" );

			return cancel_href();
		}
	}

	var oForm = document.getElementById( "actionForm" );
	gaTrack( oForm );
	oForm.submit();

	return cancel_href();
}

// vim: set ts=4 sw=4 filetype=javascript:

