// Define AJAX_XML_Builder the browser we have instead of multiple calls throughout the file
var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = ((userAgent.indexOf('opera') != -1) || (typeof(window.opera) != 'undefined'));
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == 'Apple Computer, Inc.'));
var is_webtv  = (userAgent.indexOf('webtv') != -1);
var is_ie     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv));
var is_ie4    = ((is_ie) && (userAgent.indexOf('msie 4.') != -1));
var is_moz    = ((navigator.product == 'Gecko') && (!is_saf));
var is_kon    = (userAgent.indexOf('konqueror') != -1);
var is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4    = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_mac    = (userAgent.indexOf('mac') != -1);

// Catch possible bugs with WebTV and other older browsers
var is_regexp = (window.RegExp) ? true : false;

// Is the visiting browser compatible with AJAX?
var AJAX_Compatible = false;

// Help out old versions of IE that don't understand element.style.cursor = 'pointer'
var pointer_cursor = (is_ie ? 'hand' : 'pointer');

// #############################################################################
// AJAX_Handler
// #############################################################################

/**
* XML Sender Class
*
* @param	boolean	Should connections be asyncronous?
*/
function AJAX_Handler(async)
{
	/**
	* Should connections be asynchronous?
	*
	* @var	boolean
	*/
	this.async = async ? true : false;
}

// =============================================================================
// AJAX_Handler methods

/**
* Initializes the XML handler
*
* @return	boolean	True if handler created OK
*/
AJAX_Handler.prototype.init = function()
{
	if (typeof disable_ajax != 'undefined' && disable_ajax == 2)
	{
		// disable all ajax features
		return false;
	}

	try
	{
		this.handler = new XMLHttpRequest();
		return (this.handler.setRequestHeader ? true : false);
	}
	catch(e)
	{
		try
		{
			this.handler = eval("new A" + "ctiv" + "eX" + "Ob" + "ject('Micr" + "osoft.XM" + "LHTTP');");
			return true;
		}
		catch(e)
		{
			return false;
		}
	}
}

/**
* Detects if the browser is fully compatible
*
* @return	boolean
*/
AJAX_Handler.prototype.is_compatible = function()
{
	if (typeof disable_ajax != 'undefined' && disable_ajax == 2)
	{
		// disable all ajax features
		return false;
	}

	if (is_ie && !is_ie4) { return true; }
	else if (typeof XMLHttpRequest != 'undefined')
	{
		try { return XMLHttpRequest.prototype.setRequestHeader ? true : false; }
		catch(e)
		{
			try { var tester = new XMLHttpRequest(); return tester.setRequestHeader ? true : false; }
			catch(e) { return false; }
		}
	}
	else { return false; }
}

/**
* Checks if the system is ready
*
* @return	boolean	False if ready
*/
AJAX_Handler.prototype.not_ready = function()
{
	return (this.handler.readyState && (this.handler.readyState < 4));
}

/**
* OnReadyStateChange event handler
*
* @param	function
*/
AJAX_Handler.prototype.onreadystatechange = function(event)
{
	if (!this.handler)
	{
		if  (!this.init())
		{
			return false;
		}
	}
	if (typeof event == 'function')
	{
		this.handler.onreadystatechange = event;
	}
	else
	{
		alert('XML Sender OnReadyState event is not a function');
	}
}

/**
* Sends data
*
* @param	string	Destination URL
* @param	string	Request Data
*
* @return	mixed	Return message
*/
AJAX_Handler.prototype.send = function(desturl, datastream)
{
	if (!this.handler)
	{
		if (!this.init())
		{
			return false;
		}
	}
	if (!this.not_ready())
	{
		this.handler.open('POST', desturl, this.async);
		this.handler.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		this.handler.send(datastream);

		if (!this.async && this.handler.readyState == 4 && this.handler.status == 200)
		{
			return true;
		}
	}
	return false;
}

/**
* Fetches the contents of an XML node
*
* @param	object	XML node
*
* @return	string	XML node contents
*/
AJAX_Handler.prototype.fetch_data = function(xml_node)
{
	if (xml_node && xml_node.firstChild && xml_node.firstChild.nodeValue)
	{
		return PHP.unescape_cdata(xml_node.firstChild.nodeValue);
	}
	else
	{
		return '';
	}
}

// we can check this variable to see if browser is AJAX compatible
var AJAX_Compatible = AJAX_Handler.prototype.is_compatible();

// #############################################################################
// vB_PHP_Emulator class
// #############################################################################

/**
* PHP Function Emulator Class
*/
function vB_PHP_Emulator()
{
}

// =============================================================================
// vB_PHP_Emulator Methods

/**
* Find a string within a string (case insensitive)
*
* @param	string	Haystack
* @param	string	Needle
* @param	integer	Offset
*
* @return	mixed	Not found: false / Found: integer position
*/
vB_PHP_Emulator.prototype.stripos = function(haystack, needle, offset)
{
	if (typeof offset == 'undefined')
	{
		offset = 0;
	}

	index = haystack.toLowerCase().indexOf(needle.toLowerCase(), offset);

	return (index == -1 ? false : index);
}

/**
* Trims leading whitespace
*
* @param	string	String to trim
*
* @return	string
*/
vB_PHP_Emulator.prototype.ltrim = function(str)
{
	return str.replace(/^\s+/g, '');
}

/**
* Trims trailing whitespace
*
* @param	string	String to trim
*
* @return	string
*/
vB_PHP_Emulator.prototype.rtrim = function(str)
{
	return str.replace(/(\s+)$/g, '');
}

/**
* Trims leading and trailing whitespace
*
* @param	string	String to trim
*
* @return	string
*/
vB_PHP_Emulator.prototype.trim = function(str)
{
	return this.ltrim(this.rtrim(str));
}

/**
* Emulation of PHP's preg_quote()
*
* @param	string	String to process
*
* @return	string
*/
vB_PHP_Emulator.prototype.preg_quote = function(str)
{
	// replace + { } ( ) [ ] | / ? ^ $ \ . = ! < > : * with backslash+character
	return str.replace(/(\+|\{|\}|\(|\)|\[|\]|\||\/|\?|\^|\$|\\|\.|\=|\!|\<|\>|\:|\*)/g, "\\$1");
}

/**
* Emulates unhtmlspecialchars in vBulletin
*
* @param	string	String to process
*
* @return	string
*/
vB_PHP_Emulator.prototype.unhtmlspecialchars = function(str)
{
	f = new Array(/&lt;/g, /&gt;/g, /&quot;/g, /&amp;/g);
	r = new Array('<', '>', '"', '&');

	for (var i in f)
	{
		str = str.replace(f[i], r[i]);
	}

	return str;
}

/**
* Unescape CDATA from vB_AJAX_XML_Builder PHP class
*
* @param	string	Escaped CDATA
*
* @return	string
*/
vB_PHP_Emulator.prototype.unescape_cdata = function(str)
{
	var r1 = /<\=\!\=\[\=C\=D\=A\=T\=A\=\[/g;
	var r2 = /\]\=\]\=>/g;

	return str.replace(r1, '<![CDATA[').replace(r2, ']]>');
}

/**
* Emulates PHP's htmlspecialchars()
*
* @param	string	String to process
*
* @return	string
*/
vB_PHP_Emulator.prototype.htmlspecialchars = function(str)
{
	//var f = new Array(/&(?!#[0-9]+;)/g, /</g, />/g, /"/g);
	var f = new Array(
		(is_mac && is_ie ? new RegExp('&', 'g') : new RegExp('&(?!#[0-9]+;)', 'g')),
		new RegExp('<', 'g'),
		new RegExp('>', 'g'),
		new RegExp('"', 'g')
	);
	var r = new Array(
		'&amp;',
		'&lt;',
		'&gt;',
		'&quot;'
	);

	for (var i = 0; i < f.length; i++)
	{
		str = str.replace(f[i], r[i]);
	}

	return str;
}

/**
* Searches an array for a value
*
* @param	string	Needle
* @param	array	Haystack
* @param	boolean	Case insensitive
*
* @return	integer	Not found: -1 / Found: integer index
*/
vB_PHP_Emulator.prototype.in_array = function(ineedle, haystack, caseinsensitive)
{
	var needle = new String(ineedle);

	if (caseinsensitive)
	{
		needle = needle.toLowerCase();
		for (var i in haystack)
		{
			if (haystack[i].toLowerCase() == needle)
			{
				return i;
			}
		}
	}
	else
	{
		for (var i in haystack)
		{
			if (haystack[i] == needle)
			{
				return i;
			}
		}
	}
	return -1;
}

/**
* Emulates PHP's strpad()
*
* @param	string	Text to pad
* @param	integer	Length to pad
* @param	string	String with which to pad
*
* @return	string
*/
vB_PHP_Emulator.prototype.str_pad = function(text, length, padstring)
{
	text = new String(text);
	padstring = new String(padstring);

	if (text.length < length)
	{
		padtext = new String(padstring);

		while (padtext.length < (length - text.length))
		{
			padtext += padstring;
		}

		text = padtext.substr(0, (length - text.length)) + text;
	}

	return text;
}

/**
* A sort of emulation of PHP's urlencode - not 100% the same, but accomplishes the same thing
*
* @param	string	String to encode
*
* @return	string
*/
vB_PHP_Emulator.prototype.urlencode = function(text)
{
	text = text.toString();

	// this escapes 128 - 255, as JS uses the unicode code points for them.
	// This causes problems with submitting text via AJAX with the UTF-8 charset.
	var matches = text.match(/[\x90-\xFF]/g);
	if (matches)
	{
		for (var matchid = 0; matchid < matches.length; matchid++)
		{
			var char_code = matches[matchid].charCodeAt(0);
			text = text.replace(matches[matchid], '%u00' + (char_code & 0xFF).toString(16).toUpperCase());
		}
	}

	return escape(text).replace(/\+/g, "%2B");
}

/**
* Works a bit like ucfirst, but with some extra options
*
* @param	string	String with which to work
* @param	string	Cut off string before first occurence of this string
*
* @return	string
*/
vB_PHP_Emulator.prototype.ucfirst = function(str, cutoff)
{
	if (typeof cutoff != 'undefined')
	{
		var cutpos = str.indexOf(cutoff);
		if (cutpos > 0)
		{
			str = str.substr(0, cutpos);
		}
	}

	str = str.split(' ');
	for (var i = 0; i < str.length; i++)
	{
		str[i] = str[i].substr(0, 1).toUpperCase() + str[i].substr(1);
	}
	return str.join(' ');
}

// initialize the PHP emulator
var PHP = new vB_PHP_Emulator();

function fetch_object(idname)
{
	if (document.getElementById)
	{
		return document.getElementById(idname);
	}
	else if (document.all)
	{
		return document.all[idname];
	}
	else if (document.layers)
	{
		return document.layers[idname];
	}
	else
	{
		return null;
	}
}

function flip_visibility(idname, force_visibility)
{
	var obj = fetch_object(idname);
	if (!obj)
	{
		return false;
	}

	if (typeof force_visibility != 'undefined')
	{
		obj.style.display = force_visibility;
	}
	else if (obj.style.display == '')
	{
		obj.style.display = 'none';
	}
	else
	{
		obj.style.display = '';
	}

	return true;
}

/**
* Function to emulate document.getElementsByTagName
*
* @param	object	Parent object (eg: document)
* @param	string	Tag type (eg: 'td')
*
* @return	array
*/
function fetch_tags(parentobj, tag)
{
	if (parentobj == null)
	{
		return new Array();
	}
	else if (typeof parentobj.getElementsByTagName != 'undefined')
	{
		return parentobj.getElementsByTagName(tag);
	}
	else if (parentobj.all && parentobj.all.tags)
	{
		return parentobj.all.tags(tag);
	}
	else
	{
		return new Array();
	}
}

/**
* Function to count the number of tags in an object
*
* @param	object	Parent object (eg: document)
* @param	string	Tag type (eg: 'td')
*
* @return	integer
*/
function fetch_tag_count(parentobj, tag)
{
	return fetch_tags(parentobj, tag).length;
}

// *** Tab toggle
function getByID (n) { var d = window.document; if (d.getElementById) return d.getElementById(n); else if (d.all) return d.all[n]; }
function tabToggle(selectedTab, tabs) { for (var i = 0; i < tabs.length; i++) { var tabObject = getByID('tab-' + tabs[i]) ; var contentObject = getByID('panel-' + tabs[i]) ; if (tabObject && contentObject) { if (tabs[i] == selectedTab) { tabObject.className = 'current'; contentObject.style.display = 'block'; } else { tabObject.className = 'default'; contentObject.style.display = 'none'; } } } return false; }

function fetch_bulk_eligible()
{
	var amount = bulk_eligible;
	var sequence2 = 1;
	
	// Add new licenses
	if ((document.getElementById('select_suite_mobile_qty') != undefined)  &&
		(parseInt(document.getElementById('select_suite_mobile_qty').value) > 0))
	{
		amount += parseInt(document.getElementById('select_suite_mobile_qty').value);
	}
	
	if ((document.getElementById('select_forum_mobile_qty') != undefined)  &&
		(parseInt(document.getElementById('select_forum_mobile_qty').value) > 0))
	{
		amount += parseInt(document.getElementById('select_forum_mobile_qty').value);
	}

	if ((document.getElementById('select_suite_qty') != undefined)  &&
		(parseInt(document.getElementById('select_suite_qty').value) > 0))
	{
		amount += parseInt(document.getElementById('select_suite_qty').value);
	}
	
	if ((document.getElementById('select_forum_qty') != undefined)  &&
		(parseInt(document.getElementById('select_forum_qty').value) > 0))
	{
		amount += parseInt(document.getElementById('select_forum_qty').value);
	}
	
	// Add upgrades
	var options = document.getElementsByName('sel_upgrade_' + sequence2);
	for (var upgrade_amt=0; options.length; sequence2++,options=document.getElementsByName('sel_upgrade_' + sequence2))
	{
		selected = 0;
		// getting the selected radio button value
		for (var i = 0; i < options.length; i++)
		{
			if (options[i].checked) {
				selected = parseInt(options[i].value);
				break;
			}
		}
		
		if (countstowardsbulk[selected] == 1)
		{
			if (bulkapplied[sequence2] != 1)
			{
				amount++;
			}
		}
	}

	return amount;
}

function total_new()
{
	total_price = 0;
	new_suites_mobile = 0;
	new_suites = 0;
	new_forums_mobile = 0;
	new_forums = 0;
	var new_amount = fetch_bulk_eligible();
	if ((document.getElementById('select_suite_mobile_qty') != undefined)  &&
		(parseInt(document.getElementById('select_suite_mobile_qty').value) > 0))
	{
		new_suites_mobile = parseInt(document.getElementById('select_suite_mobile_qty').value);
		
	}

	if ( (document.getElementById('select_forum_mobile_qty') != undefined)  &&
		(parseInt(document.getElementById('select_forum_mobile_qty').value) > 0))
	{
		new_forums_mobile = parseInt(document.getElementById('select_forum_mobile_qty').value);
	}

	if ((document.getElementById('select_suite_qty') != undefined)  &&
		(parseInt(document.getElementById('select_suite_qty').value) > 0))
	{
		new_suites = parseInt(document.getElementById('select_suite_qty').value);
		
	}

	if ( (document.getElementById('select_forum_qty') != undefined)  &&
		(parseInt(document.getElementById('select_forum_qty').value) > 0))
	{
		new_forums = parseInt(document.getElementById('select_forum_qty').value);
	}
	
	if (new_suites_mobile > 0)
	{
		total_price += new_suites_mobile * vbsuite_mobile[new_amount];
	}
	if (new_forums_mobile > 0)
	{
		total_price += new_forums_mobile * vbforum_mobile_owned[new_amount];
	}
	if (new_suites > 0)
	{
		total_price += new_suites * vbsuite[new_amount];
	}
	if (new_forums > 0)
	{
		total_price += new_forums * vbforum_owned[new_amount];
	}
	
	total_price += total_support();

	if (document.getElementById('new_amount') != undefined)
	{
		document.getElementById('new_amount').innerHTML = formatCurrency(total_price.toFixed(2));
	}

	return total_price;
}

function total_support()
{
	support_amount = 0;

	var support_quantity = document.getElementById('support_quantity');

	var ticket_support_select = document.getElementById('ticket_support_quantity');
	if (typeof ticket_support_select != 'undefined' && ticket_support_select != null && ticket_support_select.value != '')
	{
		support_amount += ticketsupport;
	}
	else if (document.getElementById('ticketsupt') != undefined)
	{
		support_amount += ticketsupport;
	}

	if (support_quantity != undefined)
	{
		if (support_quantity.value)
		{
			support_amount += support[support_quantity.value];
		}

		// update the display for months of phone support
		var supportElement = document.getElementById('remaining_support');
		if (supportElement != undefined)
		{
			// total amount of support left with anything selected in option list
			var phoneAmount = parseInt(remaining_support);
			switch(support_quantity.value)
			{
				case '1M':
					phoneAmount += 1;
					break;
				case '6M':
					phoneAmount += 6;
					break;
				case '12M':
					phoneAmount += 12;
					break;
				default:
					break;
			}
			
			// if we have phone support remaining, display appropriate phrase
			if (phoneAmount > 0)
			{			
				document.getElementById('notifications_section').innerHTML = nonzero_support_phrase;
				var months = document.getElementById('month_amount');
				if (months != undefined)
				{
					months.innerHTML = phoneAmount + ' month(s)';
				}
			}
			// if no phone support, display a phrase to help sell phone support
			else
			{
				document.getElementById('notifications_section').innerHTML = zero_support_phrase;
			}			
		}
	}
	
	if (typeof ticket_support_select != 'undefined')
	{
		// update the display for months of ticket support
		if ($('#remaining_ticket_support').length > 0)
		{
			// total amount of support left with anything selected in option list
			var ticketAmount = parseInt(remaining_ticket_support);
			
			if (ticketAmount == -1)
			{
				document.getElementById('ticket_notifications_section').innerHTML = lifetime_ticket_phrase;
			}
			else
			{
				if (ticket_support_select.value != '')
				{
					ticketAmount += 12;
				}
				
				// if we have ticket support remaining, display appropriate phrase
				if (ticketAmount > 0)
				{			
					document.getElementById('ticket_notifications_section').innerHTML = nonzero_ticket_support_phrase;
					var ticket_months = document.getElementById('ticket_month_amount');
					if (typeof ticket_months != 'undefined')
					{
						ticket_months.innerHTML = ticketAmount + ' month(s)';
					}
				}
				// if no ticket support, display a phrase to help sell ticket support
				else
				{
					document.getElementById('ticket_notifications_section').innerHTML = zero_ticket_support_phrase;
				}
			}
		}
	}
	
	return support_amount;
}

function total_upgrades()
{
	var sequence = 1;
	var bulk_basket = fetch_bulk_eligible();
	var discount_bulk = new Array();
	var new_price = new Array();
	var options = document.getElementsByName('sel_upgrade_' + sequence);
	for (var upgrade_amt=0; options.length; sequence++,options=document.getElementsByName('sel_upgrade_' + sequence))
	{
		selected = 0;

		// getting the selected radio button value
		for (var i = 0; i < options.length; i++)
		{
			var upgradeid = parseInt(options[i].value)
			
			if (options[i].checked) {
				selected = upgradeid;
			}
			
			new_price[upgradeid] = parseFloat(document.getElementById('cost_' + sequence + '_' + selected).value);
			
			if (upgrades[upgradeid] != undefined)
			{
				if (document.getElementById('baseprice_' + sequence + '_' + upgradeid) != undefined)
				{
					discount_bulk[upgradeid] = parseFloat(document.getElementById('baseprice_' + sequence + '_' + upgradeid).value) - upgrades[upgradeid][bulk_basket];
				}
				if (document.getElementById('discounted_price_' + sequence + '_' + upgradeid) != undefined)
				{
					// Update the red discount price right next to the crossed through price
					temp_newprice = upgrades[upgradeid][bulk_basket] - parseInt(document.getElementById('discount_amt_' + sequence + '_' + upgradeid).value);
					if (temp_newprice < parseFloat(document.getElementById('baseprice_' + sequence + '_' + upgradeid).value))
					{
						new_price[upgradeid] = temp_newprice;
						document.getElementById('discounted_price_' + sequence + '_' + upgradeid).innerHTML = formatCurrency(new_price[upgradeid].toFixed(2));
						
						// strike the baseprice if we're displaying something
						document.getElementById('baseprice_display_' + sequence + '_' + upgradeid).className = 'strike';
					}
					else
					{
						document.getElementById('discounted_price_' + sequence + '_' + upgradeid).innerHTML = '';
						document.getElementById('baseprice_display_' + sequence + '_' + upgradeid).className = '';
					}
				}
			}
		}

		var total_discount = document.getElementById('total_discount_' + sequence);
		var discount_inner = document.getElementById('discount_inner_' + sequence);
		var cost = document.getElementById('cost_' + sequence);
		var label_bulkdiscount_price = document.getElementById('label_bulkdiscount_' + sequence);
		var label_bulkdiscount_price_inner = document.getElementById('label_bulkdiscount_price_' + sequence);
		if (parseInt(selected) == 0)
		{
			if (total_discount != null)
			{
				total_discount.innerHTML = '';
			}
			if (discount_inner != null)
			{
				discount_inner.innerHTML = nothing_selected;
				discount_inner.style.display = '';
			}
			if (cost != null)
			{
				cost.innerHTML = '';
			}
			if (label_bulkdiscount_price != null)
			{
				label_bulkdiscount_price.style.display = 'none';
				label_bulkdiscount_price_inner.innerHTML = '';
			}
		}
		else
		{
			upgrade_amt += parseFloat(document.getElementById('cost_' + sequence + '_' + selected).value);
			if ((parseFloat(document.getElementById('discount_amt_' + sequence + '_' + selected).value) > 0) ||
				parseFloat(discount_bulk[selected]) > 0)
			{
				var new_total_discount = parseFloat(document.getElementById('discount_amt_' + sequence + '_' + selected).value) + discount_bulk[selected];
				total_discount.innerHTML = '-' +  formatCurrency(new_total_discount.toFixed(2));
			}
			else
			{
				total_discount.innerHTML = '';
			}
			discount_inner.innerHTML = document.getElementById('discount_text_' + sequence + '_' + selected).innerHTML;
			
			discount_inner.style.display = '';
			
			// Update and show or hide the 'Bulk Discount' row in the popup
			if (discount_bulk[selected] > 0)
			{
				label_bulkdiscount_price.style.display = '';
				label_bulkdiscount_price_inner.innerHTML = formatCurrency(discount_bulk[selected].toFixed(2));
				upgrade_amt -= discount_bulk[selected];
				
				if (parseFloat(document.getElementById('discount_amt_' + sequence + '_' + selected).value) == 0)
				{
					discount_inner.style.display = 'none';
				}
			}
			else
			{
				label_bulkdiscount_price.style.display = 'none';
				label_bulkdiscount_price_inner.innerHTML = '';
			}
			cost.innerHTML = formatCurrency(new_price[selected].toFixed(2));
		}
	} // end for loop
	if (document.getElementById('upgrade-cost-subtotal') != undefined)
	{
		document.getElementById('upgrade-cost-subtotal').innerHTML = formatCurrency(upgrade_amt.toFixed(2));
	}
	return upgrade_amt;
}

function total()
{
	new_amt = total_new();

	document.getElementById('grand_total').innerHTML = formatCurrency((new_amt + total_upgrades()).toFixed(2));
}

function doOptions()
{
	i = 1;
	total = 0;
	while(document.getElementById('cb_install_' + i) != undefined)
	{
		this_total = 0;

		if (document.getElementById('cbbrand_free_' + i) != undefined
				&& document.getElementById('cbbrand_free_' + i).checked)
		{
			this_total += parseFloat(document.getElementById('upgrade_amt_' + i + '_1').value);
		}

		if (document.getElementById('cb_install_' + i).checked)
		{
			this_total += parseFloat(document.getElementById('upgrade_amt_' + i + '_2').value);
		}
		
		if (document.getElementById('cb_vbmobile_' + i) != undefined
				&& document.getElementById('cb_vbmobile_' + i).checked)
		{
			this_total += parseFloat(document.getElementById('upgrade_amt_' + i + '_3').value);
		}
		
		if (document.getElementById('cb_vbfacebook_' + i) != undefined
				&& document.getElementById('cb_vbfacebook_' + i).checked)
		{
			this_total += parseFloat(document.getElementById('upgrade_amt_' + i + '_4').value);
		}
		
		if (document.getElementById('cost_' + i))
		{
			if (this_total == 0)
			{
				document.getElementById('cost_' + i).innerHTML = no_options_selected;
			}
			else
			{
				document.getElementById('cost_' + i).innerHTML = formatCurrency(this_total.toFixed(2));
			}
		}
		total += this_total;
		i++;
	} // while
	
	document.getElementById('total_options').innerHTML = formatCurrency(total.toFixed(2));
	total += parseFloat(document.getElementById('purchase_amount').value);
	total  += total_support();
	document.getElementById('grand_total').innerHTML = formatCurrency(total.toFixed(2));
}



//This displays and hides the wire instructions
function showWire(showit)
{
	if (showit)

		{
			document.getElementById('wire_xfer_instructions').style.display = 'block';
		}
		else
		{
			document.getElementById('wire_xfer_instructions').style.display = 'none';
		}
	}

/**
* Function to format a number as currency (add commas and decimal)
*
* @param	integer the amount to be formatted
*
* @return	string
*/
function formatCurrency(amount)
{
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = amount;
	return currency_before + amount + currency_after;
}

/**
* Function to move absolutely positioned element below passed in element
*
* @param	element we want to display below
* @param	id of element we want to reposition
*/
function repositionPopup(infoElement, popupId)
{
	var popupElement = document.getElementById(popupId);
	var thepos = findPos(infoElement);
	popupElement.style.display = 'inline';
	popupElement.style.left = (thepos.x - popupElement.clientWidth - 207) + 'px';
	popupElement.style.top = (thepos.y + 16)+ 'px';
}
function hidePopup(popupId)
{
	var execStr = "document.getElementById('"+popupId+"').style.display='none'";
	setTimeout(execStr, 2000);
}
/**
* Function to return the fixed position of an element
*
* @param	element we want to display below
* @param	id of element we want to reposition
*/
function findPos(el) {for (var lx=0,ly=0;el!=null;lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);return {x:lx,y:ly}}

var removing = false;

var errors = '';

function verify_needed()
{
	if (removing)
	{
		return '';
	}
	try
	{
		errors = '';
		
		if (document.getElementById('customer-name').value == '')
		{
			errors += "Please enter your name, as shown on your card\n";
		}
		
		if (document.getElementById('customer-address').value == '')
		{
			errors += "Please enter your address, as shown on your card\n";
		}

		if (document.getElementById('customer-city').value == '')
		{
			errors += 'Please enter your city name registered with your card\n';
		}
		
		if (document.getElementById('customer-state').value == '')
		{
			errors += 'Please enter your state registered with your card\n';
		}
		
		if (document.getElementById('customer-zip').value == '')
		{
			errors += 'Please enter your postal code registered with your card\n';
		}
		
		if (document.getElementById('customer-country').value == '')
		{
			errors += 'Please enter your country as registered with your card\n';
		}
		
		if (document.getElementById('customer-email').value == '')
		{
			errors += 'Please enter your email. This is essential because it is the only way we can contact you.\n';
		}
		else
		{
			errors += emailCheck(document.getElementById('customer-email').value);
		}

		if (document.getElementById('customer-email2').value != document.getElementById('customer-email').value)
		{
			errors += 'Your two email addresses do not match. It is extremely important that they match, so please check them and make sure they are both correct.\n';
		}
		
		if (document.getElementById('customer-phone').value == '')
		{
			errors += 'Please enter a valid phone number\n';
		}
		else if (!checkInternationalPhone(document.getElementById('customer-phone').value))
		{
			
			errors += 'Please enter a valid phone number\n';
		}
		
		
	}
	catch (err)
	{
		alert(err.description);
		return false;
	}
	finally
	{
		if (errors !== '')
		{
			alert(errors);
			return false;
		}
		return true;
	}
}

/**
* DHTML email validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
edited
*/

function emailCheck(email)
{

	var atPos = email.indexOf('@');
	var atPos2 = email.indexOf('@', (atPos + 1));
	var dotPos = email.lastIndexOf('.');
	var strLen = email.length;
	
	//We need an @ that isn't at the start, a '.' that's not earlier than character 4,
	// and at least seven characters total (a@ab.uk)
	if ((atPos < 1) || (dotPos < 4) ||(strLen < 7))
	{
		return "That is not a valid E-mail Address.\n";
	}
	
	//There must be at least two characters after the dot, and
	// @ must be at least two characters before '.'
	if (dotPos > (strLen - 2) || (atPos > (dotPos - 2) ))
	{
		return "That is not a valid E-mail Address.\n";
	}
	
	//There must be only one dot and @
	if (atPos2 > -1 )
	{
		return "That is not a valid E-mail Address.\n";
	}


	//and these characters aren't allowed ()[]\;:,<> and space
	if ((email.indexOf(" ")!=-1) || (email.indexOf("(")!=-1) ||
		(email.indexOf(")")!=-1) || (email.indexOf("[")!=-1) ||
		(email.indexOf("]")!=-1) || (email.indexOf("\\")!=-1) ||
		(email.indexOf(";")!=-1) || (email.indexOf(":")!=-1) ||
		(email.indexOf(",")!=-1) || (email.indexOf("<")!=-1) ||
		(email.indexOf(">")!=-1) )
	{
		return "That is not a valid E-mail Address.\n";
	}
	
	return '';

}

/**
* DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
*/

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()-. ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
	for (i = 0; i < s.length; i++)
	{
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}
function trim(s)
{   var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not a whitespace, append to returnString.
	for (i = 0; i < s.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (c != " ") returnString += c;
	}
	return returnString;
}
function stripCharsInBag(s, bag)
{   var i;
	var returnString = "";
	// Search through string's characters one by one.
	// If character is not in bag, append to returnString.
	for (i = 0; i < s.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function checkInternationalPhone(strPhone){
	var bracket=3
	strPhone=trim(strPhone)
	if(strPhone.indexOf("+")>1) return false
	if(strPhone.indexOf("-")!=-1)bracket=bracket+1
	if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
	var brchr=strPhone.indexOf("(")
	if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+2)!=")")return false
	if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
		s=stripCharsInBag(strPhone,validWorldPhoneChars);
	return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

function showtab(tabname)
{
	$(".module-inset-panel").each(function(index) {
		if ($(this).attr('id') == "panel-" + tabname)
		{
			$(this).css("display", "inline");
		}
		else
		{
			$(this).css("display", "none");
		}
	});
	
	$(".tab").each(function(index) {
		if ($(this).attr('id') == "tab-" + tabname)
		{
			$(this).removeClass('default').addClass('current');
		}
		else
		{
			$(this).removeClass('current').addClass('default');
		}
	});
	
	if (tabname == 'creditcard')
	{
		$("#payment-button-continue").css('display', 'none');
		$("#payment-button-makepayment").css('display', 'inline');
	}
	else
	{
		$("#payment-button-continue").css('display', 'inline');
		$("#payment-button-makepayment").css('display', 'none');
	}
}

var email_format = new RegExp('^[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$', 'i');
var uszip_format = /^(\d{5})(-\d{4})?$/;
var cazip_format = /^[a-z][0-9][a-z]\s*?[0-9][a-z][0-9]$/i;

function enable_paymentbuttons()
{
	$('input.payment-button').removeClass('button-disabled').addClass('button-enabled').attr('disabled', '');
	$('input.confirm-button').removeClass('button-disabled').addClass('button-enabled').attr('disabled', '');
}

function disable_paymentbuttons()
{
	$('input.payment-button').removeClass('button-enabled').addClass('button-disabled').attr('disabled', "disabled");
	$('input.confirm-button').removeClass('button-enabled').addClass('button-disabled').attr('disabled', "disabled");
}

function check_paymentbuttonstatus()
{
	if ($("#accept_license").attr("checked") == true)
	{
		if ($("#accept_mobile").length)
		{
			if ($("#accept_mobile").attr("checked") == true)
			{
				enable_paymentbuttons();
			}
			else
			{
				disable_paymentbuttons();
			}
		}
		else
		{
			enable_paymentbuttons();
		}
	}
	else
	{
		disable_paymentbuttons();
	}
}

$(document).ready(function() {
	$("#accept_license").attr('checked', '');
	
	if ($("#accept_mobile").length)
	{
		$("#accept_mobile").attr('checked', '');
	}

	$("#accept_license").change(check_paymentbuttonstatus);
	$("#accept_mobile").change(check_paymentbuttonstatus);
	
	$("#frm_step4").submit(function(event)
	{
		var error_missingfields = false;
		var error_badzip = false;
		var error_emailformat = false;
		var error_emailverification = false;
		var error_acceptlicense = false;
		var badfields = false;

		$('.required_field_billing').each(function() {
			if ($.trim($(this).val()) == '')
			{
				$(this).addClass('highlight_input');
				badfields = true;
				error_missingfields = true;
			}
			else
			{
				$(this).removeClass('highlight_input');
				
				// Check that email has a valid format
				if ($(this).attr('id') == 'customer-email')
				{
					if (email_format.test($(this).val()) == false)
					{
						$(this).addClass('highlight_input');
						badfields = true;
						error_emailformat = true;
					}
				}
				
				// Check that emails are the same
				if ($(this).attr('id') == 'customer-email2')
				{
					if ($(this).val() != $("#customer-email").val())
					{
						$(this).addClass('highlight_input');
						badfields = true;
						error_emailverification = true;
					}
				}
				
				if ($(this).attr('id') == 'customer-zip')
				{
					if ($("#customer-country").val() == 'US')
					{
						if (uszip_format.test($(this).val()) == false)
						{
							$(this).addClass('highlight_input');
							badfields = true;
							error_badzip = true;
						}
					}
					else if ($("#customer-country").val() == 'CA')
					{
						if (cazip_format.test($(this).val()) == false)
						{
							$(this).addClass('highlight_input');
							badfields = true;
							error_badzip = true;
						}
					}
				}
			}
		});
		
		if ($('#billing-input').is(':hidden'))
		{
			if ($("#accept_license").attr("checked") == false)
			{
				badfields = true;
				error_acceptlicense = true;
			}
		
			if ($("#processor_type_0").attr('checked') == true)
			{
				$('.required_field_payment').each(function()
				{
					if ($(this).val() == '')
					{
						$(this).addClass('highlight_input');
						badfields = true;
						error_missingfields = true;
					}
				});
			}
		}
		
		if (badfields)
		{
			var alerttext = '';
			if (error_missingfields == true)
			{
				alerttext += "Please fill in all fields.\r\n";
			}
			if (error_badzip == true)
			{
				alerttext += "Please check the format of your Postal Code.\r\n";
			}
			if (error_emailformat == true)
			{
				alerttext += "Please make sure you\'re using a valid email address.\r\n";
			}
			if (error_emailverification == true)
			{
				alerttext += "Please make sure you entered the same email address in both fields.\r\n";
			}
			if (error_acceptlicense == true)
			{
				alerttext += "Please check the checkbox to confirm that you have read and accept the license agreement.\r\n";
			}
			
			alert(alerttext);
			event.preventDefault();
		}
		else if ($('#billing-text').is(':hidden'))
		{
			$('#customer-name-text').html($('#customer-name').val());
			$('#customer-address-text').html($('#customer-address').val());
			$('#customer-city-text').html($('#customer-city').val());
			$('#customer-state-text').html($('#customer-state').val());
			$('#customer-zip-text').html($('#customer-zip').val());
			$('#customer-country-text').html($('#customer-country option:selected').text());
			$('#customer-email-text').html($('#customer-email').val());
			$('#customer-phone-text').html($('#customer-phone').val());
			if ($('#customer-company').val())
			{
				var company_val = $('#customer-company').val();
			}
			else
			{
				var company_val = '&nbsp;';
			}
			$('#customer-company-text').html(company_val);
			if ($('#customer-vatid').val())
			{
				var vatid_val = $('#customer-vatid').val();
			}
			else
			{
				var vatid_val = '&nbsp;';
			}
			$('#customer-vatid-text').html(vatid_val);
			if ($('#customer-phone').val())
			{
				var phone_val = $('#customer-phone').val();
			}
			else
			{
				var phone_val = '&nbsp;';
			}
			$('#customer-phone-text').html(phone_val);
			
			$('#billing-input').hide();
			$('#billing-text').show();
			$('#payment-options').show();
			$('.accept-content').show();
			$('#payment-button-makepayment').show();
			$('#payment-button-continue').hide();
			$('#change_details_link').show();
			
			var splitFullName = $.trim($('#customer-name').val()).split(' ');
			$('#payment-cardlastname').val(splitFullName[splitFullName.length - 1]);
			splitFullName.splice(-1,1);
			$('#payment-cardfirstname').val(splitFullName.join(' '));
			
			$(window).scrollTop(0);
			window.location.hash = 'confirmed'
			
			event.preventDefault();
		}
		
	});
	
	$("#change_billing").click(function()
	{
		$('#billing-input').show();
		$('#billing-text').hide();
		$('#payment-options').hide();
		$('.accept-content').hide();
		$('#payment-button-makepayment').hide();
		$('#payment-button-continue').show();
		$('#change_details_link').hide();
		
		$(window).scrollTop(0);
		window.location.hash = ''
	});
	
	$('#tab-wiretransfer').supersleight({shim: '/clear.gif'});
	
	if (typeof showvat != 'undefined')
	{
		if (showvat)
		{
			update_vat(); // Run it at the beginning in case we're loading with any preset data
			$('#customer-country').change(update_vat);
			$('#customer-vatid').change(update_vat);
		}
	}
	
	$('.loginlink').click(function(e) {
		$(window).scrollTop(0);
		show_loginbox(e);
	});
	
	$('.continuelink').click(function(e) {
		$('#frm_purchases').submit();
	});
	
});

$("#site-registration-loginlink").live("click", show_loginbox);

function show_loginbox(event) {
	$("#site-registration").animate({height: "70px", width: "280px"});
	$("#site-registration-loginlink").css("display", "none");
	$("#site-registration-inner").animate(
		{height: "70px"},
		{duration: "normal",
			esaing: "linear",
			complete: function()
			{
				$("#site-registration-inner").removeClass('loggedout');
				$("#site-registration-loginfields").css("display", "inline");
			}
		}
	);
	event.preventDefault();
}

function update_vat()
{
	// Two possible outcomes
	// Show VAT or Don't Show VAT (show as 0)
	
	// a) Show VAT happens if the customer is in Germany, regardless of VAT ID
	// b) Or in the EU and does not have a valid VAT ID (needs AJAX call)
	
	// c) Don't Show VAT (show as 0) happens if the customer is non EU
	// d) Or if in the EU and has a valid VAT ID (needs AJAX call)
	
	if (vat_countries[$('#customer-country').val()])
	{
		if (vat_excempt[$('#customer-country').val()])
		{
			// B or D - check VAT-ID
			if ($("#customer-vatid").val() == '')
			{
				// B: Show VAT
				hide_vat(false);
			}
			else
			{
				// Need to verify VAT ID
				$.ajax({
					type: "POST",
					url: '/ajax.php',
					datatype: 'xml',
					data: "do=checkvatid&vatid=" + $("#customer-vatid").val(),
					success: function (xml) {
						if ($(xml).find('valid_vatid').text() == 'true')
						{
							// Is a valid VAT id
							hide_vat(true);
						}
						else
						{
							// Not a valid VAT id
							hide_vat(false);
						}
					}
				});
			}
		}
		else
		{
			// A - show VAT
			hide_vat(false);
		}
	}
	else
	{
		// C - don't show VAT
		hide_vat(true);
		
	}
}

function hide_vat(hide)
{
	if (hide)
	{
		$('#inverted-vat-purchaseinfo').css('display', '');
		$('#purchaseinfo').css('display', 'none');
		$('#price_total_novat').css('display', '');
		$('#vat_total_novat').css('display', '');
		$('#vat_total').css('display', 'none');
		$('#price_total').css('display', 'none');
	}
	else
	{
		$('#inverted-vat-purchaseinfo').css('display', 'none');
		$('#purchaseinfo').css('display', '');
		$('#price_total_novat').css('display', 'none');
		$('#vat_total_novat').css('display', 'none');
		$('#vat_total').css('display', '');
		$('#price_total').css('display', '');
	}
}

