function ShippingItem(itemid,price,shippingcharge,chargeshipping,listingid, subtotalAdjustments, quantity)
{
	this.itemid = itemid || 0;
	this.price = price || 0;
	this.shippingcharge = shippingcharge || 0;
	this.chargeshipping = chargeshipping || 0;
	this.listingid = listingid || 0;
	
	this.quantity = quantity || 0;
	
	this.discount = 0; // Will get set in the javascript not passed in.
	
	this.subtotalAdjustments = subtotalAdjustments; // array contains sub objects for each adjustment ex. [{'id':#adjustmentId, 'name':#description#, 'percentage':#percentage#, 'flatfee':#flatFee#, 'isTax':#isTax#}, etc.]
}

function ShippingRule(listingid, shipping_minimum_amount, shipping_maximum_amount, shipping_rate, apply_global_shipping_rate)
{
	this.listingid = listingid;
	
	this.shipping_minimum_amount = shipping_minimum_amount;
	this.shipping_maximum_amount = shipping_maximum_amount;
	this.shipping_rate = shipping_rate;
	this.apply_global_shipping_rate = apply_global_shipping_rate;
}

var ShippingRules = new Array();
var ShippingItems = new Array();
var numShippingItems = 0;

function initShippingItem(itemid,price,shippingcharge,chargeshipping,listingid, subtotalAdjustments, quantity)
{
	ShippingItems.push(new ShippingItem(itemid,price,shippingcharge,chargeshipping,listingid, subtotalAdjustments, quantity));
	numShippingItems += 1;
}

function initShippingRule(listingid, shipping_minimum_amount, shipping_maximum_amount, shipping_rate, apply_global_shipping_rate)
{
	ShippingRules.push(new ShippingRule(listingid, shipping_minimum_amount, shipping_maximum_amount, shipping_rate, apply_global_shipping_rate));
}

function getItem(itemid)
{
	for(var i = 0; i < ShippingItems.length; i++)
	{
		if(ShippingItems[i].itemid == itemid)
		{
			return ShippingItems[i];
		}
	}
	return null;
}

function countListingItems(listingid)
{
	var c = 0;
	for(var i = 0; i < ShippingItems.length; i++)
	{
		if(ShippingItems[i].listingid == listingid)
		{
			c++;
		}
	}
	return c;
}

function clearItem(itemid)
{
	for(var i = 0; i < ShippingItems.length; i++)
	{
		if(ShippingItems[i].itemid == itemid)
		{
			var l = ShippingItems[i].listingid;
			ShippingItems[i] = new ShippingItem(0,0,0,0,0, null);
			numShippingItems -= 1;
			updateItemsCount();
			updateOrderTotals(l);
			if(countListingItems(l) == 0)
			{
				$('orderheader_' + l).empty();
				$('orderfooter_' + l).empty();
			}
		}
	}
}

function updateOrderTotals(listingid, itemsOnly)
{
	var orderTotal = 0;
	var subtotal = 0;
	var shippingtotal = 0;
	var adjustmentNames = "";
	var adjustmentValues = "";
	var shipping_was_charged = false;
	
	var subtotalAdjustmentTotals = {}; // object for subtotal adjustment totals. eq. {sa000: totalValue}
	
	for(var i = 0; i < ShippingItems.length; i++)
	{
		if(ShippingItems[i].listingid == listingid)
		{
			ShippingItems[i].productPrice = ShippingItems[i].price;

			//subtotal = subtotal + ShippingItems[i].price;
			
			for(var adjustmentCount = 0; adjustmentCount < ShippingItems[i].subtotalAdjustments.length; adjustmentCount++)
			{
				if(ShippingItems[i].subtotalAdjustments[adjustmentCount] != null)
				{ 
					var currentAdjustment = ShippingItems[i].subtotalAdjustments[adjustmentCount];
                    
					if(subtotalAdjustmentTotals['sa' +  currentAdjustment.id] == undefined)
					{
						subtotalAdjustmentTotals['sa' +  currentAdjustment.id] = {
							total: 0,
							name: currentAdjustment.name
						};
					}
            
                    
					if((currentAdjustment.flatFee < 0) || (currentAdjustment.percentage < 0))
					{
						thisAdjustment = ((ShippingItems[i].price * (currentAdjustment.percentage/100)) + (ShippingItems[i].quantity * currentAdjustment.flatFee));
							
						ShippingItems[i].productPrice += thisAdjustment; // lowers the price, because thisAdjustment is negative
					}
					else
					{
						thisAdjustment = ((ShippingItems[i].productPrice * currentAdjustment.percentage) + (100 * ShippingItems[i].quantity * currentAdjustment.flatFee));                        
						
						/*if(ShippingItems[i].chargeshipping && currentAdjustment.isTax == 1)
						{
							thisAdjustment += (ShippingItems[i].shippingcharge * currentAdjustment.percentage); // no flat on shipping + (100 * currentAdjustment.flatFee));
						}*/
										 
						subtotalAdjustmentTotals['sa' +  currentAdjustment.id].total += thisAdjustment;
					}
				}
			}
			
			subtotal = subtotal + ShippingItems[i].productPrice;
			
			ShippingItems[i].discount = ShippingItems[i].price - ShippingItems[i].productPrice;
			
			if(ShippingItems[i].discount > 0)
			{
				$('discount_row_' + ShippingItems[i].itemid).setStyle("display", "");
				$('discount_' + ShippingItems[i].itemid).innerHTML = '-$' + ShippingItems[i].discount.toFixed(2);
			}
			
			if($('shipping_' + ShippingItems[i].itemid) != null)
			{
				$('total_' + ShippingItems[i].itemid).innerHTML = '$' + ((ShippingItems[i].chargeshipping ? ShippingItems[i].shippingcharge : 0) + (ShippingItems[i].productPrice)).toFixed(2);
			}
			else
			{
				$('total_' + ShippingItems[i].itemid).innerHTML = '$' + (ShippingItems[i].productPrice);
			}
			
			if(ShippingItems[i].chargeshipping)
			{
				shippingtotal = shippingtotal + ShippingItems[i].shippingcharge;
				shipping_was_charged = true;
			}
		}
	}
	
	var promo = promos["p"+listingid];
	var shipping_adjustments_total = 0;
	
	if(shipping_was_charged)
	{
		shippingtotal = applyStoreShippingRules(listingid, subtotal, shippingtotal);
	
		for(adjustmentCount = 0; adjustmentCount < shippingAdjustments.length; adjustmentCount++)
		{
			if(shippingAdjustments[adjustmentCount] != null)
			{ 
				var currentAdjustment = shippingAdjustments[adjustmentCount];
				
				if(subtotalAdjustmentTotals['sa' +  currentAdjustment.id] == undefined)
				{
					subtotalAdjustmentTotals['sa' +  currentAdjustment.id] = {
						total: 0,
						name: currentAdjustment.name
					};
				}
		
				
				if((currentAdjustment.flatFee > 0) || (currentAdjustment.percentage > 0))
				{
					if(currentAdjustment.isTax == 1)
					{
						var shipping_adjustment_increase = (shippingtotal * currentAdjustment.percentage);
						subtotalAdjustmentTotals['sa' +  currentAdjustment.id].total += shipping_adjustment_increase;
						shipping_adjustments_total += (shipping_adjustment_increase/100);
						// no flat on shipping + (100 * currentAdjustment.flatFee));
					}
				}
			}
		}
	}
	
	// finalize the subtotalAdjustments totals
	orderTotal = subtotal + shippingtotal;
	
	/*for(adjustmentCount = 0; adjustmentCount < ShippingItems[0].subtotalAdjustments.length; adjustmentCount++)
	{		
		// Assume percent type
		if(ShippingItems[0].subtotalAdjustments[adjustmentCount] != null)
		{
			var adjustment = subtotalAdjustmentTotals['sa' +  (ShippingItems[0].subtotalAdjustments[adjustmentCount].id)];
			
			adjustment.total = (Math.round(adjustment.total) / 100);
			
			if(adjustment.total > 0)
			{
				adjustmentNames += adjustment.name + ':<br>';
				adjustmentValues += '$' +adjustment.total.toFixed(2) + '<br>';
				orderTotal += adjustment.total;
			}
		}
	}*/
	
	for(adjustment in subtotalAdjustmentTotals)
	{
		subtotalAdjustmentTotals[adjustment].total = (Math.round(subtotalAdjustmentTotals[adjustment].total) / 100);
			
		if(subtotalAdjustmentTotals[adjustment].total != 0)
		{
			adjustmentNames += subtotalAdjustmentTotals[adjustment].name + ':<br>';
			adjustmentValues += '$' + subtotalAdjustmentTotals[adjustment].total.toFixed(2) + '<br>';
			orderTotal += subtotalAdjustmentTotals[adjustment].total;
		}
	}
	
	
	promo_savings = 0; // Amount to deduct from the subtotal
	
	if(promo)
	{
		if(subtotal >= promo.minimum_subtotal)
		{
			switch(promo.type)
			{
				// Free Shipping
				case 1000:
					promo_savings = shippingtotal + shipping_adjustments_total;
					break;
					
				// Discount	
				case 1001:
					if(promo.discount_type == "$")
					{
						promo_savings = promo.value;
					}
					else if(promo.discount_type == "%")
					{
						promo_savings = subtotal * promo.value * 0.01;
					}
					break;
				case 0:
				default:
					// 0 means that there was no promo
					break;
			}
		}
		
		var promo_elem = $("promo_"+listingid);
		if(promo_elem)
		{
			promo_elem.innerHTML = "-$"+ (new Number(promo_savings).toFixed(2));
		}
		
		orderTotal -= promo_savings;
	}
	
	if(!itemsOnly)
	{
		// update order totals
		$('ordersubtotal_' + listingid).innerHTML = '$' + subtotal.toFixed(2);
		if($('adjustmentNames_' + listingid))$('adjustmentNames_' + listingid).innerHTML = adjustmentNames;
		if($('adjustmentValues_' + listingid))$('adjustmentValues_' + listingid).innerHTML = adjustmentValues;
		$('shiptotal_' + listingid).innerHTML = '$' + shippingtotal.toFixed(2);
		$('ordertotal_' + listingid).innerHTML = '$' + orderTotal.toFixed(2);
	}
	
	//return orderTotal;
}

function applyStoreShippingRules(listingid, subtotal, shippingtotal)
{
	var i = 0;
	var rules = null;
	
	// Load the shipping rules for the listing.
	for(i = 0; i < ShippingRules.length; i++)
	{
		if(ShippingRules[i].listingid == listingid)
		{
			rules = ShippingRules[i];
			break;
		}
	}
	
	if(rules != null)
	{
		if(rules.apply_global_shipping_rate == "1")
		{
			if(rules.shipping_rate != "")
			{
				shippingtotal = (subtotal * Number(rules.shipping_rate)) / 100;
			}
			
			if(rules.shipping_minimum_amount != "")
			{
				rules.shipping_minimum_amount = Number(rules.shipping_minimum_amount);
			
				if(shippingtotal <= rules.shipping_minimum_amount)
				{
					shippingtotal =  rules.shipping_minimum_amount;
				}
			}
			
			if(rules.shipping_maximum_amount != "")
			{
				rules.shipping_maximum_amount = Number(rules.shipping_maximum_amount);

				if(shippingtotal >= rules.shipping_maximum_amount)
				{
					shippingtotal = rules.shipping_maximum_amount;
				}	
			}

		}
	}
	
	return shippingtotal;
}

function chargeShipping(itemid)
{
	var i = getItem(itemid);
	i.chargeshipping = 1;
	// show shipping price
	if($('shipping_' + itemid) != null)
	{
		$('shipping_' + itemid).style.color = "#636363";
		$('shipping_' + itemid).style.background = "none";
		$('shippingcharge_' + itemid).innerHTML = '$' + (i.shippingcharge).toFixed(2);

		// update item total
		$('total_' + itemid).innerHTML = '$' + (i.shippingcharge + i.price -i.discount).toFixed(2);
	}
	
	// update order totals
	updateOrderTotals(i.listingid);
}

function chargeOrderShipping(listingid)
{
	for(var i = 0; i < ShippingItems.length; i++)
	{		
		if(listingid == ShippingItems[i].listingid)
		{
			chargeShipping(ShippingItems[i].itemid);
		}
	}
}

function removeShipping(itemid)
{
	var i = getItem(itemid);
	i.chargeshipping = 0;
	if($('shipping_' + itemid) != null)
	{
		// hide shipping price
		$('shipping_' + itemid).style.color = "#959595";
		$('shipping_' + itemid).style.background = "url('line.gif')"
	
		// update item total
		$('total_' + itemid).innerHTML = '$' + (i.price - i.discount).toFixed(2);
	}
	// update order total
	updateOrderTotals(i.listingid);
}

function removeOrderShipping(listingid)
{
	for(var i = 0; i < ShippingItems.length; i++)
	{		
		if(listingid == ShippingItems[i].listingid)
		{
			removeShipping(ShippingItems[i].itemid);
		}
	}
}

function isorderselected()
{
	var g = $('processgc');
	if(g && g.checked)
	{
		return true;
	}
	for(var i = 0; i < ShippingItems.length; i++)
	{
		var c = $('otp' + ShippingItems[i].listingid)
		if(c && c.checked)
		{
			return true;
		}
	}
	alert('Please select at least one order to process.');
	return false;
}

window.addEvent('domready', function(){
	var last_listingid = null;
	for(var i = 0; i < ShippingItems.length; i++)
	{
		updateOrderTotals(ShippingItems[i].itemid, true); // Make sure discounts are calculated.
		
		if(ShippingItems[i].listingid != last_listingid)
		{
			last_listingid = ShippingItems[i].listingid;
			var x = $('shipmethod' + last_listingid + '_2');
			if(x != null && x.checked == true)
			{
				chargeOrderShipping(last_listingid);
			}
			else
			{
				removeOrderShipping(last_listingid);
			}
		}
	}

});

