/********************************************************************************/
/*	FICHEIRO COAS FUNCIÓNS JAVASCRIPT PARA A XESTIÓN DO CARRIÑO DA COMPRA       */
/*  EMPRÉGASE A LIBRERÍA DE AJAX DWR											*/
/********************************************************************************/

/*
 * Este arquivo e parte de TVFarmaciaIglesias - www.farmaiglesias.com
 * Copyright (C) 2008 Enxenio S.L.
 *
 * == BEGIN LICENSE ==
 *
 * TVFarmaciaIglesias e software libre: vostede pode redistribuilo e/ou modificalo
 * baixo os termos da licenza GPL de GNU, tal e como publica a Free Software Foundation,
 * na version 3 da licenza ou (a sua eleccion) calquera version posterior.
 *
 * A aplicacion distribuese SEN GARANTIA DE NINGUN TIPO. Lea a Licenza GPL para mais detalles.
 *
 * Vostede deberia ter recibido unha copia da licenza GPL de GNU (arquivo COPYING.TXT). 
 * En caso contrario, pode consultala en http://www.gnu.org/licenses/gpl.html
 *
 * == END LICENSE ==
 *
 */


function fillCartStateLaterBig(){
    CartManager.getCart(function(cartView){
    	
    	dwr.util.removeAllRows("tbodylater", { filter:function(tr) {
	      return (tr.id != "patternlater" && tr.id != "iscartbigemptylater");
	    }});
    
   	    var cartView, id;
		// Recheanse as liñas de carriño
		if(cartView.cartLineViewsLater.length == 0){
    		mostrardiv("iscartbigemptylater");
    	}else{
    		ocultardiv("iscartbigemptylater");
    	}
    	for(var i = 0; i < cartView.cartLineViewsLater.length; i++){
    		cartLineView = cartView.cartLineViewsLater[i];
    		id = cartLineView.cartLineIdView;
    		dwr.util.cloneNode("patternlater", { idSuffix:id });
    		dwr.util.setValue("imagelater" + id, "<a href=\"ShopImages/products/" + cartLineView.productView.product.bigPicture + "\" title=\"" + cartLineView.productView.name + "\" class=\"thickbox\">" +
    											 "<img alt=\"" + cartLineView.productView.name + "\" src=\"ShopImages/products/" +  cartLineView.productView.product.icon +"\"/></a>"
		    									,{escapeHtml:false});
    		dwr.util.setValue("productnamelater" + id,"<a href=\"ShowProductDetailsSmallWindow.do?id=" + cartLineView.productView.product.id  +  "&amp;showAddToCart=false&amp;keepThis=true&amp;TB_iframe=true&amp;height=420&amp;width=550\" class=\"thickbox\">" 
		    										+ cartLineView.productView.name +"</a>" 
		    									,{escapeHtml:false});
    		dwr.util.setValue("unitslater" + id, cartLineView.quantity);
    		dwr.util.setValue("priceunitlater" + id, cartLineView.unitFinalPriceAsString);
    		dwr.util.setValue("pricelater" + id, cartLineView.totalFinalPriceAsString);
    		mostrardiv("patternlater"+ id);
    		}
    		tb_init('a.thickbox, area.thickbox, input.thickbox');
    });

}

/* Función que rechea contido do carriño cando este está en formato ampliado,
   é dicir, na páxina de xestión de carriño.
   Esta función solo amosa as liñas de carriño con estado "mercar agora"
   */   
function fillCartBig(){
	CartManager.getCart(function(cartView){
		 // Borra todas as filas da táboa con id "cartsmallbody" excepto a fila con id "pattern"
	    dwr.util.removeAllRows("cartbody", { filter:function(tr) {
	      return (tr.id != "pattern" && tr.id != "iscartbigempty");
	    }});
    	var cartView, id;
    	if(cartView.cartLineViews.length == 0){
    		mostrardiv("iscartbigempty");
    	}else{
    		ocultardiv("iscartbigempty");
    	}
		// Recheanse as liñas de carriño
    	for(var i = 0; i < cartView.cartLineViews.length; i++){
    		cartLineView = cartView.cartLineViews[i];
    		id = cartLineView.cartLineIdView; 
    		dwr.util.cloneNode("pattern", { idSuffix:id });
    		dwr.util.setValue("image" + id, "<a href=\"ShopImages/products/" + cartLineView.productView.product.bigPicture + "\" title=\"" + cartLineView.productView.name + "\" class=\"thickbox\">" +
    											 "<img alt=\"" + cartLineView.productView.name + "\" src=\"ShopImages/products/" +  cartLineView.productView.product.icon +"\"/></a>"
		    									,{escapeHtml:false});
		    dwr.util.setValue("productname" + id,"<a href=\"ShowProductDetailsSmallWindow.do?id=" + cartLineView.productView.product.id +"&amp;showAddToCart=false&amp;keepThis=true&amp;TB_iframe=true&amp;height=420&amp;width=550\" class=\"thickbox\">" 
		    										+ cartLineView.productView.name +"</a>" 
		    									,{escapeHtml:false});
    		dwr.util.setValue("units" + id, "<input type=\"text\" value=\"" + cartLineView.quantity + 
    										 "\" size=\"1\" maxlength=\"4\" name=\"units" + id + "\" onfocus=\"saveValue(this)\" onblur=\"setQuantityCartLine(this)\"/>", 
    										 {escapeHtml:false});
    		dwr.util.setValue("priceunit" + id, cartLineView.unitFinalPriceAsString);
    		dwr.util.setValue("price" + id, cartLineView.totalFinalPriceAsString);
    		mostrardiv("pattern"+ id);
    	}
    	// Rechease o prezo total do carriño
    	dwr.util.setValue("total",cartView.totalPriceAsString);
    	// Rechease a data de modificación do carriño
    	dwr.util.setValue("dateupdate",cartView.lastUpdateAsString);
    	
    	//Se non hai liñas de carriño no carriño impidese a acción de vaciar carriño
        //e a de tramitar pedido
        if(cartView.cartLineViewsLater.length==0 && cartView.cartLineViews.length==0){
        	ocultardiv("emptycart");
        	ocultardiv("neworder");
        }
        if(cartView.cartLineViewsLater.length + cartView.cartLineViews.length >0){
           mostrardiv("emptycart");
        }
        
        //Se non hai liñas en estado "mercar agora" impidese crear pedido
        if(cartView.cartLineViews.length==0){
        	ocultardiv("neworder");
        }else{
            mostrardiv("neworder");
        }
    	tb_init('a.thickbox, area.thickbox, input.thickbox');
	});
}

/* Función que rechea contido do carriño cando este está en formato reducido
   (En páxina do buscador de produtos por exemplo)
   Esta función solo amosa as liñas de carriño con estado "mercar agora"
   */
function fillCart(){

	CartManager.getCart(function(cartView){
		 // Borra todas as filas da táboa con id "cartsmallbody" excepto a fila con id "pattern"
	    dwr.util.removeAllRows("cartsmallbody", { filter:function(tr) {
	      return (tr.id != "pattern" && tr.id!="isemptysmall");
	    }});
    	var cartView, id;
    	//Para amosar ou non a mensaxe de o carriño está vacío
    	if(cartView.cartLineViews.length == 0){
    		mostrardiv("isemptysmall");
    	}else{
    		ocultardiv("isemptysmall");
    	}
    	
		// Recheanse as liñas de carriño
    	for(var i = 0; i < cartView.cartLineViews.length; i++){
    		cartLineView = cartView.cartLineViews[i];
    		id = cartLineView.cartLineIdView; 
    		dwr.util.cloneNode("pattern", { idSuffix:id });
    		// Amosase solamente os 10 primeiros dixitos do nome
    		productName = cartLineView.productView.name;
    		if(productName.length > 10){
    			productName = productName.substring(0, 10) + " ...";
    		}
    		dwr.util.setValue("productname" + id, productName);
    		//dwr.util.setValue("units" + id, cartLineView.quantity);
    		//dwr.util.setValue("priceunit" + id, cartLineView.unitFinalPriceAsString);
    		dwr.util.setValue("price" + id, cartLineView.quantity + " * " + cartLineView.unitFinalPriceAsString + " = " 
    							+ cartLineView.totalFinalPriceAsString + " &euro;", {escapeHtml:false});
    		mostrardiv("pattern"+ id);
    	}
    	// Rechease o prezo total do carriño
    	dwr.util.setValue("total",cartView.totalPriceAsString);
	});
}
// Para executar a función ó cargar a imaxe (jquery)
/*$(document).ready(function(){
    fillCart();
    //Aqui tu codigo
});*/

/* Engade un novo produto ó carriño
/* productId: Identificador do produto */
/* functionFill: Función utilizada para rechear o táboa de datos do carriño*/
function addCartLine(productId, functionFill){
	// Ocultanse os erros para ese carriño
	ocultardiv("quantityerror" + productId);
	ocultardiv("quantityerrormandatory" + productId);
	ocultardiv("productcartadd" + productId);
	// Recupéranse o número de unidades
	var quantity = document.getElementById("textinput" + productId).value;
	// Compróbase o campo cantidade, xa que é obrigatorio
	if(quantity != ""){
		CartManager.addCartLine(productId, quantity, function(errors){
			var errors;
		  	for(var i = 0; i < errors.length; i++){
		  		mostrardiv(errors[i]);
		  		}
		  		var fillCartFunction = functionFill;
		  		fillCartFunction();
		  	if(errors.length == 0){	
		  		mostrardiv("productcartadd" + productId);
		  	}
		});
	}else{
		mostrardiv("quantityerrormandatory" + productId);
	}

}

/* Función empregada para engadir un novo produto ó carriño dende o iframe de "Detalles do produto"
/* É necesario separala da función anterior polo problema do acceso o iframe.
/* Engade un novo produto ó carriño
/* productId: Identificador do produto */
/* functionFill: Función utilizada para rechear o táboa de datos do carriño*/
function addCartLineIFrame(productId, functionFill){
	// Ocultanse os erros para ese produto
	var documentFrame = window.frames[0].document; 
	
	var div = documentFrame.getElementById("quantityerror" + productId);
	if(div!=null) div.style.display = 'none';
	div = documentFrame.getElementById("quantityerrormandatory" + productId);
	if(div!=null) div.style.display = 'none';
	div = documentFrame.getElementById("productcartadd" + productId);
	if(div!=null) div.style.display = 'none';
		
	// Recupéranse o número de unidades
	var quantity = documentFrame.getElementById("textinput").value;
	// Compróbase o campo cantidade, xa que é obrigatorio
	if(quantity != ""){
		CartManager.addCartLine(productId, quantity, function(errors){
			var errors;
		  	for(var i = 0; i < errors.length; i++){
		  		var error = documentFrame.getElementById(errors[i]);
		  		if(error!=null) error.style.display = '';
		  		}
		  	if(errors.length == 0){
		  		// Se non hai erros amósase a mensaxe de que o produto foi engadido ao carriño
		  		documentFrame.getElementById("productcartadd" + productId).style.display = '';
		  	}	
	  		var fillCartFunction = functionFill;
	  		fillCartFunction();
		});
	}else{
		var error = documentFrame.getElementById("quantityerrormandatory" + productId);
		if(error!=null) error.style.display = '';
	}
}
/* Elimina unha liña de carriño
   functionFill: Función utilizada para rechear o táboa de datos do carriño*/
function deleteCartLine(object, functionFill){

    rowId =  object.parentNode.parentNode.id;
    
    if(functionFill!=fillCartStateLaterBig){
    	cartLineId = rowId.substring(7);
    	}
    else{
    	cartLineId = rowId.substring(12);
    }	
    CartManager.deleteCartLine(cartLineId, function(){
    	var fill = functionFill;
    	fill();
    });

}


/*Modifica a cantitade de unidades de produto asociada a cada liña de carriño
	object: Obxecto desde o que se invocou a función [tipicamente imaxe +/- no carriño]
    quantity: Número de unidades a incrementar / decrementar 
    functionFill: función utilizada para rechear os valores
    functionGetCurrentValue: función para recuperar o identificador da liña
    */
function modifyUnits(object, quantityAsString, functionFill){

	rowId =  object.parentNode.parentNode.parentNode.id;
    cartLineId = rowId.substring(7);
    CartManager.modifyUnits(cartLineId, quantityAsString, function(){
    	var fill = functionFill;
    	fill();
    }
    )
}

// Gárdase o valor do textbox antes de que se modifique
var currentTextBoxValue = "";

function saveValue(object){
   currentTextBoxValue = object.value;
}

/* 
Función que modifica o número de unidades en función do valor existente no textbox
Valida que os cambios no número de unidades nos textbox do carriño
sexan válidos (valor enteiro e > 0)
Non devolve erros, senon que o que fai é manter o valor no anterior no textbox
*/
function setQuantityCartLine(object){

     valor = parseInt(object.value);
     cartLineId = object.parentNode.id.substring(5);
      // Validacións
      if (isNaN(valor) || valor < 1) {
            object.value = currentTextBoxValue;
      }else{
            object.value = valor;
            CartManager.setQuantityCartLine(cartLineId, valor, function(){
            	fillCartBig();
            });
            
      }
}

var STATE_LATER = '1';
var STATE_NOW = '0';
/* Cambia o estado dunha liña de carriño
*/
function changeStateLater(object){

    cartLineId = object.parentNode.parentNode.id.substring(7);
    // StateLater = 1 (en CartLine.STATE_LATER)
    CartManager.changeState(cartLineId, STATE_LATER, function(){
       fillCartBig();
       fillCartStateLaterBig();
       
    });
}


/* Cambia o estado dunha liña de carriño a "mercar agora"
*/
function changeStateNow(object){

    cartLineId = object.parentNode.parentNode.id.substring(12);
    // StateLater = 1 (en CartLine.STATE_NOW)
    CartManager.changeState(cartLineId, STATE_NOW, function(){
       fillCartBig();
       fillCartStateLaterBig();
    });
}

// Función que elimina tódalas liñas de carriño
function emptyCart(){

	CartManager.emptyCart(function(){
		 fillCartBig();
       	 fillCartStateLaterBig();
	});


}