/* masterchef.js
(c) 2009 Philippe Thomassigny - Alternativa Digital SA de CV
Javascript modificado para sitio masterchef.com.mx
*/

function verresumen()
{
  var d = $('resumencarritoframe');
  if (d.style.display == '')
  {
    d.activo = false;
    d.style.display = 'none';
    // some animation ?
  }
  else // undefined or false
  {
    d.activo = true;
    d.style.display = '';
    // some animation ?
  }
  ajax('/?P=carritoresumenajax', 'POST', 'status='+d.activo, null, true);
}

function formatnumber(num, fix)
{
  num = num.toFixed(fix);
	num += '';
	x = num.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.'+x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function addquantity(id, qt, base, totalid)
{
  var v = parseInt($(id).value, 10);
  if (!v)
    $(id).value = 1;
  else
    $(id).value = (v+qt<1)?1:v+qt;

  calculatetotal(base, id, totalid);
}

function calculatetotal(base, quantityid, totalid)
{
  var q = $(quantityid).value;
  var t = base * q;
  $(totalid).innerHTML = formatnumber(t,2);
}

function addquantitycombos(id, qt, base, unittotalid, totalid)
{
  var v = parseInt($(id).value, 10);
  if (!v)
    $(id).value = 1;
  else
    $(id).value = (v+qt<1)?1:v+qt;

  calculatetotalcombos(base, id, unittotalid, totalid);
}

function calculatetotalcombos(base, quantityid, unittotalid, totalid)
{
  var adjust = 0.0;
  for (var i in combos)
  {
    if (i == '__init')
      continue;
    var cb = $(i).value;
    adjust += combos[i][cb]?combos[i][cb]:0;
  }
  var q = $(quantityid).value;
  var t = (base + adjust) * q;
  $(unittotalid).innerHTML = formatnumber((base + adjust),2);
  $(totalid).innerHTML = formatnumber(t,2);
}

function endanim()
{
  var n = $('animimage');
  var c = $('cuerpo');
  if (n)
    c.removeChild(n);

  // ahora animamos el carrito
  animManager.createSprite('cart', 'textocarrito', null, {autostart:true, loop:false, chain: [{type:'move',time:100,tinit:100,tend:0},{type:'wait',time:200},{type:'move',time:100,tinit:0,tend:100},{type:'wait',time:200},{type:'move',time:100,tinit:100,tend:0},{type:'wait',time:200},{type:'move',time:100,tinit:0,tend:100}]});
}

function setcartquantity()
{
  browser.setInnerHTML($('carritocantidad'), parseInt($('quantityproductcart').innerHTML, 10));
}

function cartok(r)
{
  // got the response for the cart
  browser.setInnerHTML($('resumencarrito'), r.responseText);
  setcartquantity();
}

function sendtocart_a(imgid, href)
{
  // get all the params of the form (ajaxform)
  var request = ajaxManager.createRequest(href, 'POST', '', cartok, false);
  request.addParameter('P', 'carritoajax'); // we replace P
  request.send();

  // animar la imagen
  var img = $(imgid);
  if (!img)
  {
    endanim();
    return;
  }
  var n = img.cloneNode(false);
  var c = $('cuerpo'); // we move into the body

  var startleft = browser.getNodeNodeLeft(img, c);
  var starttop = browser.getNodeNodeTop(img, c);
  var endleft = browser.getNodeNodeLeft($('botoncarrito'), c);
  var endtop = browser.getNodeNodeTop($('botoncarrito'), c);
  var startwidth = browser.getNodeWidth(img);
  var startheight = browser.getNodeHeight(img);

  n.style.position = 'absolute';
  n.id='animimage';
  n.style.left = browser.getNodeNodeLeft(img, c) + 'px';
  n.style.top = browser.getNodeNodeTop(img, c) + 'px';
  n.style.zIndex = 10000;
  c.appendChild(n);

  // animar la imagen
  animManager.createSprite('image', 'animimage', endanim, {autostart:true, loop:false, chain: [{type:'move',time:500,xinit:startleft,xend:endleft,yinit:starttop,yend:endtop,winit:startwidth,wend:16,hinit:startheight,hend:16}]});
}

function sendtocart(formid)
{
  // get all the params of the form (ajaxform)
  var request = ajaxManager.createRequest('/', 'POST', 'P=carritoajax', cartok, false);
  addFormValues($('product'), request);
  request.send();

  // animar la imagen
  var n = $('prodimage').cloneNode(false);
  var c = $('cuerpo'); // we move into the body

  var startleft = browser.getNodeNodeLeft($('prodimage'), c);
  var starttop = browser.getNodeNodeTop($('prodimage'), c);
  var endleft = browser.getNodeNodeLeft($('botoncarrito'), c);
  var endtop = browser.getNodeNodeTop($('botoncarrito'), c);
  var startwidth = browser.getNodeWidth($('prodimage'));
  var startheight = browser.getNodeHeight($('prodimage'));

  n.style.position = 'absolute';
  n.id='animimage';
  n.style.left = browser.getNodeNodeLeft($('prodimage'), c) + 'px';
  n.style.top = browser.getNodeNodeTop($('prodimage'), c) + 'px';
  n.style.zIndex = 10000;
  c.appendChild(n);

  // animar la imagen
  animManager.createSprite('image', 'animimage', endanim, {autostart:true, loop:false, chain: [{type:'move',time:500,xinit:startleft,xend:endleft,yinit:starttop,yend:endtop,winit:startwidth,wend:16,hinit:startheight,hend:16}]});
}

function addFormValues(form, request)
{
  for(var i = 0;i < form.elements.length;i++)
  {
    // we ignore the page for AJAX since we force it manually
    if (form.elements[i].name == 'P')
      continue;
    switch(form.elements[i].type)
    {
      case "text":
      case "textarea":
      case "hidden":
      case "password":
        request.addParameter(form.elements[i].name, utf8_encode(form.elements[i].value));
        break;
      case "radio":
        if (form.elements[i].checked)
          request.addParameter(form.elements[i].name, utf8_encode(form.elements[i].value));
        break;
      case "select-one":
        if (form.elements[i].selectedIndex >= 0)
          request.addParameter(form.elements[i].name, utf8_encode(form.elements[i].options[form.elements[i].selectedIndex].value));
        break;
      case "select-multiple":
      case "checkbox":
        if (form.elements[i].checked)
          request.addParameter(form.elements[i].name, utf8_encode(form.elements[i].value));
        break;
      case "file":
        // no se puede leer por JS
      case "image":
      case "button":
      case "submit":
      case "reset":
        // ignorado
      default:
        break;
    }
  }
}

var background = null;
var modal = null;

function zoom(link)
{
  // 1. put the modal background
  if (!background)
  {
    background = WA.createDomNode('div', 'lightbg', 'modalbg');
    document.body.appendChild(background);
    on('click', background, closezoom, true);
  }
  background.style.display = 'block';
  background.style.height = browser.getDocumentHeight() + 'px';

  if (!modal)
  {
    modal = WA.createDomNode('div', 'light', 'modal');
    background.appendChild(modal);
  }

  browser.setInnerHTML(modal, '<div id="modalloader" style="padding: 15px; background-color: white; width: 120px; height: 30px; position: absolute; left: -60px; top: -30px;"><img src="/pics/ajax-loading.gif" style="vertical-align: middle;" alt="" title="" /> <b>Cargando...</b></div><div id="modalcontainer" style="background-color; white; position: absolute; visibility: hidden; overflow: auto; opacity: 0; filter: alpha(opacity: 0); "><img id="modalimg" src="'+link+'" alt="" title="" /></div>');

  adjustsize();
}

function adjustsize()
{
  var width = browser.getNodeWidth($('modalimg'));
  if (width == 0)
  {
    setTimeout(adjustsize, 100);
    return;
  }

  var widthmax = browser.getWindowWidth() - 100;
  var heightmax = browser.getWindowHeight() - 100;
  var height = browser.getNodeHeight($('modalimg'));
  if (height > heightmax)
  {
    height = heightmax;
    width += 20;
  }
  if (width > widthmax)
  {
    width = widthmax;
    height += 20;
  }

  // 1. move vertical
  // 2. move horizontal
  animManager.createSprite('zoom', 'modalloader', fades, {autostart:true, loop:false, chain: [{type:'move',time:400,xinit:-60,xend:-60,yinit:-30,yend:-(height/2),winit:120,wend:120,hinit:30,hend:height-30}, {type:'move',time:300,xinit:-60,xend:-(width/2),yinit:-(height/2),yend:-(height/2),winit:120,wend:width-30,hinit:height-30,hend:height-30}]});

  $('modalcontainer').style.width = width+'px';
  $('modalcontainer').style.height = height+'px';
  $('modalcontainer').style.left = -(width/2)+'px';
  $('modalcontainer').style.top = -(height/2)+'px';
}

function fades()
{
  animManager.createSprite('zoom1', 'modalloader', null, {autostart:true, loop:false, chain: [{type:'move', time:500, tinit:100, tend: 0}]});
  animManager.createSprite('zoom2', 'modalcontainer', null, {autostart:true, loop:false, chain: [{type:'move',time:500, tinit:0, tend:100}]});
  $('modalcontainer').style.visibility = '';
}

function closezoom()
{
  background.style.display = 'none';
  // empty the modal
  browser.setInnerHTML(modal, '');
}

/* CART FUNCTIONS */

function checkallcart()
{
  alert('check all checkboxes');
}

function deletecartentry(id)
{
  // deletes the line
  var tr = $(id);
  if (tr)
    tr.parentNode.removeChild(tr);
  calculatecarttotal();
  var entry = id.substr(5); // entryNNN
  sendcartajax('del', entry);
}

function addcartquantity(id, qt)
{
  var v = parseInt($(id).value, 10);
  if (!v)
    $(id).value = 1;
  else
    $(id).value = (v+qt<1)?1:v+qt;
  // recalculate all formulas
  calculatecarttotal();
  // send ajax to modify quantities on server
  var entry = id.substr(8); // quantityNNN
  sendcartajax('quantity', entry, $(id).value);
}

// recalculate ALL totals and quantities
function calculatecarttotal()
{
  var bignum = 0;
  var bigquantity = 0;
  var bigtotal = 0;
  var all_tr = document.getElementsByTagName('tr');
  for (var i=0; i<all_tr.length; i++)
  {
    if (all_tr[i].className != 'cartline')
      continue;
    if (!all_tr[i].id)
      continue;

    var entry = all_tr[i].id.substr(5);
    var price = parseFloat($('price'+entry).innerHTML);
    var quantity = parseInt($('quantity'+entry).value, 10);
    var total = price * quantity;
    bigtotal += total;
    bigquantity += quantity;
    bignum ++;
    $('total'+entry).innerHTML = formatnumber(total,2);
  }

  // down the list
  if ($('grannum'))
  {
    $('grannum').innerHTML = bignum;
    $('granquantity').innerHTML = bigquantity;
    $('grantotal').innerHTML = formatnumber(bigtotal,2);
  }

  // our resume
  if ($('numproductcarttotal'))
  {
    $('numproductcarttotal').innerHTML = bignum;
    $('quantityproductcarttotal').innerHTML = bigquantity;
    $('totalcostcarttotal').innerHTML = formatnumber(bigtotal,2);
  }

  // float div
  if ($('numproductcart'))
  {
    $('numproductcart').innerHTML = bignum;
    $('quantityproductcart').innerHTML = bigquantity;
    $('totalcostcart').innerHTML = formatnumber(bigtotal,2);
    $('carritocantidad').innerHTML = bigquantity;
  }
}

function deletecartselected()
{
  alert('delete cart selected');
}

function modifcartquantity()
{
  alert('modif cart');
}

function receivecartajax(r)
{
  browser.setInnerHTML($('resumencarrito'), r.responseText);
}

function sendcartajax(order, entry, quantity)
{
  ajax('/?P=carritoajax', 'POST', 'CARTOrder='+order+(entry?'&CARTEntry='+entry:'')+(quantity?'&quantity='+quantity:''), receivecartajax, true);
}

/* Funciones de Direcciones */

function necesitafactura(status)
{
  if (status == 'si')
  {
    $('sifacturacion').style.display = '';
    $('sifacturaciondata').style.display = '';
  }
  else
  {
    $('sifacturacion').style.display = 'none';
    $('sifacturaciondata').style.display = 'none';
  }
}

function necesitafacturamismadireccion(status)
{
  if (status == 'si')
  {
    $('facturaotradireccion').style.display = 'none';
  }
  else
  {
    $('facturaotradireccion').style.display = '';
  }
}

function necesitaenviofactura(status)
{
  if (status == 'otro')
  {
    $('direccionenviofactura').style.display = '';
  }
  else
  {
    $('direccionenviofactura').style.display = 'none';
  }
}

function putdivenvio(r)
{
  $('direccionenvio').innerHTML = r.responseText;
  TestInfo_1000();
}

function putdivfactura(r)
{
  $('direccionfactura').innerHTML = r.responseText;
  TestInfo_4000();
}

function putdivdatosfactura(r)
{
  $('datosfactura').innerHTML = r.responseText;
  TestInfo_5000();
}

function putdivenviofactura(r)
{
  $('direccionenviofacturadata').innerHTML = r.responseText;
  TestInfo_3000();
}

function useaddress(type, href, param, order)
{
  var val = $(param).value;
  if (type == 1)
  {
    ajax(href, 'POST', 'P=direccionenvio&'+order+'=Update&'+param+'='+val, putdivenvio, true);
  }
  else if (type == 2)
  {
    ajax(href, 'POST', 'P=direccionfactura&'+order+'=Update&'+param+'='+val, putdivfactura, true);
  }
  else if (type == 4)
  {
    ajax(href, 'POST', 'P=direccionfactura&'+order+'=Update&'+param+'='+val, putdivfactura, true);
  }
  else if (type == 5)
  {
    ajax(href, 'POST', 'P=datosfactura&'+order+'=Update&'+param+'='+val, putdivdatosfactura, true);
  }
  else
  {
    ajax(href, 'POST', 'P=direccionenviofactura&'+order+'=Update&'+param+'='+val, putdivenviofactura, true);
  }
}

function deleteaddress(type, href, param, order)
{
  var val = $(param).value;
  if (confirm('¿Esta seguro que desea borrar esta dirección?'))
  {
    if (type == 1)
    {
      ajax(href, 'POST', 'P=direccionenvio&'+order+'=Delete&'+param+'='+val, putdivenvio, true);
    }
    else if (type == 2)
    {
      ajax(href, 'POST', 'P=direccionfactura&'+order+'=Delete&'+param+'='+val, putdivfactura, true);
    }
    else if (type == 4)
    {
      ajax(href, 'POST', 'P=direccionfactura&'+order+'=Delete&'+param+'='+val, putdivfactura, true);
    }
    else if (type == 5)
    {
      ajax(href, 'POST', 'P=datosfactura&'+order+'=Delete&'+param+'='+val, putdivdatosfactura, true);
    }
    else
    {
      ajax(href, 'POST', 'P=direccionenviofactura&'+order+'=Delete&'+param+'='+val, putdivenviofactura, true);
    }
  }
}

function direccionsiguiente()
{
  // checkar que las 3 direcciones esten bien capturadas !
  // Guardar todo y saltar a la pagina de pago !
  var result = !TestInfo_1000();
  if ($('sifacturacion').style.display != 'none')
  {
    result |= !TestInfo_5000();
  }
  if ($('facturaotradireccion').style.display != 'none')
  {
    result |= !TestInfo_4000();
  }
  if ($('sifacturacion').style.display != 'none' && $('direccionenviofactura').style.display != 'none')
  {
    result |= !TestInfo_3000();
  }
  if (result)
  {
    alert('Tiene que capturar todos los campos para poder seguir.');
  }
  else
  {
    $('direccion').submit();
  }
}

var transporteactual = null;

function cambiartransporte()
{
  // si cambiamnos el transporte, recargamos toda la pagina con un indicador para que el codigo recalcule
  // 1. cual es el valor cliqueado
  var tr1 = $('TRANSPORTE1').checked;
  var tr2 = $('TRANSPORTE2').checked;
  var tr = (tr1?1:2);
  if (tr != transporteactual)
  {
    transporteactual = tr;
    window.location.href = '/?P=carrito&transporte='+tr;
  }
}

function switchorder(idbutton, iddiv)
{
  if ($(iddiv).style.display == '')
  {
    $(iddiv).style.display = 'none';
    $(idbutton).innerHTML = 'Ver la orden completa';
  }
  else
  {
    $(iddiv).style.display = '';
    $(idbutton).innerHTML = 'Esconder la orden';
  }
}
