var request; // xml http request object

// Create an XMLHttpRequest object
function create_xml_http_request()
{
	var request = null;
	
	try
	{
		request = new XMLHttpRequest();
	}
	catch( e )
	{
		try
		{
			request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(  e )
		{
			request = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	return request;
}

function get_xml_node( xml_doc, id, index )
{
	var result = null;
	if( xml_doc.getElementsByTagName( id )[ index ] )
	{
		if( xml_doc.getElementsByTagName( id )[ index ].childNodes.length > 0 ) result = xml_doc.getElementsByTagName( id )[index].childNodes[0].nodeValue;
	}
	return result;
}

/////////////////////////////////////
// ADD
////////////////////////////////////////////////////////////////////////////////

// Updates the product using AJAX
function add( id )
{
	request = create_xml_http_request();
	
	var quantity = document.getElementById( 'icon_quantity_' + id ).value;
	var url = "ajax/basket-add.php"; // creates the XML document
	url = url + "?id=" + id + "&quantity=" + quantity;
	
	request.onreadystatechange=add_state_changed;
	request.open("GET",url,true);
	request.send(null);		
}

// Retrieves the XML data 
function add_state_changed()
{
	if( request.readyState == 4 )
	{
		var xml_doc = request.responseXML.documentElement;
		var id = get_xml_node( xml_doc, "id", 0 ); 
		var product_id = get_xml_node( xml_doc, "product_id", 0 );
		var product_quantity = get_xml_node( xml_doc, "product_quantity", 0 );
		var brand = get_xml_node( xml_doc, "brand", 0 ); 
		var name = get_xml_node( xml_doc, "name", 0 ); 
		var thumb = get_xml_node( xml_doc, "thumb", 0 ); 
		var description = get_xml_node( xml_doc, "description", 0 ); 
		var quantity = get_xml_node( xml_doc, "quantity", 0 );
		var unit_price = get_xml_node( xml_doc, "unit_price", 0 ); 
		var price = get_xml_node( xml_doc, "price", 0 ); 
		var stock = get_xml_node( xml_doc, "stock", 0 );
		var postage_id = get_xml_node( xml_doc, "postage_id", 0 );
		var postage_price = get_xml_node( xml_doc, "postage_price", 0 );
		var postage_description = get_xml_node( xml_doc, "postage_description", 0 );
		
		var objs = document.getElementsByTagName( 'input' );
		
		for( var i = 0; i < objs.length; i++ )
		{
			var obj = objs[ i ];
			if( obj.className == "icon_quantity" )
			{
				obj.value = 1;
			}
		}
		
		add_button( product_id, product_quantity );
		add_basket( id, product_id, brand, name, thumb, description, unit_price, quantity, price, stock, postage_price ); 
		recalculate( 'basket_quantity', 'basket_quantity_' );
		if( document.getElementById( 'timer_' + product_id ) ) hide_div( 'timer_' + product_id );
	}
}

function add_button( id, quantity )
{
	var obj = null;
	if( obj = document.getElementById( 'label_quantity_' + id ) )
	{
		if( quantity == 0 ) 
			document.getElementById( 'icon_' + id ).style.display = "none";

		
		if( obj )
		{
			obj.innerHTML = quantity;
		}
		
		if( quantity != 0 ) 
			document.getElementById( 'icon_' + id ).style.display = "inline";
	}
}

function add_basket( id, product_id, brand, name, thumb, description, unit_price, quantity, price, stock, postage_price )
{
	var obj = document.getElementById( 'basket_' + id );
	// if the variation does not exist then create a new entry
	if( obj == null )
	{
		add_basket_create( id, brand, name, description, quantity, price, stock, postage_price );
		add_checkout_create( id, brand, name, thumb, description, unit_price, quantity, price );
		document.getElementById( 'basket_empty' ).style.display  = "none";
		document.getElementById( 'basket_footer' ).style.display = "block";
	}
	else
	{
		// If the quantity is zero then delete the entry from the list
		if( quantity == null ) remove_item( id );	
		else
		{
			// update the entry value
			document.getElementById ( 'basket_quantity_' + id ).value = quantity;
			document.getElementById ( 'basket_price_' + id ).innerHTML = price;
		}
	}
	
}

function add_basket_create( id, brand, name, description, quantity, price, stock, postage_price )
{	
	var div = document.createElement('div');
	div.setAttribute( 'id', 'basket_' + id );
	div.className = 'item';
	var div_name = document.createElement('div');
	
	div_name.setAttribute( 'class', 'name' );
	var title = "";
	if( brand != '' && brand != null ) title = brand + " ";
	
	title += name;
	if( description != '' && description != null )
		title += ": " + description;
	div_name.innerHTML = title;
	div.appendChild( div_name );
	
	var img_cross = document.createElement( 'span' );
	img_cross.innerHTML = "<a href='' onclick='remove_item(" + id + "); return false;'><img src='images/cross.gif' alt='Remove' title='Remove' style='vertical-align:middle' /></a>";
	
	/*
	var img_cross = document.createElement( 'img' );
	img_cross.setAttribute( 'src', 'images/cross.gif' );
	img_cross.setAttribute( 'alt', 'Remove' );
	img_cross.setAttribute( 'title', 'Remove' );
	img_cross.style.verticalAlign = "bottom";
	
	var href_cross = document.createElement( 'a' );
	href_cross.setAttribute( 'onclick', "remove_item( " + id + " ); return false;" );
	href_cross.setAttribute( 'href', '#' );
	href_cross.appendChild( img_cross );
	div.appendChild( href_cross );
	*/
	div.appendChild( img_cross );
	
	var input_quantity = document.createElement( 'input' );
	input_quantity.setAttribute( 'type', 'text' );
	input_quantity.setAttribute( 'id', 'basket_quantity_' + id );
	input_quantity.className = "basket_quantity";
	input_quantity.setAttribute( 'name', 'basket_quantity_' + id );
	input_quantity.value = quantity;
	input_quantity.style.marginLeft = "5px";
	input_quantity.style.marginRight = "5px";
	div.appendChild( input_quantity );
	
	var str = document.createElement( 'span' );
	str.innerHTML = " @ ";
	div.appendChild( str );
	
	var span_price = document.createElement( 'span' );
	span_price.setAttribute( 'id', 'basket_price_' + id );
	span_price.innerHTML = price;
	div.appendChild( span_price );
	
	document.getElementById( 'basket_items' ).appendChild( div ); 
}

function add_checkout_create( id, product_id, brand, name, thumb, description, unit_price, quantity, price )
{
	
	// TODO: CREATE THE CHECKOUT ROW HERE
	var table = document.getElementById( 'checkout_table' );
	if( table )
	{
		var tr = table.insertRow( -1 );
		tr.id = 'checkout_' + id;
		tr.setAttribute( 'class', "checkout_row" );
		
		var td = null;
		
		td = tr.insertCell( -1 );
		td.setAttribute( 'width', '15px' );
		td.innerHTML = "<a href='' onclick='remove_item(" + id + "); return false;'><img src='images/cross.gif' alt='Remove' title='Remove' style='vertical-align:middle' /></a>";	
		
		td = tr.insertCell( -1 );
		var url = "product.php?product_id=" + product_id;
		
		var title = "";
		if( brand != '' && brand != null ) title = brand + " ";
		
		title += name;
		if( description != '' && description != null )
			title += ": " + description;
		var str = '<div class="checkout_image">' + 
				  '<div class="thumb" style="float:left; width:100px; margin-right:15px; background-image:url( \'images/' + thumb + '\' );"><a href="' + url + '"><img class="border" src="images/border-image-thumb.png" alt="' + title + '" title="' + title + '" style="width:100px; height:70px" /></a></div></div>' +
				  '<div style="float:left; width:185px"><a href="' + url + '">' + title + '</a></div><div class="clear"><!-- //--></div>';
		td.innerHTML = str;
		
		td = tr.insertCell( -1 );
		td.setAttribute( 'id', 'checkout_uprice_' + id );
		td.innerHTML = unit_price;
		
		td = tr.insertCell( -1 );
		var input = document.createElement( 'input' );
		input.setAttribute( 'id', 'checkout_quantity_' + id );
		input.setAttribute( 'name', 'checkout_quantity_' + id );
		input.className = "checkout_quantity";
		input.value = quantity;
		input.style.width = "50px";
		td.appendChild( input );
		
		td = tr.insertCell( -1 );
		td.setAttribute( 'id', 'checkout_price_' + id );
		td.innerHTML = price;
	}
}

/////////////////////////////////////
// REMOVE
////////////////////////////////////////////////////////////////////////////////

function remove_item( id )
{
	request = create_xml_http_request();
	
	var url = "ajax/basket-remove.php"; // creates the XML document
	url = url + "?id=" + id;
	
	document.getElementById( 'basket_loading' ).style.display = "block";
	
	request.onreadystatechange=remove_state_changed;
	request.open("GET",url,true);
	request.send(null);		
}

function remove_state_changed()
{
	if( request.readyState == 4 )
	{		
		var xml_doc = request.responseXML.documentElement;
		var id = get_xml_node( xml_doc, "id", 0 );
		var product_id = get_xml_node( xml_doc, "product_id", 0 );
		var product_quantity = get_xml_node( xml_doc, "product_quantity", 0 );
		remove_basket( id );
		add_button( product_id, product_quantity );
		recalculate( 'basket_quantity', 'basket_quantity_' );
	}
}

function remove_basket( id )
{
	var obj = document.getElementById( 'basket_' + id );
	var parent_obj = obj.parentNode;
	parent_obj.removeChild( obj );
	
	//alert( 'basket_' + id );
	
	if( obj = document.getElementById( 'checkout_' + id ) )
	{
			//alert( 'checkout_id' + id );
		var parent_obj = obj.parentNode;
		parent_obj.removeChild( obj );
		if( parent_obj.childNodes.length == 2 ) window.location = "checkout.php";
	}
	
	var count = 0;
	for( var i = 0; count == 0 && i < document.getElementsByTagName( 'input' ).length; i++ )
	{
		obj = document.getElementsByTagName( 'input' )[ i ];
		if( obj.className == "basket_quantity" )
			count = 1;
	}
	
	if( count == 0 )
	{
		document.getElementById( 'basket_empty' ).style.display  = "block";
		document.getElementById( 'basket_footer' ).style.display = "none";
		
		// TODO: HIDE THE CHECKOUT TABLE HERE
		if( document.getElementById( 'basket_num_items' ) ) document.getElementById( 'basket_num_items' ).innerHTML = 0;
	}
	
	document.getElementById( 'basket_loading' ).style.display = "none";
}

/////////////////////////////////////
// RECALCULATE
////////////////////////////////////////////////////////////////////////////////

function recalculate( className, prefix )
{
	
	request = create_xml_http_request();
	
	var url = "ajax/basket-recalculate.php"; // creates the XML document
	
	var query_string = null;
	var objs = document.getElementsByTagName( 'input' );
	query_string = "prefix=" + prefix;
	
	for( var i = 0; i < objs.length; i++ )
	{
		var obj = objs[ i ];
		
		if( obj.className == className )
		{
			query_string += "&";
			var str = obj.id + "=" + obj.value;
			query_string += str;
		}
	}
	
	var obj = document.getElementById( 'postage_type' );
	if( obj && obj.options.length != 0 )
		query_string += "&postage_type=" + obj.options[ obj.selectedIndex ].value;

	document.getElementById( 'basket_loading' ).style.display = "block";
	request.onreadystatechange=recalculate_state_changed;
	request.open("POST",url, true);
	request.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
	//request.setRequestHeader( 'Content-length', query_string.length );
	//request.setRequestHeader( 'Connection', 'close' );
	request.send(query_string);
}

function recalculate_state_changed()
{
	if( request.readyState == 4 )
	{
		if( request.responseXML )
		{
			var xml_doc = request.responseXML.documentElement;
			
			var postage_id = get_xml_node( xml_doc, "postage_id", 0 );
			var postage_description = get_xml_node( xml_doc, "postage_description", 0 );
			var postage_price = get_xml_node( xml_doc, "postage_price", 0 );
			
			var country_name = get_xml_node( xml_doc, "country_name", 0 );
			
			var sub_total = get_xml_node( xml_doc, "sub_total", 0 );
			var vat = get_xml_node( xml_doc, "vat", 0 );
			var total = get_xml_node( xml_doc, "total", 0 );
			
			var num_items = 0;
			
			for( var i = 0; i < xml_doc.getElementsByTagName( "variation" ).length; i++ )
			{
				var xml_node = xml_doc.getElementsByTagName( "variation" )[ i ];
				var id = get_xml_node( xml_node, "id", 0 );
				var quantity = get_xml_node( xml_node, "quantity", 0 );
				
				num_items += parseInt(quantity);
				
				var price = get_xml_node( xml_node, "price", 0 );
				var product_id = get_xml_node( xml_node, "product_id", 0 );
				var product_quantity = get_xml_node( xml_node, "product_quantity", 0 );
	
				recalculate_basket( id, quantity, price, postage_price, total );
				recalculate_checkout( id, quantity, price, postage_price, sub_total, vat, total, country_name );
				add_button( product_id, product_quantity );
			}
			
			if( document.getElementById( 'basket_num_items' ) ) document.getElementById( 'basket_num_items' ).innerHTML = num_items;
			
			var opts = document.getElementById( 'postage_type' );
			if( opts )
			{
				opts.options.length = 0;
				
				//TODO: check the above and add the items to the SELECT statement
				// also perform a check to highlight the selected ID
				for( var i = 0; i < xml_doc.getElementsByTagName( "postage_item" ).length; i++ )
				{
					var xml_node = xml_doc.getElementsByTagName( "postage_item" )[ i ];
					var postage_item_id = get_xml_node( xml_node, "postage_item_id", 0 );
					var postage_item_name = get_xml_node( xml_node, "postage_item_name", 0 );
					var postage_item_description = get_xml_node( xml_node, "postage_item_description", 0 );
		
					opts.options[ i ] = new Option( postage_item_name, postage_item_id );
					if( postage_item_id == postage_id )
					{
						opts.selectedIndex = i;
						var obj = document.getElementById( 'postage_description' );	
						if( postage_item_description )
						{
							obj.innerHTML = "* " + postage_item_description;
							obj.style.display = "block";
						}
						else
						{
							obj.innerHTML = "";
							obj.style.display = "none";
						}
					}
		
					
				}
			}
			
			var div_order = null;
			var div_save = null;
			if( ( div_order = document.getElementById( 'div_order' ) ) && ( div_save = document.getElementById( 'div_save' ) ) )
			{
				if( postage_id != null )
				{	
					div_order.style.display = "block";
					div_save.style.display = "none";
				}
				else
				{
					div_order.style.display = "none";
					div_save.style.display = "block";
				}
			}
		}
		
		document.getElementById( 'basket_loading' ).style.display = "none";
		if( document.getElementById( 'timer_' + product_id ) ) hide_div( 'timer_' + product_id );
	}
}

function recalculate_basket( id, quantity, price, postage_price, total )
{
	if( obj = document.getElementById( 'basket_quantity_' + id ) ) 
	{
		if( quantity > 0 )
		{
			// quantity greater than zero
			obj.value = quantity;
			if( obj = document.getElementById( 'basket_price_' + id ) )		obj.innerHTML = price;
			if( obj = document.getElementById( 'basket_postage_price' ) )	obj.innerHTML = postage_price;
			if( obj = document.getElementById( 'basket_total' ) )			obj.innerHTML = total;
		}
		else
		{
			// quantity less than or equal to zero
			remove_basket( id );
		}
	}
}

function recalculate_checkout( id, quantity, price, postage_price, sub_total, vat, total, country_name )
{
	// TODO: REASSIGN THE VARIATION VARIABLES -- NOTE< WE ALSO NEED AN IMAGE!!
	if( obj = document.getElementById( 'country_name' ) )				obj.innerHTML = country_name;
	if( obj = document.getElementById( 'checkout_quantity_' + id ) )	obj.value = quantity;	  
	if( obj = document.getElementById( 'checkout_price_' + id ) )		obj.innerHTML = price;
	if( obj = document.getElementById( 'checkout_sub_total' ) )			obj.innerHTML = sub_total;
	if( obj = document.getElementById( 'checkout_sub_total2' ) )		obj.innerHTML = sub_total;
	if( obj = document.getElementById( 'checkout_postage' ) )			obj.innerHTML = postage_price;
	if( obj = document.getElementById( 'checkout_vat' ) )				obj.innerHTML = vat;
	if( obj = document.getElementById( 'checkout_total' ) )				obj.innerHTML = total;
	
	// TODO: - dirty hack! FIX ME AT SOME POINT
	if( obj = document.getElementById( 'postage_message' ) )			
	{
		obj.innerHTML = '';
		if( country_name == "United Kingdom" )
		{
			obj.innerHTML = '<p>For non-mainland shipping please select one of the following options:</p>' + 
							'<p><a href="country-select-postage.php?country_id=244&amp;url=checkout.php">Click here</a> to ship to <b>Scottish Highlands</b> (postcodes include: IV1-IV28, PH19-PH44, PA20-PA29 &amp; KA27-KA28)</p>' + 
							'<p><a href="country-select-postage.php?country_id=245&amp;url=checkout.php">Click here</a> to ship to <b>Scottish Islands &amp; Isle of Man</b></p>' +
							'<p><a href="country-select-postage.php?country_id=247&amp;url=checkout.php">Click here</a> to ship to <b>Channel Islands</b></p>' +
							'<p><a href="country-select-postage.php?country_id=246&amp;url=checkout.php">Click here</a> to ship to <b>Northern Island</b></p>';
		}
	}
}