// OGGETTI    
function Vehicle() {

	this.step;
	this.lang;

	this.Model = new Model;
	this.Mvs = new Mvs;
	this.MvsInnerPreparation = new MvsInnerPreparation;
	this.MvsBodyColor = new MvsBodyColor;
	this.Optional = new Optional;
	this.Promo = new Promo;

	this.Optionals = new Array();
	this.Promos = new Array();
	this.Filters=new Array();

	this.setModel = setModel;
	this.setMvs = setMvs;
	this.setMvsBodyColor = setMvsBodyColor;
	this.setMvsInnerPreparation = setMvsInnerPreparation;
	this.addOptional = addOptional;
	this.delOptional = delOptional;

}

function Model(codeArg,categoryArg,descArg,imgSmallArg,flashNameArg,imgBigArg,imgNormalArg) {
	this.code = codeArg;
	this.category = categoryArg;
	this.desc = descArg;
	this.imgSmall = imgSmallArg;
	this.flashName = flashNameArg;
	this.imgBig=imgBigArg;
	this.imgNormal=imgNormalArg;
}

function Mvs(codeArg,descArg,imgSmallArg,priceArg,priceNoVatArg) {
	this.code = codeArg;
	this.desc = descArg;
	this.imgSmall = imgSmallArg;
	this.price = priceArg;
	this.priceNoVat = priceNoVatArg;
}

function MvsBodyColor(codeArg,descArg,imgSmallArg,priceArg,codeOptArg,paraFlashArg,priceNoVatArg) {
	this.code = codeArg;
	this.desc = descArg;
	this.imgSmall = imgSmallArg;
	this.price = priceArg;
	this.codeOpt = codeOptArg;
	this.paraFlash = paraFlashArg;
	this.priceNoVat = priceNoVatArg;
}

function MvsInnerPreparation(codeArg,descArg,imgSmallArg,imgNormalArg,imgBigArg,priceArg,codeOptArg, priceNoVatArg) {
	this.code = codeArg;
	this.desc = descArg;
	this.imgSmall = imgSmallArg;
	this.imgNormal = imgNormalArg;
	this.imgBig = imgBigArg;
	this.price = priceArg;
	this.codeOpt = codeOptArg;
	this.priceNoVat = priceNoVatArg;
}

// Uricchio
// Aggiunta di tutti i parametri mancanti dagli ultimi aggiornamenti
function Optional(codeArg,optTypeArg,descArg,categoryArg,categoryTitleArg,imgSmallArg,imgNormalArg,imgBigArg,flashNameArg,priceArg,infoArg,priceNoVatArg,buybackLinkedToMvsArg,buybackPercentArg,flashBigNameArg,isCompanyCarEnableArg,isCompanyCarIncludeArg,familyArg) {
	this.code = codeArg;
	this.optType = optTypeArg;
	this.desc = descArg;
	this.category = categoryArg;
	this.categoryTitle = categoryTitleArg;
	this.imgSmall = imgSmallArg;
	this.imgNormal = imgNormalArg;
	this.imgBig = imgBigArg;
	this.flashName = flashNameArg;
	this.price = priceArg;
	this.info = infoArg;
    this.priceNoVat=priceNoVatArg;
    this.buybackLinkedToMvs=buybackLinkedToMvsArg;
    this.buybackPercent=buybackPercentArg;
    this.flashBigName=flashBigNameArg;
    this.isCompanyCarEnable = isCompanyCarEnableArg;
	this.isCompanyCarInclude = isCompanyCarIncludeArg;
	this.family = familyArg;
}

//BEGIN LCV EXTENSION
function Filter(codeTypeArg,showAsArg,codeSelectedArg,valueSelectedArg,descArg,titleArg,filterAllowedValuesArg){
	this.codeType=codeTypeArg;//COD_TIPO_DATO_TECNICO
	this.showAs=showAsArg; //Allowed: 'I' - 'C'
	this.codeSelected=codeSelectedArg;
	this.valueSelected=valueSelectedArg;
	this.desc=descArg;
	this.title=titleArg;
	this.filterAllowedValues=filterAllowedValuesArg; //Array of FilterValue objects
}
function FilterAllowedValue(codeArg,valueArg,imageArg){
	this.code=codeArg;//COD_DATO_TECNICO
	this.value=valueArg;
	this.image=imageArg;
}
function MvsTD(mvsCodeArg,techDataValuesArg){
	this.mvsCode=mvsCodeArg;
	this.techDataValues=techDataValuesArg; //Array of TechDataValue objects
}
function TDV(codeTypeArg,codeArg,valueArg){ //TechDataValue
	this.codeType=codeTypeArg;
	this.code=codeArg;
	this.value=valueArg;
}

//END LCV EXTENSION

// Set Method
function setModel(code) {

	for (i = 0; i < ModelList.length; i++) {
		if (ModelList[i].code == code) {
			Vehicle.Model = ModelList[i];
			break;
		}
	}

}

function setMvs(code) {

	for (i = 0; i < MvsList.length; i++) {
		if (MvsList[i].code == code) {
			Vehicle.Mvs = MvsList[i];
			break;
		}
	}
}

function setMvsBodyColor(code) {
	//cancellazione eventuale promo precedente
	for(var i in Vehicle.Promos){
		//alert("checking promo: "+Vehicle.Promos[i].objCode+" vs. "+Vehicle.MvsBodyColor.codeOpt);
		if(Vehicle.Promos[i].obj=="OPT" && Vehicle.Promos[i].objCode == Vehicle.MvsBodyColor.codeOpt){
			//alert("deleting promo: "+Vehicle.MvsBodyColor.codeOpt);
			//delPromoIfPresent('OPT', Vehicle.MvsBodyColor.codeOpt);
			break;
		}
	}
	for (var i = 0; i < MvsBCList.length; i++) {
		if (MvsBCList[i].code == code) {
			Vehicle.MvsBodyColor = MvsBCList[i];
			if(Vehicle.MvsBodyColor.codeOpt!=""){
				//addPromoIfPresent('OPT', Vehicle.MvsBodyColor.codeOpt);
			}
			break;
		}
	}
}

function setMvsInnerPreparation(code) {
	//cancellazione eventuale promo precedente
	for(var i in Vehicle.Promos){
		//alert("checking promo: "+Vehicle.Promos[i].objCode+" vs. "+Vehicle.MvsInnerPreparation.codeOpt);
		if(Vehicle.Promos[i].obj=="OPT" && Vehicle.Promos[i].objCode == Vehicle.MvsInnerPreparation.codeOpt){
			//alert("deleting promo: "+Vehicle.MvsInnerPreparation.codeOpt);
			delPromoIfPresent('OPT', Vehicle.MvsInnerPreparation.codeOpt);
			break;
		}
	}
	for (i = 0; i < MvsIPList.length; i++) {
		if (MvsIPList[i].code == code) {
			Vehicle.MvsInnerPreparation = MvsIPList[i];
			if(Vehicle.MvsInnerPreparation.codeOpt!=""){
				addPromoIfPresent('OPT', Vehicle.MvsInnerPreparation.codeOpt);
			}
			break;
		}
	}
}

function addOptional(code) {
	for (i = 0; i < OptionalList.length; i++) {
		if (OptionalList[i].code == code) {
			//non aggiungo se gia' optional BC o IP
			if(code==Vehicle.MvsBodyColor.codeOpt || code==Vehicle.MvsInnerPreparation.codeOpt){
				continue;
			}
			Vehicle.Optionals[code] = OptionalList[i];
			addPromoIfPresent('OPT', code);
			break;
		}
	}
}

function delOptional(code) {
	var newArr = new Array();
	var cont = 0;
	var hasCerchione=false;
	for (var Ox in Vehicle.Optionals) {
		if(code != Vehicle.Optionals[Ox].code){
			newArr[Vehicle.Optionals[Ox].code] = Vehicle.Optionals[Ox];
			cont++;
			if(Vehicle.Optionals[Ox].category == '-') {
				hasCerchione=true;
			}
			delPromoIfPresent('OPT', code);
		}
		else{
			delPromoIfPresent('OPT', code);
		}
	}
	Vehicle.Optionals = newArr;
	if(!hasCerchione){
		for(i=0 ;i<OptionalList.length; i++){
			if(OptionalList[i].category=='-'){
				setOptional(OptionalList[i].code);
				break;
			}
		}
	}
}

function setOptional(code) {
	for (i = 0; i < OptionalList.length; i++) {
		if (OptionalList[i].code == code) {
			VOTemp = new Array();
			VOTemp[0]=code;
			var cont=1;
			for (var Ox in Vehicle.Optionals) {
				if (Vehicle.Optionals[Ox].category != OptionalList[i].category) {
					VOTemp[cont]=Vehicle.Optionals[Ox].code;
					cont++;
				}
				else{
					delPromoIfPresent('OPT', Vehicle.Optionals[Ox].code);
				}
			}
			//assembling
			Vehicle.Optionals=new Array();
			for(var j=0;j<VOTemp.length;j++){
				addOptional(VOTemp[j]);
			}
			addPromoIfPresent('OPT', code);
			break;
		}
	}
}


 
/* PROMOZIONI */
function Promo(codeArg,descArg,promoTypeArg,choiceArg,communicationArg,priceArg,objArg,objCodeArg,startStateArg,switchableArg,discountArg,targetDiscountArg,priceNoVatArg,discountNoVatArg,popupDescArg,esclusiveInTypeArg) {
	this.code  = codeArg;
	this.desc  = descArg;
	this.promoType  = promoTypeArg; //A to F
	this.choice  = choiceArg;
	this.communication  = communicationArg;
	this.price = priceArg;
	this.obj   = objArg; // OPT oppure MVS
	this.objCode = objCodeArg;
	this.startState = startStateArg;
	this.switchable = switchableArg;
	this.discount = discountArg;
	this.targetDiscount = targetDiscountArg;
	this.priceNoVat = priceNoVatArg;
	this.discountNoVat = discountNoVatArg;
	this.popupDesc = popupDescArg;
	this.esclusiveInType = esclusiveInTypeArg;
}

function addPromo(code) {
	var esclusiveInType=false;
	var promo;
	for (var i = 0; i < PromoList.length; i++) {
		if (PromoList[i].code == code && (PromoList[i].promoType!="MVS" || PromoList[i].objCode==Vehicle.Mvs.code)){
			promo=PromoList[i];
			if(promo.esclusiveInType=="1"){
				esclusiveInType=true;
			}
		}
	}
	//promozioni esclusive
	for(var i in Vehicle.Promos){
		if(promo!=null){
			if(Vehicle.Promos[i].promoType==promo.promoType){
				if(esclusiveInType){
					//cancello tutte le promozioni dello stesso tipo
					//solo se a loro volta esclusive				
					if(Vehicle.Promos[i].esclusiveInType=="1"){
						delPromo(Vehicle.Promos[i].code);
					}
				}
			}
		}
	}
	if(promo!=null){
		Vehicle.Promos[code] = promo;
	}
}

function delPromo(code) {
	var newArr = new Array();
	for (var Ox in Vehicle.Promos) {
		if(code != Vehicle.Promos[Ox].code){
			newArr[Vehicle.Promos[Ox].code] = Vehicle.Promos[Ox];
		}
	}
	Vehicle.Promos = newArr;
}

function clearPromos(){
	Vehicle.Promos = new Array();
}

function addPromoIfPresent(obj, objCode){
	if(PromoList!=null){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj==obj && PromoList[i].objCode==objCode){
				addPromo(PromoList[i].code);
			}
		}
	}
}

function delPromoIfPresent(obj, objCode){
	if(PromoList!=null){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj==obj && PromoList[i].objCode==objCode){
				delPromo(PromoList.code);
			}
		}
	}
}


/* torna booleano se la linea del boxPrice deve essere visualizzata
tipi di prezzo:
- basicPrice
- basicPricePromo
- optPrice
- optPricePromo
- totalPrice
*/
function boxPriceLine(type) {
	var hasPaymentOpt=false;
	if(Vehicle.step==0) return false; //exitPoint
	if(Vehicle.step>0){
		//BASICPRICE E TOTALPRICE
		if(type=='basicPrice' || type=='totalPrice') return true;
		//BASICPRICEPROMO
		if(type=='basicPricePromo'){
			if(Vehicle.Promos!=null){
				for (var x in Vehicle.Promos) {
					if(Vehicle.Promos[x].obj!=null && Vehicle.Promos[x].obj=='MVS'){
						if(Vehicle.Promos[x].promoType=='B' || Vehicle.Promos[x].promoType=='F'
						   || (Vehicle.Promos[x].promoType=='E' && Vehicle.Promos[x].targetDiscount=="01" )){
							return true; //exitPoint
						}
						if(Vehicle.Promos[x].promoType=='A' && Vehicle.Promos[x].priceNoVat<0){
							return true;
						}
						if(Vehicle.Promos[x].promoType=='A' && Vehicle.Promos[x].priceNoVat>0){
							return true;
						}
					}
				}
			}
		}
		
		//OPTPRICE
		//ricerca se l'utente ha selezionato almeno un optional a pagamento
		if(Vehicle.Optionals!=null){
			for (var Ox in Vehicle.Optionals) {
				if(Vehicle.Optionals[Ox].priceNoVat!=null && Vehicle.Optionals[Ox].priceNoVat!=0){
					hasPaymentOpt=true;
					break;
				}
			}
		}
		//aggiunta prezzo BC e IP
		if(Vehicle.MvsBodyColor!= null && Vehicle.MvsBodyColor.priceNoVat!=null && Vehicle.MvsBodyColor.priceNoVat!=0) hasPaymentOpt=true;
		if(Vehicle.MvsInnerPreparation!= null && Vehicle.MvsInnerPreparation.priceNoVat!=null && Vehicle.MvsInnerPreparation.priceNoVat!=0) hasPaymentOpt=true;
		if(type=='optPrice' && hasPaymentOpt) return true; //exitPoint
		
		//OPTPRICEPROMO
		if(Vehicle.Promos!=null && Vehicle.Optionals!=null  && hasPaymentOpt){
			for (var Ox in Vehicle.Promos) {
				if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='OPT' 
				   && (Vehicle.Promos[Ox].promoType=='C')){
					for (var Oy in Vehicle.Optionals) {
						if(Vehicle.Promos[Ox].objCode==Vehicle.Optionals[Oy].code){
							return true; //exitPoint
						}
					}
				}
			}
		}
		//aggiunta promo BC e IP
		if(Vehicle.MvsBodyColor.codeOpt!= null && Vehicle.MvsBodyColor.codeOpt!=''){
			for(var i=0;i<PromoList.length;i++){
				if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
				   && (PromoList[i].promoType=='C')){
				   if(PromoList[i].objCode==Vehicle.MvsBodyColor.codeOpt || PromoList[i].objCode==Vehicle.MvsInnerPreparation.codeOpt){
						return true; //exitPoint
					}
				}
			}
		}
	}
	//defaut
	return false;
} 

// INIZIO FUNZIONE CHE RITORNA IL PREZZO 
function calculatePrice(type) {    
	var hasPaymentOpt=false;
	if(Vehicle.step==0) return false; //exitPoint
	//BASICPRICE
	var basicPrice=Vehicle.Mvs.price;
	if(type=='basicPrice') return basicPrice; //exitPoint
	
	//BASICPRICEPROMO
	var basicPricePromo=basicPrice;
	
	if(Vehicle.Promos!=null){
		//loop 1 ricerca del prezzo base promozionale iniziale
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='F' ){
					basicPricePromo=Vehicle.Promos[Ox].price; 
				}
			}
		}
		//loop 2 aggiunta sconti
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='E' && Vehicle.Promos[Ox].targetDiscount=="01" ){
					//absolute value
					if(Vehicle.Promos[Ox].discount<0){
						basicPricePromo=Vehicle.Mvs.price+(Vehicle.Promos[Ox].discount);
					}
					//percent value
					if(Vehicle.Promos[Ox].discount>0){
						basicPricePromo=Vehicle.Mvs.price - (Vehicle.Mvs.price * (Vehicle.Promos[Ox].discount/100)); 
					}
				}
			}
		}
		//loop 3 ricerca del prezzo base promozionale rottamazione (sopravanza la promozione iniziale)
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='B'){
					basicPricePromo=Vehicle.Promos[Ox].price; 
				}
			}
		}
		
	}
	
	if(type=='basicPricePromo') return basicPricePromo;
	
	//OPTPRICE
	//somma degli optional a pagamento
	var optPrice=0;
	if(Vehicle.Optionals!=null){
		for (var Ox in Vehicle.Optionals) {
			if(Vehicle.Optionals[Ox].price!=null && Vehicle.Optionals[Ox].price!=0){
				optPrice+=Vehicle.Optionals[Ox].price;
				hasPaymentOpt=true;
			}
		}
	}
	//aggiunta prezzo BC e IP
	if(Vehicle.MvsBodyColor!= null && Vehicle.MvsBodyColor.price!=null){
		optPrice+=Vehicle.MvsBodyColor.price;
		hasPaymentOpt=true;
	}
	if(Vehicle.MvsInnerPreparation!= null && Vehicle.MvsInnerPreparation.price!=null){
		optPrice+=Vehicle.MvsInnerPreparation.price;
		hasPaymentOpt=true;
	}
	if(type=='optPrice') return optPrice; //exitPoint
	 
	//OPTPRICEPROMO
	var optPriceDiscount=0;
	if(Vehicle.Promos!=null && Vehicle.Optionals!=null  && hasPaymentOpt){
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='OPT' 
			   && (Vehicle.Promos[Ox].promoType=='C')){
				for (var Oy in Vehicle.Optionals) {
					if(Vehicle.Promos[Ox].objCode==Vehicle.Optionals[Oy].code){
						optPriceDiscount+=Vehicle.Promos[Ox].price;
					}
				}
			}
		}
	}
	//aggiunta promo BC 
	if(Vehicle.MvsBodyColor.codeOpt!= null && Vehicle.MvsBodyColor.codeOpt!=''){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
			   && (PromoList[i].promoType=='C')){
			   if(PromoList[i].objCode==Vehicle.MvsBodyColor.codeOpt){
					optPriceDiscount+=PromoList[i].price; 
				}
			}
		}
	}
	//aggiunta promo IP
	if(Vehicle.MvsInnerPreparation.codeOpt!= null && Vehicle.MvsInnerPreparation.codeOpt!=''){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
			   && (PromoList[i].promoType=='C')){
			   if(PromoList[i].objCode==Vehicle.MvsInnerPreparation.codeOpt){
					optPriceDiscount+=PromoList[i].price; 
				}
			}
		}
	}
	var optPricePromo=optPrice+optPriceDiscount;
	if(type=='optPricePromo') return optPricePromo; //exitPoint
	  
	//TOTALPRICE
	var totalPrice=basicPricePromo+optPricePromo;
	var totalPriceDiscount=0;
	//applying discount promo 
	if(type=='totalPrice'){
		if(Vehicle.Promos!=null){
			//passo da promolist per mantenere l'ordine di calcolo
			for(var i=0;i<PromoList.length;i++){
				if(Vehicle.Promos[PromoList[i].code]!=null){
					var promo=PromoList[i];
					if(promo.obj!=null && promo.obj=='MVS' && PromoList[i].objCode==Vehicle.Mvs.code){
						//type E
						if(promo.promoType=='E' && promo.targetDiscount=="02"){
							//absolute value
							if(promo.discount<0){
								totalPriceDiscount+= -(promo.discount);
							}
							//percent value
							if(promo.discount>0){
								totalPriceDiscount+= (totalPrice-totalPriceDiscount) * (promo.discount/100);
							}
						}
						//type A
						if(promo.promoType=='A' ){
							//absolute value
							if(promo.price<0){
								totalPriceDiscount+= -(promo.discount);
							}
							//percent value
							if(promo.price>0){
								totalPriceDiscount+= (totalPrice-totalPriceDiscount)* (promo.discount/100);
							}
						}
					}
				}
			}
		}
		totalPrice=totalPrice-totalPriceDiscount;
		return totalPrice;
	}
	if(type=='totalPriceNoPromo') return totalPrice;
}

/* OLD
function calculatePrice(type) {    
	var hasPaymentOpt=false;
	if(Vehicle.step==0) return false; //exitPoint
	//BASICPRICE
	var basicPrice=Vehicle.Mvs.price;
	if(type=='basicPrice') return basicPrice; //exitPoint
	
	//BASICPRICEPROMO
	var basicPricePromo=basicPrice;
	
	if(Vehicle.Promos!=null){
		//loop 1 ricerca del prezzo base promozionale iniziale
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='F' ){
					basicPricePromo=Vehicle.Promos[Ox].price; 
				}
			}
		}
		//loop 2 aggiunta sconti
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='E' && Vehicle.Promos[Ox].targetDiscount=="01" ){
					//absolute value
					if(Vehicle.Promos[Ox].discount<0){
						basicPricePromo=Vehicle.Mvs.price+(Vehicle.Promos[Ox].discount);
					}
					//percent value
					if(Vehicle.Promos[Ox].discount>0){
						basicPricePromo=Vehicle.Mvs.price - (Vehicle.Mvs.price * (Vehicle.Promos[Ox].discount/100)); 
					}
				}
				if(Vehicle.Promos[Ox].promoType=='A' ){
					basicPricePromo=basicPricePromo + Vehicle.Promos[Ox].price;
				}
			}
		}
		//loop 3 ricerca del prezzo base promozionale rottamazione (sopravanza la promozione iniziale)
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='B'){
					basicPricePromo=Vehicle.Promos[Ox].price; 
				}
			}
		}
		
	}
	
	if(type=='basicPricePromo') return basicPricePromo;
	
	//OPTPRICE
	//somma degli optional a pagamento
	var optPrice=0;
	if(Vehicle.Optionals!=null){
		for (var Ox in Vehicle.Optionals) {
			if(Vehicle.Optionals[Ox].price!=null && Vehicle.Optionals[Ox].price!=0){
				optPrice+=Vehicle.Optionals[Ox].price;
				hasPaymentOpt=true;
			}
		}
	}
	//aggiunta prezzo BC e IP
	if(Vehicle.MvsBodyColor!= null && Vehicle.MvsBodyColor.price!=null){
		optPrice+=Vehicle.MvsBodyColor.price;
		hasPaymentOpt=true;
	}
	if(Vehicle.MvsInnerPreparation!= null && Vehicle.MvsInnerPreparation.price!=null){
		optPrice+=Vehicle.MvsInnerPreparation.price;
		hasPaymentOpt=true;
	}
	if(type=='optPrice') return optPrice; //exitPoint
	 
	//OPTPRICEPROMO
	var optPriceDiscount=0;
	if(Vehicle.Promos!=null && Vehicle.Optionals!=null  && hasPaymentOpt){
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='OPT' 
			   && (Vehicle.Promos[Ox].promoType=='C')){
				for (var Oy in Vehicle.Optionals) {
					if(Vehicle.Promos[Ox].objCode==Vehicle.Optionals[Oy].code){
						optPriceDiscount+=Vehicle.Promos[Ox].price;
					}
				}
			}
		}
	}
	//aggiunta promo BC 
	if(Vehicle.MvsBodyColor.codeOpt!= null && Vehicle.MvsBodyColor.codeOpt!=''){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
			   && (PromoList[i].promoType=='C')){
			   if(PromoList[i].objCode==Vehicle.MvsBodyColor.codeOpt){
					optPriceDiscount+=PromoList[i].price; 
				}
			}
		}
	}
	//aggiunta promo IP
	if(Vehicle.MvsInnerPreparation.codeOpt!= null && Vehicle.MvsInnerPreparation.codeOpt!=''){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
			   && (PromoList[i].promoType=='C')){
			   if(PromoList[i].objCode==Vehicle.MvsInnerPreparation.codeOpt){
					optPriceDiscount+=PromoList[i].price; 
				}
			}
		}
	}
	var optPricePromo=optPrice+optPriceDiscount;
	if(type=='optPricePromo') return optPricePromo; //exitPoint
	  
	//TOTALPRICE
	var totalPrice=basicPricePromo+optPricePromo;
	var totalPriceDiscount=0;
	//applying discount promo type E
	if(type=='totalPrice'){
		if(Vehicle.Promos!=null){
			for (var Ox in Vehicle.Promos) {
				if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
					if(Vehicle.Promos[Ox].promoType=='E' && Vehicle.Promos[Ox].targetDiscount=="02"){
						//absolute value
						if(Vehicle.Promos[Ox].discount<0){
							totalPriceDiscount=-(Vehicle.Promos[Ox].discount);
						}
						//percent value
						if(Vehicle.Promos[Ox].discount>0){
							totalPriceDiscount=totalPrice*(Vehicle.Promos[Ox].discount/100);
						}
					}
				}
			}
		}
		totalPrice=totalPrice-totalPriceDiscount;
		return totalPrice;
	}
	if(type=='totalPriceNoPromo') return totalPrice;
} 
*/

// FINE FUNZIONE CHE VISUALIZZA IL PREZZO
 
// INIZIO FUNZIONE CHE RITORNA IL PREZZO SENZA IVA
function calculatePriceNoVat(type) {    
	var hasPaymentOpt=false;
	if(Vehicle.step==0) return false; //exitPoint
	//BASICPRICE
	var basicPrice=Vehicle.Mvs.priceNoVat;
	if(type=='basicPrice') return basicPrice; //exitPoint
	
	//BASICPRICEPROMO
	var basicPricePromo=basicPrice;
	
	if(Vehicle.Promos!=null){
		//loop 1 ricerca del prezzo base promozionale iniziale
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='F' ){
					basicPricePromo=Vehicle.Promos[Ox].priceNoVat; 
				}
			}
		}
		//loop 2 aggiunta sconti
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='E' && Vehicle.Promos[Ox].targetDiscount=="01" ){
					//absolute value
					if(Vehicle.Promos[Ox].discountNoVat<0){
						basicPricePromo=Vehicle.Mvs.priceNoVat+(Vehicle.Promos[Ox].discountNoVat);
					}
					//percent value
					if(Vehicle.Promos[Ox].discountNoVat>0){
						basicPricePromo=Vehicle.Mvs.priceNoVat - (Vehicle.Mvs.priceNoVat * (Vehicle.Promos[Ox].discountNoVat/100)); 
					}
				}
			}
		}
		//loop 3 ricerca del prezzo base promozionale rottamazione (sopravanza la promozione iniziale)
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='MVS'){
				if(Vehicle.Promos[Ox].promoType=='B'){
					basicPricePromo=Vehicle.Promos[Ox].priceNoVat; 
				}
			}
		}
		
	}
	
	if(type=='basicPricePromo') return basicPricePromo;
	
	//OPTPRICE
	//somma degli optional a pagamento
	var optPrice=0;
	if(Vehicle.Optionals!=null){
		for (var Ox in Vehicle.Optionals) {
			if(Vehicle.Optionals[Ox].priceNoVat!=null && Vehicle.Optionals[Ox].priceNoVat!=0){
				optPrice+=Vehicle.Optionals[Ox].priceNoVat;
				hasPaymentOpt=true;
			}
		}
	}
	//aggiunta prezzo BC e IP
	if(Vehicle.MvsBodyColor!= null && Vehicle.MvsBodyColor.priceNoVat!=null){
		optPrice+=Vehicle.MvsBodyColor.priceNoVat;
		hasPaymentOpt=true;
	}
	if(Vehicle.MvsInnerPreparation!= null && Vehicle.MvsInnerPreparation.priceNoVat!=null){
		optPrice+=Vehicle.MvsInnerPreparation.priceNoVat;
		hasPaymentOpt=true;
	}
	if(type=='optPrice') return optPrice; //exitPoint
	 
	//OPTPRICEPROMO
	var optPriceDiscount=0;
	if(Vehicle.Promos!=null && Vehicle.Optionals!=null  && hasPaymentOpt){
		for (var Ox in Vehicle.Promos) {
			if(Vehicle.Promos[Ox].obj!=null && Vehicle.Promos[Ox].obj=='OPT' 
			   && (Vehicle.Promos[Ox].promoType=='C')){
				for (var Oy in Vehicle.Optionals) {
					if(Vehicle.Promos[Ox].objCode==Vehicle.Optionals[Oy].code){
						optPriceDiscount+=Vehicle.Promos[Ox].priceNoVat;
					}
				}
			}
		}
	}
	//aggiunta promo BC 
	if(Vehicle.MvsBodyColor.codeOpt!= null && Vehicle.MvsBodyColor.codeOpt!=''){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
			   && (PromoList[i].promoType=='C')){
			   if(PromoList[i].objCode==Vehicle.MvsBodyColor.codeOpt){
					optPriceDiscount+=PromoList[i].priceNoVat; 
				}
			}
		}
	}
	//aggiunta promo IP
	if(Vehicle.MvsInnerPreparation.codeOpt!= null && Vehicle.MvsInnerPreparation.codeOpt!=''){
		for(var i=0;i<PromoList.length;i++){
			if(PromoList[i].obj!=null && PromoList[i].obj=='OPT' 
			   && (PromoList[i].promoType=='C')){
			   if(PromoList[i].objCode==Vehicle.MvsInnerPreparation.codeOpt){
					optPriceDiscount+=PromoList[i].priceNoVat; 
				}
			}
		}
	}
	var optPricePromo=optPrice+optPriceDiscount;
	if(type=='optPricePromo') return optPricePromo; //exitPoint
	  
	//TOTALPRICE
	var totalPrice=basicPricePromo+optPricePromo;
	var totalPriceDiscount=0;
	//applying discount promo 
	if(type=='totalPrice'){
		if(Vehicle.Promos!=null){
			//passo da promolist per mantenere l'ordine di calcolo
			for(var i=0;i<PromoList.length;i++){
				if(Vehicle.Promos[PromoList[i].code]!=null){
					var promo=PromoList[i];
					if(promo.obj!=null && promo.obj=='MVS' && PromoList[i].objCode==Vehicle.Mvs.code){
						//type E
						if(promo.promoType=='E' && promo.targetDiscount=="02"){
							//absolute value
							if(promo.discountNoVat<0){
								totalPriceDiscount+= -(promo.discountNoVat);
							}
							//percent value
							if(promo.discountNoVat>0){
								totalPriceDiscount+= (totalPrice-totalPriceDiscount) * (promo.discountNoVat/100);
							}
						}
						//type A
						if(promo.promoType=='A' ){
							//absolute value
							if(promo.priceNoVat<0){
								totalPriceDiscount+= -(promo.discountNoVat);
							}
							//percent value
							if(promo.priceNoVat>0){
								totalPriceDiscount+= (totalPrice-totalPriceDiscount)* (promo.discountNoVat/100);
							}
						}
					}
				}
			}
		}
		totalPrice=totalPrice-totalPriceDiscount;
		return totalPrice;
	}
	if(type=='totalPriceNoPromo') return totalPrice;
} // FINE FUNZIONE CHE VISUALIZZA IL PREZZO


function areOtpionalsCompatible(opt1, opt2){
	// Uricchio
	// Controllo sugli optional di serie
	var o1 = getOptionalFromCode(opt1);
	var o2 = getOptionalFromCode(opt2);
	
	if(o1.optType == "S" || o2.optType == "S")
		return true;
	
	if(o1.optType != "S" && o2.optType != "S" &&  o1.family != "" && o2.family != "" && o1.family == o2.family)
		return false;
	
	var ris=true;
	var arr=new Array(); 
	arr=OptEsclusive[opt1];
	if(arr==null) return true;
	for(var i=0;i<arr.length;i++){
		if(arr[i]==opt2){
			ris=false;
			break;
		}
	}
	return ris;
} 

function areBCIPCompatible(opt1, opt2){		
	var ris=true;
	var arr=new Array(); 
	arr=IPEsclusiveByBC[opt1];
	if(arr==null) return true;
	for(var i=0;i<arr.length;i++){
		if(arr[i]==opt2){
			ris=false;
			break;
		}
	}
	return ris;
} 


function getFirstValidIPCode(){
	//if compatible, return current MvsInnerPreparation
	if(Vehicle.MvsInnerPreparation!=null && Vehicle.MvsInnerPreparation.code!=null && Vehicle.MvsInnerPreparation.code!=""){
		if(areBCIPCompatible(Vehicle.MvsBodyColor.code, Vehicle.MvsInnerPreparation.code)){
			return Vehicle.MvsInnerPreparation.code;
		}
	}
	//loop
	for(var i=0;i<MvsIPList.length;i++){
		if(areBCIPCompatible(Vehicle.MvsBodyColor.code,MvsIPList[i].code)){
			return MvsIPList[i].code;
		}
	}
}

function addDefaultMvsPromos(){
	for (i = 0; i < PromoList.length; i++) {
		if(Vehicle.step==1){
			if ((PromoList[i].objCode == Vehicle.Mvs.code) && (PromoList[i].promoType == "E" || PromoList[i].promoType == "F")) {
				addPromo(PromoList[i].code);
			}
		}
		if(Vehicle.step==3){
			if ((PromoList[i].objCode == Vehicle.Mvs.code) && ((PromoList[i].promoType == "A" || PromoList[i].promoType == "B" ) && PromoList[i].startState=="1") || PromoList[i].promoType == "D") {
				addPromo(PromoList[i].code);
			}
		}
	} 
}

function toEntity(toBeConverted){
	if(toBeConverted==null || toBeConverted=="") return toBeConverted;
	var entArr=new Array();
	entArr["<"]="&#60;";
	entArr[">"]="&#62;";
	entArr["&"]="&#38;";
	entArr["'"]="&#39;";
	entArr["\""]="&#34;";
	var newString="";
	for(var i=0;i<toBeConverted.length;i++){
		var car=toBeConverted.charAt(i);
		var convCar=entArr[car];
		if(convCar==null || convCar==""){
			newString+=car;
		}
		else{
			newString+=convCar;
		}
	}
	return newString;
}

/*---------------------------------
             FLASH
-----------------------------------*/

function setFlash(target){
	if(target=="BC"){
		setFlashColor(Vehicle.MvsBodyColor.code);
	}
	if(target=="OPT"){
		for (var Ox in Vehicle.Optionals) {
			if(Vehicle.Optionals[Ox].category=="-"){
				setFlashRim(Vehicle.Optionals[Ox].flashName.substring(0, Vehicle.Optionals[Ox].flashName.length -4));
				break;
			}
		}
	}
}

function setFlashColor(mvsBodyColorCode){
	if(ServerSide["useFlash"]=="true" && IsNE6()==false){
		//Flash setting does not work with MacIntosh
		var InternetExplorer = (navigator.appName.indexOf("Microsoft") != -1);
		var movie = null;
		movie = (InternetExplorer) ? film : document.film;
		for(var i=0;i<MvsBCList.length;i++){
			if(MvsBCList[i].code==mvsBodyColorCode){
				movie.SetVariable("_root.farbe_name",MvsBCList[i].desc);
				var tmpArr=new Array();
				tmpArr=MvsBCList[i].paraFlash;
				movie.SetVariable("_root.farbe_lack_ra", tmpArr[0]);
				movie.SetVariable("_root.farbe_lack_rb", tmpArr[1]);
				movie.SetVariable("_root.farbe_lack_ga", tmpArr[2]);
				movie.SetVariable("_root.farbe_lack_gb", tmpArr[3]);
				movie.SetVariable("_root.farbe_lack_ba", tmpArr[4]);
				movie.SetVariable("_root.farbe_lack_bb", tmpArr[5]);
				movie.SetVariable("_root.farbe_lack_aa", tmpArr[6]);
				movie.SetVariable("_root.farbe_lack_ab", tmpArr[7]);
				movie.SetVariable("_root.farbe_kontrast_ra", tmpArr[8]);
				movie.SetVariable("_root.farbe_kontrast_rb", tmpArr[9]);
				movie.SetVariable("_root.farbe_kontrast_ga", tmpArr[10]);
				movie.SetVariable("_root.farbe_kontrast_gb", tmpArr[11]);
				movie.SetVariable("_root.farbe_kontrast_ba", tmpArr[12]);
				movie.SetVariable("_root.farbe_kontrast_bb", tmpArr[13]);
				movie.SetVariable("_root.farbe_kontrast_aa", tmpArr[14]);
				movie.SetVariable("_root.farbe_kontrast_ab", tmpArr[15]);
				break;
			}
		}
	}
}

function setFlashRim(rimFlashCode){
	if(ServerSide["useFlash"]=="true" && IsNE6()==false){
		//Flash setting does not work with MacIntosh
		var InternetExplorer = (navigator.appName.indexOf("Microsoft") != -1);
		var movie = (InternetExplorer) ? film : document.film;
		movie.SetVariable("_root.felge",rimFlashCode);
	}
}

// Handle all the the FSCommand messages in a Flash movie
function film_DoFSCommand(command, args) {
  var InternetExplorer = (navigator.appName.indexOf("Microsoft") != -1);
  var movie = InternetExplorer ? film : document.film;
}

//FUNZIONI NUOVO POPUP DI ALERT OPTIONALS

function mustInclude2(code){
	var retRoots=getOptInclusiveRoot(code);
	var retRootsOrigLength=retRoots.length;
	if(retRoots==null || retRoots.length==0) return false;
	retRoots=filterOptIncVsVehicle(retRoots);
	if(retRoots==null || retRoots.length==0) return false;
	retRoots=dropVoidRoots(retRoots);
	if(retRoots==null || retRoots.length==0) return false;
	var retRootsFinalLength=retRoots.length;
	if(retRootsOrigLength!=retRootsFinalLength) return false;
	var tmpArr=new Array(0);
	for(var i=0;i<retRoots.length;i++){
		for(var j=0;j<retRoots[i].length;j++){
			for(var y in Vehicle.Optionals){
				if(areOtpionalsCompatible(y, retRoots[i][j])){
					tmpArr[retRoots[i][j]]=retRoots[i][j];
				}
			}
		}
	}
	for(var x in tmpArr){
		return true;
	}
	return false;
}

/*
	Uricchio David
	Controlla che non ci siano altri optional da includere
*/
function mustInclude3(code){
	return creaGruppi(code).length;
}

function getOptInclusiveListRemoving(code){
	var retList=new Array(0);
	var tmpList=new Array(0);
	
	// Uricchio David
	// Modifica per la gestione del codice optional e progressivo
	for(var opt in OptInclusive){
		var x = opt.getCodice();
		if(Vehicle.Optionals[x]!=null && Vehicle.Optionals[x]!="" && code!=x){
			var tmpOptInc=new Array(0); 
			tmpOptInc=OptInclusive[x];
			if(tmpOptInc!=null && tmpOptInc!=''){
				if((findInArray(code, tmpOptInc))!=-1 && findInArray(x, tmpList) == -1){
					tmpList[tmpList.length]=x;
				}
			}
		}
	}

	//trasformazione in list di optional
	for(var i=0;i<tmpList.length;i++){
		retList[i]=getOptionalFromCode(tmpList[i]);
	}
	
	return retList;
}

function getOptInclusiveTree(code){
	var retTree=new Array(0);
	var retRoots=getOptInclusiveRoot(code);
	var retRootsOrigLength=retRoots.length;
	//FILTRI
	retRoots=filterOptIncVsVehicle(retRoots);
	//PULIZIA
	retRoots=dropVoidRoots(retRoots);
	
	var retRootsFinalLength=retRoots.length;
	if(retRootsOrigLength!=retRootsFinalLength) return retTree;
		
	//trasformazione in tree
	for(var i=0;i<retRoots.length;i++){
		var tmpTree=new Array(0);
		for(var j=0;j<retRoots[i].length;j++){
			var tmpOpt=getOptionalFromCode(retRoots[i][j]);
			tmpTree[tmpTree.length]=tmpOpt;
		}
		retTree[retTree.length]=tmpTree;
	}
	//eliminazione alberi con optional incompatibili al loro interno
	var newRetTree=new Array(0);
	for(var i=0;i<retTree.length;i++){
		var testPassed=true;
		var tmpArr=retTree[i];
		for(var j=0;j<tmpArr.length;j++){
			for(var k=0;k<tmpArr.length;k++){
				if(!areOtpionalsCompatible(tmpArr[j].code, tmpArr[k].code)){
					testPassed=false;
				}
			}
		}
		if(testPassed){
			newRetTree[newRetTree.length]=retTree[i];
		}
	}
	return newRetTree;
}

function dropVoidRoots(roots){
	//tolgo i root vuoti
	var newRoot=new Array(0);
	for(var i=0;i<roots.length;i++){
		if(roots[i]!=null && roots[i].length>0){
			newRoot[newRoot.length]=roots[i];
		}
	}
	return newRoot;
}

function  filterOptIncVsVehicle(roots){
//tolgo dal root gli accessori gia nel veicolo
	for(var i=0;i<roots.length;i++){
		var newBranch=new Array(0);
		var cont=0;
		for(var j=0;j<roots[i].length;j++){
			if(Vehicle.Optionals!= null && (Vehicle.Optionals[roots[i][j]]==null || Vehicle.Optionals[roots[i][j]]=="")){
				//controllo con colore/interni
				if(Vehicle.MvsBodyColor.codeOpt!=roots[i][j] && Vehicle.MvsInnerPreparation.codeOpt!=roots[i][j]){
					newBranch[cont]=roots[i][j];
					cont++;
				}
			}
		}
		roots[i]=newBranch;
	}
	return roots;
}

function getOptInclusiveRoot(code){
	roots=new Array(0);
	var tmpInc=OptInclusive[code];
	if(tmpInc==null || tmpInc=='') return roots;
	var retRoots=new Array(0);
	retRoots=splitArr(tmpInc);
	return retRoots;
}

function splitArr(roots){
	var tmpRoots=new Array(roots.length);
	for(var i=0;i<roots.length;i++){
		var arr=new Array(0);
		arr[0]=roots[i]; 
		tmpRoots[i]=arr;
	}
	for(var i=0;i<tmpRoots.length;i++){
		var opt1=tmpRoots[i][0];
		for(var j=0;j<roots.length;j++){
			var opt2=roots[j];
			if(opt1!=opt2){
				if(areOtpionalsCompatible(opt1, opt2)){
					if(findInArray(opt2, tmpRoots[i]) ==-1){
						tmpRoots[i][tmpRoots[i].length]=opt2;
					}
				}
			}
		}
	}
	//eleminazione array contenenti gli stessi elementi
	var tmpRoots2=new Array(0);
	for(var i=0;i<tmpRoots.length;i++){
		var toAdd=true;
		for(var j=0;j<tmpRoots2.length;j++){
			if(arrayContainsSameElements(tmpRoots[i],tmpRoots2[j])) toAdd=false;
		}
		if(toAdd) tmpRoots2[tmpRoots2.length]=tmpRoots[i];
	}
	tmpRoots=tmpRoots2;
	return tmpRoots;
	
}


function arrayContainsSameElements(tmpArr1,tmpArr2){
	if(tmpArr1==null || tmpArr2==null || tmpArr1.length!=tmpArr2.length) return false;
	tmpArr1.sort();
	tmpArr2.sort();
	for(var i=0;i<tmpArr1.length;i++){
		if(tmpArr1[i]!=tmpArr2[i]) return false;
	}
	return true;
}

function getNextOptInclusive(leaves){
	var pointer=leaves.length-1;
	alert('pointer='+pointer);
	alert('leaves[pointer]='+leaves[pointer]);
	var tmp=OptInclusive[leaves[pointer]];

	if(tmp==null || tmp=="") return "";
	for(var i=0;i<tmp.length;i++){
		if(findInArray(tmp[i],leaves)==-1) return tmp[i];
	}
	return "";
}

function findInArray(value, into){
	for(var i=0;i<into.length;i++){
		if(value==into[i]) return i;
	}
	return -1;
}

function getOptionalFromCode(code){
	for(var i=0;i<OptionalList.length;i++){
		if(OptionalList[i].code==code){
			return OptionalList[i];
		}
	} 
}

function getOptionalPriceSum(optionalList){
	if(optionalList==null || optionalList.length==0) return 0;
	var optsum=0;
	for(var i=0;i<optionalList.length;i++){
		optsum+=optionalList[i].priceNoVat;
		for (var j = 0; j < PromoList.length; j++) {
			if (PromoList[j].promoType == 'C' && PromoList[j].objCode == optionalList[i].code) {
				optsum+=PromoList[j].priceNoVat;
			}
		}
	}
	return optsum;
}

function getOptEsclusiveList(code){
	var optBunch=new Array(0);
	// Uricchio David
	// INIZIO VECCHIA GESTIONE
	/*
	var tmpList=OptEsclusive[code];
	if(tmpList==null || tmpList.length==0) return optBunch;
	var cont=0;
	for(var i=0;i<tmpList.length;i++){
		if(Vehicle.Optionals!= null && (Vehicle.Optionals[tmpList[i]]!=null && Vehicle.Optionals[tmpList[i]]!="")){
			optBunch[cont]=getOptionalFromCode(tmpList[i]);
			cont++;
		}
	}
	*/
	// FINE VECCHIA GESTIONE
	
	// INIZIO NUOVA GESTIONE
	var initOpt = getOptionalFromCode(code);
	var optFamily = initOpt.family;
	
	for(var opt in Vehicle.Optionals){
		var curOpt = getOptionalFromCode(opt);
		// Se l'optional corrente è nella lista degli optional da escludere o appartiene alla stessa famiglia dell'optiona da selezionare
		if(initOpt.optType != "S" && curOpt.optType != "S" && code != opt && ((OptEsclusive[code] != undefined && findInArray(opt, OptEsclusive[code]) != -1) || (optFamily != "" && curOpt.family != "" && optFamily == curOpt.family)))
			addToArray(optBunch, curOpt);
	}
	
	// FINE NUOVA GESTIONE
	return optBunch;
}

//ESTENSIONI FIAT

function ExternalLink(codeArg,disabledArg,descArg,imageArg,imageOverArg,linkTo,group,groupPos, displayAs){
	this.code = codeArg;
	this.disabled = disabledArg;
	this.desc = descArg;
	this.image = imageArg;
	this.imageOver = imageOverArg;
	this.linkTo	= linkTo;
	this.group=group;
	this.groupPos=groupPos;
	this.displayAs=displayAs;
}

function getExternalLinkByCode(code){
	for(var i=0;i<ExternalLinkList.length;i++){
		if(ExternalLinkList[i].code==code){
			return ExternalLinkList[i];
		}
	}
	return null;
}

function calculateSingleOptPromoPrice(code) { 
	var optsum=0;
	for (var j = 0; j < PromoList.length; j++) {
		if (PromoList[j].promoType == 'C' && PromoList[j].objCode == code) {
			optsum+=PromoList[j].priceNoVat;
		}
	}
	return (getOptionalFromCode(code)).priceNoVat + optsum;
}

function findExternalLinkMaxGroup(){
	var maxGroup=0;
	for(var i=0;i<ExternalLinkList.length;i++){
		if(ExternalLinkList[i].group>maxGroup){
			maxGroup=ExternalLinkList[i].group;
		}
	}
	return maxGroup;
}

function findExternalLinkMaxGroupPos(){
	var maxGroupPos=0;
	for(var i=0;i<ExternalLinkList.length;i++){
		if(ExternalLinkList[i].groupPos>maxGroupPos){
			maxGroupPos=ExternalLinkList[i].groupPos;
		}
	}
	return maxGroupPos;
}

//FINE ESTENSIONI FIAT

//ESTENSIONI LCV

//calculate net price
//type: "OPT" - "BC" - "IP"
function calculatePromoPriceNoVat(type, obj){
	var promoPriceNoVat=obj.priceNoVat;
	var objCode;
	if(type=="OPT"){
		objCode=obj.code;
	}
	if(type=="BC" || type=="IP"){
		objCode=obj.codeOpt;
	}
	for(var i=0;i<PromoList.length;i++){
		if(PromoList[i].obj=="OPT" || type=="BC" || type=="IP"){
			if(PromoList[i].objCode==objCode){
				promoPriceNoVat+=PromoList[i].priceNoVat;
				break;
			}
		}
	}
	return promoPriceNoVat;
}

//called only at page startup
function addDefaultFilters(){
	for(var i=0;i<FilterList.length;i++){
		Vehicle.Filters[FilterList[i].codeType]=FilterList[i];
	}
	addToHistory();
}


function setFilter(tdv) {
	for (var i = 0; i < FilterList.length; i++) {
		if (FilterList[i].codeType == tdv.codeType) {
			Vehicle.Filters[tdv.codeType]=FilterList[i];
			Vehicle.Filters[tdv.codeType].codeSelected=tdv.code;
			Vehicle.Filters[tdv.codeType].valueSelected=tdv.value;
			break;
		}
	}
}

/*
function setFilter(codeType, code, value) {
	for (var i = 0; i < FilterList.length; i++) {
		if (FilterList[i].codeType == codeType) {
			Vehicle.Filters[codeType].codeSelected=code;
			Vehicle.Filters[codeType].valueSelected=value;
			break;
		}
	}
}
*/

var stackCounter=0;

function countMvsByFilter(codeType,value,blockAfterFirstFound,returnAsList){
	var checkVsParameters=false;
	if(codeType!=null && value!=null && codeType!="" && value!=""){
		checkVsParameters=true;
	}
	var cont=0;
	var list=new Array(0);
	for(var i=0;i<MvsTDList.length;i++){
		list[MvsTDList[i].mvsCode]=MvsTDList[i];
		//stackCounter++;
	}
	var filterMap=new Array();
	for(var i in Vehicle.Filters){
		//stackCounter++;
		filterMap[Vehicle.Filters[i].codeType]=Vehicle.Filters[i];
	}
	for(var i=0;i<MvsTDList.length;i++){
		var dropped=false;
		var mvsTD=MvsTDList[i];
		var forceDrop=false;
		//check che per il codeType ci sia il dato tecnico
		if(checkVsParameters){
			var tdPresent=false;
			for(var n=0;n<mvsTD.techDataValues.length;n++){
				if(mvsTD.techDataValues[n].codeType==codeType){
					tdPresent=true;
				}
			}
			if(!tdPresent){
				forceDrop=true;
			}
			if(forceDrop){
				list[mvsTD.mvsCode]=null;
				dropped=true;
				continue;
			}
		}
		for(var j=0;j<mvsTD.techDataValues.length;j++){
			var tdv=mvsTD.techDataValues[j];
			//stackCounter++;
			var filter=filterMap[tdv.codeType];
			if(filter==null){
				continue;
			}
			if(checkVsParameters){
				if(tdv.codeType==codeType){
					if(tdv.value!=value){
						list[mvsTD.mvsCode]=null;
						dropped=true;
						continue;
					}
				}
			}
			if(filter.valueSelected!=""){
				if(tdv.value!=filter.valueSelected){
					list[mvsTD.mvsCode]=null;
					dropped=true;
				}
			}
		}
		if(blockAfterFirstFound){
			if(!dropped){
				//alert("loop blocked: "+codeType+" - "+value);
				break;
			}
		}
	}
	
	var cont2=0;
	var newList=new Array(0);
	for (var i in list) {
		if(list[i]!=null){
			if(returnAsList){
				//alert(newList.length+" :"+list[i].mvsCode);
				newList[newList.length]=list[i];
				
			}
			else{
				cont2++;
			}
		}
		//stackCounter++;
	}

	//alert("returning: "+cont2);
	if(returnAsList){
		return newList;
	}
	else{
		return cont2;
	}
	
	//return cont;
}

function createMvsFilteredKeysString(mvsFilteredTDList){
	var keysString="";
	for(var i=0;i<mvsFilteredTDList.length;i++){
		if(i!=0){
			keysString+="|";
		}
		keysString+=mvsFilteredTDList[i].mvsCode;
	}
	return keysString;
}

function getFilterByCodeType(codeType){
	var filter=null;
	for(var i in Vehicle.Filters){
		//stackCounter++;
		if(Vehicle.Filters[i].codeType==codeType){
			filter=Vehicle.Filters[i];
			break;
		}
	}
	return filter;
}

function addToHistory(){
	//alert("addHistory() called");
	//var clonedVehicle=clone(Vehicle);
	var clonedVehicle=clone(Vehicle, true);
	//verifyVehicles(Vehicle, clonedVehicle);
	HistoryList[HistoryList.length]=clonedVehicle;
	//alert("HistoryList.length now is: "+HistoryList.length);
}

function removeFromHistory(){
	//alert("removeFromHistory() called");
	//alert("HistoryList.length was: "+HistoryList.length);
	var newHistoryList=new Array();
	if(HistoryList.length>1){
		for(var i=0;i<HistoryList.length-1;i++){
			newHistoryList[i]=HistoryList[i];
		}
		HistoryList=newHistoryList;
		//alert("HistoryList.length now is: "+HistoryList.length);
		getFromHistory(HistoryList[HistoryList.length-1]);
	}
}

function clearHistory(){
	//alert("clearHistory() called");
	//alert("HistoryList.length was: "+HistoryList.length);
	var newHistoryList=new Array();
	if(HistoryList.length>0){
		newHistoryList[0]=HistoryList[0];
		HistoryList=newHistoryList;
		//alert("HistoryList.length now is: "+HistoryList.length);
		getFromHistory(HistoryList[HistoryList.length-1]);
	}
}

function getFromHistory(obj){
	var clonedVehicle=clone(obj, true);
	Vehicle=clonedVehicle;
}

function clone (obj, deep) {
  var objectClone = new obj.constructor();
  for (var property in obj)
    if (!deep)
      objectClone[property] = obj[property];
    else if (typeof obj[property] == 'object')
      objectClone[property] = clone(obj[property], deep);
    else
      objectClone[property] = obj[property];
  return objectClone;
}
//Add method clone to all objects
//Object.prototype.clone = clone;



//debug only
function verifyVehicles(real, cloned){
	var s="";
	s+=vvp("step",real.step,cloned.step);
	s+=vvp("Model",real.Model,cloned.Model);
	s+=vvp("Model.code",real.Model.code,cloned.Model.code);
	s+=vvp("Filters",real.Filters,cloned.Filters);
	s+=vvp("Filters.length",real.Filters.length,cloned.Filters.length);
	
	alert(s);
}
function vvp(desc, real, cloned){
	var s=desc+": "+real+" - "+cloned+"\n";
	return s;
}


/*
	Uricchio
	Recupera il codice optional dalla forma "COD_OPT-PGR"
*/
String.prototype.getCodice = function(){
	var index = this.lastIndexOf("-");
	
	if(index == -1)
		return this;
	
	return this.substr(0, index);
}

/*
	Uricchio David
	Recupera il progressivo optional dalla forma "COD_OPT-PGR"
*/
String.prototype.getProgressivo = function(){
	var index = this.lastIndexOf("-");
	
	if(index == -1)
		return "0";
				
	return this.substr(index + 1);
}

/*
	Uricchio David
	Appende un nuovo elemento ad un array
*/
function addToArray(myArray, elemento){
	myArray[myArray.length] = elemento;
}

/*
	Uricchio David
	Indica se la posizione richiesta dell'array è valida
*/
function isArrayElementValid(myArray, index){
	if(myArray[index] != undefined)
		return true;
	else
		return false;
}

/*
	Uricchio David
	Crea un array con i gruppi di optional compatibili a quello richiesto utilizzando il progressivo
*/
function creaGruppi(code){
	var gruppi = new Array();
	var esclusioniSelezionati = new Array();
	
	if(OptInclusive[code] != undefined){
		for(var i = 0; i < OptInclusive[code].length; i++){
			var elemento = OptInclusive[code][i];
			
			var optCode = elemento.getCodice();
			var pgr = elemento.getProgressivo();
			
			
			if(gruppi[pgr] == undefined)
				gruppi[pgr] = new Array();
		
			var opt = getOptionalFromCode(optCode);
			// Controllo che gli optional non siano stati già selezionati	
			if(	Vehicle.Optionals[optCode] != undefined || 
				Vehicle.MvsInnerPreparation.codeOpt == optCode || 
				Vehicle.MvsBodyColor.codeOpt == optCode || 
				opt.optType == "S"){
				
				if(esclusioniSelezionati[pgr] == undefined)
					esclusioniSelezionati[pgr] = 0;
					
				esclusioniSelezionati[pgr]++;
			}
			
			addToArray(gruppi[pgr], opt);
		}

		// Se un gruppo ha già tutti gli optional facenti parte della configurazione corrente,
		// l'utente non deve operare alcuna scelta
		for(var i = 0; i < gruppi.length; i++){
		
			if(isArrayElementValid(gruppi, i) && isArrayElementValid(esclusioniSelezionati, i) && gruppi[i].length == esclusioniSelezionati[i]){
				gruppi = new Array();
				break;
			}

		}
	}
	
	return gruppi;
}



