var _ecCesta = {};

_ecCesta.blocked = true;

_ecCesta.products = {};

_ecCesta.productVersionsId = {};

_ecCesta.registerProduct = function ( product )
{
	if ( typeof product.object_id != 'undefined' )
	{
		_ecCesta.products[product.object_id] = product;
	}
	for ( var i in product.formatos )
	{
		_ecCesta.productVersionsId[product.formatos[i].producto_id] = product.formatos[i];
		product.formatos[i].producto = product;
		product.formatos[i].version = i;
	}
}

_ecCesta.getVersion = function ( id , version )
{
	var p = _ecCesta.products[id];
	if ( typeof p == 'undefined' || p == null || typeof p.formatos == 'undefined' || p.formatos == null || typeof p.formatos[version] == 'undefined' || p.formatos[version] == null )
	{
		return;
	}
	return p.formatos[version];
}

_ecCesta.disponible = function ( id , version )
{
	var v = _ecCesta.getVersion ( id , version );
	return typeof v != 'undefined' && v != null && v.estado == 'disponible';
}

_ecCesta.getPrecio = function ( id , version )
{
	var v = _ecCesta.getVersion ( id , version );
	return typeof v != 'undefined' && v != null ? v.precio  : v;
}

_ecCesta.getMaxCesta = function ( producto_a_la_venta_id )
{
	var p = _ecCesta.productVersionsId[producto_a_la_venta_id];
	var max;
	if ( typeof p != 'undefined' && p != null && typeof p.atributos != 'undefined' && typeof p.atributos.max_cesta != 'undefined' )
	{
		max = p.atributos.max_cesta;
	}
	return max;
}

_ecCesta.getMinCesta = function ( producto_a_la_venta_id )
{
	var p = _ecCesta.productVersionsId[producto_a_la_venta_id];
	var min;
	if ( typeof p != 'undefined' && p != null && typeof p.atributos != 'undefined' && typeof p.atributos.min_cesta != 'undefined' )
	{
		min = p.atributos.min_cesta;
	}
	return min;
}

_ecCesta.getCesta = function ()
{
	if ( typeof tiendaId == 'undefined' )
	{
		return;
	}
	$.getJSON ( '/srv/frontTienda2/getCesta' , ( { tienda_id: tiendaId } ) , _ecCesta.getCestaCallBack );
}

_ecCesta.getCestaCallBack = function ( data )
{
	if ( data.errno == 0 )
	{
		_ecCesta.cesta = data.data;
		_ecCesta.showCesta ( data.data );
	}
	else
	{
		_ecCesta.showError ( data.errstr );
	}
	_ecCesta.blocked = false;
}

_ecCesta.addProductId = function ( id , cantidad )
{
	if ( _ecCesta.blocked )
	{
		return;
	}
	_ecCesta.blocked = true;
	if ( typeof cantidad == 'undefined' )
	{
		cantidad = 1;
	}
	var max = _ecCesta.getMaxCesta ( id );
	if ( typeof max != 'undefined' && typeof _ecCesta.cesta != 'undefined' )
	{
		for ( var i = 0 ; i < _ecCesta.cesta.length ; i++ )
		{
			if ( _ecCesta.cesta[i].producto_a_la_venta.producto_a_la_venta_id == id )
			{
				if ( _ecCesta.cesta[i].cantidadencesta + cantidad > max )
				{
					alert ( _ecCesta.getLiteral ( 'max_reached' ) );
					_ecCesta.blocked = false;
					return;
				}
			}
		}
	}
	$.getJSON ( '/srv/frontTienda2/addProduct' , ( { producto_id: id , cantidad: cantidad } ) , _ecCesta.addProductCallBack );
}

_ecCesta.addProduct = function ( id , version , cantidad )
{
	if ( _ecCesta.blocked )
	{
		return;
	}
	var v = _ecCesta.getVersion ( id , version );
	_ecCesta.addProductId ( v.producto_id , cantidad );
}

_ecCesta.addProductQuestion = function ( id , version )
{
	if ( _ecCesta.blocked )
	{
		return;
	}
	var v = _ecCesta.getVersion ( id , version );
	if ( typeof _ecCesta.cesta != 'undefined' )
	{
		for ( var i = 0 ; i < _ecCesta.cesta.length ; i++ )
		{
			if ( _ecCesta.cesta[i].producto_a_la_venta.producto_a_la_venta_id == v.producto_id )
			{
				_ecCesta.addProductId ( v.producto_id );
				return;
			}
		}
	}
	var productLabel = v.nombre + ' ' + _ecCesta.getLiteral ( v.version ) + ( typeof v.producto != 'undefined' && typeof v.producto.producto_tipo != 'undefined' && v.producto.producto_tipo != null ? ' (' + v.producto.producto_tipo.etiqueta + ')' : '' );
	var max = _ecCesta.getMaxCesta ( v.producto_id );
	if ( typeof max != 'undefined' && max == 1 )
	{
		var msg = _ecCesta.getLiteral ( 'pregunta_anhadir' );
		msg = msg.replace ( /\$producto\$/g , productLabel );
		if ( confirm ( msg ) )
		{
			_ecCesta.addProductId ( v.producto_id );
		}
		return;
	}
	var min = _ecCesta.getMinCesta ( v.producto_id );
	if ( typeof min == 'undefined' )
	{
		min = '1';
	}
	var msg = _ecCesta.getLiteral ( 'pregunta_cantidad' );
	msg = msg.replace ( /\$producto\$/g , productLabel );
	var cantidad = prompt ( msg , min );
	if ( cantidad == null )
	{
		return;
	}
	if ( isNaN ( cantidad ) || cantidad < 1 )
	{
		cantidad = 1;
	}
	_ecCesta.addProductId ( v.producto_id , cantidad );
	
}

_ecCesta.addProductIdQuestion = function ( id )
{
	if ( _ecCesta.blocked )
	{
		return;
	}
	if ( typeof _ecCesta.cesta != 'undefined' )
	{
		for ( var i = 0 ; i < _ecCesta.cesta.length ; i++ )
		{
			if ( _ecCesta.cesta[i].producto_a_la_venta.producto_a_la_venta_id == id )
			{
				_ecCesta.addProductId ( id );
				return;
			}
		}
	}
	var v = _ecCesta.productVersionsId[id];
	var productLabel = v.nombre + ' ' + _ecCesta.getLiteral ( v.version ) + ( typeof v.producto != 'undefined' && typeof v.producto.producto_tipo != 'undefined' && v.producto.producto_tipo != null ? ' (' + v.producto.producto_tipo.etiqueta + ')' : '' );
	var max = _ecCesta.getMaxCesta ( v.producto_id );
	if ( typeof max != 'undefined' && max == 1 )
	{
		var msg = _ecCesta.getLiteral ( 'pregunta_anhadir' );
		msg = msg.replace ( /\$producto\$/g , productLabel );
		if ( confirm ( msg ) )
		{
			_ecCesta.addProductId ( v.producto_id );
		}
		return;
	}
	var min = _ecCesta.getMinCesta ( v.producto_id );
	if ( typeof min == 'undefined' )
	{
		min = '1';
	}
	var msg = _ecCesta.getLiteral ( 'pregunta_cantidad' );
	msg = msg.replace ( /\$producto\$/g , productLabel );
	var cantidad = prompt ( msg , min );
	if ( cantidad == null )
	{
		return;
	}
	if ( isNaN ( cantidad ) || cantidad < 1 )
	{
		cantidad = 1;
	}
	_ecCesta.addProductId ( v.producto_id , cantidad );
	
}

_ecCesta.addProductCallBack = function ( data )
{
	if ( data.errno == 0 )
	{
		_ecCesta.getCesta();
		if ( typeof addCestaCallback == 'function' )
		{
			addCestaCallback ( data.data )
		}
	}
	else
	{
		_ecCesta.showError ( data.errstr );
		_ecCesta.blocked = false;
	}
}

_ecCesta.removeProductId = function ( id , cantidad )
{
	if ( _ecCesta.blocked )
	{
		return;
	}
	_ecCesta.blocked = true;
	if ( typeof cantidad == 'undefined' )
	{
		cantidad = -1;
	}
	$.getJSON ( '/srv/frontTienda2/addProduct' , ( { producto_id: id , cantidad: cantidad } ) , _ecCesta.removeProductCallBack );
}

_ecCesta.removeProduct = function ( id , version , cantidad )
{
	if ( _ecCesta.blocked )
	{
		return;
	}
	_ecCesta.blocked = true;
	var v = _ecCesta.getVersion ( id , version );
	if ( typeof cantidad == 'undefined' )
	{
		cantidad = -1;
	}
	$.getJSON ( '/srv/frontTienda2/addProduct' , ( { producto_id: v.producto_id , cantidad: cantidad } ) , _ecCesta.removeProductCallBack );
}

_ecCesta.removeProductCallBack = function ( data )
{
	if ( data.errno == 0 )
	{
		_ecCesta.getCesta();
		if ( typeof removeCestaCallback == 'function' )
		{
			removeCestaCallback ( data.data )
		}
	}
	else
	{
		_ecCesta.showError ( data.errstr );
		_ecCesta.blocked = false;
	}
}

_ecCesta.showError = function ( msg )
{
	msg = _ecCesta.getLiteral ( msg );
	alert ( msg );
}

_ecCesta.showCesta = function ( cesta )
{
	if ( typeof $('cesta') == 'undefined' )
	{
		alert ( 'no encuentro');
		return;
	}
	var cont = 0;
	var precio = 0;
	for ( var i = 0 ; i < cesta.length ; i++)
	{
		cont += parseInt ( cesta[i].cantidadencesta , 10 );
		if ( cesta[i].producto_a_la_venta.impuestos_incluidos_en_precio == '0' )
		{
			cesta[i].producto_a_la_venta.precioFinal = parseFloat ( cesta[i].producto_a_la_venta.precio ) * ( 1 + ( parseFloat ( cesta[i].producto_a_la_venta.impuestos ) / 100 ) );
		}
		else
		{
			cesta[i].producto_a_la_venta.precioFinal = parseFloat ( cesta[i].producto_a_la_venta.precio );
		}
		cesta[i].producto_a_la_venta.descuento_label = '';
		cesta[i].producto_a_la_venta.precioFull = cesta[i].producto_a_la_venta.precioFinal;
		if ( typeof cesta[i].producto_a_la_venta.descuento != 'undefined' && cesta[i].producto_a_la_venta.descuento != null && cesta[i].producto_a_la_venta.descuento != 0 )
		{
			if ( typeof cesta[i].producto_a_la_venta.descuento_porcentaje != 'undefined' && cesta[i].producto_a_la_venta.descuento_porcentaje != null && cesta[i].producto_a_la_venta.descuento_porcentaje )
			{
				cesta[i].producto_a_la_venta.precioFinal *= 1.0 - ( cesta[i].producto_a_la_venta.descuento / 100.0 );
				cesta[i].producto_a_la_venta.descuento_label = ' ' + cesta[i].producto_a_la_venta.descuento + '% dto.';
			}
			else
			{
				cesta[i].producto_a_la_venta.precioFinal -= cesta[i].producto_a_la_venta.descuento;
				cesta[i].producto_a_la_venta.descuento_label = ' ' + cesta[i].producto_a_la_venta.descuento + '¤ dto.';
			}
		}
		precio += parseInt ( cesta[i].cantidadencesta , 10 ) * parseFloat ( cesta[i].producto_a_la_venta.precioFinal );
	}
	$('#carrito_content').empty();
	$('.ok_carrito').remove();
	
	if ( cont > 0 )
	{
		$('#carrito_content').append ( '<ul class="productos"></ul>' );
		for ( var i = 0 ; i < cesta.length ; i++ )
		{
			$('#carrito_content ul').append  ( '<li class="producto"></li>' );
			$('#carrito_content ul li:last').append  ( '<div class="producto_titulo">' + cesta[i].producto_a_la_venta.nombre + ' ' + _ecCesta.getLiteral ( cesta[i].producto_a_la_venta.tipo ) + ( typeof cesta[i].producto_a_la_venta.producto != 'undefined' && typeof cesta[i].producto_a_la_venta.producto.producto_tipo != 'undefined' && cesta[i].producto_a_la_venta.producto.producto_tipo != null ? ' (' + cesta[i].producto_a_la_venta.producto.producto_tipo.etiqueta + ')': '' ) + ( cesta[i].producto_a_la_venta.descuento_label != '' ? '<span style="color: #FF0000;">' + cesta[i].producto_a_la_venta.descuento_label + '</span>' : '' ) + '</div>' );
			$('#carrito_content ul li:last').append  ( '<div class="producto_precio">' + cesta[i].cantidadencesta + 'x' + _ecCesta.formatNumber ( cesta[i].producto_a_la_venta.precioFull , 2 ) + '</div>' );
			var max = undefined;
			if ( typeof cesta[i].producto_a_la_venta.atributos != 'undefined' && typeof cesta[i].producto_a_la_venta.atributos.max_cesta != 'undefined' )
			{
				max = cesta[i].producto_a_la_venta.atributos.max_cesta;
			}
			if ( typeof max == 'undefined' || cesta[i].cantidadencesta < max )
			{
				$('#carrito_content ul li:last').append  ( '<a href="#" onclick="_ecCesta.addProductId ( ' + cesta[i].producto_a_la_venta.producto_a_la_venta_id + ' ); return false;"><img class="f-r" src="' + _ecCesta.getLiteral ( 'imagen_mas' ) + '"/></a>' );
			}
			if ( typeof cesta[i].producto_a_la_venta.descuento_porcentaje == 'undefined' || cesta[i].producto_a_la_venta.descuento_porcentaje == null || !cesta[i].producto_a_la_venta.descuento_porcentaje || cesta[i].producto_a_la_venta.descuento != 100 )
			{
				$('#carrito_content ul li:last').append  ( '<a href="#" onclick="_ecCesta.removeProductId ( ' + cesta[i].producto_a_la_venta.producto_a_la_venta_id + ' ); return false;"><img class="f-r" src="' + _ecCesta.getLiteral ( 'imagen_menos' ) + '"/></a>' );
			}
		}
		$('#carrito_content').append( '<div class="tipo_publicacion"></div>' );
		$('#carrito_content').append ( '<ul class="productos"></ul>' );
		$('#carrito_content ul').append  ( '<li class="producto"></li>' );
		$('#carrito_content ul li:last').append  ( '<span class="producto_titulo total">' + _ecCesta.getLiteral ( 'total' ) + ' (' + cont + ' ' + ( cont == 1 ? _ecCesta.getLiteral ( 'unidad' ) : _ecCesta.getLiteral ( 'unidades' ) ) + ')</span>' );
		$('#carrito_content ul li:last').append  ( '<div class="producto_precio total">' + _ecCesta.formatNumber ( precio , 2 ) + _ecCesta.getLiteral ( 'monedaSymbol' ) + '</div>' );
		$('#cesta').append ( '<div class="ok_carrito"></div>' );
		$('#cesta .ok_carrito').append ( '<a href="/srv/frontTienda2/checkout?tienda_id=' + tiendaId + '&tpl=' + tpl + '" onclick="">Proceder a la compra</a>' );

	}
	else
	{
		$('#carrito_content').append ( '<p id="vacio">' + _ecCesta.getLiteral ( 'mensaje_vacio' ) + '</p>' );
	}

}

$(document).ready(function() {
   _ecCesta.getCesta();
} );

_ecCesta.literales = {};
_ecCesta.literales['unidad'] = 'artículo';
_ecCesta.literales['unidades'] = 'artículos';
_ecCesta.literales['moneda'] = 'euro';
_ecCesta.literales['monedaSymbol'] = '&euro;';
_ecCesta.literales['monedas'] = 'euros';
_ecCesta.literales['mensaje_vacio'] = 'Por ahora no tienes productos en el carrito';
_ecCesta.literales['imagen_carrito'] = '/frontTienda2/images/bullet_carrito.png';
_ecCesta.literales['texto_carrito'] = 'Carrito de publicaciones';
_ecCesta.literales['imagen_eliminar'] = '/frontTienda2/img/ic_borrar.gif';
_ecCesta.literales['imagen_mas'] = '/frontTienda2/images/ico_mas.png';
_ecCesta.literales['imagen_menos'] = '/frontTienda2/images/ico_menos.png';
_ecCesta.literales['texto_eliminar'] = 'Eliminar del carrito este elemento';
_ecCesta.literales['total'] = 'Total';
_ecCesta.literales['proceder'] = 'Proceder a la compra';
_ecCesta.literales['max_reached'] = 'No puede añadir más veces este producto';
_ecCesta.literales['pregunta_anhadir'] = 'Va a añadir $producto$ a su cesta';
_ecCesta.literales['pregunta_cantidad'] = 'Va a añadir $producto$ a su cesta. ¿Cuántas unidades quiere?';

_ecCesta.getLiteral = function ( key )
{
	return typeof literales != 'undefined' && typeof literales[key] != 'undefined' ? literales[key] : ( typeof _ecCesta.literales[key] != 'undefined' ? _ecCesta.literales[key] : key );
}

_ecCesta.formatNumber = function (num, decplaces)
{
   num = parseFloat(num);
   if (!isNaN(num))
   {
      var sign = '';
      if ( num < 0 )
      {
         num = - num;
         sign = '-';
      }
      var str = "" + Math.round (eval(num) * Math.pow(10,decplaces) + 1e-10 );
      if (str.indexOf("e") != -1) {
         return "Out of Range";
      }
      while (str.length <= decplaces) {
         str = "0" + str;
      }
      str = sign + str;
      var decpoint = str.length - decplaces;
      return ( str.substring(0,decpoint) == '-' || str.substring(0,decpoint) == '' ? str.substring(0,decpoint) + '0' : str.substring(0,decpoint) ) + ( decplaces > 0 ? "." + str.substring(decpoint,str.length) : '' );
   } else {
      return "NaN";
   }
}



