if (location.port) {
	var host = location.protocol+'//'+location.hostname+':'+location.port;
}else{
	var host = location.protocol+'//'+location.hostname;
}

var abrirEditor = true;

jQuery(window).load(function() {
	
// jQuery(document).ready(function() {
	// Pagina de producto con editor (iframe)
	if(jQuery('.tabsGama').length > 0){
		
		var tab = jQuery('.albums');
		if(tab.length > 1)
			gama = 'Basic';
		else
			gama = tab.attr('id');
		
		openGama(gama);

	}


	if(jQuery('#editorWC').length > 0){

		if(jQuery('#pa_diametro-bubble').length > 0){
			jQuery('#pa_diametro-bubble').change(function() {
			  recargaEditorWP();
			});
			jQuery('.single_add_to_cart_button').hide();
		}
		if(jQuery('#pa_medida_pod').length > 0){
			jQuery('#pa_medida_pod').change(function() {
			  recargaEditorWP();
			});
			jQuery('.single_add_to_cart_button').hide();
		}	
		if(jQuery('#pa_formato-copia').length > 0){
			jQuery('#pa_formato-copia').change(function() {
			  recargaEditorWP();
			});
			jQuery('.single_add_to_cart_button').hide();
		}				
		if(jQuery('#pa_tamano-copia-photogallery').length > 0){
			jQuery('#pa_tamano-copia-photogallery').change(function() {
			  recargaEditorWP();
			});
			jQuery('.single_add_to_cart_button').hide();
		}		
		if(jQuery('#pa_modelos-de-cojin').length > 0){
			jQuery('#pa_modelos-de-cojin').change(function() {
			  recargaEditorWP();
			});
			jQuery('.single_add_to_cart_button').hide();
		}
		// console.log('Existe edición')
	}



});


jQuery('#editorWC').load(function(){
    // console.log('load the iframe');
    checkFile();
    //the console won't show anything even if the iframe is loaded.
})

function cargarEditor(){

	var tipo = jQuery('#producto-tipo').val();
	if(tipo == 'simple'){
		abrirEditor = true;
	}

	if(abrirEditor){
		jQuery('#editorWC').toggle(); 
		checkFile();
	}else{
		alert('¡Seleccona las opciones del producto!')
	}
}
function checkFile(){
	var file = jQuery('#imagen_usuario').val();


	if(jQuery('#pa_formato-copia').length > 0){
		jQuery('#producto-sku').val(jQuery('.sku').html());
	}

	if(file.length > 10)
	{
		jQuery('.single_add_to_cart_button').show();
	}else{
		jQuery('.single_add_to_cart_button').hide();
	}
}
function recargaEditorWP(){

	var tipo = jQuery('#producto-tipo').val();
	var articulo = 124292;
	var formato = jQuery('#producto-tamano').val();
	var nombre = jQuery('.product_title').html();
	var precio = 0;
	var slug = jQuery('#producto-slug').val();
	var familia = jQuery('#producto-familia').val();
	var minimo = jQuery('#producto-minimo').val();
	var pack = jQuery('#producto-pack').val();
	var modelo = jQuery('#producto-modelo').val();
	var margen = jQuery('#producto-margen').val();
	var sku = jQuery('.sku').html();
	

	if(jQuery('#pa_diametro-bubble').length > 0){
		var f = jQuery('#pa_diametro-bubble').val();
		switch (f) {
			case '20-cm':
				formato = '20x20';
				break;
			case '30-cm':
				formato = '30x30';
				break;
			case '50-cm':
				formato = '50x50';
				break;
			case '70-cm':
				formato = '70x70';
				break;
			default:
				formato = '20x20';
				break;
		}
	}
	if(jQuery('#pa_medida_pod').length > 0){
		var f = jQuery('#pa_medida_pod').val();
		jQuery('#producto-tamano').val(f);
		formato = f;
	}	
	if(jQuery('#pa_formato-copia').length > 0){

		var f = jQuery('#pa_formato-copia').val();
		jQuery('#producto-tamano').val(f);
		// jQuery('#producto-sku').val(sku);
		formato = f;
		precio = parseFloat(document.getElementsByClassName("amount")[document.getElementsByClassName("amount").length - 1].textContent.replace(",",'.'));
	}		

	if(jQuery('#pa_tamano-copia-photogallery').length > 0){
		var f = jQuery('#pa_tamano-copia-photogallery').val();
		jQuery('#producto-tamano').val(f);
		formato = f;
	}

	if(jQuery('#pa_modelos-de-cojin').length > 0){
		var f = jQuery('#pa_modelos-de-cojin').val();
		if(f == 'corazon'){
			formato = '38x38';
			nombre += ' '+formato ;
			slug += '-'+formato+'-'+f;
		}else{
			formato = f;
		}
		jQuery('#producto-tamano').val(f);
	}

	if(typeof(f) == "undefined" || f.length == 0){
		if(tipo == 'simple'){
			abrirEditor = true;
		}else{

			alert("¡Seleciona un tamaño!");
			console.log('Selecciona un tamaño!:'+f)
			abrirEditor = false;
		}
		
	}else{
		abrirEditor = true;
	}

	if(abrirEditor){
		sku = jQuery('.sku').html();
		jQuery('#producto-sku').val(jQuery('.sku').html());
		var urlEditor = host+'/labApp/index.php/editwp/index/'+articulo+'/'+formato+'/'+nombre+'/'+precio+'/'+slug+'/'+familia+'/' + modelo + '/' + pack + '/' + sku + '/' + margen + '/' + minimo ;
		// console.log('Ruta:'+urlEditor);

		jQuery('#editorWC').attr('src', urlEditor);
		jQuery('.single_add_to_cart_button').hide();
	}else{
		jQuery('#editorWC').attr('src', '');
	}

}	




// Funciones página de precios

var gama = 'Basic';
var mintripa = 20;
var jsonPrecios = '';
// var host = 'https://pruebas.snappybook.es';

function quitaImgTamanos(){
	jQuery('#img'+gama+'0').click();
}

// jQuery('#expandedImg').on('mouseover',function(event) {quitaImgTamanos();});

// jQuery('.formatos-cuadros li').on('mouseout',function(event) {
// 	setTimeout(quitaImgTamanos,15000)
	
// });


function openImgFormato(formato, g='Photo') {

		// gama = 'Photo';
	  // Get the expanded image
	  var expandImg = document.getElementById("expandedImg"+gama);
	  // Get the image text
	  var imgText = document.getElementById("imgtext"+gama);
	  // Use the same src in the expanded image as the image being clicked on from the grid
	  expandImg.src = './recursoscalculadora/'+g+'_'+formato+'.jpg';
	  // Use the value of the alt attribute of the clickable image as text inside the expanded image
	  // imgText.innerHTML = imgs.alt;
	  // Show the container element (hidden with CSS)
	  expandImg.parentElement.style.display = "block";
}

function openInfo(tab) {
	// console.log(gama+'-'+tab);
	jQuery(".tabsInfo li").each(function( index ) {jQuery(this).removeClass('selectedC'); });
	jQuery('#'+gama+'-'+tab).addClass('selectedC');
	jQuery('.especificaciones').hide();
	jQuery('#'+tab+'-'+gama).show();
	
}


function openGama(gam) {
    var i;
    gama = gam;
    var x = document.getElementsByClassName("albums");
    var g = document.getElementById("G"+gam);
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";        
      document.getElementById("G"+x[i].id).classList.remove('selected');
    }
    document.getElementById(gam).style.display = "inline-block";  
    g.classList.add('selected'); 

    var d = new Date();
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {

          var formatoGama = document.getElementById('formatos'+gama);
          formatoGama.innerHTML = '';
          preciosJson =JSON.parse(this.response)
          var htmlFormatos = '';
          preciosJson.forEach( function(i, value) {

            // var x = i[0].title;
            var x = i.title;
            // console.log(gam)
            // console.log(x)
            var nombreTam = x.split(' ');
            if(x.indexOf(gam) > -1){
              var tamano = '';
              var id = 0;
              // id = i[0].id;
              id = i.id;
              // if(typeof(i[0].desc_tam) == 'undefined')
              if(typeof(i.desc_tam) == 'undefined')
                tamano = nombreTam[2];
              else
                tamano = i.desc_tam;
                // tamano = i[0].desc_tam;

              htmlFormatos += '<li id="F-'+id+'" class="formini"><a href="#'+tamano+'" onclick="openFormato(\''+id+'\')" data-id="'+id+'"><div style="width: 54px; text-align:center; padding:5px">'+tamano+'</div></a></li>';
            }
          });
          formatoGama.innerHTML = htmlFormatos;
          formatoGama.lastChild.firstChild.click()
          openInfo('C');
      }
    };
    // xhttp.open('GET','./calculadora.json?nx='+d.getMinutes(), true);
    xhttp.open('GET',host+'/calculadora.json?nx='+d.getMinutes(), true);
    xhttp.send();
    
}


function openGamaOLD(gam) {
    var i;
    gama = gam;
    var x = document.getElementsByClassName("albums");
    var g = document.getElementById("G"+gam);
    for (i = 0; i < x.length; i++) {
       	x[i].style.display = "none";        
    	document.getElementById("G"+x[i].id).classList.remove('selected');
    }
    document.getElementById(gam).style.display = "inline-block";  
    g.classList.add('selected'); 
    // calculadora(gama, id); 

    var d = new Date();

	jQuery.getJSON( host + '/calculadora.json?nx='+d.getMinutes())
	  	.done(function( data ) {
	  		// console.log(gam+' formato');
  		    preciosJson = data;
			jQuery('#formatos'+gam).html('');
	    	jQuery.each(data, function (i, value) {
	    		if(typeof(value) == 'object'){
	    			jQuery.each(value, function (x, val) {
	    				if(x.indexOf(gam) > -1){
	    					var tamano = '';
	    					var id = 0;
		    					id = val.id;
		    					tamano = val.desc_tam;
			    				jQuery('#formatos'+gam).append('<li id="F-'+id+'" class="formini"><a href="#'+tamano+'" onclick="openFormato(\''+id+'\')" data-id="'+id+'"><div style="width: 54px; text-align:center; padding:5px">'+tamano+'</div></a></li>');
// jQuery.each(val, function (n, valz) {
// 			if(n == 'id'){	
// 				console.log('openGama: '+val.desc_tam)
// 				//onmouseover="openImgFormato('+valz+')"
// 				tamano = valz;
// 				id = valz;
// 				// jQuery('#formatos'+gam).append('<li id="F-'+valz+'" class="formini"><a href="#'+valz+'" onclick="openFormato('+valz+')" ><div style="width: 54px; text-align:center; padding:5px">'+tamano+'</div></a></li>');
// 			}else{	
// 				if(n == 'desc_tam'){
// 					// console.log('Tamaño:'+valz);
// 					tamano = valz;
// 					jQuery('#formatos'+gam).append('<li id="F-'+id+'" class="formini"><a href="#'+tamano+'" onclick="openFormato(\''+id+'\')" data-id="'+id+'"><div style="width: 54px; text-align:center; padding:5px">'+tamano+'</div></a></li>');
// 				}	
	// }
// });
		    			}
		    		});
	    		}
	    	});
	    // Seleccionamos el primero
	    jQuery('#formatos'+gam+' > .formini:last').contents('a').click();

	    openInfo('C');
    });
}


function openFormato(formato) {
	
    var i;
    var x = document.getElementsByClassName("formini");
    var g = document.getElementById("F-"+formato);
    for (i = 0; i < x.length; i++) {
    	// console.log(x[i].id)
       	// x[i].style.display = "none";
       	var tam = x[i].id.split("-");
       	document.getElementById("F-"+tam[1]).classList.remove('selectedF'); 
       	// console.log("F"+tam[1]);
    }
    // document.getElementById('espec-'+formato).style.display = "block";  
    g.classList.add('selectedF');
    calculadora(formato);

    // document.getElementById("F"+formato).classList.add('selectedF');       
}

function ocultaTitulo(){
    var i;
    var x = document.getElementsByClassName("entry-title");
 	for (i = 0; i < x.length; i++) {
       	x[i].style.display = "none"; 
    }
}


function recuento(){
	jQuery('#img'+gama+'c0').click();
	var suma = 0;
	var calcpercent = 0;	
	jQuery(".recuento"+gama ).each(function( index ) {
		console.log(this.nodeName+'--'+this.type)
		
		if(this.nodeName == 'SELECT' && this.type == 'select-one'){
			// console.log('___SELET: '+jQuery(this).val());

			if(jQuery(this).val() > 0)
				suma += parseFloat(jQuery(this).val());

			// console.log('----------------------------');
		}

		if(this.nodeName == 'INPUT' && this.type == 'checkbox'){
			var obj = jQuery(this);
			if(obj[0].checked){
				calcpercent = 0;
				calcpercent = parseFloat(jQuery(this).val());

				// console.log('___INPUT Checkbox:'+parseFloat(jQuery(this).val()));
			}else{
				calcpercent = 0;
			}

			// console.log('----------------------------');
		}


		if(this.nodeName == 'INPUT' && this.type == 'number'){

			var ppagina = parseFloat(jQuery(this).attr('data-precio'));
			var cantidad = 0;
			cantidad = parseFloat(jQuery(this).val());

			if(isNaN(cantidad))
				cantidad = 0;

			var min = parseInt(jQuery(this).attr('min'));
			var max = parseInt(jQuery(this).attr('max'));

			if(cantidad < min || cantidad > max){
				cantidad = mintripa;
				jQuery(this).val('___CANTIDAD: '+cantidad);
			}
			cantidad -= mintripa;
			suma += ppagina * cantidad / 2 ;
			console.log('----------------------------');
			// console.log('PPagina: '+cantidad+'*'+ppagina+'('+ppagina * cantidad+')='+suma);
		
		}

		// console.log('############## SUMA antes:'+suma+'############');

		if(calcpercent > 0){
			var sumapercent = suma * calcpercent / 100;
			// console.log(suma+' + '+calcpercent+'% ='+sumapercent);
			suma += sumapercent;
			// suma += calcpercent;
		}
		// console.log('############## SUMA después:'+suma+'############');

		if(isNaN(suma)){
	    	jQuery('#precio'+gama).html('Importe no disponible');
		}else{
	    	jQuery('#precio'+gama).html(suma.toFixed(2)+'€');
	    }	
	});
}




function calculadora(id){
  
    var d = new Date();

    document.getElementById('cuadros'+gama).innerHTML = '';

    var fcuadros = document.getElementsByClassName('formatos-cuadros');
    // for (var i = 0; i < fcuadros.length; i++) {
       // fcuadros[i].innerHTML = '';
    // }

    var htmlImages = '';
    preciosJson.forEach( function(i, value) {

    htmlImages = '';
    // var x = i[0].title;
    var x = i.title;
    var nombreTam = x.split(' ');

    if(x.indexOf(gama) > -1){
      // var obj = i[0];
      var obj = i;
      // document.getElementById('formato'+gama).innerHTML = i[0].title;
      document.getElementById('formato'+gama).innerHTML = i.title;
      document.getElementById('description'+gama).innerHTML = obj.description;
      document.getElementById('short_description'+gama).innerHTML = obj.short_description;

      if(id == obj.id){
        
        var indices = obj.componentes;
        var artsHtml = '';
        var cont = 0;
        obj.images.forEach( function(z, v) {
          // statements
          if(v == 0)
            htmlImages += '<div class="column"><img src="'+z+'" alt="'+gama+'" id="img'+gama+v+'" onLoad="openImg(this);" onclick="openImg(this);"></div>';
          else
            htmlImages += '<div class="column"><img src="'+z+'" alt="'+gama+'" id="img'+gama+v+'" onclick="openImg(this);"></div>';
        });
        for (var i = 0; i < indices.length; i++) {

          if(typeof(indices[i].articulos) != 'undefined'){
            var arts = Object.values(indices[i].articulos);

            //OPCIONAL
            if(indices[i].optional){
              artsHtml += '<tr><td colspan="2"><input type="checkbox" name="'+arts[0].id+'" class="recuento'+gama+'" onchange="recuento(\''+gama+'\')" value="'+arts[0].price+'"><label for="'+arts[0].id+'" style="padding-left:5px; font-size:1rem">'+arts[0].title+'</label></td>';
            }else{
              //RANGE
              if(indices[i].quantity_max > indices[i].quantity_min){
                artsHtml += '<tr><td><strong>Nº de páginas</strong></td><td><input class="recuento'+gama+'" id="paginas" type="number" onchange="recuento(\''+gama+'\')" min="'+mintripa+'" max="'+indices[i].quantity_max+'" value="'+mintripa+'" step="2" pattern="[0-9]" data-precio="'+arts[0].price+'" title="'+arts[0].title+'" style="width:85px; font-size:20px;margin-top:10px"><span class="validity"></span></td>';
              }else{
                var estilo = 'display:inline-block';
                if(arts.length == 1)
                  var estilo  = 'display:none;'

                if(arts.length > 0){
                  artsHtml +='<tr id="linea'+cont+'" style="'+estilo+'"><td><select id="sel'+cont+'" class="recuento'+gama+'" onchange="recuento(\''+gama+'\')">';
                  for (var z = 0; z < arts.length; z++) {
                    artsHtml +='<option value="'+arts[z].price+'">'+arts[z].title+'</option>';
                  }
                  artsHtml +='</select></td>';
                  cont++;
                }
              }
            }
          }
        }
        document.getElementById('cuadros'+gama).innerHTML = artsHtml;
        document.getElementById('images'+gama).querySelector('div.row').innerHTML = htmlImages;
      }
    }
  });
  var imgprincipal = document.getElementById('img'+gama+'0');
  openImg(imgprincipal);

  recuento(gama);
}



function calculadoraOLD(id){
	
	// console.log('Consultango '+gama+' ID: '+id)
	
	jQuery('#images'+gama+' > div.row').html('Cargando información...');
	// Limpiamos
	jQuery('table[id*=cuadros]').html('');
   
   	var d = new Date();
	// jQuery.getJSON( host + '/calculadora.json?nx='+d.getMinutes())
	//   	.done(function( data ) {
	  		var data = preciosJson;
	    	jQuery('#cuadros'+gama).html('');
	    	jQuery('#formatos-cuadros').append('');
	    	jQuery.each(data, function (i, value) {

	    		var nombre = i;
	    		if(typeof(value) == 'object'){
	    			var cont = 0;

	    			jQuery.each(value, function (x, val) {
	    				console.log(x)
	    				if(x.indexOf(gama) > -1){
	    					var idformato = 0;

		    				jQuery.each(val, function (n, valz) {
				    			if(n == 'id' && valz == id){
		    						idformato = id;
		    						jQuery('#formato'+gama).html(x);
					    		}

				    			if(n == 'description' && idformato == id){
				    				jQuery('#description'+gama).html(valz);
				    			}

				    			if(n == 'short_description' && idformato == id){
				    				jQuery('#short_description'+gama).html(valz);
				    			}

				    			if(n == 'images' && idformato == id){
				    				// console.log('Hay imágenes '+val.length);
									jQuery('#images'+gama+' > div.row').html('');

		    						jQuery.each(valz, function (z, v) {

										if(z == 0){
											jQuery('#images'+gama+' > div.row').append('<div class="column"><img src="'+v+'" alt="'+gama+'" id="img'+gama+z+'" onLoad="openImg(this);" onclick="openImg(this);"></div>');
										}else{
											jQuery('#images'+gama+' > div.row').append('<div class="column"><img src="'+v+'" alt="'+gama+'" id="img'+gama+z+'" onclick="openImg(this);"></div>');
										}
		    						});
		    						var imgprincipal = jQuery('#img'+gama+'0');
									// jQuery('#expandedImg').attr('src', val[0]);
									openImg(imgprincipal);
				    			}
			    			

		    					if(n != 'id'&& n !='description' && n !='short_description' && n !='images'){

		    						if(idformato == id){
				    					// --------------------------- OPCIONAL
				    					if(valz.optional){
				    						jQuery.each(valz.articulos, function (z, v) {
												jQuery('#cuadros'+gama).append('<tr><td colspan="2"><input type="checkbox" name="'+v.id+'" class="recuento'+gama+'" onchange="recuento(\''+gama+'\')" value="'+v.price+'"><label for="'+v.id+'">'+v.title+'</label></td>');
				    						});
				    					}else{

				    						// RANGE 
				    						if(valz.quantity_max > valz.quantity_min){

												jQuery('#cuadros'+gama).append('<tr><td><strong>Nº de páginas</strong></td><td><input class="recuento'+gama+'" id="paginas" type="number" onchange="recuento(\''+gama+'\')" min="'+mintripa+'" max="'+valz.quantity_max+'" value="'+mintripa+'" step="2" pattern="[0-9]" data-precio="'+valz.articulos[0].price+'" title="'+valz.articulos[0].title+'" style="width:85px; font-size:20px;margin-top:10px"><span class="validity"></span></td>');
				    						}else{
				    							// SELECT

				    							if(typeof(valz.articulos) != 'undefined'){
				    								if(valz.articulos.length > 0){
														jQuery('#cuadros'+gama).append('<tr id="linea'+cont+'"><td><select id="sel'+cont+'" class="recuento'+gama+'" onchange="recuento(\''+gama+'\')"></select></td>');
														// console.log('Articulos: '+valz.articulos.length)
							    						jQuery.each(valz.articulos, function (z, v) {
							    							// console.log(v);
															jQuery('#sel'+cont).append('<option value="'+v.price+'">'+v.title+'</option>');
							    						});
						    						}
					    						}
				    								
						    						if(typeof(valz.articulos)!= 'undefined' && valz.articulos.length == 1){
						    							// console.log(jQuery('#sel'+cont).val());
						    							jQuery('#linea'+cont).hide();
						    						}
				    						}
				    					}
			    					}
		    					}
			    				cont++;
		    				});
		    			}
	    			});
	    		}
	    	});
	    	recuento(gama);
	 //  	})
	 //  	.fail(function( jqxhr, textStatus, error ) {
	 //    	var err = textStatus + ", " + error;
	 //    	console.log( "Request Failed: " + err );
		// });

}


function openImg(imgs) {
  // Get the expanded image
  var expandImg = document.getElementById("expandedImg"+gama);
  // Get the image text
  var imgText = document.getElementById("imgtext"+gama);
  // Use the same src in the expanded image as the image being clicked on from the grid
  expandImg.src = imgs.src;
  // Use the value of the alt attribute of the clickable image as text inside the expanded image
  imgText.innerHTML = imgs.alt;
  // Show the container element (hidden with CSS)
  expandImg.parentElement.style.display = "block";
} 




function productosInicio(){
	

	jQuery.getJSON( host + '/calculadora.json', { tipo: id } )
	  	.done(function( data ) {
	    	jQuery.each(data, function (i, value) {
	    		jQuery('#formato'+gama).html(i);

	    		var nombre = i;
	    		if(typeof(value) == 'object'){
	    			var cont = 0;

	    			jQuery.each(value, function (x, val) {
 
		    			if(x == 'description')
		    				jQuery('#description'+gama).html(val);
		    			if(x == 'short_description')
		    				jQuery('#short_description'+gama).html(val);

		    			if(x == 'images'){
		    				// console.log('Hay imágenes '+val.length);
    						// jQuery.each(val, function (z, v) {
    							// console.log(x)
								jQuery('#images'+gama).html('');
								jQuery('#images'+gama).append('<img src="'+val[0]+'" width="100%">');
    						// });
		    			}
    					// if(x != 'id' && x !='description' && x !='short_description' && x !='images'){}
	    				cont++;
	    			});
	    			
	    		}
	    	});

	  	})
	  	.fail(function( jqxhr, textStatus, error ) {
	    	var err = textStatus + ", " + error;
	    	console.log( "Request Failed: " + err );
		});

}


function openTabs(gama) {
    var i;
    gama = gama;
    // console.log('Gama:'+gama);
    var x = document.getElementsByClassName("tabsp");
    var g = document.getElementById("G"+gama);
    // console.log('-----------------------')
    // console.log(g)
    for (i = 0; i < x.length; i++) {
       	x[i].style.display = "none";        
    	document.getElementById("G"+x[i].id).classList.remove('selectedT');
    	// console.log("G"+x[i].id)
    }
    document.getElementById(gama).style.display = "inline-block";  
    g.classList.add('selectedT'); 
}

function selFormato(clase){
// console.log(clase)
var tablas = document.getElementsByClassName('formatos-precio');
for(var x=0; x<tablas.length; x++){

  var filas = tablas[x].rows;
  for (var i=1; i<filas.length; i++){
    if(clase == 'todos'){
      filas[i].style.opacity = 1;
    }else{      
      if(filas[i].classList[0] == clase){
        filas[i].style.opacity = 1;
      }else{
        filas[i].style.opacity = 0;
      }
    }
  }
}
}
