/******************************************************************************
* gshpBasketManager.js
*******************************************************************************
Gestionnaire d panier (et son complement)
*******************************************************************************
Les fonctions de complement du "basket manager complement" sont :
- runAnalysis							Parametres : manager
- onSubmit								Parametres : manager, formManager, onSubmitResult		Return : Result of check

Les fonctions de remplacement du "basket manager complement" sont :
- overridenRunAnalysis					Parametres : manager
- overridenOnSubmit						Parametres : manager, formManager, onSubmitResult		Return : Result of check

Attention,
 le paramètre onSubmitResult et le résultat des fonctions onSubmit et overridenOnSubmit peut être de type boolean/string/array of string

*******************************************************************************
*                                                                             *
* Copyright 2008									                          *
*                                                                             *
******************************************************************************/

//
// ------------------------------------- class GshpBasketManager
//
function GshpBasketManager()
{
	// Global init
	this._oComplement = null;

	this._initMode = "standard";
	this._basketType = "B2C";
	this._step = 1;
	this._cmd = "";

	this._manageSectoring			= false;
	this._sectoringLabel			= "";
	this._createOneCommandBySector	= false;
	this._limitBasketToSector	    = false;

	// Command types
	this._nbCommandType = 0;
	this._commandTypeMap = new Object();

	// Basket and basket items
	this.currentBasket = null;
	this._basketItemMap = new Object();
	this._sectorBasketItemMap = new Object();

	// Carriers
	this._nbCarrier = 0;
	this._carrierMap = new Object();
}

//	=================== CONSTANTS
//

//	-------------------------------------------------------------------------
//	Global init
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.setInitMode = function(initMode)
{
	this._initMode = initMode;
}

GshpBasketManager.prototype.setBasketType = function(basketType)
{
	this._basketType = basketType;
}

GshpBasketManager.prototype.setBasketState = function(step, cmd)
{
	this._step = step;
	this._cmd = cmd;
}

//	-------------------------------------------------------------------------
//	Sectoring init
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.setSectoring = function(manageSectoring, sectoringLabel, createOneCommandBySector, limitBasketToSector)
{
	this._manageSectoring			= manageSectoring;
	this._sectoringLabel			= sectoringLabel;
	this._createOneCommandBySector	= createOneCommandBySector;
	this._limitBasketToSector	    = limitBasketToSector;
}

//	-------------------------------------------------------------------------
//	Basket init
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.setBasket = function(oid, typeOid, label)
{
	this.currentBasket = new GshpBasket(oid, typeOid, label);
}

GshpBasketManager.prototype.setBasketCount = function(nbItems, quantity)
{
	if (this.currentBasket != null)
		this.currentBasket.setCount(nbItems, quantity);
}

GshpBasketManager.prototype.setBasketAmount = function(amount, vatAmount)
{
	if (this.currentBasket != null)
		this.currentBasket.setAmount(amount, vatAmount);
}

//	-------------------------------------------------------------------------
//	Addition of command types
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.addCommandTypes = function(list)
{
	for (var i=0; i<list.length; i++) {
		var record = list[i].split("|");
		var commandType = new GshpCommandType();
		if (commandType != null) {
			commandType.init(record);
			this._commandTypeMap[commandType.oid] = commandType;
			this._nbCommandType++;
		}
	}
}

//	-------------------------------------------------------------------------
//	Addition of basket items
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.addBasketItems = function(type, list)
{
	if (this.currentBasket == null) return;

	for (var i=0; i<list.length; i++) {
		var record = list[i].split("|");
		var basketItem = this.currentBasket.addBasketItem(type, record);

		// Map to find basket item
		if (basketItem != null) {
			this._basketItemMap[basketItem.oid] = basketItem;

			var sector = basketItem.sector;
			var basketItemList = this._sectorBasketItemMap[sector];
			if (basketItemList == null) this._sectorBasketItemMap[sector] = basketItemList = new Array();
			basketItemList[basketItemList.length] = basketItem;
		}
	}
}

//	-------------------------------------------------------------------------
//	Addition of carrier
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.addCarrier = function(descr)
{
	var record = descr.split("|");
	var carrier = new GshpCarrier();
	if (carrier != null) {
		carrier.init(record);
		this._carrierMap[carrier.oid] = carrier;
		this._nbCarrier++;
	}
}
//	-------------------------------------------------------------------------
//	Analysis of step
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.runAnalysis = function()
{
	// Override by manager complement
	if ((this._oComplement != null) && (typeof(this._oComplement.overridenRunAnalysis) == "function"))
		return this._oComplement.overridenRunAnalysis(this);

	// Analysis of step context
	if (this._step == 1) {
		var hideOrderBtn = false;

		// -  Check about 'minimal quantity' and 'by how much' values
		for (var oid in this._basketItemMap) {
			var basketItem = this._basketItemMap[oid];
			var warningMsg = "";
			if (basketItem.byHowMuch > 1) {
				var quantity = basketItem.quantity;
				if (isNaN(quantity) || (quantity < 0)) quantity = 0;
				if (quantity != 0) {
					var multiple1 = (quantity/basketItem.byHowMuch);
					var multiple2 = Math.ceil(multiple1);
					if (multiple2 != multiple1) {
						warningMsg = objThesaurus.translate("gshpInsufficientQuantityForByHowMuch", ""+basketItem.byHowMuch);
					}
				}
			}

			if (basketItem.minimalQuantity > 1) {
				if (basketItem.quantity < basketItem.minimalQuantity) {
					if (warningMsg != "") warningMsg += "<br/>";
					warningMsg += objThesaurus.translate("gshpInsufficientQuantityForMinimal", ""+basketItem.minimalQuantity);
				}
			}

			// Display of warning message
			if (warningMsg != "") {
				hideOrderBtn = true;
				var warningMsgSpan = document.getElementById("gshpWarningQuantityMsg_" + basketItem.oid);
				if (warningMsgSpan != null) {
					warningMsgSpan.style.display = "block";
					warningMsgSpan.innerHTML = warningMsg;
				}
				else {
					var warningMsgSpan = document.getElementById("gshpWarningProductQuantityMsg_" + basketItem.productOid);
					if (warningMsgSpan != null) {
						warningMsgSpan.style.display = "block";
						warningMsgSpan.innerHTML = objThesaurus.translate("gshpInsufficientProductQuantity");
					}
				}
			}
		}

		// -  Check about command type
		if ((this.currentBasket != null) && (this.currentBasket.typeOid != "")) {
			var warningMsg = "";
			var commandType = this._commandTypeMap[this.currentBasket.typeOid];
			if (commandType == null)
				warningMsg = objThesaurus.translate("gshpUndefinedClientCommandType");
			else
			if (commandType.userHasVisibilityRights == false) 
				warningMsg = objThesaurus.translate("gshpClientCommandTypeInvalidRights");
			else
			if (commandType.isValidDate == false) 
				warningMsg = objThesaurus.translate("gshpClientCommandTypeInvalidDate");
			else
			if (commandType.isValid == false) 
				warningMsg = objThesaurus.translate("gshpInvalidClientCommandType");
			else
			if ( !(((commandType.thresholdMin == null) || (commandType.thresholdMin <= this.currentBasket.amount)) &&
				   ((commandType.thresholdMax == null) || (commandType.thresholdMax >= this.currentBasket.amount))))
				warningMsg = objThesaurus.translate("gshpClientCommandTypeInvalidThreshold");

			// Display of warning message
			if (warningMsg != "") {
				hideOrderBtn = true;
				var warningMsgSpan = document.getElementById("gshpWarningCommandTypeMsg");
				if (warningMsgSpan != null) {
					warningMsgSpan.style.display = "block";
					warningMsgSpan.innerHTML = warningMsg;
				}
			}
		}

		// Disabling of button to go to next step
		if (hideOrderBtn == true) {
			var orderDiv = document.getElementById("gshpBasketButtonDiv_command");
			if (orderDiv != null)
				orderDiv.style.display = "none";
		}
	}

	// Add-on by manager complement
	if ((this._oComplement != null) && (typeof(this._oComplement.runAnalysis) == "function"))
		this._oComplement.runAnalysis(this);
}

//	-------------------------------------------------------------------------
//	OnSubmit of form
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.onSubmit = function(formManager, onSubmitResult)
{
	if (onSubmitResult == null) onSubmitResult = true;

	// Override by manager complement
	if ((this._oComplement != null) && (typeof(this._oComplement.overridenOnSubmit) == "function"))
		return this._oComplement.overridenOnSubmit(this, formManager, onSubmitResult);

	// Analysis of step context
	if (this._basketType == "B2C") { 
		if (this._step == 2)
			onSubmitResult = gshpCheckInscriptionForm(formManager);
		else
		if (this._step == 4)
			onSubmitResult = gshpCheckShippingForm("carrier");
		else
		if (this._step == 5)
			onSubmitResult = gshpCheckPaymentForm();
	}
	else
	if (this._basketType == "B2B") { 
		if (this._step == 2)
			onSubmitResult = gshpCheckShippingForm("shippingCarrier");
		else
		if (this._step == 3)
			onSubmitResult = gshpCheckPaymentForm();
	}

	// Add-on by manager complement
	if ((this._oComplement != null) && (typeof(this._oComplement.onSubmit) == "function"))
		onSubmitResult = this._oComplement.onSubmit(this, formManager, onSubmitResult);

	return onSubmitResult;
}

//	-------------------------------------------------------------------------
//	getManagerComplement/setManagerComplement
//	Get/Set of basket manager complement
//	-------------------------------------------------------------------------
GshpBasketManager.prototype.getManagerComplement = function()
{
	return this._oComplement;
}

GshpBasketManager.prototype.setManagerComplement = function(managerComplement)
{
	this._oComplement = managerComplement;
}


//
// ------------------------------------- class GshpCommandType
//
function GshpCommandType()
{
	// Data
	this.oid 					= "";
	this.code 					= "";
	this.label 					= "";
	this.startDate				= null;
	this.endDate				= null;
	this.thresholdMin 			= null;
	this.thresholdMax 			= null;
	this.isValid				= false;
	this.userHasVisibilityRights= false;
	this.isValidDate			= false;
}

//	-------------------------------------------------------------------------
//	Init
//	-------------------------------------------------------------------------
GshpCommandType.prototype.init = function(record)
{
	// Reading of record
	this.oid 			= record[0];
	this.code 			= record[1];
	this.label 			= record[2];

	this.startDate				= (record[3] == "") ? null : parseFloat(record[3]);
	this.endDate				= (record[4] == "") ? null : parseFloat(record[4]);
	this.thresholdMin			= (record[5] == "") ? null : parseFloat(record[5]);
	this.thresholdMax			= (record[6] == "") ? null : parseFloat(record[6]);
	this.isValid				= (record[7] == "true");
	this.userHasVisibilityRights= (record[8] == "true");
	this.isValidDate			= (record[9] == "true");
}


//
// ------------------------------------- class GshpCarrier
//
function GshpCarrier()
{
	// Data
	this.oid 		= "";
	this.code 		= "";
	this.codeISO	= "";
	this.codeERP	= "";
	this.label		= "";
	this.price		= null;
	this.vatPrice	= null;
	this.isValid	= false;
}

//	-------------------------------------------------------------------------
//	Init
//	-------------------------------------------------------------------------
GshpCarrier.prototype.init = function(record)
{
	// Reading of record
	this.oid 		= record[0];
	this.code 		= record[1];
	this.codeISO	= record[2];
	this.codeERP	= record[3];
	this.label		= unescape(record[4]);
	this.price		= parseFloat(record[5]);
	this.vatPrice	= parseFloat(record[6]);
	this.isValid	= (record[7] == "true");
}


// ------------------------------------- Global object
//
var objGshpBasketManagerComplement;	// May be overriden by decor
var objGshpBasketManager = new GshpBasketManager();

// Recovery of overriden of default manager complement
if (objGshpBasketManagerComplement != null)
	objGshpBasketManager.setManagerComplement( objGshpBasketManagerComplement );
else
	objGshpBasketManager.setManagerComplement( new GshpBasketManagerComplement() );