﻿var shippingTable = new Object();   
var CODTable = new Object();  // cash on delivery
var packetPrice = new Object();
var packetWeight = new Object();
var itemWeight = new Object();

var COMMON_ITEM_PRICE = 10; //EUR
var PAYPAL_TAX_PERC_1 = 0.034; //% for Spain
var PAYPAL_TAX_PERC_2 = 0.039; //% for other countries
var PAYPAL_TAX_FIX = 0.35; //EUR.
var COD_ACCOUNT_CHARGE_PERCENT = 0.008; //%
var PAYPAL_PAYMENT_INDEX = 2;
var TRANSFER_PAYMENT_INDEX = 3;
var CONTRARREEMBOLSO_PAYMENT_INDEX = 4;
var PAYPAL_PAYMENT_ARRAY_INDEX = 1;
var TRANSFER_PAYMENT_ARRAY_INDEX = 2;
var CONTRARREEMBOLSO_PAYMENT_ARRAY_INDEX = 3;

var SPAIN_INDEX = 1;
var EUROPE1_INDEX = 2;
var EUROPE2_INDEX = 3;
var OTHER_COUNTRY_INDEX = 4;

var order = new Object();  // object to store order items in
var root  = new Object();  // selection criteria
var on    = true;
var off   = false;
var cntr  = 0;             // items in object
var opts  = 5;             // number of options to allow
var shpr  = function (wt) {return 0;} // what to charge for shipping;
var stxt  = "";            // shipping text
var countryIndex  = -1;            // shipping position selector
var paymentIndex  = -1;            // payment option position selector
var ttax  = 0;             // percent for taxes
var ttxt  = "0";           // tax text
var tpos  = -1;            // tax position selector
var tamt=0,tqty=0,twgt=0,wgt=0,thnd=0;  // totals

root.hamt = 0;     // amount, below which, handling charge applies
root.hand = 0;     // handling charge for orders less than hamt
root.shp  = on;    // shipping selection line
root.tax  = on;    // tax selection line
// place for user-specific options
root.xx_can  = ""; // place for PayPal cancel return path
root.xx_cur  = "EUR"; // enter default currency code (or null)
root.xx_id   = "angeldarkmusic@gmail.com";  // PayPal ID
root.xx_img  = ""; // image URL
root.xx_lc   = ""; // enter default country code (or null)
root.xx_ret  = ""; // place for PayPal return path
root.xx_sty  = ""; // place for PayPal page style
root.xx_xtra = ""; // place for other PayPal commands

//Post office costs
shippingTable[1] = new Object();  //Spain
shippingTable[2] = new Object();  //Europe 1
shippingTable[3] = new Object();  //Europe 2
shippingTable[4] = new Object();  //Other countries
//Spain
shippingTable[1][1] = 1.25; 	//0-200gr  
shippingTable[1][2] = 2.10;  	//201-350
shippingTable[1][3] = 3.65;  //351-500
shippingTable[1][4] = 4.15;  //501-1000
shippingTable[1][5] = 4.65;  //1001-1500
shippingTable[1][6] = 5.00;  //1501-2000
//Europe1
shippingTable[2][1] = 3.80; 	//0-200gr  
shippingTable[2][2] = 7.05;  	//201-350
shippingTable[2][3] = 9.80;  //351-500
shippingTable[2][4] = 11.50;  //501-1000
shippingTable[2][5] = 17.40;  //1001-1500
shippingTable[2][6] = 20.00;  //1501-2000
//Europe2
shippingTable[3][1] = 3.28; 	//0-200gr  
shippingTable[3][2] = 6.08;  	//201-350
shippingTable[3][3] = 8.45;  //351-500
shippingTable[3][4] = 9.91;  //501-1000
shippingTable[3][5] = 15.00;  //1001-1500
shippingTable[3][6] = 17.24;  //1501-2000
//Other countries
shippingTable[4][1] = 5.25; 	//0-200gr  
shippingTable[4][2] = 9.60;  	//201-350
shippingTable[4][3] = 16.50;  //351-500
shippingTable[4][4] = 19.35;  //501-1000
shippingTable[4][5] = 32.00;  //1001-1500
shippingTable[4][6] = 36.90;  //1501-2000

//CoD
CODTable[1] = new Object();  //Spain
//Spain
CODTable[1][1] = 5.20; 	//0-200gr  
CODTable[1][2] = 6.04;  	//201-350
CODTable[1][3] = 7.60;  //351-500
CODTable[1][4] = 8.10;  //501-1000
CODTable[1][5] = 8.60;  //1001-1500
CODTable[1][6] = 8.94;  //1501-2000

var packetPrice = new Object();
var packetWeight = new Object();
//Packet prices
packetPrice[1] = 0.30; // CD size
packetPrice[2] = 0.75; // Medium
packetPrice[3] = 1; // Large
//Packet weights
packetWeight[1] = 0.10; //grams (CD size)
packetWeight[2] = 0.25; //grams (Medium)
packetWeight[3] = 0.45; //¿?grams (Large)
//Item weights
itemWeight[1] = 520;//grams
itemWeight[10] = 120;//grams
itemWeight[11] = 170;//grams
itemWeight[12] = 155;//grams
itemWeight[20] = 140;//grams
itemWeight[21] = 125;//grams

function initShopping()
{
	cntr = 0;  
  shpr = function (wt) {return 0;}
  //if (root.shp)
  	countryIndex = 0;
  //if (root.tax)
  	tpos = 0;
  tamt=0;
  tqty=0;
  twgt=0;
  wgt=0;
  thnd=0;
	document.orderf.reset();
  var rowDiv=document.getElementById('SCDiv'+10);
  rowDiv.style.display = 'none';
   rowDiv=document.getElementById('SCDiv'+11);
  rowDiv.style.display = 'none';
 rowDiv=document.getElementById('SCDiv'+12);
  rowDiv.style.display = 'none';
 rowDiv=document.getElementById('SCDiv'+20);
  rowDiv.style.display = 'none';  
 rowDiv=document.getElementById('SCDiv'+21);
  rowDiv.style.display = 'none';
  var emptySCDiv=document.getElementById('emptySCDiv');
  emptySCDiv.style.display = 'block';

  var paymentCombo=document.getElementById('paymentType');
  paymentCombo.selectedIndex=2;

}

function CalcRoot ()
{  // calc root stuff
  if (root.shp) countryIndex=0; 
  if (root.tax) tpos=0;
}

function DispTots ()
{
var tmp,d;
  d = document.orderf;
  d.sub.value = Smooth (tamt);
//TODO: descomentar si se utilizan pesos totales->  d.wgt.value = twgt;
  if (root.shp) d.shp.value = Smooth (shpr (twgt));
/*  tmp = tamt * ttax/100;
  if (root.tax) d.tax.value = Smooth (tmp);
  thnd = 0;                    // assume the worst;
  if (d.hnd) d.hnd.value = "0.00";
  if (tamt*1.0 < root.hamt) {  // calculate handling charge
      thnd = root.hand;        // figure it out
      if (d.hnd) d.hnd.value = Smooth (thnd);
  }*/
  d.tot.value = Smooth (tamt + shpr (twgt)/* + tmp + thnd*/);
  var emptySCDiv=document.getElementById('emptySCDiv');
  if(d.tot.value > 0)
  	emptySCDiv.style.display = 'none';
  else
  	emptySCDiv.style.display = 'block';
}

function Smooth (val)
{     // force to valid dollar amount
	var str,pos,rnd=0;
  if (val < .995)
  	rnd = 1;  // for old Netscape browsers
  str = escape (val*1.0 + 0.005001 + rnd);  // float, round, escape
  pos = str.indexOf (".");  // should be one, but OK if not
  if (pos > 0)
  	str = str.substring (rnd, pos + 3);
  return str;               // return valid string
}

function GetOrder (id, des, amt, wgt) {  // get all ordered items
var i,nr,val,qty,pos;
var op = new Array ();    // accumulate options here
  tamt=0,tqty=0,twgt=0;   // zero totals
  nr = id.substring (2);  // get number part of ID
  qty = document.orderf["qty" + nr].value;  // get qty
  if (isNaN (qty) || (Number(qty)==0) || (qty < 0)) {      // test entry
    alert ("That is not a valid quantity!  Try again.");
    return;
  }
  if(nr>10)
  {
  	nr = parseInt(nr) + document.orderf["chs" + nr].selectedIndex;
  	id="id"+nr;
  }
  wgt = itemWeight[parseInt(nr)];
  amt = COMMON_ITEM_PRICE;
  //Después de "retocar" nr...
  qty = parseInt(document.orderf["scq" + nr].value) + parseInt(qty);
  var rowDiv=document.getElementById('SCDiv'+nr);
  if(qty > 0)
  	rowDiv.style.display = 'block';
  else
  	rowDiv.style.display = 'none';
  for (i=1; i<=opts; i++) {     // see if any options
    if (document.orderf["op" + i + nr]) {
      val = document.orderf["op" + i + nr].value;  // get option
      op[i] = val;
    }
    else op[i] = "";
  }
  document.orderf["prc" + nr].value = Smooth (qty * amt);
  document.orderf["toz" + nr].value = qty * wgt;
  document.orderf["scq" + nr].value = qty;
  if (cntr == 0) order = new Object (); // zap object
  cntr = cntr + 1;               // bump counter so no zap next time
  order[id] = new Object ();     // create new entry
  for (i=1; i<=opts; i++)        // load options
    if (op[i] != "") des = des + ", " + op[i];//if (op[i] != "") des = des + ", OP" + i + "=" + op[i];
  order[id].des = des;           // load up values
  order[id].amt = Smooth (amt);
  order[id].qty = qty;
  if (wgt) order[id].wgt = wgt;
    else order[id].wgt = 0;
  for (i in order) {             // calc totals we might use
    qty = order[i].qty*1.0;
    tamt = tamt + order[i].amt * qty;  // total amount
    tqty = tqty + qty;                 // total quantity
    twgt = twgt + order[i].wgt * qty;  // total ounces
  }
	SetShp(1);
  DispTots ();                         // calc totals
  if(qty>0)
  	viewCart('not move');
}

function SendCart () 
{  // send the cart to PayPal
	var heavyOrderMsg;
	var emptyCartMsg;
	var emailOrderMsg;
	var CODMsg;
	if(root.xx_lc == "US")
	{
		heavyOrderMsg = "e-mail us to get orders heavier than 2Kg (info@angeldarkweb.com)";
		emptyCartMsg = "Your shopping cart is empty!"
		emailOrderMsg = "Here is your order's price for bank transfer payment.\ne-mail us your address and chosen items to confirm your order: info@angeldarkweb.com\n\n Thanks!";
		CODMsg = "Cash on delivery payment is only available for orders in Spain.";
	}
	else
	{
		heavyOrderMsg = "Para pedidos mayores de 2Kg solicita un pedido personalizado, enviando un email a info@angeldarkweb.com";
		emptyCartMsg = "El carrito de la compra está vacío!";
		emailOrderMsg = "Este es el precio de tu pedido para pago por transferencia bancaria.\nPara confirmarlo simplemente envíanos tu dirección, método de pago y los artículos escogidos: info@angeldarkweb.com\n\n ¡Gracias!";
		CODMsg = "Sólo se permite pago contrarreembolso para pedidos en España.";
	}
	if(twgt >2000)
  {
  		alert(heavyOrderMsg);	
	  	return;
  }
	if((paymentIndex == CONTRARREEMBOLSO_PAYMENT_ARRAY_INDEX) && (countryIndex != SPAIN_INDEX))
	{
			alert(CODMsg);
			return;
	}
 	if((paymentIndex == TRANSFER_PAYMENT_ARRAY_INDEX) || (paymentIndex == CONTRARREEMBOLSO_PAYMENT_ARRAY_INDEX))
	{
			alert(emailOrderMsg);
			return;
	}
	var frst = true;  // 1st pass thru items.
	var winpar = "width=1000,height=690,scrollbars," +
             "location,resizable,status";
	var strn   = "https://www.paypal.com/cgi-bin/webscr?cmd=_cart" +
             "&upload=1" +
             "&business=" + root.xx_id + root.xx_xtra;
	var i,j=0,des;
  if (root.xx_cur.length > 0)
    strn = strn + "&currency_code=" + root.xx_cur;
  if (root.xx_lc.length > 0)
    strn = strn + "&lc=" + root.xx_lc;
  if (root.xx_can.length > 0)
    strn = strn + "&cancel_return=" + root.xx_can;
  if (root.xx_ret.length > 0)
    strn = strn + "&return=" + root.xx_ret;
  if (root.xx_sty.length > 0)
    strn = strn + "&page_style=" + root.xx_sty;
  if (root.xx_img.length > 0)
    strn = strn + "&image_url=" + root.xx_img;
  if (tpos > 0) strn = strn + "&tax_cart=" + Smooth (tamt*ttax/100);
  for (i in order) {  // send all valid data
    if (order[i].qty > 0) {
      j = j + 1;
      des = order[i].des;
      /*if (j == 1) {  // put in descriptions for 1st item
        des = des + ", SHP=" + stxt;
        des = des + ", TAX=" + ttxt;
        strn = strn + "&handling_cart=" + Smooth (thnd);
      }*/
      strn = strn + "&item_name_"    + j + "=" + escape (des) +
                    /*"&item_number_"  + j + "=" + i +*/
                    "&quantity_"     + j + "=" + order[i].qty +
                    "&amount_"       + j + "=" + order[i].amt;
      if (countryIndex >= 0) {  // there is some shipping activity
        if (frst) {     // first time thru
          strn = strn + "&shipping_" + j + "=" + Smooth (shpr(twgt));
        } else {        // every other time thru
          strn = strn + "&shipping_" + j + "=0";
        }
      }
      frst = false;
    }
  }
  if (j > 0) 
  	window.open (strn, "paypal", winpar);
  else
	  alert(emptyCartMsg);  	
}

function GetPacketIndex()
{
	var res;
	var CDcount = 0;
	var tshirtCount = 0;
	for (i in order)
	{
			if(i == "id10") //CD
				CDcount = CDcount + order[i].qty;
			else
				tshirtCount = tshirtCount + order[i].qty;
	}	

		//alert('tqty:'+tqty + '    CDcount:'+CDcount + '      tshirtCount:' + tshirtCount);
	if((tqty <= 2) && (CDcount == tqty)) //particular case: 1 or 2 items and all are CD
		return 1; // CD size
	if((tqty < 2) && (tshirtCount == tqty)) //particular case: 1 item and it's a t-shirt
		return 2; // Medium size
	else //More than 1 items
	{
		switch(tqty)
		{
			case 0: return 1; //This should be an imposible case
			case 2: 
				{
					if(CDcount == 2)
						return 1; //CD size
					else
						return 2; //medium size
				}
			case 3:
				{
					if(CDcount == 0)	//no CDs
						return 3; //large size
					else
						return 2; //Medium size is enough
				}
			default: //by now more than 3 items => large size packet
				return 3;
		}
	}	
	return 1;
}


function SetShp (obj) 
{  // set shipping on user selection
	var heavyOrderMsg;
	var emptyCartMsg;
	var CODMsg;
	if(root.xx_lc == "US")
	{
		heavyOrderMsg = "e-mail us to get orders heavier than 2Kg (info@angeldarkweb.com)";
		emptyCartMsg = "Your shopping cart is empty!"
		CODMsg = "Cash on delivery payment is only available for orders in Spain.";
	}
	else
	{
		heavyOrderMsg = "Para pedidos mayores de 2Kg solicita un pedido personalizado, enviando un email a info@angeldarkweb.com";
		emptyCartMsg = "El carrito de la compra está vacío!";
		CODMsg = "Sólo se permite pago contrarreembolso para pedidos en España.";
	}
  shpr = function (wt) {return 0;}  // zap it
  var shippingCombo=document.getElementById('shipper');
  countryIndex = shippingCombo.selectedIndex;
  shippingCombo.style.backgroundColor="#76543B";
  var shippingValue = shippingCombo.value;
	if(shippingValue=="inv")
  {
  	countryIndex = 0;
  	DispTots ();
  	return;
  }
  if(countryIndex < 4)
  	countryIndex = SPAIN_INDEX; // No sobra
  else
  if(countryIndex < 41)
  	countryIndex = EUROPE1_INDEX;//Europa Zona 1
  else if(countryIndex < 63)
  	countryIndex = EUROPE2_INDEX;//Europa Zona 2
  else
  	countryIndex = OTHER_COUNTRY_INDEX;// Resto del mundo  	


  var paymentCombo=document.getElementById('paymentType');
  paymentIndex = paymentCombo.selectedIndex;
  paymentCombo.style.backgroundColor="#76543B";
  var paymentValue = paymentCombo.value;
	if(paymentValue=="inv")
  {
  	paymentIndex = 0;
  	DispTots ();
  	return;
  }
  var payment;
  if(paymentIndex <= PAYPAL_PAYMENT_INDEX) //PayPal
  	paymentIndex = PAYPAL_PAYMENT_ARRAY_INDEX;
  else if (paymentIndex == TRANSFER_PAYMENT_INDEX) // Transferencia
  	paymentIndex = TRANSFER_PAYMENT_ARRAY_INDEX;
  else
  	paymentIndex = CONTRARREEMBOLSO_PAYMENT_ARRAY_INDEX; //Contra reembolso

	if((paymentIndex == CONTRARREEMBOLSO_PAYMENT_ARRAY_INDEX) && (countryIndex != SPAIN_INDEX))
	{
			alert(CODMsg);
			return;
	}


  var weightIndex;
  if(twgt <=200)
  	weightIndex = 1;
  else if(twgt <=350)
  	weightIndex = 2;
  else if(twgt <=500)
  	weightIndex = 3;
  else if(twgt <=1000)
  	weightIndex = 4;
  else if(twgt <=1500)
  	weightIndex = 5;
  else if(twgt <=2000)
  	weightIndex = 6;
  else
  {
  	alert(heavyOrderMsg);	
  	return;
  }
	if(twgt <= 0)
	  shpr = function () {return 0;}
	else
	{
	  shpr = function () 
	  	{
	  		//First of all: post office costs + packet price
	  			//alert("Packet type="+GetPacketIndex());
	  		var shipping;
	  		if(paymentIndex == CONTRARREEMBOLSO_PAYMENT_ARRAY_INDEX)
	  			 shipping = CODTable[1][weightIndex] + packetPrice[GetPacketIndex()];
	  		else
	  			 shipping = shippingTable[countryIndex][weightIndex] + packetPrice[GetPacketIndex()];
	  		  //alert("shipping1="+shipping);
	  		//base = post office costs + packet price + items subtotal;
	  		var paypalVarCommisionBase = shipping + tamt;
	  		  //alert("paypalVarCommisionBase="+paypalVarCommisionBase);
	  		var paypalCommision;
	  		if(countryIndex == 1) //Spain
	  			paypalCommision = PAYPAL_TAX_PERC_1;
	  		else //other countries
	  			paypalCommision = PAYPAL_TAX_PERC_2;
	  		var paypalVarCommision = paypalVarCommisionBase*paypalCommision;
	  		  //alert("paypalVarCommision="+paypalVarCommision);
	  		//shipping costs = post office costs + packet costs + paypal commisions
	  		if(paymentIndex == PAYPAL_PAYMENT_ARRAY_INDEX) //for PayPal payment only
		  		shipping = shipping + paypalVarCommision + PAYPAL_TAX_FIX;
	  		  //alert("shipping NO IVA="+shipping);
	  		//Now add shipping IVA 16% grrrrrrrrrrrrrr!!!
	  		shipping = shipping*1.16;
	  		//  alert("shipping WITH IVA="+shipping);
	  		return shipping;
	  		//return shippingTable[countryIndex][weightIndex];
	  	}
	}
  DispTots ();
}

function SetTax (obj) {
  tpos = obj.selectedIndex;  // which option selected
  ttxt = obj.options[tpos].text;
  ttax = obj.options[tpos].value*1.0;
  DispTots ();
}

function checkout()
{
	var msg;
	var cartIsEmptyMsg;
	var paymentTypeMsg;
	if(root.xx_lc == "US")
	{
		msg = "You must select your order's delivery country!";
		cartIsEmptyMsg = "Your shopping cart is empty!";
		paymentTypeMsg = "You must select the payment option!";
	}
	else
	{
		msg = "Te falta seleccionar el país de destino del envío!";
		cartIsEmptyMsg = "Tu carrito está vacío!";
		paymentTypeMsg = "Te falta seleccionar el modo de pago!";
	}	
	
	if(tqty < 1)
	{
		alert(cartIsEmptyMsg);
		return false;
	}
	if (countryIndex < 1) 
	{
		alert (msg);
	  var shippingCombo=document.getElementById('shipper');
  	shippingCombo.style.backgroundColor="red";
		return false; 
	} 
	if (paymentIndex < 1) 
	{
		alert (paymentTypeMsg);
	  var combo=document.getElementById('paymentType');
  	combo.style.backgroundColor="red";
		return false; 
	} 
	SendCart ();
}

function viewCart(gotoCart)
{
	var div = document.getElementById('shoppingCart');
	div.style.height = 'auto';
	div.style.visibility = 'visible';
	div.style.display = 'block';
	if(gotoCart == 'move')
		window.scrollTo(0,200);

/*	if(toggle)
	{
		if(div.style.display == 'block')
			div.style.display = 'none';
		else
		{
			div.style.display = 'block';
			window.scrollTo(0,200);
		}
	}
	else //Show always
	{
		div.style.display = 'block';
		window.scrollTo(0,200);
	}*/
}