//=====================================================================||
//                       version based on                              ||
//               NOP Design JavaScript Shopping Cart                   ||
//                                                                     ||
// For more information on SmartSystems, or how NOPDesign can help you ||
// Please visit us on the WWW at http://www.nopdesign.com              ||
//                                                                     ||
// Javascript portions of this shopping cart software are available as ||
// freeware from NOP Design.  You must keep this comment unchanged in  ||
// your code.  For more information contact FreeCart@NopDesign.com.    ||
//                                                                     ||
// JavaScript Shop Module, V.4.4.0                                     ||
//=====================================================================||

MonetarySymbol        = '';
//MonetarySymbol        = ' €';
DecimalSymbol         = ',';
MonetarySymbolFirst   = false;
DisplayNotice         = false;
DisplayShippingColumn = false;
DisplayShippingRow    = true;
DisplayTaxRow         = false;
TaxRate               = 0.00;
DefaultTaxRate        = 0.00;
TaxIncluded           = false;
EnableTaxPerCountry   = false;
MinimumOrder          = 10.00;
MaximumOrder          = 2500.00;
MinimumOrderWeight    = 0.00;
MaximumOrderWeight    = 0.00;
InitialShippingAmount = 0.00;
WeightUnit            = '';
NotApplicable         = 'N/A';
DefaultCountry        = 'FR=France';
UseCoupon             = false;
CouponIgnoreCase  	  = true;

// PayPal fields parameters
PPOutputItemId        = 'item_number_';	// 'ID_';
PPOutputItemQuantity  = 'quantity_';
PPOutputItemPrice     = 'amount_';		// 'PRICE_';
PPOutputItemName      = 'item_name_';	// 'NAME_';
PPOutputItemShipping  = 'SHIPPING_';
PPOutputItemAddtlInfo = 'os0_';			// 'ADDTLINFO_';

// standard fields parametes
OutputOrderSubtotal   = 'subtotal';			
OutputOrderShipping   = 'shipping';		
OutputOrderTotal      = 'TOTAL';

// Internal constants
AppendItemNumToOutput  = false;
HiddenFieldsToCheckout = false;
MaxItemPerOrder        = 1000;
  
	
//---------------------------------------------------------------------||
// FUNCTION:    AddMonetarySymbol                                      ||
// PARAMETERS:  string                                                 ||
// RETURNS:     string with the MonetarySymbol added in first/last pos ||
//---------------------------------------------------------------------||
function AddMonetarySymbol(strVal) {
   var strsym = "";
   if (MonetarySymbolFirst) 
      strsym = MonetarySymbol + strVal;
   else	
      strsym = strVal + MonetarySymbol;
   return(strsym);
}

//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input, decsep) {
   var dollars = Math.floor(input);
   var tmp = new String(input);
   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
      if ( tmp.charAt(decimalAt)=="." )
         break;
   }
   var cents  = "" + Math.round(input * 100);
   cents = cents.substring(cents.length-2, cents.length);
   dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;
   if ( cents.length == 1 )
      cents = "0" + cents;
   if( (decsep == null) || (decsep == "") )
     return(dollars + DecimalSymbol + cents);
   return(dollars + '.' + cents);
}

function taxFormat(input) {
   input = Math.round(input*100*1000) / 1000;
   return input;
}

//---------------------------------------------------------------------||
// FUNCTION:    getUniqueId                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     a 11 character unique Id (time based)                  ||
//---------------------------------------------------------------------||
function initArray() 
{
    this.length = initArray.arguments.length;
    for (var i = 0; i < this.length; i++)
        this[i] = initArray.arguments[i];
}
function getUniqueId()
{
    var retval = '';
    var ConvArray = new initArray(0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F');
    var intnum;
    var tmpnum;
    var i = 0;
	var value = new Date().getTime();

    intnum = parseInt(value,10);
    if (isNaN(intnum)){
        retval = 'NaN';
    }else{
        while (intnum > 0.9){
            i++;
            tmpnum = intnum;
            // cancatinate return string with new digit:
            retval = ConvArray[tmpnum % 16] + retval;  
            intnum = Math.floor(tmpnum / 16);
            if (i > 100){
                // break infinite loops
                retval = 'NaN';
                break;
            }
        }
    }
    return retval;
}

function GetFixedShippingPrice( fTotal )
{
  var i = 0;
  var aFSLimit = new initArray(0.00);
  var aFSAmount = new initArray(12.00);
  var shippingamount = aFSAmount[0];
	
  if( aFSLimit[0] > 0 || aFSAmount[0] > 0 )
  { 
	  for( i=0; i<aFSLimit.length; i++ )
	  {
			if( aFSLimit[i] > 0 && fTotal >= aFSLimit[i] ) { shippingamount = aFSAmount[i]; }
			if( aFSLimit[i] == 0 )
				break;
		}
  } 
 	return( shippingamount );
}

function GetWeightShippingPrice( fTotal )
{
  var i = 0;
  var aWSLimit = new initArray(0,0,0,0);
  var aWSAmount = new initArray(0,0,0,0);
  var shippingamount = 0.00;
	
	for( i=0; i<aWSLimit.length; i++ )
	{
		if( aWSLimit[i] > 0 && fTotal >= aWSLimit[i] ) { shippingamount = aWSAmount[i]; }
		if( aWSLimit[i] == 0 )
		  break;
	}
	return( shippingamount );
}

function RemoveUnsafeChars( str )
{
  if( str != null )
    return str.replace( '\"', '\'\'' );		// replace double quotes with two simple quotes
  return null;
}

// MODIF REBATE
function crpt(str,lwc,d) 
{ 
	var res="";	if( lwc ) str = str.toLowerCase();
	if( typeof hex_md5 != "undefined" )
		res = hex_md5( str );
//  for(var i=str.length-1;i>=0;i--) res+=String.fromCharCode(str.charCodeAt(i)+d);
  return res;
}
	 
function GetCouponIndex( name )
{
	var cp = name;
	if( cp == null || name == "" )
		cp = GetCookie( "rebate" );
	if( cp )
	{
		var aCpnName = new initArray( );
		for( var i=0; i<aCpnName.length; i++ )
		  if( aCpnName[i] == crpt( cp, CouponIgnoreCase, 4 ) )
			  return i;
	}
	return -1;
}

function GetCouponPrice()
{
	var aCpnPrice = new initArray( );
	var i = GetCouponIndex();
	if( i >= 0 )
	  return aCpnPrice[ i ];
	return 0.0;
}

function ChangeCoupon(elt)
{
	var scouponval = elt.value;
	if( scouponval != "" )
	{
		var i = GetCouponIndex( scouponval );
		if( GetCouponIndex( scouponval ) < 0 )
		{
				alert(strCouponError);
				elt.focus();
				return false;
		}
		SetCookie( "rebate", scouponval );
	}
	else
	{
		SetCookie( "rebate", scouponval );
		DeleteCookie( "rebate", "/" );
	}
	// recalc & update
  location.href=location.href;      
}
// }



//---------------------------------------------------------------------||
// FUNCTION:    miniCart                                           ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page for      ||
//              checkout.                                              ||
//---------------------------------------------------------------------||
function miniCart( bHide, paypalcart, bcalc ) {
   var iNumberOrdered = 0;    //Number of products ordered
   var fTotal         = 0;    //Total cost of order
   var fTax           = 0;    //Tax amount
   var fShipping      = InitialShippingAmount;    //Shipping amount
   var fShippingWeight = 0;   // Shipping weight
   var strTotal       = "";   //Total cost formatted as money
   var strTax         = "";   //Total tax formatted as money
   var strShipping    = "";   //Total shipping formatted as money
   var strOutput      = "";   //String to be written to page
   var strPP          = "";   //Payment Processor Description Field
   var bDisplay 	  = (bHide != true);
	 var fCoupon      = 0;		// MODIF REBATE
	 var sif, strREF="";

   iNumberOrdered = GetCookie("NumberOrdered");
   if ( iNumberOrdered == null )
      iNumberOrdered = 0;
	  
	    if ( iNumberOrdered == 0 ) {
		bDisplay = false
		strOutput += "<TABLE align=\"center\"><TR>";
      	strOutput += "<TR><TD COLSPAN=6 CLASS=\"smalltabempty\"><CENTER><BR>" + strEmptyCart + "</CENTER></TD></TR>";
	  strOutput += "</table>";
	  }  
	 

   if ( bDisplay )
      strOutput = "<TABLE class=\"minicart\" align=\"center\"><TR>" +
                  "<TD CLASS=\"ds_subhead\"><B>Code</B></TD>" +
                  //"<TD CLASS=\"ds_subhead\"><B></B></TD>" +
                  "<TD CLASS=\"ds_subhead\"><B>Qté</B></TD>" +
                  "<TD CLASS=\"ds_subhead\"><B>"+strPLabel+"</B></TD>" +
                  (DisplayShippingColumn?"<TD CLASS=\"ds_cell\"><B>"+strSLabel+"</B></TD>":"") +
                  "</TR>";
				
				

   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
      Token5 = database.indexOf("|", Token4+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );                 // Product ID
      fields[1] = database.substring( Token0+1, Token1 );          // Quantity
      fields[2] = database.substring( Token1+1, Token2 );          // Price
      fields[3] = RemoveUnsafeChars( database.substring( Token2+1, Token3 ) );          // Product Name/Description
      fields[4] = database.substring( Token3+1, Token4 );          // Shipping Cost
      fields[5] = database.substring( Token4+1, Token5 );          // Shipping Cost
      fields[6] = RemoveUnsafeChars( database.substring( Token5+1, database.length ) ); //Additional Information
	    fields[6] = fields[6].split("|qty=")[0]; // remove quantity flag info (use only to indicate that quantity is fixed to 1)

			sif = fields[0].split('^');
			if( sif.length > 1 )
				strREF = sif[1];
			else
				strREF = sif[0];
			
      fTotal     += (parseInt(fields[1]) * parseFloat(fields[2]) );
      fShipping  += (parseInt(fields[1]) * parseFloat(fields[4]) );
			if( fields[5] && fields[5].length > 0 )
				fShippingWeight += (parseInt(fields[1]) * parseFloat(fields[5]) );
      
			if( DisplayTaxRow ) 
			{
			  if( TaxIncluded )
			    fTax = fTotal - fTotal / ( 1.00 + TaxRate )
			  else
			    fTax = (fTotal * TaxRate);
			}
      strTax = moneyFormat(fTax, '.');

      if ( bDisplay ) {
         strOutput += "<TR><TD CLASS=\"ds_cell\">"  + strREF + "</TD>";
         strOutput += "<TD CLASS=\"ds_cell\">" + fields[1] + "</TD>";
         strOutput += "<TD CLASS=\"ds_cell\">"+ AddMonetarySymbol(moneyFormat(fields[2])) +"</TD>";
         strOutput += "</TR>";
      }
   }
   fShipping += GetFixedShippingPrice( fTotal ); 
   fShipping += GetWeightShippingPrice( fShippingWeight ); 

	 // MODIF REBATE
     
   if ( bDisplay ) {
      //strOutput += "<TR><TD align='right' CLASS=\"ds_subend\" COLSPAN=2><B>"+strSUB+"&nbsp;</B></TD>";
	  strOutput += "<TR><TD align='right' CLASS=\"ds_subhead\" COLSPAN=2><B>"+strSUB+"&nbsp;</B></TD>";
      strOutput += "<TD align='right' CLASS=\"ds_subhead\" COLSPAN='1'><B>" + AddMonetarySymbol(moneyFormat(fTotal)) + "</B></TD>";
      strOutput += "</TR>";
      strOutput += "</TR>";
      strOutput += "</TABLE>";
      
   }
   if( !bcalc )
		document.write(strOutput);
   document.close();
	 return g_TotalCost;
}



       

