var itemsAddedToBasket = 0;
var products_in_basket = [];
var last_received_ajax_id = 0;
var last_ajax_id = 0;
var ajax_requests = new Array();
var order_basket_when_complete = false;

function add_to_basket(_product)
{
	log('add_to_basket');

	_product.server_id = 0;
	_product.count = 1;
	_product.basket_id = Math.round(Math.random() * 99999999);
		
	products_in_basket.push(_product);

	addProductToTable(_product);
	send_product_to_server(_product);
}

function server_add_to_basket(
	_server_id, 
	_data, 
	_description, 
	_product_type,
	_width,
	_height,
	_color, 
	_price, 
	_count, 
	_disable_edit)
{
	log('server_add_to_basket');

	try {
  	var product = new Object;
		
  	product.basket_id = Math.round(Math.random() * 99999999);
  	product.server_id = _server_id;
  	product.description = _description;
		product.sign_type = _product_type;
		product.get_sign_type = function () { return this.sign_type; }
		product.width = _width;
		product.height = _height;
		product.colors_as_text = function(){ return _color };
  	product.price = _price;
  	product.count = _count;
		product.data = _data;
		product.to_string = function () { return this.data; };
  	products_in_basket.push(product);
  	
  	addProductToTable(product, _disable_edit);
		return product;
  } 
  catch (e) {
  }
}
/*
function local_measurement(_mm)
{
	return _mm;
}

function local_measurement_str()
{
	return $$('money_type').getAttribute('measurement')
}
*/
function price_with_sign(_price)
{
	if ($$('money_type').getAttribute('money_first') == "true")
		return $$('money_type').getAttribute('money_name') + _price;
	else
		return _price + " " + $$('money_type').getAttribute('money_name');
}

function local_price(_price)
{
	var relative_value = $$('money_type').getAttribute('rel_value') * 1;
	var price = (_price / relative_value).toFixed($$('money_type').getAttribute('decimals'));
	
	return price_with_sign(price);
}

function local_price_tax(_price)
{
	var relative_value = $$('money_type').getAttribute('rel_value') * 1;
	var tax = $$('money_type').getAttribute('tax') / 100;
	var price = (_price / relative_value * tax).toFixed($$('money_type').getAttribute('decimals'));
	return price_with_sign(price);
}

function local_price_with_tax(_price)
{
	var relative_value = $$('money_type').getAttribute('rel_value') * 1;
	var tax = $$('money_type').getAttribute('tax') / 100 + 1;
	
	var price = (_price / relative_value * tax).toFixed($$('money_type').getAttribute('decimals'));
	return price_with_sign(price);
}

var first_product = true;

function addProductToTable(_product, _disable_edit)
{
	log('addProductToTable');
	
	_disable_edit = _disable_edit || first_product;
	first_product = false;

	var tbl = $$('order_basket_table');
	var tbl_rows = tbl.rows.length;
	
	if ($$('basket_discount')) tbl_rows -= 1;
	if ($$('basket_total_price_row')) tbl_rows -= 1;
	
  var row = tbl.insertRow(tbl_rows);

	row.onmouseover = function () { row.style.backgroundColor = "#ddd"; };
	row.onmouseout = function () { row.style.backgroundColor = "#fff"; };
	
	var row_id = _product.basket_id;
	
  // left cell
  var cellLeft = row.insertCell(0);
  cellLeft.appendChild(document.createTextNode(tbl_rows));
  
	var description_cell = row.insertCell(1);
	description_cell.style.textAlign = 'left';
	description_cell.basket_id = row_id;

/*	description_cell.onclick = function () { 
		var data = decodeURIComponent(find_product_from_basket_id(this.basket_id).to_string());
		
		if (data.length < 5) return;
		
		sign = new Sign( data ); 
		sign.save_to_cookie();
		document.location = document.location.href;
		return;
	}*/
	
	var description = document.createElement("div");
	description.className = "basket_description";
	description.innerHTML = _product.description;
  description_cell.appendChild(description);

  var cellColor = row.insertCell(2);
	cellColor.style.textAlign = "center";
	cellColor.appendChild(document.createTextNode(_product.colors_as_text()));

  var cellPrice = row.insertCell(3);
	cellPrice.id = "basket_item_price_" + row_id;
	cellPrice.appendChild(document.createTextNode(local_price(_product.price)));

	if (!_disable_edit) {
  	var count_input = document.createElement('input');
  	count_input.type = 'text';
  	count_input.name = "basket_item_count_" + row_id;
  	count_input.id = "basket_item_count_" + row_id;
  	count_input.size = 3;
		count_input.width = "40";
		
  	count_input.value = _product.count;
  	  	
  	count_input.onkeydown = function(event){
  		return numericInput(event, function(){
  			basket_item_count_changed(_product);
  		});
  	};
  	count_input.onchange = function(){
  		update_basket_item_count(_product);
  	};
  	row.insertCell(4).appendChild(count_input);
  }
	else
	{
		if (_product.count == null) _product.count = 1;
  	row.insertCell(4).appendChild(document.createTextNode(_product.count));
	}
	
  var cellTotalPrice = row.insertCell(5);
	cellTotalPrice.id = "basket_item_total_price_" + row_id;
	cellTotalPrice.appendChild(document.createTextNode(local_price(0)));
	
	if (!_disable_edit) {
  	var link = document.createElement('span');
  	link.onclick = function(){
  		remove_product(_product);
  	}

		link.id = "basket_remove_button";

  	link.innerHTML = $$('basket_remove').innerHTML;
		var link_cell = row.insertCell(6);
		link_cell.style.textAlign = 'center';
		
  	link_cell.appendChild(link);
  }
	else
	{
		if (tbl.rows[0].childNodes.length == 13)
	  	row.insertCell(6).appendChild(document.createTextNode(""));
	}
	
 	basket_item_count_changed(_product);
	log('addProductToTable done');
}	

function isIE()
{
  return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function update_total_price()
{
	log('update_total_price');
	var total_price = 0;
	var plastic_price = 0;
	var text_in_basket = '';
	var name_count = 0;

	var postage_price = 0; //$$('postage_price').innerHTML * 1;

	for (var i = 0; i < products_in_basket.length; i++)
	{
		var product = products_in_basket[i];

		total_price += product.price * product.count;

		if ((product.get_sign_type() == "plastic_sign") || (product.get_sign_type() == "name_sign"))
			plastic_price += product.price * product.count;
/*		else
			plastic_price += product.price * product.count * 0.5;*/
		
		if (product.get_sign_type() == "name_sign")
			name_count += product.count;
			
		text_in_basket += "(" + products_in_basket[i].description + ")";
/*
		if (product.get_sign_type() == "aluminium_sign") 
			if ((product.width + product.height) > 900)
				postage_price = $$('package_price').innerHTML * 1;
*/
	}
/*
	var shipping_item = products_in_basket[0];
	shipping_item.price = postage_price;
	$$('basket_item_price_' + shipping_item.basket_id).innerHTML = local_price(postage_price);
	$$('basket_item_total_price_' + shipping_item.basket_id).innerHTML = local_price(postage_price);
*/

	total_price += postage_price;

	if (typeof(debugmode) != 'undefined') {
  	$$('items_in_basket').innerHTML = products_in_basket.length;
  	$$('text_in_basket').innerHTML = text_in_basket;
  }


	if ($$('basket_discount')) {
  	var discount_percent = 0;
		
		if (plastic_price > 700)
			discount_percent = 5;

		if (plastic_price > 1000)
			discount_percent = 10;
			
		if (plastic_price > 2000)
			discount_percent = 15;

		if (plastic_price > 5000)
			discount_percent = 20;

		if (plastic_price > 11000)
			discount_percent = 25;

		if (plastic_price > 18000)
			discount_percent = 30;
			  	
		if (plastic_price > 25000)
			discount_percent = 35;

  	if (discount_percent >= 10 || (name_count > 4)) {
  		var discount_count = Math.max(name_count - 4, 0) * 6;
  		var discount = Math.floor(plastic_price * (discount_percent / 100) + discount_count);
  		
  		discount_percent = Math.round((discount / total_price) * 100);
  		total_price = total_price - discount;  			
  		
  		$$('basket_discount_percent').innerHTML = discount_percent + " %";
  		$$('basket_discount_price').innerHTML = $$('rabatt').innerHTML + ': ' + local_price(discount);
			
			if ($$('order_discount_field'))
				$$('order_discount_field').value = discount;
			
			if (isIE())			
				$$('basket_discount').style.display = "inline";
			else
	  		$$('basket_discount').style.display = "table-row";
  	}
  	else {
  		$$('basket_discount').style.display = "none";
  	}
  }

	$$('basket_total_price').innerHTML = local_price(total_price);

	if ($$('basket_total_price_2'))
		$$('basket_total_price_2').innerHTML = local_price(total_price);

	$$('basket_total_price_total').innerHTML = local_price_with_tax(total_price);

	if ($$('basket_total_price_tax'))
		$$('basket_total_price_tax').innerHTML = local_price_tax(total_price);
	
	try
	{
		update_basket_buttons();
	}
	catch (e)
	{
	}
}

function basket_item_count_changed(_product)
{
	var id = _product.basket_id;

	try
	{	
		_product.count = $$('basket_item_count_' + id).value * 1;
	}
	catch (e)
	{
	}

	$$('basket_item_total_price_' + id).innerHTML = local_price(_product.count * _product.price);
	update_total_price();
}

function update_basket_item_count(_product)
{
	basket_item_count_changed(_product);
	send_product_to_server(_product);
}

function find_product_from_basket_id(_basket_id)
{
	for (var i = 0; i < products_in_basket.length; i++)
		if (products_in_basket[i].basket_id == _basket_id)
			return products_in_basket[i];
	
	return null;
}

function send_product_to_server(_product)
{
	ajax_request('/order/add', 'product=' + encodeURIComponent($.toJSON(_product)));
}

function ajax_request(_func, _params)
{
	log('ajax_request');

	last_ajax_id++
	_func = _func + "?ajax_id=" + last_ajax_id;
	if (_params) _func = _func + "****&****" + _params;
	
	ajax_requests[last_ajax_id] = _func;

	if ($$('basket_status') && ($$('basket_status').innerHTML == ""))
		$$('basket_status').innerHTML = $$('uppdaterar_kundvagnen').innerHTML;

	if (last_ajax_id == (last_received_ajax_id+1))
		send_next_ajax_request();	
}

var ajax_updater_timer;
var ajax_error = false;

function send_next_ajax_request() 
{
	log('send_next_ajax_request');
	if (ajax_updater_timer) clearInterval(ajax_updater_timer);
	ajax_updater_timer = setInterval(function()
	{
		send_next_ajax_request();
	}, 10000);

	var ajax_request = ajax_requests[last_received_ajax_id + 1].split("****&****")
	
	$.ajax({
		url: ajax_request[0],
		data: ajax_request[1],
		type: "post",
		complete: function(request){
			log('ajax complete call');

			if (request.responseText == (last_received_ajax_id + 1)) 
			{
				last_received_ajax_id++;
				delete ajax_requests[request.responseText];
				
				if (last_received_ajax_id == last_ajax_id) {
					clearInterval(ajax_updater_timer);
					if ($$('basket_status')) $$('basket_status').innerHTML = '';
					ajax_error = false;
					
					if (order_basket_when_complete)
						order_basket();
					else
						update_basket_buttons();
				}
				else 
					send_next_ajax_request();
			}
			else{
				if ($$('basket_status')) $$('basket_status').innerHTML = '<span style="color:red">' +
				  $$('vantar_pa_skyltmax').innerHTML + "</span>"
				ajax_error = true;
				order_basket_when_complete = false;
				update_basket_buttons();
			}
		}
	});
}

function update_basket_buttons()
{
	if (!$$("basket_order_button")) return;
	
	var no_items = products_in_basket.length == 1;
	
	if ((ajax_error) || no_items) {
  	$$("basket_order_button").style.display = "none";
  	$$("basket_view_button").style.display = "none";
  }
  else {
  	$$("basket_order_button").style.display = "block";
  	$$("basket_view_button").style.display = "block";
  }
}

function update_row_index()
{
	var tbl = $$('order_basket_table');		
	
	for (var i = 0; i < tbl.tBodies[0].rows.length-1; i++) {
  	tbl.tBodies[0].rows[i].childNodes[0].innerHTML = i + 1;
  }
}

function remove_product(_product)
{
	log('remove_product');
	var index = products_in_basket.indexOf(_product);

	if (index != -1) {
		var tbl = $$('order_basket_table');		
		tbl.deleteRow(index + 1);
  	products_in_basket.splice(index, 1);
		ajax_request('/order/remove', 'product=' + encodeURIComponent($.toJSON(_product)))
  	update_total_price();
		update_row_index();
  }
}

function empty_basket()
{
	log('empty_basket');
	var tbl = $$('order_basket_table');		
	var rows = tbl.tBodies[0].rows.length - 1;
	
	for (var i = 0; i < rows; i++)
  	tbl.tBodies[0].deleteRow(0);
	
	products_in_basket = [];
	update_total_price();
	ajax_request('/order/remove_all');
}
