﻿$(document).ready(function() {
	//Inicializamos todos los productos (Añadimos el onClick y los deshabilitamos)
	if($("#configurator").length > 0){
		//Inicializamos todos los productos (Añadimos el onClick y los deshabilitamos)
		$('.producto').attr('onClick', 'recalcula(this)');
		$('.qty').attr('onChange', 'recalcula_qty(this)');
		$('.opt').attr('onChange', 'recalcula_opt(this,this.value)');
		$('.prods').attr('onClick', 'final_prods(this)');
		$('.servs').attr('onClick', 'final_servs(this)');
		inicializa();

	}
});

function inicializa(){
	$('.producto').attr('checked','');
	$('.producto').attr('selected','');
	$('.prods').attr('checked','');
	$('.prods').attr('selected','');
	$('.servs').attr('checked','');
	$('.servs').attr('selected','');
	
	$('.producto').attr('selected','false');
	$('.producto').attr('disabled','disabled');
	$('.producto').attr('selected','false');
	$('.qty').attr('disabled','disabled');
	$('.opt').attr('disabled','disabled');
	$('.prods').attr('disabled','disabled');
	$('.servs').attr('disabled','disabled');
	//$('.producto').attr('checked','false');
	
	//Todos menos el step 1
	$('#step1>fieldset>table>tbody>tr>td>input.producto').attr('disabled','');
	$('#step1>fieldset>table>tbody>tr>td>input.qty').attr('disabled','');
	$('#step1>fieldset>table>tbody>tr>td>select.opt').attr('disabled','');
	
	$('.prod').css('display','none');
	$('.serv').css('display','none');
	$('#carrito').css('display','none');
	
}

var total			= trata_precio(0.0);			//El total del pago.
var step			= 1;							//El step maximo activo.
var selecs			= new Array();					//El array con los que ya hemos seleccionado.
var totalSetup		= trata_precio(0.0);
var totalMonthly	= trata_precio(0.0);
var totalOneTime	= trata_precio(0.0);
var totalSubs3m		= trata_precio(0.0);
var totalSubs9m		= trata_precio(0.0);

function recalcula(objeto){
	var idO = $(objeto).attr('id');
	var qant=1;
	var i = 0;
	if($('#'+idO+'_qty').length > 0){
		qant = $('#'+idO+'_qty').attr('value');
	}
  	var aux = eval(idO);
  	if($(objeto).attr('type')=='radio'){
  		actualizaSelecs(aux[2]); //Quitamos de selecs todos los que tengan step >= al del que añadimos
  		quitarSelecs(idO);
  		for(i=0;i<qant;++i){
  			selecs.push(idO);
  		}
  	}
  	else{
  		if($(objeto).is(":checked")){
  			quitarSelecs(idO);
  			for(i=0;i<qant;++i){
  	  			selecs.push(idO);
  	  		}
  		}
  		else {
  			quitarSelecsCheck(idO);
  		}
  	}
  	step = nextStep();
  	stepActivado(); //Activamos hasta el step que haya
  	ejecutaSelecs(); //Ya tenemos todo preparado en selecs, pintamos la barra de la derecha y activamos los dependientes
}

function borra_carrito(){
	//if($('input.defaultbutton').length > 0){
		//var aux= $('input.defaultbutton').get(0);
		var oldAction = $("#formEnvio").attr("action");
		var aux= $('#cart-button').get(0);
		while($('#carrito>td.centered').length > 0){
			$('#carrito>td.centered').remove();
		}
		$('#carrito').append("<td class='centered' colspan='2'><form id='formEnvio' method='post' action='" + oldAction + "'><input type='hidden' name='ContentObjectID' value='dummy'></form></td>");
		$('#formEnvio').append(aux);
	//}
}

function final_carrito(val){
	borra_carrito();
	var aux, id, idprod, input, qty, value, texto_input, str, ops, preu;
	var qtyPuesto="";
	while($('.input_dcha').length > 0){
		$('.input_dcha').remove();
	}
	totalMonthly	= trata_precio(0.0);
	texto_input="";
	for(elem in selecs){
		//Tenemos que crear el input de cantidad, de opciones y de 
		qty=1;
		aux=eval(selecs[elem]);
		idprod=selecs[elem];
		id=idprod+"_qty";
		if($(".input_"+idprod).length > 0){//Ya esta en la derecha (Tenemos varios)
			qtyPuesto = $(".input_"+idprod).get(0);
			qtyPuesto=$(qtyPuesto).attr('value');
			str=idprod+"_Qty_";
			qtyPuesto=qtyPuesto.substring(str.length,(qtyPuesto.length));
			qty=parseInt(qtyPuesto);
			qty = qty+1;
		}
		value=idprod+"_Qty_"+qty;
		input=generaInput(id,idprod,value);
		while($(".input_"+idprod).length > 0){
			$(".input_"+idprod).remove();
		}
		$("#formEnvio").append(input);
		preu=eval(selecs[elem]+"_prices");
		value=idprod+"_Option_"+preu+"_Value_"+val;
		input=generaInput(id,idprod,value);
		$("#formEnvio").append(input);
		totalSetup		+= trata_precio(aux[1]);
		totalMonthly	+= trata_precio(aux[5]);
		ops=eval(selecs[elem]+"_options");
		for(el in ops){
			//1,Prueba 1000,1000,false,7600
			var opt=ops[el];
			if(opt[3]!=false){
				value=idprod+"_Option_"+opt[4]+"_Value_"+opt[0];
				input=generaInput(id,idprod,value);
				$("#formEnvio").append(input);
			}
		}
	}

}


function final_prods(object){
	var id=$(object).attr('id');
	selecs.push(id);
	var value=$(object).attr('value');
	final_carrito(value);
	var input;
	$(".prod").css('display','');
	
	totalOneTime=trata_precio(total);

	totalSubs3m=trata_precio(total/30);
	totalSubs9m=trata_precio(total/18);
	var doce=(totalSubs9m*9)+(totalSubs3m*3);
	$('#one-time-price').html(trata_precio(totalOneTime));
	$('#first-3-price').html(trata_precio(totalSubs3m));
	$('#following-9-price').html(trata_precio(totalSubs9m));
	$('#total-12-price').html(trata_precio(doce));
	$('.prod').css('display','');
	$('#carrito').css('display','');

}
function final_servs(object){
	var id=$(object).attr('id');
	var value=$(object).attr('value');
	selecs.push(id);
	final_carrito(value);
	var input;
	
	$(".serv").css('display','');
	$('#set-up').html(trata_precio(total));
	$('#monthly-fixed').html(trata_precio(totalMonthly));
	$('.serv').css('display','');
	$('#carrito').css('display','block');
}

function generaInput(id,idprod,value){
	var ret= '<input id="input_'+value+'" type="hidden" class="input_dcha input_'+idprod+'" name="Config_Basket_Products[]" value="'+value+'">';
	return ret;
}

//Introducimos en selecs la cantidad de elementos que haya en el value
function recalcula_qty(object){
	var aux=object.id;
	aux=aux.substring(0,(aux.length-4)); //4 Por el _qty
	var obj=eval(aux);
	if(object.value >= obj[4]){
		aux=$('#'+aux);
		recalcula(aux);
	}
	else{
		object.value=obj[4];
	}
}

//Cuando añadimos una opcion se ha de marcar
function recalcula_opt(object,value){
	var idO=object.id;
	idO=idO.substring(0,(idO.length-7)); //7 Por el _Option
	if(value != 0){
	  	var aux = eval(idO+"_options");
	  	var tmp;
	  	var rep=new Array();
	  	for(elem in aux){
	  		tmp=aux[elem];
	  		if(tmp[0]==value){
	  			tmp[3]=true;
	  		}else{
	  			tmp[3]=false;
	  		}
	  		rep.push(tmp);
	  	}
	  	aux=eval(idO+"_options = rep;");
	}
	idO=$('#'+idO);
	recalcula(idO);
}

//Quitamos del array de selecs todos los productos que tengan step >= al que hemos indicado
function actualizaSelecs(stp){ 
	var act="";
	var selecs2=new Array();
	for (elem in selecs){
		act= eval(selecs[elem]);
		if(act[2]<stp){
			selecs2.push(selecs[elem]);
		}
	}
	selecs=selecs2;
	return;
}

//Quitamos un elemento del array de selecs
function quitarSelecs(id){
	var selecs2=new Array();
	if (!Array.prototype.indexOf){ //En IE no existe indexOf
		for(elem in selecs){
			if(selecs[elem]!=id){
				selecs2.push(selecs[elem]);
			}
		}
		selecs=selecs2;
	}
	else{
		var ind=selecs.indexOf(id);
		if(ind!=-1){
			selecs.splice(ind,1);
		}
	}
}

//Quitamos un elemento del array de selecs y todos sus dependientes
function quitarSelecsCheck(id){
	var selecs2=new Array();
	for(elem in selecs){
		if(selecs[elem]!=id){
			selecs2.push(selecs[elem]);
		}
	}
	selecs=selecs2;
	var aux = descend(id);
	for(el in aux){
		quitarSelecs(aux[el]);
	}
}

//Cargamos todos los descendientes del objeto (recursivo)
function descend(id){
	var desc=eval(id+"_deps");
	var deps=eval(id+"_deps");
	
	for(el in deps){
		desc=desc.concat(descend(deps[el]));
		if(deps[el]!=undefined){
			desc=desc.concat(eval(deps[el]+"_deps"));
		}
	}
	return desc;
}


// Nos dice cual es el siguiente step que tiene productos clickables.
// Equivale a escoger el menor step de los siguientes dependientes que haya en la lista (o 9) 
// y que sea mayor al mayor de los steps de los productos de dentro del listado de selecs
function nextStep(){
	var minlocal=9;
	var deps, aux, act;
	var min=1;
	for(elemn in selecs){
		aux=eval(selecs[elemn]);
		min=Math.max(min,aux[2]);
	}
	for(elem in selecs){
		act = selecs[elem];
		deps=eval(act+"_deps");
		for(element in deps){
			aux=eval(deps[element]);
			if(aux[3]!=false){
				if(aux[2] > min){
					minlocal=Math.min(minlocal,aux[2]);
				}
			}
		}
	}
	return minlocal;
}

//Apagamos los steps mayores del que hemos seleccionado.
function stepActivado(){
 	var i = 0;
  	for (i=i;i<=step;++i){
  		$("#stp"+i+"_box").removeClass("stp"+i+"_disabled");
  		$("#stp"+i+"_box_top").removeClass('stp_top_disabled');
  	}
  	for (i=step+1;i<10;++i){
  		$("#stp"+i+"_box").addClass("stp"+i+"_disabled");
  		$("#stp"+i+"_box_top").addClass('stp_top_disabled');
  	}
}

//Pintamos la columna derecha y activamos los dependientes de todos los que tenemos seleccionados
function ejecutaSelecs(){
	//Inicializamos como al principio
  	inicializa();
	vaciar_dcha();
  	for(elemento in selecs){
  		dependientes(selecs[elemento]);
  		$('#'+selecs[elemento]).attr('checked','checked');
  		anadir_dcha(selecs[elemento]);
  	}
  	$('.prod').css('display','none');
	$('.serv').css('display','none');
	$('#carrito').css('display','none');
}

//Quitamos de la columna de la derecha todo el contenido
function vaciar_dcha(){
	total=0.0;
	while($("#summary-table>tbody").length > 0){
		$("#summary-table>tbody").remove();
	}
	$("#summary-table").append("<tbody></tbody>");
}

//Activamos los dependientes del objeto con el id del parametro
function dependientes(idObj){
	var deps=eval(idObj+"_deps");
	var aux="";
	for(elem in deps){
		aux=eval(deps[elem]);
		if((aux[2] <= step)){
			if((aux[3]!=false)){
				activa(deps[elem]);
			}
		}
	}
	return;
}

function activa(id){
	$("."+id).attr('disabled','');
}

function anadir_dcha(idobj){
	var aux=eval(idobj);
	var precio=(aux[1]).replace(/,/g, "."); 
	var nombre = aux[0];
	precio=parseFloat(precio);
	var qty=1;
	if($("#tr_"+idobj).length > 0){ //Ya esta en la derecha (Tenemos varios)
		var qtyPuesto=parseInt($("#tr_"+idobj+">.qty").html());
		while($("#tr_"+idobj).length > 0){
			$("#tr_"+idobj).remove();
		}
		qty=qtyPuesto+1;
	}
	var ops=eval(idobj+"_options")
	var act;
	var extra;
	for(el in ops){
		act=ops[el];
		if(act[3]==true){
			extra=act[2];
			if(extra==""){
				extra=0;
			}
			precio = precio + parseFloat(extra); 
			nombre = nombre+" + ("+act[1]+")";
		}
	}
	total+=precio;
	$("#summary-table>tbody").append(dcha(idobj,qty,nombre,precio,aux[5],aux[6]));
	//Añadimos el precio
	while($("#summary-total").length > 0){
		$("#summary-total").remove();
	}
	var texto_total= '<tr id="summary-total"><td class="centered" colspan="4"><h3 class="red">Total:  '+trata_precio(total)+' &euro;</h3></td></tr>';
	$("#summary-table").append(texto_total);
}

function dcha(id,qty,texto,price,monthly,tipo){
	//Tipo = 0 -> Producto, Tipo = 1 -> Servicio
	var p=trata_precio(price);
	var m=trata_precio(monthly);
	if(p==0){
		p="---";
	}
	if(m==0 || tipo==0){
		m="---";
	}
	var texto_dcha='<tr id="tr_'+id+'"><td class="qty">'+qty+'</td><td>'+texto+'</td> <td class="summary-qty-unit">'+p+'</td><td class="monthly">'+m+'</td></tr>';
	return texto_dcha;
}

function trata_precio(cant){
	cant=parseFloat(cant);
	var fact = 100;
	return Math.round(cant * fact) / fact;
} 



/*
<tr id="tr_">
	<td class="qty">
		1
	</td>
	<td>
		Flumotion Software
	</td>
	<td class="summary-qty-unit">
		450,00
	</td>
	<td class="monthly">
		
	</td>
</tr>
 */

/*
 * 
 * function anadir_dcha(idobj){
  		var aux=eval(idobj);
  		var opt=eval(idobj+"_options");
  		var precio=(aux[1]).replace(/,/g, "."); 
  		precio = parseFloat(precio);
		total += precio;
  		var texto_dcha='<tr id="tr_'+idobj+'"> <td>'+aux[0]+'</td> <td class="summary-qty-unit">'+aux[1]+'</td></tr>';
		var texto_input = "";
		texto_input=input(idobj,idobj);
		if(opt.length > 0){
			for(elem in opt){
				if(opt[elem][3]==true){
					var idOpt=idobj+"_Option_"+opt[elem][4]+"_Value_"+opt[elem][0];
					texto_input=texto_input+input(idOpt,idOpt);
				}
			}
		}
		if(aux[4]<=1){
			quitar_dcha(idobj);
		}
		$("#formEnvio").append(texto_input);
		$("#summary-table>tbody").append(texto_dcha);
		while($("#summary-total").length > 0){
			$("#summary-total").remove();
		}
		var texto_total= '<tr id="summary-total"><td class="centered" colspan="2"><h3 class="red">Total:  '+trata_precio(total)+' &euro;</h3></td></tr>';
 		$("#summary-table").append(texto_total);
  	}
 * 
 * 
 * 
 */


