// Funzioni lavorazione carrello.js

var tpTableHeader      = '<table border="0" cellspacing="2" cellpadding="0" width="100%" bgcolor="#FFFFFF">' + "\r\n";
var tpTableFooter      = '</table>';
var tpRowTitle;
var tpRowHeader;
var tpRowArt;
var tpRowSubTotal;
var tpRowShipping;
var tpRowNoShipping;
var tpRowCash;
var tpRowTotal;
var tpRowEmpty;
var tpOrderBtnEnabled;
var tpOrderBtnDisabled;
var tpOrderBtnEmpty;
var tpOrderSubDisabled;
var tpOrderResComuneSelect;
var tpOrderResComuneInput;
var tpOrderResComuneASelect;
var tpOrderResComuneAInput;

var hFormResNazione;
var hFormResProvincia;
var hFormResComune;
var hFormResCap;
var hFormPayment;
var hFormAResComune;
var hFormDivResComune;

var aMD5AuthFields    = [ 'md5_1'          , 'md5_2'         , 'md5_3'           ];
var aMD5RawFields     = [ 'md5_rt1'        , 'md5_rt2'       , 'md5_rt3'         ];

var aOrderGrids       = [ 'OrderGridRSMTax', 'OrderGridNoTax', 'OrderGridITATax' ];
var aOrderForms       = [ 'OrderRSMTax'    , 'OrderNoTax'    , 'OrderITATax'     ];

var cTotal            = 0.0;
var cGridCashCost     = 0.0;
var cTaxTypeDesc      = [ '' // Posizione 0 => Tipo ordine non selezionato
					    , '', '(IVA ESENTE)', '(IVA 20% INCLUSA)' ];

function InitGrid()
{
	tpRowHeader 	   		= "<tr>" + document.getElementById('BasketRowHeader').innerHTML     + "</tr>\r\n";
	tpRowArt    	   		= "<tr>" + document.getElementById('BasketRowTemplate').innerHTML   + "</tr>\r\n";
	tpRowSubTotal  	   		= "<tr>" + document.getElementById('BasketRowSubTotal').innerHTML   + "</tr>\r\n";
	tpRowShipping	   		= "<tr>" + document.getElementById('BasketRowShipping').innerHTML   + "</tr>\r\n";
	tpRowNoShipping	   		= "<tr>" + document.getElementById('BasketRowNoShipping').innerHTML + "</tr>\r\n";
	tpRowCash  	   			= "<tr>" + document.getElementById('BasketRowCash').innerHTML       + "</tr>\r\n";
	tpRowTotal  	   		= "<tr>" + document.getElementById('BasketRowTotal').innerHTML      + "</tr>\r\n";
	tpRowEmpty  	   		= "<tr>" + document.getElementById('BasketRowEmpty').innerHTML      + "</tr>\r\n";

	tpOrderBtnEnabled  		= document.getElementById('OrderBtnEnabled').innerHTML;
	tpOrderBtnDisabled 		= document.getElementById('OrderBtnDisabled').innerHTML;
	tpOrderBtnEmpty  		= document.getElementById('OrderBtnEmpty').innerHTML;
	tpOrderSubDisabled 		= document.getElementById('OrderSubDisabled').innerHTML;
	tpOrderResComuneSelect	= document.getElementById('OrderResComuneSelect').innerHTML;
	tpOrderResComuneInput	= document.getElementById('OrderResComuneInput').innerHTML;
	tpOrderResComuneASelect	= document.getElementById('OrderResComuneASelect').innerHTML;
	tpOrderResComuneAInput	= document.getElementById('OrderResComuneAInput').innerHTML;
	
	PayUpdateShipping(); // Nel caso merce superiore ai 10Kg visualizzazione immediata
	RenderGrid();

	if( BasketContent.length == 0 )
   		PaySwitchBtns_Empty();

	document.getElementById('BasketGrid').style.visibility = 'visible';
	document.getElementById('BasketGrid').style.overflow   = 'auto';
	document.getElementById('BasketGrid').style.width      = 'auto';
	document.getElementById('BasketGrid').style.height     = 'auto';
	
// Patch 21/06/2010
	PaySwitch(1);

	if( cTotal > Costants[1] ) // Costants[1] contiene il limite di pagamento per il contrassegno
	{
		hFormPayment.selectedIndex = 1;
		cGridCashCost = 0;
	}
	else
	{
		hFormPayment.selectedIndex = 0;
		cGridCashCost = 4;
		RenderGrid(); // In precedenza cGridCashCost era uguale a 0 => nuovo aggiornamento
	}
}

function RenderGrid()
{
var vsRow;
var voGrid = tpRowHeader;

	cTotal = 0.0;
	if( BasketContent.length )
	{
		for( xx=0; xx<BasketContent.length; xx++ )
		{
			cTotal  = cTotal + BasketContent[xx][5];
			
			vsRow   = tpRowArt;
			
			vsRow   = vsRow.replace( /'\%1'/g, BasketContent[xx][0] );
			vsRow   = vsRow.replace( /'\%2'/g, BasketContent[xx][1] );
			vsRow   = vsRow.replace( /'\%3'/g, FormatPrice( BasketContent[xx][5] ) );
			vsRow   = vsRow.replace( /'\%4'/g, BasketContent[xx][3] );		

			vsRow   = vsRow.replace( /\%1/g,   BasketContent[xx][0] );
			vsRow   = vsRow.replace( /\%2/g,   BasketContent[xx][1] );
			vsRow   = vsRow.replace( /\%3/g,   FormatPrice( BasketContent[xx][5] ) );
			vsRow   = vsRow.replace( /\%4/g,   BasketContent[xx][3] );		
			
			voGrid  = voGrid + vsRow;
		}

		vsRow   = tpRowSubTotal;
		vsRow   = vsRow.replace( /\%1/g, 'Totale Merce ' + cTaxTypeDesc[cGridTaxType] );
		vsRow   = vsRow.replace( /\%2/g, FormatPrice( cTotal ) );
		voGrid  = voGrid + vsRow;

		if( cGridShippingCost != -1 ) // Trasporto nei parametri
		{
			cTotal  = cTotal + cGridShippingCost;
			vsRow   = tpRowShipping;
			vsRow   = vsRow.replace( /\%1/g, FormatPrice( cGridShippingCost ) );
			if( cGridShippingCost > 0 )
				vsRow = vsRow.replace( /Spese di Trasporto<\/b><br>\(impostate dopo la scelta della Provincia di spedizione\)/g, 'Spese di Trasporto</b>' );
			voGrid  = voGrid + vsRow;
		}

		if( cGridCashCost ) // Contrassegno
		{
			cTotal  = cTotal + cGridCashCost;
			vsRow   = tpRowCash;
			vsRow   = vsRow.replace( /\%1/g, FormatPrice( cGridCashCost ) );
			voGrid  = voGrid + vsRow;
		}

		if( cGridShippingCost == -1 ) // Trasporto eccessivo
			voGrid  = voGrid + tpRowNoShipping;
		else
		{
			vsRow   = tpRowTotal;
			vsRow   = vsRow.replace( /\%1/g, 'TOTALE ORDINE ' + cTaxTypeDesc[cGridTaxType] );
			vsRow   = vsRow.replace( /\%2/g, FormatPrice( cTotal ) );
			voGrid  = voGrid + vsRow;
		}		
	}
	else
		voGrid = tpRowEmpty;
		
	if( tpRowTitle )
		voGrid = tpTableHeader + tpRowTitle + voGrid + tpTableFooter;
	else
		voGrid = tpTableHeader + voGrid + tpTableFooter;
		
	document.getElementById('BasketGrid').innerHTML = voGrid;
}

function QtyEnter( AEvent, AArtID, ANewQty )
{
	if( window.event ) // IE
		KeyCode = AEvent.keyCode;
	else if( AEvent.which ) // Netscape/Firefox/Opera
  		KeyCode = AEvent.which;
  
	if( KeyCode == 13 ) // Invio
	{
		window.location = 'carrello.php?p_arID=' + AArtID + '&p_caQta=' + parseInt(ANewQty);
		return false;
	}
	else
		return true;
}

function QtySet( AArtID, ANewQty )
{
	window.location = 'carrello.php?p_arID=' + AArtID + '&p_caQta=' + parseInt(ANewQty);
}

function PaySwitch( AType )
{
var NeedUpdate = 0;
// Patch 21/06/2010
/*	if( cTaxType != 0 )
	{
		PaySwitchBtn_Enable( cTaxType );
		PayRender( cTaxType, false );
	}
*/
	if( AType == cTaxType )
		cTaxType = 0; // Disabilito la scelta corrente
	else
		cTaxType = AType;
	
//	if( cTaxType != 0 )
//		PaySwitchBtn_Disable( cTaxType );		

//	PayRender( cTaxType, true );

	if( cTaxType != 0 )
		PayFormInit();
		
	NeedUpdate  = PayUpdateBasket();
	NeedUpdate += PayUpdateShipping();

	if( NeedUpdate ) // se qualche procedura ha richiesto aggiornamento e' necessario aggiornare la griglia!!!!
		RenderGrid();

	if( cTaxType != 0 && PayUpdatePayment() )
		RenderGrid();
}


function PayRender( AType, AEnable )
{
var TabDim = 'auto';
var TabVis = 'visible';
var TabOvr = 'auto';

	if( AType > 0 )
		hOrderGrid   = document.getElementById( aOrderGrids[AType-1] );
	hOrderGridFooter = document.getElementById('OrderGridFooter');

	if( !AEnable )
	{
		TabDim = '1';
		TabVis = 'hidden';
		TabOvr = 'hidden';
	}

	if( AType > 0 )
	{
		hOrderGrid.style.visibility       = TabVis;
		hOrderGrid.style.overflow         = TabOvr;
		hOrderGrid.style.width            = TabDim;
		hOrderGrid.style.height           = TabDim;
	}
	
		hOrderGridFooter.style.visibility = TabVis;
		hOrderGridFooter.style.overflow   = TabOvr;
		hOrderGridFooter.style.width      = TabDim;
		hOrderGridFooter.style.height     = TabDim;
}

function PaySwitchBtn_Enable( ABtn )
{
	vsCell = tpOrderBtnEnabled;
	vsCell = vsCell.replace( /'\%1'/g, ABtn );

	document.getElementById('Pay_Cell_' + ABtn).innerHTML = vsCell;
}

function PaySwitchBtn_Disable( ABtn )
{
	document.getElementById('Pay_Cell_' + ABtn).innerHTML = tpOrderBtnDisabled;
}

function PaySwitchBtns_Empty()
{
	document.getElementById('Pay_Cell_1').innerHTML = tpOrderBtnEmpty;
	document.getElementById('Pay_Cell_2').innerHTML = tpOrderBtnEmpty;
	document.getElementById('Pay_Cell_3').innerHTML = tpOrderBtnEmpty;
}

function PaySwitchCityInput()
{
	if( hFormResComune.tagName == 'SELECT' ) // Da lista a text
	{
		hFormDivResComune.innerHTML = tpOrderResComuneInput;
		hFormResComune              = document.getElementById( aOrderForms[cTaxType-1] ).elements['RES_Comune'];
		hFormAResComune.innerHTML   = tpOrderResComuneAInput;
	}
	else // Da text a lista
	{
		hFormDivResComune.innerHTML = tpOrderResComuneSelect;
		hFormResComune              = document.getElementById( aOrderForms[cTaxType-1] ).elements['RES_Comune'];
		hFormAResComune.innerHTML   = tpOrderResComuneASelect;
		PayFormChangeProv(); // Riempio nuovamente la lista dei comuni
	}
}

function PaySubmit()
{
var CampiOk = true;
var Campi;
var Valore;
var MailErr = false;
var MD5Text = '';
var MD5Value;
	
	document.getElementById( aMD5AuthFields[cTaxType-1] ).value = '';  // Azzero il valore di MD5

	Campi = document.getElementById( aOrderForms[cTaxType-1] ).elements;
	
	for( xx=0; xx<Campi.length; xx++ )
	{
		Valore = new String( Campi[xx].value );
		Valore = Valore.replace(/^\s+|\s+$/g,'');
		if( Campi[xx].className == 'CssOrderFieldInputNotNull'
			&& Valore == '' )
				CampiOk = false;

		if( CampiOk )
		{
			if( Campi[xx].name == 'pi_CON_Email' )
				MailErr = !MailCheck( Valore );

			if( Campi[xx].name.substr( 0, 4 ) != 'md5_' )
				MD5Text = MD5Text + Campi[xx].name + PayFieldNormalize( Valore );
		}
	}
	
	if( MailErr )
		alert( "L'indirizzo E-mail inserito non e' corretto.\r\n\r\nRicontrollare l'indirizzo E-mail!" );
	else if( !CampiOk )
		alert( 'Non sono state ancora inserite alcune informazioni obbligatorie.\r\n\r\nInserire le informazioni in tutte le righe scure.' );
	else
	{
		MD5Value = MD5( PayMD5Normalize( '' + GetCookie('Muratastore_Session') + MD5Text ) );
		document.getElementById( aMD5AuthFields[cTaxType-1] ).value = MD5Value;
		document.getElementById( aMD5RawFields[cTaxType-1] ).value  = PayMD5Normalize( '' + GetCookie('Muratastore_Session') + MD5Text );
		document.getElementById('DIV_OrderSubmit').innerHTML = tpOrderSubDisabled;
		document.getElementById( aOrderForms[cTaxType-1] ).submit();
	}
}

function PayFieldNormalize( AText )
{
var Normalized = new String("");

	for( yy=0; yy<AText.length; yy++ )
	{
		if( AText.charAt(yy) != '\r' && AText.charAt(yy) != '\n' )
			Normalized = Normalized + AText.charAt(yy);
	}
	
	Normalized = Normalized.replace(/^\s+|\s+$/g,'');
	
	return( Normalized );
}

function PayMD5Normalize( AText )
{
var Dictionary = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
var Normalized = "";
var UpperText = "";

	for( xx=0; xx<AText.length; xx++ )
	{
		if( Dictionary.lastIndexOf( AText.charAt(xx) ) == -1 )
			CurCar = '' + (xx % 10);
		else
			CurCar = '' + AText.charAt(xx);
		Normalized = Normalized + CurCar;
	}
	return( Normalized );
}

function PayFormInit()
{
	hFormResNazione   = document.getElementById( aOrderForms[cTaxType-1] ).elements['RES_Nazione'];
	hFormResProvincia = document.getElementById( aOrderForms[cTaxType-1] ).elements['RES_Provincia'];
	hFormResComune    = document.getElementById( aOrderForms[cTaxType-1] ).elements['RES_Comune'];
	hFormResCap       = document.getElementById( aOrderForms[cTaxType-1] ).elements['RES_Cap'];
	hFormPayment      = document.getElementById( aOrderForms[cTaxType-1] ).elements['ORD_Pagamento'];
	hFormAResComune   = document.getElementById( 'A_RES_Comune_'   + cTaxType );
	hFormDivResComune = document.getElementById( 'DIV_RES_Comune_' + cTaxType );

	if( hFormResProvincia.options && !hFormResProvincia.options.length )
		PayFormChangeCountry();
}

function PayFormChangeCountry()
{
var NeedUpdate = 0;

	if( hFormResNazione && hFormResNazione.value == 'San Marino' )
		Comuni_CaricaSelectProvincieRSM( hFormResProvincia );
	else
		Comuni_CaricaSelectProvincieITA( hFormResProvincia );

	Comuni_ImpostaSelectComuni(
		  hFormResProvincia
		, hFormResComune
		, hFormResCap );

	NeedUpdate  = PayUpdateBasket();
	NeedUpdate += PayUpdateShipping();

	if( NeedUpdate ) // se qualche procedura ha richiesto aggiornamento e' necessario aggiornare la griglia!!!!
	{
		RenderGrid();
		if( PayUpdatePayment() ) // Se modificato il tipo di pagamento
			RenderGrid();
	}
}

function PayFormChangeProv()
{
var NeedUpdate = 0;

	Comuni_ImpostaSelectComuni(
		  hFormResProvincia
		, hFormResComune
		, hFormResCap );

	NeedUpdate  = PayUpdateBasket();
	NeedUpdate += PayUpdateShipping();

	if( NeedUpdate ) // se qualche procedura ha richiesto aggiornamento e' necessario aggiornare la griglia!!!!
	{
		RenderGrid();
		if( PayUpdatePayment() ) // Se modificato il tipo di pagamento
			RenderGrid();
	}
}

function PayFormChangeCom()
{
	Comuni_SelezionaComuni(
		  hFormResProvincia
		, hFormResComune
		, hFormResCap );
}

function PayFormChangePayment()
{
// 13-07-2010: Se contrassegno maggiorazione 4 euro
	if( hFormPayment.selectedIndex == 1 )
		cGridCashCost = 0;
	else
		cGridCashCost = 4;

	PayUpdateBasket();
	PayUpdateShipping();

	RenderGrid();

/*
// Patch 16-04-2010: Se importo > max contrassegno imposto bonifico ma non tolgo contrassegno
	if( cTotal > Costants[1] ) // Costants[1] contiene il limite di pagamento per il contrassegno
		hFormPayment.selectedIndex = 1;
	else
		hFormPayment.selectedIndex = 0;

	if( cTotal > Costants[1] ) // Costants[1] contiene il limite di pagamento per il contrassegno
	{
		if( hFormPayment.options.length == 2 )
		{
			hFormPayment.remove(0);
			hFormPayment.selectedIndex = 0;
		}
	}
	else
		if( hFormPayment.options.length == 1 )
			hFormPayment.options.add( 
				  new Option( "Contrassegno", "Contrassegno" )
				, 0 );
*/			
}


function PayUpdateBasket()
{
var rNeedUpdate = 0;

	if( cGridTaxType == 0 && cTaxType == 1 )
		cGridTaxType = cTaxType;  // Nessun update necessario perche' parto da default
	else if( cGridTaxType != cTaxType )
	{
		cGridTaxType = cTaxType;
		rNeedUpdate  = 1;
		for( xx=0; xx<BasketContent.length; xx++ )
			BasketContent[xx][5] = PayUpdateTaxConvert( BasketContent[xx][2] ) * BasketContent[xx][1]; // Street Price arrotondato moltiplicato per quantita
	}
	return( rNeedUpdate );
}

function PayUpdateShipping()
{
var rNeedUpdate = 0;
var vfWeight    = 0;
var cNewCost    = 0;
var vArea;

	for( xx=0; xx<BasketContent.length; xx++ )
		vfWeight += BasketContent[xx][4];
	
	if( vfWeight <= Costants[0] ) // Il peso minimo e' indicato nella prima costante
	{
		if( cTaxType > 0 )
		{
			vArea = Comuni_ScanTrasporto( hFormResProvincia ) ;
			if( vArea )
				cNewCost = PayUpdateTaxConvert( ShippingPrices[ vArea-1 ] ); // vArea e' 1-Based!
		}
	}
	else
		cNewCost = -1;

	if( cNewCost != cGridShippingCost )
	{
		cGridShippingCost = cNewCost;
		rNeedUpdate       = 1;
	}

	return( rNeedUpdate );
}

function PayUpdatePayment()
{
var rNeedUpdate = 0;
	
	if( hFormPayment.selectedIndex != 1  // Deseleziono solo se non e' bonifico bancario
	   	&& cTotal > Costants[1] )		 // E il totale e' superiore all'importo massimo del contrassegno
	{
		hFormPayment.selectedIndex = 1;
		cGridCashCost = 0;
		rNeedUpdate   = 1;
	}
	
	return(rNeedUpdate);
}

function PayUpdateTaxConvert( ARSMPrice )
{
	switch( cTaxType )
	{
		case 0:
		case 1:
			return( ARSMPrice ); // in 2 gia' prezzo al 17%
				
		case 2:
			return( Math.round( (ARSMPrice * 100.0) / 1.17 ) / 100.0 ); // Esenzione
				
		case 3:
			return( Math.round( ((ARSMPrice * 100) / 1.17) * 1.2 ) / 100.0 ); // Iva 20%
	}
	return( 0 );
}
