// 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 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";
	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;
	
	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: solo vendita in esenzione
	PaySwitch(1);

//	if( cTotal > Costants[1] ) // Costants[1] contiene il limite di pagamento per il contrassegno
//	{
		hFormPayment.selectedIndex = 0;
		cGridCashCost = 0;
//	}
//	else
//	{
//		hFormPayment.selectedIndex = 2;
//		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( cGridCashCost ) // Contrassegno
		{
			cTotal  = cTotal + cGridCashCost;
			vsRow   = tpRowCash;
			vsRow   = vsRow.replace( /\%1/g, FormatPrice( cGridCashCost ) );
			voGrid  = voGrid + vsRow;
		}

		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();	

//		if( cTotal > Costants[1] ) // Costants[1] contiene il limite di pagamento per il contrassegno
			hFormPayment.selectedIndex = 0;
//		else
//			hFormPayment.selectedIndex = 2;

//		if( cTotal > Costants[1] ) // Costants[1] contiene il limite di pagamento per il contrassegno
//		{
//			if( hFormPayment.options.length == 3 )
//			{
//				hFormPayment.selectedIndex = 0;
//				hFormPayment.remove(2);
//			}
//		}
/*
		else
			if( hFormPayment.options.length == 1 )
				hFormPayment.options.add( 
					  new Option( "Contrassegno", "Contrassegno" )
					, 0 );		
*/
	}
	
	NeedUpdate  = PayUpdateBasket();

	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 CampiErrati = '';
var Campi;
var Valore;
var MailErr = false;
var MD5Text = '';
var MD5Value;
	
	ListaCampi = new Array(
			 	       new Array( 'pi_CON_Email'       , 'L\'e-mail'       , 'o' )
					 , new Array( 'pi_GEN_Cognome'     , 'Il cognome'      , 'o' )
					 , new Array( 'pi_GEN_Nome'        , 'Il nome'         , 'o' )
					 , new Array( 'pi_RES_IND_Via'     , 'La via'          , 'a' )
					 , new Array( 'pi_RES_IND_NCiv'    , 'Il numero civico', 'o' )
					 , new Array( 'pi_RES_Nazione'     , 'La nazione'      , 'a' )
					 , new Array( 'pi_RES_Provincia'   , 'La provincia'    , 'a' )
					 , new Array( 'pi_RES_Comune'      , 'Il comune'       , 'o' )
					 , new Array( 'pi_RES_Cap'         , 'Il CAP'          , 'o' )
					 , new Array( 'pi_CON_Telefono'    , 'Il numero di telefono'     , 'o' )
					 , new Array( 'pi_CON_Telefono_Rep', 'La reperibilità telefonica', 'a' )
					 , new Array( 'pi_ORD_Pagamento'   , 'Il tipo di pagamento'      , 'o' ) );
						  
						  
	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 == '' )
		{
			NomeCampo  = 'Un\'informazione richiesta';
			SessoCampo = 'a';
			
			for( yy=0; yy<ListaCampi.length; yy++ )
				if( ListaCampi[yy][0] == Campi[xx].name )
				{
					NomeCampo  = ListaCampi[yy][1];
					SessoCampo = ListaCampi[yy][2];
					yy = ListaCampi.length;
				}
			
			CampiErrati = CampiErrati + '\r\n' + NomeCampo + ' non è stat' + SessoCampo + ' inserit' + SessoCampo;
		}

		if( CampiErrati == '' ) // Nessun errore
		{
			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( CampiErrati != '' )
		alert( 'Le seguenti informazioni obbligatorie non sono state inserite:\r\n' + CampiErrati );
	else
	{
		MD5Value = hex_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();

	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 );

/* Patch 20-07-2011: Non e' piu' richiesto l'aggiornamento del dettaglio dell'ordine
    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 == 2 )
//		cGridCashCost = 4;
//	else
		cGridCashCost = 0;

	PayUpdateBasket();

	RenderGrid();
}


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 PayUpdatePayment()
{
var rNeedUpdate = 0;
	
/*
	if( hFormPayment.selectedIndex == 2  // Deseleziono solo se e' contrassegno
	   	&& cTotal > Costants[1] )		 // e il totale e' superiore all'importo massimo del contrassegno
	{
		hFormPayment.selectedIndex = 0;
		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 );
}

