var objectRowStatus = 
[
	["0", "U", "U"],
	["0", "D", "D"],
	["I", "U", "I"],
	["I", "D", "X"],
	["U", "U", "U"],
	["U", "D", "D"]
];


function updateStatus(status, newStatus)
{
	for (var idx=0; idx<objectRowStatus.length; idx++)
	{
		if ( (objectRowStatus[idx][0]==status) && (objectRowStatus[idx][1]==newStatus) )
		{
			return objectRowStatus[idx][2];
		}
	}
	throw "Status errato: attuale = " + status + ", nuovo = " + newStatus;
}



function cartHeaderRecord()
{
	this.wishListId=0;
	this.isPermanent=false;
	this.name='';
	this.notes=null;
	this.isNet = false;
	this.priceAmount = 0;
	this.billingAddressId;
	this.shippingAddressId;
	this.paymentId=null;
	this.shippingId=null;
	this.shippingName=null;
	this.shippingLastName=null;
	this.shippingCompanyName=null;
	this.shippingAddress=null;
	this.shippingZipCode=null;
	this.shippingCity=null;
	this.shippingProvince=null;
	this.shippingCountryId=null;
	this.shippingPhone=null;
	this.shippingFax=null;
	this.shippingMobilePhone=null;
	this.shippingEMail=null;
	this.shippingStateName=null;
	this.shippingPriceAmount=0;
	this.taxPriceAmount=0;
	this.taxId=0;
	this.taxRate=0;
	this.applyTaxRate=false;
	this.differentAddress=false;
	this.percDiscount=0;
	this.discount=0;
	this.bonus=0;	
}


function objectRow (productId, displayCode, description, qty, priceamount, notes) 
{
	this.productId = productId;
	this.displayCode = displayCode;
	this.description = description;	
	this.qty = qty;
	this.notes = notes;
	this.priceAmount = priceamount;
	this.src = "unavailable.jpg"
}




function CartObject() 
{
	this.record = new cartHeaderRecord() 	// dati di testata carrello
	this.cartId = 0;
	this.rows = [];	
}

CartObject.PERSIST_ROWS = 0;
CartObject.PERSIST_HEADER = 1;
CartObject.PERSIST_ALL = 2;


CartObject.REFRESH_ROWS = 0;
CartObject.REFRESH_HEADER = 1;
CartObject.REFRESH_ALL = 2;

CartObject.prototype.WsMethodUrl = "";
CartObject.prototype.WsMethod = "UpdateCart";
CartObject.prototype.WsRefreshMethod = "RefreshCart";
CartObject.prototype.DescriptionType = "M";
CartObject.prototype.ImageType = "N";
CartObject.prototype.ImageId = "1";

CartObject.prototype.addRow
= // =================================
function(row)
{
	var id = -1;
	for (var i=0; i<this.rows.length; i++)
	{
		if (this.rows[i][0] > id) id = this.rows[i][0];
	}
	id++;
	var objRow = [id, "I", row];
	this.rows[this.rows.length] = objRow;
	this.doDataEvent('I', row, id);
	return id;
}

CartObject.prototype.setRowModified 
= // ================================
function(rowId)
{

	for (var idx=0;idx<this.rows.length;idx++)
	{
		if ( this.rows[idx][0] == rowId )
			this.rows[idx][1] = updateStatus(this.rows[idx][1], 'U')
	}

	
}

CartObject.prototype.removeRow
= // =================================
function(rowId)
{
	for (var idx=0;idx<this.rows.length;idx++)
	{
		if ( this.rows[idx][0] == rowId )
		{
			this.rows[idx][1] = updateStatus(this.rows[idx][1], "D");
			this.doDataEvent('D', this.rows[idx][2], rowId);
		}
	}
	
}


CartObject.prototype.removeAll
= // =================================
function()
{
	while (this.length() > 0)
	{
		var id = this.getRowByIndex(0).id;
		this.removeRow(id);
	}
}

CartObject.prototype.updateCompleted 
= // =================================
function ()
{
	var newrows = [];
	for (var i = 0; i<this.rows.length;i++)
	{
		if ( "IU0".indexOf(this.rows[i][1]) >= 0 )
		{
			var newindex = newrows.length;
			newrows[newindex] = this.rows[i];
			newrows[newindex][1] = '0';


		}
	}
	this.rows = newrows;
}


CartObject.prototype.Refresh 
= // ==================================
function (mode)
{

	if (this.cartId == 0) return;

	var SoR = new CSoapRequest(this.WsMethodUrl, this.WsRefreshMethod, "requestMsg");
	var requestObject = {cartId: this.cartId, imageType: this.ImageType, imageId: this.ImageId, descriptionType: this.DescriptionType, refreshMode:mode }
	if (SoR.sendRequestObject(requestObject) == true)
	{
		var objResponse = CXmlDeserializer.Deserialize(null, SoR.responseNode.node());
		
		
		if ( (mode == CartObject.REFRESH_ROWS) || (mode == CartObject.REFRESH_ALL) )
		{
		
			var len = objResponse.tableCartItems.rows.length;
	
			this.rows = [];
			for (var i = 0;i<len;i++)
			{
				var newrow = new objectRow (objResponse.tableCartItems.rows[i]["PRODUCTID"], objResponse.tableCartItems.rows[i]["DISPLAYCODE"], objResponse.tableCartItems.rows[i]["DESCRIPTION"], objResponse.tableCartItems.rows[i]["QUANTITY"], objResponse.tableCartItems.rows[i]["PRICEAMOUNT"],objResponse.tableCartItems.rows[i]["NOTES"]);
				newrow.src=objResponse.tableCartItems.rows[i]["SRC"];
				var rowitem = [objResponse.tableCartItems.rows[i]["ITEMID"], "0", newrow];
				this.rows[this.rows.length] = rowitem;
			}
		}
		
		if ( (mode == CartObject.REFRESH_HEADER) || (mode == CartObject.REFRESH_ALL) )
		{
			var table = objResponse.tableCartHeader;
			

			if (table.rows.length > 0)
			{
				this.record.wishListId = table.rows[0]["WISHLISTID"];
				this.record.isPermanent = table.rows[0]["ISPERMANENT"];
				this.record.name = table.rows[0]["NAME"];
				this.record.notes = table.rows[0]["NOTES"];
				this.record.isNet = table.rows[0]["ISNET"];
				this.record.priceAmount = table.rows[0]["PRICEAMOUNT"];
				this.record.billingAddressId = table.rows[0]["BILLINGADDRESSID"];
				this.record.shippingAddressId = table.rows[0]["SHIPPINGADDRESSID"];
				this.record.paymentId = table.rows[0]["PAYMENTID"];
				this.record.shippingId = table.rows[0]["SHIPPINGID"];
				this.record.shippingName = table.rows[0]["SHIPPINGNAME"];
				this.record.shippingLastName = table.rows[0]["SHIPPINGLASTNAME"];
				this.record.shippingCompanyName = table.rows[0]["SHIPPINGCOMPANYNAME"];
				this.record.shippingAddress = table.rows[0]["SHIPPINGADDRESS"];
				this.record.shippingZipCode = table.rows[0]["SHIPPINGZIPCODE"];
				this.record.shippingCity = table.rows[0]["SHIPPINGCITY"];
				this.record.shippingProvince = table.rows[0]["SHIPPINGPROVINCE"];
				this.record.shippingCountryId = table.rows[0]["SHIPPINGCOUNTRYID"];
				this.record.shippingPhone = table.rows[0]["SHIPPINGPHONE"];
				this.record.shippingFax = table.rows[0]["SHIPPINGFAX"];
				this.record.shippingMobilePhone = table.rows[0]["SHIPPINGMOBILEPHONE"];
				this.record.shippingEMail = table.rows[0]["SHIPPINGEMAIL"];
				this.record.shippingStateName = table.rows[0]["SHIPPINGSTATENAME"];
				this.record.differentAddress = table.rows[0]["DIFFERENTADDRESS"];
				//this.record.TaxRate = 0;
				//this.record.ApplyTaxRate = false;
				this.record.taxRate = table.rows[0]["TAXRATE"];
				this.record.applyTaxRate = table.rows[0]["APPLYTAXRATE"];
				//todo cambiare su cart.js
				this.record.shippingPriceAmount = table.rows[0]["SHIPPINGPRICEAMOUNT"];
				this.record.taxPriceAmount = table.rows[0]["TAXPRICEAMOUNT"];
				this.record.taxId = table.rows[0]["TAXID"];
				this.record.taxRate = table.rows[0]["TAXRATE"];
				this.record.percDiscount = table.rows[0]["PERCDISCOUNT"];
				this.record.discount = table.rows[0]["DISCOUNT"];
				this.record.bonus = table.rows[0]["BONUS"];				
			}
			
		}		
		

	}
	

	this.doDataEvent('R',null, null);
	return true;
	
}


CartObject.prototype.persistToDb
= // =================================
function(mode)
{
	var requestObject = new Object();
	var bNeedUpdate = false;
	requestObject.UpdateMode = mode;
	
	
	if ( (mode == CartObject.PERSIST_HEADER) || (mode == CartObject.PERSIST_ALL) )
	{
		bNeedUpdate = true;
		requestObject.record =
		{
			wishListId : this.record.wishListId,
			isPermanent : this.record.isPermanent,
			name : this.record.name,
			notes : this.record.notes,
			isNet : this.record.isNet,
			billingAddressId : this.record.billingAddressId,
			shippingAddressId : this.record.shippingAddressId,
			paymentId : this.record.paymentId,
			shippingId : this.record.shippingId,
			shippingName : this.record.shippingName,
			shippingLastName : this.record.shippingLastName,
			shippingCompanyName : this.record.shippingCompanyName,
			shippingAddress : this.record.shippingAddress,
			shippingZipCode : this.record.shippingZipCode,
			shippingCity : this.record.shippingCity,
			shippingProvince : this.record.shippingProvince,
			shippingCountryId : this.record.shippingCountryId,
			shippingPhone : this.record.shippingPhone,
			shippingFax : this.record.shippingFax,
			shippingMobilePhone : this.record.shippingMobilePhone,
			shippingEMail : this.record.shippingEMail,
			shippingStateName : this.record.shippingStateName,
			priceAmount: this.record.priceAmount,
			shippingPriceAmount : this.record.shippingPriceAmount,
			taxPriceAmount : this.record.taxPriceAmount,
			taxId : this.record.taxId,
			taxRate : this.record.taxRate,
			applyTaxRate : this.record.applyTaxRate,
			differentAddress : this.record.differentAddress,
			percDiscount : this.record.percDiscount,
			discount : this.record.discount,
			bonus : this.record.bonus			
			
		}
	}


	
	if ( (mode == CartObject.PERSIST_ROWS) || (mode == CartObject.PERSIST_ALL) )
	{
		requestObject.cartRows = [];
		
		
		
		for ( var i = 0;i<this.rows.length;i++)
		{
			if (this.rows[i][1] != 'X')
			{
				bNeedUpdate = true;
				var row = this.rows[i];
				var objrec = {productId: row[2].productId, displayCode: row[2].displayCode, description:row[2].description,qty: row[2].qty,notes: row[2].notes,priceamount: row[2].priceAmount,pricerowamount: row[2].priceRowAmount}
				requestObject.cartRows[requestObject.cartRows.length] = {id: row[0], status: row[1], record:objrec}
			}
		}
	}

	requestObject.cartId=this.cartId;
	
	if (bNeedUpdate)
	{
		var SoR = new CSoapRequest(this.WsMethodUrl, this.WsMethod, "requestMsg");

		if (SoR.sendRequestObject(requestObject) == true)
		{
			var objResponse = CXmlDeserializer.Deserialize(null, SoR.responseNode.node());
			this.cartId = objResponse.cartid;
			this.updateCompleted();		
		}
		else
		{
			requestObject = null;
		}
	}

	return requestObject;
}


CartObject.prototype.isDeletedRow 
= // =================================
function (rowIndex)
{
	return !(this.rows[rowIndex][1] != "D" && this.rows[rowIndex][1] != "X")
}


CartObject.prototype.getRowByIndex
= // =================================
function(rowIndex, bSkipDeleted)
{

	if (bSkipDeleted == null) bSkipDeleted = true;

	for (var i=0,result=-1;i<this.rows.length;i++)
	{
		if (bSkipDeleted)
			result += this.isDeletedRow(i) ? 0 : 1;
		else
			result++;
			
		if (result == rowIndex)
		{
			return {id:this.rows[i][0], data:this.rows[i][2]};
		}
	}
	
	return null;

	
}



CartObject.prototype.getRow
= // =================================
function(rowId)
{
	for (var idx=0;idx<this.rows.length;idx++)
	{
		if ( this.rows[idx][0] == rowId )
			return this.getRowByIndex(idx, false);
	}
	return null;
}


CartObject.prototype.updateRow
= // =================================
function(rowId, newRow)
{
	for (var idx=0;idx<this.rows.length;idx++)
	{
		if ( this.rows[idx][0] == rowId )
		{
			if (newRow != null)
				this.rows[idx][2] = newRow;
			this.rows[idx][1] = updateStatus(this.rows[idx][1], "U");
			this.doDataEvent('U', this.rows[idx][2], rowId);
		}
	}
}


CartObject.prototype.length 
= // ===============================
function ()
{
	for (var i=0,result=0;i<this.rows.length;i++)
	{
		result += this.isDeletedRow(i) ? 0 : 1;
	}
	return result;
}


CartObject.prototype.doDataEvent 
= // ================================
function (eventType, row, rowId) 
{
	if (this.dataEvent != null) this.dataEvent(eventType, row, rowId); 
}


CartObject.prototype.dataEvent = null;
