	// Define required variables.
	var http = createRequestObject();  
    var ajaxaction = "";	
	var store = "";
	var selectedObjectName = "";
	//var ajax_url = "ajax-worker.php";
	var ajax_url = base_url + "index.php/ajaxcart/";
	var inProgress = false; 
	var delayedAction = "";		// Set this is another function call needs to be made after an ajax load.  	
	
	$(document).ready(function() {
		loadCartSummary();	
	});	
	
	function loadCartSummary()
	{		
		showCartMessage("Loading, please wait...");	
		showCartLoader();
		
		// Create the ajax request and send it
		var randomnumber = Math.floor(Math.random()*999999);
		ajaxaction = "loadcartsummary";
		params = ajaxaction + "/" + randomnumber;
		
		sndReq(ajax_url+"/"+ajaxaction, params);
		hideCartLoader();
	}
	
	function applyPromoCode()
	{
		
		ajaxaction = "/applyPromoCode";
		showCartLoader2();
		//sndReq(ajax_url, params);	
		$.post(ajax_url + ajaxaction, {coupon_code : $('#coupon_code').val()}, function(data) {
							$('#total_amount').html(data);
							if ($('#total_discount_amount').length)
							{
								var s = '<td colspan="3" align="right">';
									s += '<b>'+$('#applied_discount_type').val()+'</b>';
									s += '</td>';
									s += '<td align="right"><b>$'+$('#total_discount_amount').val()+'</b></td>';
									s += '<td><b>&nbsp;</b></td>';
									s += '<td><b>&nbsp;</b></td>';
									s += '<td><b>&nbsp;</b></td>';
								$('#discount_amount').html(s);
							}
							else
								$('#discount_amount').html('');
							if ($('#error_message').length)
							{
								var s = '<td style="font-weight: bold; color: red;" colspan="7">';
									s += ''+$('#error_message').val()+'';
									s += '</td>';
								$('#display_error_message').html(s);
							}
							else
							{
								$('#display_error_message').html('');
								if ($('#hidePromoCodeAvailable').length)
								{
									$('#frmCoupon').hide();
								}
							}
							hideCartLoader2();
							});

	}

	function showCartMessage(message)
	{
		var objCartMessage = document.getElementById("cartSummaryMessage");
		if(!objCartMessage)
			return;
		objCartMessage.style.display = 'block';	
		objCartMessage.innerHTML = message;		
	}

   function showCartLoader()
   {
   	var objLoader = document.getElementById("cart_loader");
   	if(!objLoader)
   		return;
   	objLoader.style.visibility = "visible";     
	}
	
   function hideCartLoader(evt)
   {
	var objCartMessage = document.getElementById("cartSummaryMessage");
	if(objCartMessage)
		objCartMessage.style.display = 'none';
   	var objLoader = document.getElementById("cart_loader");
   	if(!objLoader)
   		return;
   	objLoader.style.visibility = "hidden";      		
	}	
	
   function showCartLoader2()
   {
   	var objLoader = document.getElementById("cart_loader2");
   	if(!objLoader)
   		return;
   
   	objLoader.style.visibility = "visible";     		
	}
	
   function hideCartLoader2()
   {
   	var objLoader = document.getElementById("cart_loader2");
   	if(!objLoader)
   		return;
   	
   	objLoader.style.visibility = "hidden";      		
	}	
	
	function handleLoadCart(response)
	{
		showCartMessage(response);
	}
	
	function trim(str, chars) 
	{
		return ltrim(rtrim(str, chars), chars);
	}
	 
	function ltrim(str, chars) 
	{
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
	}
	 
	function rtrim(str, chars) 
	{
		chars = chars || "\\s";
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	}	
	
	function calcTotal()
	{
		var total = 0;
		var item_no = 0;
		
		var objTotal = document.getElementById("total_price");
		if(!objTotal)
			return;
		
		for(item_no = 1; item_no <= numItems; item_no++)
		{
			var objPrice = document.getElementById("price_" + item_no);
			var objQty = document.getElementById("qty_" + item_no);
			var objHidden =  document.getElementById("itemid_" + item_no);		
			var objItemName = document.getElementById("itemname_" + item_no);
			var objUseStockLevel = document.getElementById("use_stock_level_"+item_no);

			var stock_level = $(objHidden).attr("title");
			var item_name = trim($(objItemName).html());

			if((objPrice) && (objQty))
			{
				if(isNumeric(objQty.value))
				{
					var qty = objQty.value * 1;
					var price = objPrice.value * 1;
					var use_stock_level = objUseStockLevel.value;
					if (use_stock_level != 0)
					{
//						if((qty > 0) && (stock_level <= 0))
//						{
//							objQty.value = 0; 
//							alert("Sorry, there are no '" + item_name + "'  items in stock.  We appologise for any inconvenience.");
//						}
//						else if((qty > 0) && (qty > stock_level))
//						{
//							objQty.value = 0;
//							if (stock_level < 0)
//							{
//								stock_level = 0;
//							}
//							alert("Sorry, there are only " + stock_level + " '" + item_name + "'  items left.  If you still wish to buy this item, please enter a valid quantity.");
//						}
//						else
//						{
							total = total + (price * qty);	
//						}
					}
					else
					{
						total = total + (price * qty);	
					}
				}
			}
		}
		
		//objTotal.innerHTML = roundNumber(total, 2);
		objTotal.innerHTML = total.toFixed(2);
	}
	
	function reloadCart()
	{


	}

	function addToCart()
	{
		var item_no = 0;
		
		var randomnumber = Math.floor(Math.random()*999999);
		ajaxaction = "addtocart";
		var params = ajaxaction + "/" + randomnumber;	
		var totalQty = 0;
		
		// Loop through all the items on the screen and build a string containing 
		// ids, quantities and prices.
		var itemStr = "";
		
		if ($('#packCampaignSubmit').length)
		{
			var foundError = false;
			for(item_no = 1; item_no <= numItems; item_no++)
			{
				var objItemID = document.getElementById("itemid_" + item_no);
				if (objItemID)
				{
					if (objItemID.value == "" || objItemID.value == 0)
						foundError = true;
				}
				else
					foundError = true;
			}
			if (foundError)
			{
				alert("Please fill up all the item colour selections.");
				return false;
			}
		}
		for(item_no = 1; item_no <= numItems; item_no++)
		{
			var objPrice = document.getElementById("price_" + item_no);
			var objIsSales = document.getElementById("is_sales_" + item_no);
			var objQty = document.getElementById("qty_" + item_no);
			var objItemID = document.getElementById("itemid_" + item_no);
			var objHidden =  document.getElementById("itemid_" + item_no);		
			var objItemName = document.getElementById("itemname_" + item_no);
			var stock_level = $(objHidden).attr("title");
			//var item_name = trim($(objItemName).html());			
			
			if((objPrice) && (objQty) && (objItemID))
			{
				if(isNumeric(objQty.value))
				{
					var qty = objQty.value * 1;
					var price = objPrice.value * 1;
					var is_sales = objIsSales.value;
					var item_id = objItemID.value;
					
					if(qty > 0)
					{
						if(itemStr != "")
							itemStr = itemStr + "|";
							
						itemStr = itemStr + (item_id + "^" + qty + "^" + price + "^" + is_sales);
						
						totalQty = totalQty + qty;
						
				//		var new_stock_level = stock_level - qty;
				//		$(objHidden).attr("title", new_stock_level);
						objQty.value = 0;
					}
				}
			}
		}

	
		if(totalQty == 0)
		{
			if (objItemID)
				alert("Please enter a quantity for at least one item.");
			else
				alert("Please fill up all the item colour selections.");
			return false;	
		}
		else
		{
			for(item_no = 1; item_no <= numItems; item_no++)
			{
				if ($('#cboItemColour_'+item_no).length)
					$('#cboItemColour_'+item_no).attr('disabled', 'disabled');
			}
			if ($('#rdoSizeChoiceQueen').length)
				$('#rdoSizeChoiceQueen').attr('disabled', 'disabled');
			if ($('#rdoSizeChoiceKing').length)
				$('#rdoSizeChoiceKing').attr('disabled', 'disabled');
		}

		// Append the itemstring to the params and send the ajax requst.
		store = itemStr;
		params = params + itemStr;
		
		showCartLoader();
		//sndReq(ajax_url, params);
		$.post(ajax_url + ajaxaction, {itemStr : itemStr}, function(data) {
							loadCartSummary();
							if ($('#total_price').length)
							{
								$('#total_price').html('0.00');
							}
							hideCartLoader();
							if (data != '')
								alert(data);
							});
		if ($('#packCampaignSubmit').length)
			return true;
	}
	
	function handleAddToCart(response)
	{
		// Hide the spinning wheel
		hideCartLoader2();
		
		if(response == "OK")
		{
			// Clear the input fields
			clearInputFields();
			
			// Recalculate total.
			calcTotal();
			
			// Set the delayed action
			delayedAction = "CHECK_SUGGESTIVE_SELL";
			
			// Load the cart summary
			loadCartSummary();	
		}
		else
		{
			alert("Sorry, there was a problem whilst trying to add your items to the cart. Please try again later");	
		}
	}
	
	function checkSuggestiveSell()
	{
		var randomnumber = Math.floor(Math.random()*999999);
		ajaxaction = "loadsuggestivesell";
		var params = "action=" + ajaxaction + "&r=" + randomnumber + "&items=" + store;	
		
		sndReq(ajax_url, params);	
	}
	
	function handleCheckSuggestiveSell(response)
	{
		// Write the response back into the suggestive block.
		var objSuggestive = document.getElementById("suggestiveSell");
		if(objSuggestive)
		{
			objSuggestive.innerHTML = response;	
		}
	}
	
   function addSuggestedToCart(blockNo, item_id)
   {
   	// Get a handle on quantity of the suggested product that the user is trying to add to the cart.
   	var objQty = document.getElementById("suggested_qty_" + blockNo);
   	var objPrice = document.getElementById("suggested_price_" + blockNo);
   	var objLoader = document.getElementById("suggested_loader_" + blockNo);
   	
   	if((objQty) && (objPrice) && (objLoader))
   	{
   		// Ensure that the user has entered a valid quantity.
   		if(!isNumeric(objQty.value))
   		{
   			alert("Please enter a valid quantity");
   			objQty.focus();
   			return false;	
			}
			
			if(objQty.value == "0")
			{
   			alert("Please enter a value greater than 0");
   			objQty.focus();
   			return false;					
			}
			
			// Now add the item to the cart.
			var price = objPrice.innerHTML;
			var qty = objQty.value;

			ajaxaction = "addsuggestedtocart";
			store = blockNo;	// Store the blockNo so the handler function knows which suggested box was used.
			params = "action=" + ajaxaction + "&item_id=" + item_id + "&qty=" + qty + "&price=" + price;
			
			// Show the ajax loader
			objLoader.style.visibility = 'visible';
			
			sndReq(ajax_url, params);			
		}
	}	
	
	// The handleAddSuggestedToCart method fires when the server responds after a addSuggestedToCart request.
	// If the suggested product was added to the cart successfully, the server will send an "OK" message back.
	function handleAddSuggestedToCart(response)
	{
		if(response != "OK")
		{
			alert("Sorry, the item could not be added to your cart.  Please try again later.");
			return;
		}	
		
		// Retreive the block number from the store
		var blockNo = store;
		
		// Clear the quantity field for the relevant block.
		var objQty = document.getElementById("suggested_qty_" + blockNo);
		var objLoader = document.getElementById("suggested_loader_" + blockNo); 
		
   	if((objQty) && (objLoader))
   	{	
   		objQty.value = "0";
   		objLoader.style.visibility = 'hidden';
   		
   		// Clear the stored variable
   		store = "";
   		
   		// Now reload the cart summary
   		loadCartSummary();
		}	 
	}
	
	
	function clearInputFields()
	{
		var item_no = 0;
		
		// Loop through all the items on the screen and set values to 0.
		var itemStr = "";
		
		for(item_no = 1; item_no <= numItems; item_no++)
		{
			var objQty = document.getElementById("qty_" + item_no);
			
			if(objQty)
			{
				objQty.value = 0;	
			}
		}
	}	
	
   function handleResponse() 
   {
      if(http.readyState == 4)
      {
      	inProgress = false;
      	
      	hideCartLoader();
         var response = http.responseText;
         
         if(response != "")
         {
         	if(response.substr(0,1) == "#")
         	{
         		alert("Warning: " + response.substr(1,response.length - 1));
				}
				else
				{
					if(ajaxaction == "addtocart")
					{
						handleAddToCart(response);  
					}							
		         else if(ajaxaction == "loadcartsummary")
		         {
		            handleLoadCart(response);
		            
						// Check if a delayed action was set
						if(delayedAction != "")
						{
							var doAction = delayedAction;
							delayedAction = "";
							
							if(doAction == "CHECK_SUGGESTIVE_SELL")
							{
								checkSuggestiveSell();	
							}
							else
							{
								alert("Unhandled delayed action: " + doAction); 	
							}
						}		            
		         }	
		         else if(ajaxaction == "loadsuggestivesell")
		         {
		            handleCheckSuggestiveSell(response);
		         }	
		         else if(ajaxaction == "addsuggestedtocart")
		         {
		            handleAddSuggestedToCart(response);
		         }		         		         
					else
					{	
						alert("Undefined action: *" + ajaxaction + "*");
					}
				}
			}
			else
			{
				// A blank response was received.  For some actions this is perfectly valid.
		      if(ajaxaction == "loadsuggestivesell")
		      {
		         handleCheckSuggestiveSell("");
		      }					
			}	   
      }
   }	
   
	
	// Utility Functions
	function isNumeric(sText)
	{
	   var ValidChars = "0123456789.";
	   var IsNumber=true;
	   var Char;
	   
	   if(sText == "")
	   	return false;

	   for (i = 0; i < sText.length && IsNumber == true; i++) 
	   { 
	      Char = sText.charAt(i); 
	      if (ValidChars.indexOf(Char) == -1) 
	      {
	         IsNumber = false;
	      }
	   }
	   
	   return IsNumber; 
	}
	
	function isInteger(sText)
	{
	   var ValidChars = "0123456789";
	   var IsNumber=true;
	   var Char;

	   for (i = 0; i < sText.length && IsNumber == true; i++) 
	   { 
	      Char = sText.charAt(i); 
	      if (ValidChars.indexOf(Char) == -1) 
	      {
	         IsNumber = false;
	      }
	   }
	   
	   return IsNumber; 
	}
	
	function roundNumber(rnum, rlength) 
	{ 
		// Arguments: number to round, number of decimal places
		var n = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength) + "";
		
		var dotPos = n.lastIndexOf(".");
		
		if(dotPos > 0)
		{
			var afterDot = n.substring(dotPos + 1);
			var diff = rlength - afterDot.length;
			 
			while(diff > 0)
			{
				n = n + "0";
				diff = diff - 1;	
			}
		}
		
		return n;
	}	
	
	function mouseX(evt) 
	{
		if (evt.pageX) return evt.pageX;
		else if (evt.clientX)
		   return evt.clientX + (document.documentElement.scrollLeft ?
		   document.documentElement.scrollLeft :
		   document.body.scrollLeft);
		else return null;
	}
	
	function mouseY(evt) 
	{
		if (evt.pageY) return evt.pageY;
		else if (evt.clientY)
		   return evt.clientY + (document.documentElement.scrollTop ?
		   document.documentElement.scrollTop :
		   document.body.scrollTop);
		else return null;
	}
	
   function createRequestObject() 
   {
       var ro;
       var browser = navigator.appName;
       
       if(browser == "Microsoft Internet Explorer")
       {
           ro = new ActiveXObject("Microsoft.XMLHTTP");
       }
       else
       {
           ro = new XMLHttpRequest();
       }
       
       return ro;
   }

   function sndReq(url, params) 
   {
   	http.open('POST', url, true);
   	http.onreadystatechange = handleResponse;
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");       
      http.send(params);

		inProgress = true;  
   }
   
function removeFromCart(item_id, cart_id)
{
	if(item_id == "")
		return;
			
	if(confirm("Are you sure you want to remove this product from your shopping cart?"))
	{
		document.frmRemove.item_id.value = item_id;
		document.frmRemove.cart_id.value = cart_id;
		document.frmRemove.submit();
	}	
}

// The changeQty method allows the user to change the quantity of an item in their cart.
function changeQty(item_id, cart_id, old_qty, item_name)
{
	if(item_id == "")
		return;
		
	var obj = document.getElementById("qty_" + item_id + '_' + cart_id);	
	if(!obj)
		return;
		
	var qty = obj.options[obj.selectedIndex].value;
	
	if(confirm("You are about to change the quantity of '" + item_name + "' from " + old_qty + " to " + qty + ".  Continue?"))
	{
		document.frmChange.item_id.value = item_id;
		document.frmChange.cart_id.value = cart_id;
		document.frmChange.qty.value = qty;
		document.frmChange.submit();	
	}
	else
	{
		obj.selectedIndex = old_qty;	
	}
}

// The clearCart allows the user to clear their shopping cart after a confirmation/warning.
function clearCart()
{
	if(confirm("Warning, you are about to remove all items from your cart.  Continue?"))
	{
		document.frmClear.submit();
	}	
}

function constraintToNumberKeyPress(evt) {
    if (!evt) evt = window.event

    if (evt.shiftKey)
        return false;
    else {
        var key = evt.keyCode;
        if (!key) key = evt.keyCode;
        if (!key) key = evt.charCode;
        key = parseInt(key);
        if (((key >= 96) && (key <= 105)) || ((key >= 48) && (key <= 57)) || (key == 127) || (key == 27) || (key == 9) || (key == 11) || (key == 8) || (key == 37) || (key == 39) || (key == 46))
            return true;
        else
            return false;
    }
}

function calcAvailableStocks(itemID, cartID)
{
//	if ($('#itemid_'+itemID).length)
//	{
//		if (parseInt($('#qty_'+itemID+'_'+cartID).val()) > parseInt($('#itemid_'+itemID).val()))
//		{
//			if ($('#itemid_'+itemID).val() == 0)
//				alert("Sorry, '" + $('#itemname_'+itemID).val() + "' is out of stock.");
//			else
//				alert("Sorry, there are only " + $('#itemid_'+itemID).val() + " '" + $('#itemname_'+itemID).val() + "'  items left.  If you still wish to buy this item, please enter a valid quantity.");
//			$('#qty_'+itemID+'_'+cartID).val($('#itemid_'+itemID).val());
//		}
//	}
}

function remove_product_promo_code(product_promo_code)
{
	$('#remove_product_promo_code').val(product_promo_code);
	$('#frmViewCart').submit();
}

function remove_promo_code(promo_code, is_referral_code)
{
	if (is_referral_code == 'A' || is_referral_code == 'B')
		$('#remove_referral_code').val(is_referral_code);
	else
		$('#remove_promo_code').val(promo_code);
	$('#frmViewCart').submit();
}

function jsTrim(s) {
     var nLen = s.length;
     var nStart = 0;
     var nEnd = nLen - 1;
     var i;
     for (nStart = 0; nStart <= nEnd; nStart++)
        if (nonWS(s.charAt(nStart))) break;
     for (nEnd = nLen - 1; nEnd >= nStart; nEnd--)
        if (nonWS(s.charAt(nEnd))) break;
     return s.substr(nStart, nEnd - nStart + 1);
}

function jsIsNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

function jsLen(str)
/***
        IN: str - the string whose length we are interested in
        RETVAL: The number of characters in the string
***/
{  return String(str).length;  }

function jsLeft(str, n){
    if (n <= 0)
        return "";
    else if (n > String(str).length)
        return str;
    else
        return String(str).substring(0,n);
}

function jsRight(str, n)
{
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else 
    {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function jsMid(str, start, len)
/***
IN: str - the string we are LEFTing
start - our string's starting position (0 based!!)
len - how many characters from start we want to get
RETVAL: The substring from start to start+len
***/
{
// Make sure start and len are within proper bounds
if (start < 1 || len < 1) return "";
var iEnd, iLen = jsLen(str);
if (start + len > iLen)
iEnd = iLen;
else
iEnd = (start - 1) + len;
return String(str).substring(start - 1,iEnd);
}


// InStr function written by: Steve Bamelis - steve.bamelis@pandora.be
function jsInstr(nStartCharPos, strSearch1, strSearchFor)
/*
InStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
was found in the string str. (If the character is not
found, -1 is returned.)
Requires use of:
Mid function
Len function
*/
{
if (strSearch1.indexOf(strSearchFor) < 0)
return 0;
else
{
if ((jsLen(strSearch1) - nStartCharPos) >= 0)
{
if (strSearch1.lastIndexOf(strSearchFor) >= (nStartCharPos - 1))
{
var strSearch2 = jsMid(strSearch1, nStartCharPos, jsLen(strSearch1) - nStartCharPos + 1);
return strSearch2.indexOf(strSearchFor) + nStartCharPos;
} 
else
return 0;
}
else
return 0;
}
}

function prompt_confirm_replace_refer_a_friend_coupon1()
{
 	var confirm_msg = {
			state0: {
				html:"A coupon discount cannot be used with a Refer A Friend discount.<div></div>By applying this coupon, you will remove your refer a friend discount.<div></div>Do you wish to proceed?",
				buttons: { Yes: true, No: false },
				submit:function(v,m,f){ 
					if(v)
						$('#frmCoupon').submit();
					$.prompt.close();
					$('.jqi').css('width', '570px');
					$('.jqi').css('top', '40%');
					$('.jqi').css('left', '42%');
					$('.jqimessage').css('width', '575px');
				}
			}
	};
	$.prompt(confirm_msg);
}
function prompt_confirm_replace_refer_a_friend_coupon2(referal_type)
{
 	var confirm_msg = {
			state0: {
				html:"A coupon discount cannot be used with a Refer A Friend discount.<div></div>By applying this coupon, you will remove your refer a friend discount.<div></div>Do you wish to proceed?",
				buttons: { Yes: true, No: false },
				submit:function(v,m,f){ 
					if(v)
					{
						$('#referal_user_type').val(referal_type);
						$('#frmCoupon').submit();
					}
					$.prompt.close();
					$('.jqi').css('width', '570px');
					$('.jqi').css('top', '40%');
					$('.jqi').css('left', '42%');
					$('.jqimessage').css('width', '575px');
				}
			}
	};
	$.prompt(confirm_msg);
}

function update_selected_item_colour(obj, row_number, flag)
{
	loadCartSummary();
	if (flag == 1)
	{
		//alert(obj.options[obj.selectedIndex].text);
		for (row_number1 = 0; row_number1 < 20; row_number1++)
		{
			if ($('#item_color_text_'+row_number1).length)
			{
				if (obj.selectedIndex == 0)
				{
					if ($('#predefined_item_colour_'+row_number1).length)
						$('#item_color_text_'+row_number1).html($('#predefined_item_colour_'+row_number1).val());
				}
				else
					$('#item_color_text_'+row_number1).html(obj.options[obj.selectedIndex].text);

			}
		}
	}
	$('#itemid_'+row_number).val(get_selected_pack_size_item_id(obj.options[obj.selectedIndex].value));
	hideCartLoader();
}

function update_all_selected_item_ids()
{
	loadCartSummary();
	for (var row_number = 1; row_number <= numItems; row_number++)
	{
		$('#itemid_'+row_number).val(get_selected_pack_size_item_id($('#itemid_'+row_number).val()));
	}
	hideCartLoader();
}

function get_selected_pack_size_item_id(equivalent_item_id)
{

	var return_id = 0;
	var found = false;
	var n = 0;

	if ($('#rdoSizeChoiceQueen').attr("checked"))
	{
		while (n < queen_ids.length && !found)
		{
			if (queen_ids[n] == equivalent_item_id)
				found = true;
			else
				n++;
		}
		if (found)
			return_id = equivalent_item_id;
		else
		{
			var found = false;
			var n = 0;
			while (n < king_ids.length && !found)
			{
				if (king_ids[n] == equivalent_item_id)
				{
					return_id = queen_ids[n];
					found = true;
				}
				else
					n++;
			}
		}
	}
	else
	{
		while (n < king_ids.length && !found)
		{
			if (king_ids[n] == equivalent_item_id)
				found = true;
			else
				n++;
		}
		if (found)
			return_id = equivalent_item_id;
		else
		{
			var found = false;
			var n = 0;
			while (n < queen_ids.length && !found)
			{
				if (queen_ids[n] == equivalent_item_id)
				{
					return_id = king_ids[n];
					found = true;
				}
				else
					n++;
			}
		}
	}

	return return_id;
}
