/********************************************************************************/
/*	FICHEIRO COAS FUNCIÓNS JAVASCRIPT PARA AS REXIÓNS DE FACTURACIÓN			*/
/********************************************************************************/

/*
 * 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 sortComponents(g1,g2){

   if(g1.name < g2.name){
      return -1;
   }else if(g1.name == g2.name){
   	  return 0;
   }else{
      return 1;
   }
}


/* Función que obtén a lista dos compoñentes xeográficos candidatos para a rexión
type: 0 nacional, 1 internacional*/
function getAllGeographicComponentsAvailable(type){

	FactureRegionManager.getAllGeographicComponentsAvailable(type == '0', function(geographicComponents){
		
		dwr.util.removeAllRows("candidatesbody", { filter:function(tr) {
		      		return (tr.id != "patterncandidates");
		    	}});
		 
		 geographicComponents.sort(sortComponents);   		 
		 for (var i = 0; i < geographicComponents.length; i++) {
		    	
		 	geographicComponent = geographicComponents[i];
	    	id = i + 1;
	    	dwr.util.cloneNode("patterncandidates", { idSuffix:id });
	    	checkboxId = geographicComponent.countryId + "-";
	    	if(geographicComponent.geographicRegionId != null){
	    		checkboxId = checkboxId + geographicComponent.geographicRegionId;
	    	}else{
	    		checkboxId = checkboxId + "#";
	    	}
	    	dwr.util.setValue("namecandidate" + id, "<input type='checkbox'  id=\"" + checkboxId + "\">&#160;&#160;" 
	    								+ "<span id='name" + checkboxId + "'>" +  geographicComponent.name + "</span>", { escapeHtml:false });
	    	mostrardiv("patterncandidates"+ id);
		 }
	});

}

/* Función que obtén a lista dos compoñentes relacionados coa rexión actual
geographicRegionId: identificador da rexión, ou '' se a rexión non foi creada*/
function getRelateds(){

	FactureRegionManager.getRelateds(function(geographicComponents){
		
		dwr.util.removeAllRows("relatedsbody", { filter:function(tr) {
		      		return (tr.id != "patternrelateds");
		    	}});
	   	 geographicComponents.sort(sortComponents);  	 
		 for (var i = 0; i < geographicComponents.length; i++) {
		    	
		 	geographicComponent = geographicComponents[i];
	    	id = i + 1;
	    	dwr.util.cloneNode("patternrelateds", { idSuffix:id });
	    	checkboxId = geographicComponent.countryId + "-";
	    	if(geographicComponent.geographicRegionId != null){
	    		checkboxId = checkboxId + geographicComponent.geographicRegionId;
	    	}else{
	    		checkboxId = checkboxId + "#";
	    	}
	    	dwr.util.setValue("namerelated" + id, "<input type='checkbox'  id=\"" + checkboxId + "\">&#160;&#160;" 
	    								+ "<span id='name" + checkboxId + "'>" +  geographicComponent.name + "</span>", { escapeHtml:false });
	    	mostrardiv("patternrelateds"+ id);
		 }
	});

}

/* Función que selecciona todos os checkboxes */
/* id: identificador da táboa na que estan contidos os checks
boolean: valor ó que poñer todos os checkboxes */
function manageSelects(id, boolean){

	table = document.getElementById(id);
	inputs = table.getElementsByTagName("input");
	for(var i=0; i<inputs.length; i++){
	   inputs[i].checked = boolean;
	}
}

var  selectedCountryId = new Array(241);
var  selectedGeographicRegionId = new Array(241);
var  selectedName = new Array(241);

/* Función que obtén os elementos seleccionados dunha táboa 
id: identificador da táboa na que estan contidos os checks 
return: collecion de obxectos geographicComponent que están seleccionados */
function calculateInputsSelected(id){
	
	table = document.getElementById(id);
	inputs = table.getElementsByTagName("input");
	i = 0;
	for(var j=0; j<inputs.length; j++){
	 	if(inputs[j].checked){   
	 		idInput = inputs[j].id;
	 		idSplit = idInput.split("-");
	 		countryId = idSplit[0];
	 		geographicRegionId = null;
	 		if(idInput.substring(idInput.length-1)!= "#"){
	 			geographicRegionId = idSplit[1];
	 			}
	 		name = dwr.util.getValue("name" + inputs[j].id);
	 		selectedCountryId[i] = countryId;
	 		selectedGeographicRegionId[i] = geographicRegionId;
	 		selectedName[i] = name;
			i++;
			selectedCountryId[i] = null;
			selectedGeographicRegionId[i] = null;
			selectedName[i] = null;
		}
	}

}


function addToRelateds(type){

        calculateInputsSelected("candidatesbody");
        FactureRegionManager.addToRelateds(selectedCountryId, selectedGeographicRegionId, selectedName, function(){
         	getRelateds();
         	getAllGeographicComponentsAvailable(type);
         });

}


function quitToRelateds(type){

        calculateInputsSelected("relatedsbody");
        FactureRegionManager.quitToRelateds(selectedCountryId, selectedGeographicRegionId, selectedName, function(){
         	getRelateds();
         	getAllGeographicComponentsAvailable(type);
         });
         
}


/* Calcula o prezo total asociado a un pedido, tendo en conta a comisión
de pago contrarreembolso e o destino do envío 
calculateParam: indica se debe executarse a función
calculateShipmentCost: indica se debe calcularse os custos de envío
freeShipmentCostPriceLimitAsString: indica a cantidade máxima a partir da cal os gastos de envío
son 0. Se vale 0 non se considera.
*/

function calculateTotalOrderPrice(calculateParam, calculateShipmentCost, freeShipmentCostPriceLimitAsString){

	calculate = true;
	if(calculateParam == ''){
	   calculate = false;
	}

// Cálculo do total coa comisión de pago contrarreembolso
    if(calculate){
    	
      var isReimburgsegment = document.getElementById("paymentModeRadio").checked;
      var teoricPriceOrder = parseFloat(dwr.util.getValue("teoricPriceOrder").toString().replace(",","."));
      var paymentCommission = 0;
      var freeShipmentCostPriceLimit = 0;
      
      if(isReimburgsegment){
           paymentCommission = parseFloat(dwr.util.getValue("commissionvalue").toString().replace(",","."));
           mostrardiv("reimbugsegmentCommission");
           mostrardiv("reimburgsegmentComInForm");
      } else{
      	   paymentCommission = 0;
      	   ocultardiv("reimbugsegmentCommission");
      	   ocultardiv("reimburgsegmentComInForm");
      }
      var shipmentCostResult = 0;
      var totalPrice = 0;
      if (calculateShipmentCost){
     	  freeShipmentCostPriceLimit = parseFloat(freeShipmentCostPriceLimitAsString.toString().replace(",","."));
     	  if (freeShipmentCostPriceLimit > 0 && teoricPriceOrder >= freeShipmentCostPriceLimit) {
	      	dwr.util.setValue("shipmentCostsValue", "0,00");
	      	dwr.util.setValue("shipmentCostsValueInForm", "0,00");
	      	totalPrice = paymentCommission + teoricPriceOrder;
	      	totalPrice = Math.round(totalPrice*100)/100;
	      	dwr.util.setValue("totalPrice", totalPrice.toString().replace(".", ","));
     	  } else {
          	if(document.getElementById("countryEs").checked){
	          countryId = "ES";
	          geographicRegionId = dwr.util.getValue("geographicRegionId");
          	}else{
          	  countryId = dwr.util.getValue("countryId");
          	  geographicRegionId = null;
          	}
          	var unitsCart = dwr.util.getValue("unitsCart");
	      	FactureRegionManager.getShipmentCost(countryId, geographicRegionId, unitsCart, function(shipmentCostResult){
	      		dwr.util.setValue("shipmentCostsValue", shipmentCostResult);
	      		dwr.util.setValue("shipmentCostsValueInForm", shipmentCostResult);
	      		totalPrice = paymentCommission + teoricPriceOrder + parseFloat(shipmentCostResult);
	      		totalPrice = Math.round(totalPrice*100)/100;
	      		dwr.util.setValue("totalPrice", totalPrice.toString().replace(".", ","));
	      	});
	      }
      }
      else{
	      totalPrice = paymentCommission + teoricPriceOrder;
	      totalPrice = Math.round(totalPrice*100)/100;
	      dwr.util.setValue("totalPrice", totalPrice.toString().replace(".", ","));
      }
      
      }

}