var ajax_timeout = null;
var ajax_request;
var ajax_request2;

var num2 = Number.implement({
 
  /*
  Property: numberFormat
   Format a number with grouped thousands.
 
  Arguments:
   decimals, optional - integer, number of decimal percision; default, 2
   dec_point, optional - string, decimal point notation; default, '.'
   thousands_sep, optional - string, grouped thousands notation; default, ','
 
  Returns:
   a formatted version of number.
 
  Example:
   >(36432.556).numberFormat()  // returns 36,432.56
   >(36432.556).numberFormat(2, '.', ',')  // returns 36,432.56
  */
 
  numberFormat : function(decimals, dec_point, thousands_sep) {
   decimals = Math.abs(decimals) + 1 ? decimals : 2;
   dec_point = dec_point || '.';
   thousands_sep = thousands_sep || ',';
 
   var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[2] as decimals
   var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
   return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + 
     (decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
  }
 
 
 });


function GetOptionIDs(noDelay) 
{
	var str = "";

	$$('.calc_options input').each(function (el) {

		var type = el.type || el.getAttribute("type");
		var is_tickable = (String(type).match(/radio|check/i) && el.checked);
		var is_hidden = String(type).match(/hidden/i);

		if (is_tickable || is_hidden) str+= "option_id[]=" + el.value + "&"
	});

	$$('.sale_type_select input').each(function (el) {

		var type = el.type || el.getAttribute("type");
		var is_tickable = (String(type).match(/radio|check/i) && el.checked);
		var is_hidden = String(type).match(/hidden/i);

		if (is_tickable || is_hidden) str+= "sale_type=" + el.value + "&"
	});

	$$('.lamp_options input').each(function (el) {

		var type = el.type || el.getAttribute("type");
		var is_tickable = (String(type).match(/radio|check/i) && el.checked);
		var is_hidden = String(type).match(/hidden/i);

		if (is_tickable || is_hidden) str+= "lamp=" + el.value + "&"
	});


	str+= "prod_id=" + $('prod_id').value;

	if (ajax_timeout) clearTimeout(ajax_timeout);
//		ajax_timeout = setTimeout("DoPriceAjax('" + str + "')",noDelay ? 0 : 500);
	ajax_timeout = setTimeout("DoPriceAjax('" + str + "')",noDelay ? 0 : 500);

}

function DoPriceAjax(str) 
{
	$('ajax_total').innerHTML = "Calculating...";

	// do Ajax
		ajax_request.send(str);
		ajax_request2.send(str);
}


function UpdateChosenDiv(src) 
{
	// are we updating one label?
		if (String(src.getAttribute("type")).match(/radio/i))
		{
			// update name
				var span = $(src.parentNode).getElement('span.option_name');
				var dst = $(src.parentNode.parentNode.parentNode).getElement('div.option_group_chosen span.chosen_name');

				if (span && dst) dst.innerHTML = span.innerHTML;

			// update price
				span = $(src.parentNode).getElement('span.option_price_offset');
				dst = $(src.parentNode.parentNode.parentNode).getElement('div.option_group_chosen span.chosen_price_offset');

				if (span && dst) dst.innerHTML = span.innerHTML;

			// scroll back up if we're clicking on an element quite low down
				var src_pos = $(src).getPosition(window);
				var dst_pos = $(src.parentNode.parentNode.parentNode).getPosition(window);

				if (src_pos.y - dst_pos.y > 150) window.scrollTo(0, dst_pos.y);

		}
	// ok we'll have to see which items are ticked...
		else
		{
			var chosen_text = "";
			var chosen_price = 0;

			$(src.parentNode.parentNode.parentNode).getElements('input[type=checkbox]').each(function (el) 
			{
				if (el.checked)
				{
					/*if (chosen_text) chosen_text+= ", ";

					chosen_text+= $(el.parentNode).getElement('span.option_name').innerHTML;

					if (isNaN(chosen_price)) return;

					var temp_price = String($(el.parentNode).getElement('span.option_price_offset').innerHTML);
					if (temp_price.match(/call/i))
					{
						chosen_price = temp_price;
						return;
					}

					while (temp_price.match(/[^0-9\.\+\-]/)) temp_price = temp_price.replace(/[^0-9\.\+\-]/,"");
					chosen_price+= temp_price.toFloat();*/
				}
			});

			/*var dst_name = $(src.parentNode.parentNode.parentNode).getElement('div.calc_options span.chosen_name'); 
			var dst_price = $(src.parentNode.parentNode.parentNode).getElement('div.calc_options span.chosen_price_offset');

			if (!dst_name || !dst_price) return;

			if (!chosen_text)
			{
				chosen_text = "None";
				chosen_price = "";
			}
			
			dst_name.innerHTML = chosen_text;

			if (!String(chosen_price).match(/call/i))
			{
				if (chosen_price > 0)
					chosen_price = "+ £" + chosen_price;
				else if (chosen_price < 0)
					chosen_price = "- £" + chosen_price;
			}

			dst_price.innerHTML = chosen_price;*/

			
			// show chosen group
			/*	if (src.checked)
				{
					var chosen = $(src.parentNode.parentNode.parentNode).getElement('.option_group_chosen');
					chosen.setStyle.delay(500, chosen, ["display", ""]);
				}*/
		}
}


window.addEvent('domready', function() {

	if (!$('ajax_total')) return;

	var do_ajax_price = true;

	// get the price if there isn't one, there's no point carrying on...
	/*	if (!String($('price').innerHTML).match(/^[0-9\.]+$/))
		{
			$('ajax_total').innerHTML = "CALL US FOR PRICE";
			var do_ajax_price = false;
		} */

	// create Ajax Request
		if (do_ajax_price)
		{
			ajax_request = new Request({
				url: "ajax_calculate_options.php",
				method: 'post',
				//data: req,
				onSuccess: function(response_text) {
					if (String(response_text).match(/call/i))
					{
						$('ajax_total').innerHTML = "CALL US FOR PRICE";
						$('add_product').disabled = true;
					}
					else
					{
						var result =  Number(response_text);

						result = result.numberFormat(2, '.', ',');

						$('ajax_total').innerHTML = "&pound;" + result;
						$('add_product').disabled = false;
					}
				},
				onFailure: function () 
				{
					$('ajax_total').innerHTML = "ERROR";
					$('add_product').disabled = false;
				},
				onException: function (headerName, value) 
				{
					$('ajax_total').innerHTML = "ERROR";
					$('add_product').disabled = false;
				}
			});

			ajax_request2 = new Request({
				url: "ajax_calculate_options.php?formdata=true",
				method: 'post',
				//data: req,
				onSuccess: function(response_text2) {

						var result =  response_text2;

						$('ajax_form').innerHTML = result;
						$('add_product').disabled = false;
	
				},
				onFailure: function () 
				{
					$('ajax_form').innerHTML = "ERROR";
					$('add_product').disabled = false;
				},
				onException: function (headerName, value) 
				{
					$('ajax_form').innerHTML = "ERROR";
					$('add_product').disabled = false;
				}
			});
		}

	// add click event to each radio/check button
		$$('.calc_options input').each(function (el) {
			el.addEvent('click', function(e) {

				// get all option IDs chosen (they'll get passed to AJAX)
					if (do_ajax_price) GetOptionIDs();

				// get the obj we clicked on
					var src = e.target || e.srcElement;

				// if we've clicked on a radio then hide the option group
				//	if (String(src.getAttribute("type")).match(/radio/i) && typeof(myAccordion) != "undefined") myAccordion.display(-1);

				// update the chosen group DIV
					UpdateChosenDiv(src);
			});
		});

		$$('.sale_type_select input').each(function (el) {
			el.addEvent('click', function(e) {

				// get all option IDs chosen (they'll get passed to AJAX)
					if (do_ajax_price) GetOptionIDs();

				// get the obj we clicked on
					var src = e.target || e.srcElement;

				// if we've clicked on a radio then hide the option group
				//	if (String(src.getAttribute("type")).match(/radio/i) && typeof(myAccordion) != "undefined") myAccordion.display(-1);

				// update the chosen group DIV
					UpdateChosenDiv(src);
			});

		});

		$$('.lamp_options input').each(function (el) {
			el.addEvent('click', function(e) {

				// get all option IDs chosen (they'll get passed to AJAX)
					if (do_ajax_price) GetOptionIDs();

				// get the obj we clicked on
					var src = e.target || e.srcElement;

				// if we've clicked on a radio then hide the option group
				//	if (String(src.getAttribute("type")).match(/radio/i) && typeof(myAccordion) != "undefined") myAccordion.display(-1);

				// update the chosen group DIV
					UpdateChosenDiv(src);
			});

		});
	// do the ajax calculation
		if (do_ajax_price) GetOptionIDs(1);


});
