/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */
 
	var ventanaCarrito;
	var ventanaDetallesProducto; 
	var carritoStore;
	var gridCarrito;
	var subTotal=0;
	var total=0;	
	 var xg;
 						
Ext.onReady(function(){

    Ext.QuickTips.init();		
    xg = Ext.grid;
	ventanaCarrito=new Ext.Window({
				title: 'Res&uacute;men de Compras (Puedes cambiar las cantidades) | TOTAL: <span id="total-compra-visible"></span>',
		    	id: 'ventanaCarrito',
				width:620,
				heigth:350,
				x:-1000,
				y:-1000,
				modal: false,
				border: true,
				closable:true,
				closeAction :'hide',
				animCollapse:true,
				collapsible:true,
				collapsed:false,
				shim:true,
				shadow:true,			
				html:'<div id="carrito"></div>'
				});
	
			ventanaCarrito.show();
			//ventanaCarrito.collapse();

				ventanaDetallesProducto=new Ext.Window({
				title: 'Detalles del Producto',
		    	id: 'ventanaDetallesProducto',
				width:640,
				heigth:500,
				x:380,
				y:350,
				modal: true,
				border: true,
				rezisable:false,
				closeAction:'hide',
				animCollapse:true,
				collapsible:false,
				collapsed:false,
				html:'<div id="detallesProducto" style="overflow:auto; max-height:500px; max-width:630px;"></div>'
				});

<!-- INICIO CREACION DE DATA STORE -->
    carritoStore = new Ext.data.Store(
    {
                proxy: new Ext.data.HttpProxy({
                url: 'scripts_php/loadCarritoProductos.php', //url to data object (server side script)
                method: 'POST'
            }),   
            baseParams:{kynneTabla: 'vista_carrito_productos'},
			reader:new Ext.data.JsonReader({
										   root: 'results',
           								   totalProperty: 'total',
            							   id: ''},
				[
				{name: 'idcarrito'},
				{name: 'idproducto'},
				{name: 'eliminar'},				
				{name: 'imagen1'},
				{name: 'nombre'},
				{name: 'precio'},
				{name: 'cantidad'},
				{name: 'importe'},
				])
    });
	carritoStore.load();
<!-- FIN CREACION DE DATA STORE -->	

<!-- INICIO CREACION DE COLUMNAS DEL GRID -->
var columnModel = new Ext.grid.ColumnModel([
    {
        id:'idcarrito',
        header: "ID",
        dataIndex: 'idregistro',
        width: 20,
		hidden:true
    },
	{
        id:'idproducto',
        header: "ID",
        dataIndex: 'idproducto',
        width: 20,
		hidden:true
    },
	{
        id:'eliminar',
        header: "Quitar",
        width: 50,
		hidden:false,
		renderer: function(v, params, data){
			var botonAccion=data.get('idcarrito');
		   	if(botonAccion!="") {
			 //alert(data.get('idregistro'));
            return '<div align="center"><a href="javascript:;" onclick="quitaCarrito('+data.get('idcarrito')+')"><img src="imagenes/iconos/delete_item.png"></a></div>';
			}
		} //renderer
    },	
    {
		id: 'imagen1',
		header: "",
		width: 80,
		sortable: false,
		dataIndex: 'imagen1',
		hideable: false,
		renderer: function(v, params, data){
			if(v!=''){
				/*return '<image src="kynneBackEnd/scripts_php/show_image.php?filename='+v+'&height=40&width=40&rnd='+Math.random()+'">';*/
				return "<center><img src='"+v+"' height=40 width=40></center>";
			}else{				//return '<image src="kynneBackEnd/scripts_php/show_image.php?filename=images/ind.png&height=40&width=40&rnd='+Math.random()+'">';
				return "<img src='kynneBackEnd/_FILES/ck_nodisponible.jpg' height=40 width=40>";
			}
		}
     },
	 {
        id:'nombre',
        header: "Nombre",
        dataIndex: 'nombre',
        width: 180,		
        hideable: false              
    },
	{
        id:'precio',
        header: "P.unit.",
        dataIndex: 'precio',
        width: 80,		
        hideable: false              
    },
	{
        id:'cantidad',
        header: "Cant.",
        dataIndex: 'cantidad',
        width: 60,		
        hideable: false,
		editor: new Ext.form.NumberField({
                   allowBlank: false,
                   allowNegative: false,
				   minValue:1,
				   maxValue:999,
                   style: 'text-align:left'
                })
    },
	{
        id:'importe',
        header: "Importe",
        dataIndex: 'importe',
        width: 100,		
        hideable: false               
    }
    ]);
<!-- FIN CREACION DE COLUMNAS DEL GRID -->


	    gridCarrito = new Ext.grid.EditorGridPanel({										   		
        store: carritoStore,
        cm: columnModel,
		stripeRows:true,
        width:600,
        height:500,
        title:'',
        frame:true,				        
        clicksToEdit: 1,
		collapsed:false,
		collapsible: false,
        animCollapse: true,
        trackMouseOver: false,
		 //enableColumnMove: false,
        iconCls: 'icon-grid',
        renderTo: 'carrito',		
		footer: Ext.get("carrito-footer")
    });

	gridCarrito.addListener('afteredit', handleEdit);
	//gridCarrito.addListener('contextmenu', menuContextual);
	
	function menuContextual(node, e) {
								//if(node.leaf){return false;}
								node.select();
								menu_arbol.node = node;
								menu_arbol.show(e.getTarget());
	}
							
	   	
	function handleEdit(editEvent) {
			//determine what column is being edited
			var gridField = editEvent.field;
			updateDB(editEvent);
		}
		
        function updateDB(oGrid_Event) {
			var fieldValue = oGrid_Event.value;
            Ext.Ajax.request(
                {
                    waitMsg: 'Guardando Cambios...',
                    url: 'scripts_php/guardaCambiosCarrito.php', 
                    params: { 
                        task: "update", //pass task to do to the server script
                        key: 'idcarrito',//pass to server same 'id' that the reader used
                        keyID: oGrid_Event.record.data.idcarrito,
                        field: oGrid_Event.field,//the column name
                        value: fieldValue,//the updated value
                        originalValue: oGrid_Event.record.modified
                    },//end params
                    failure:function(response,options){
                        Ext.MessageBox.alert('Alerta','Problema de conexion Intente de Nuevo...');
                        carritoStore.rejectChanges();//undo any changes
                    },//end failure block      
                    success:function(response,options){
						var responseData = Ext.util.JSON.decode(response.responseText);//passed back from server
						if(responseData.success){carritoStore.commitChanges();agregaCarrito('');}else{carritoStore.rejectChanges();}
                    }//end success block                                      
                 }//end request config
            ); //end request  
        }; //end updateDB 
		
});

function preAgregaCarrito(id) {
 document.getElementById('span_cantidad_'+id).style.display='block';
 document.getElementById('cantidad_'+id).focus();
}

function agregaCarrito(id){   
 ajaxCallback('scripts_php/agregaCarrito.php','','idproducto='+id+'&cantidad=1',true,"",false);
 ventanaCarrito.expand(true);
 mueveResumenCarrito('btn_agregar'+id); 
} //funcion

function limpiaCantidadesCarrito(id) {
 document.getElementById('cantidad_'+id).value='';
 try{document.getElementById('observaciones_'+id).value='';}catch(e){};  
 document.getElementById('span_cantidad_'+id).style.display='none';	
} //funcion

function quitaCarrito(id){
 if(!confirm('Desea eliminar este articulo del carrito?')){return;}
  ajaxCallback('scripts_php/quitaCarrito.php','','idcarrito='+id,true,"",false);
} //funcion	

function detallesProducto(id){
 ventanaDetallesProducto.show();
 document.getElementById('detallesProducto').innerHTML='<br>Cargando...<br><br>';
 setTimeout("ajaxCallback('ck_detallesProducto.php','detallesProducto','idproducto="+id+"',false,'',true,false);",1600);		
} //funcion


function mueveResumenCarrito(ref) {  
 var referencia=document.getElementById(ref);
 var obj=document.getElementById('ventanaCarrito');  
 posIzq=referencia.offsetLeft-225;
 posTop=referencia.offsetTop-200;
 //obj.style.left = posIzq+'px';
 //ventanaCarrito.hide();
 //obj.style.top = posTop+'px';
 ventanaCarrito.setPosition(380,posTop);
 //ventanaCarrito.show();
} //funcion

function actualizaCarrito(cantidades,subtotal,iva,descuento,total_total,total_bruto) {
 carritoStore.reload();
 try{    
  document.getElementById('total-compra-visible').innerHTML="$ "+total_total;
  document.getElementById('total-articulos').innerHTML=cantidades;
  document.getElementById('subtotal-compra').innerHTML="$ "+subtotal; 
  document.getElementById('iva-compra').innerHTML="$ "+iva; 
  document.getElementById('descuento-compra').innerHTML="$ "+descuento; 
  document.getElementById('total-compra').innerHTML="$ "+total_total; 
  document.getElementById('total-compra-hidden').value=total_bruto; 
  document.getElementById('amount').value=total_bruto;   
 }catch(e){}; 	
} //funcion

function cargarValoresInicioCarrito() {
 ajaxCallback('scripts_php/cargarValoresInicioCarrito.php','','',true,"",false);	
} //funcion

function checkoutCarrito() {
 var total=parseFloat(document.getElementById('total-compra-hidden').value);
 //alert(total);
 if(total<=0)
  alert("La compra no se puede finalizar si el total es menor que $0.00");
 else
  document.formEnvio.submit();
} //funcion

function reiniciaPosicionCarrito() {  
 //ventanaCarrito.x='380';
 //ventanaCarrito.y='350';
 //return
 
 var obj=document.getElementById('ventanaCarrito');  
 obj.style.left = '-1000px';
 obj.style.top = '-1000px'; 
 ventanaCarrito.show();
} //funcion


function inicio() {
 reiniciaPosicionCarrito();
 //alert('algo');
 ventanaCarrito.collapse();
 cargarValoresInicioCarrito();
} //funcion


