$(document).ready(function(){
  switch(idiomaPrincipal){
    case "es":
      txt_aviso = "Ya ha añadido productos a su taller.\nSi continúa se borrarán y tendrá que volver a añadirlos.\n¿DESEA CONTINUAR?";
      txt_borrar = "Haga doble click para borrar este producto.";
      txt_unidades = "unidad/es";
      txt_modelo = "Concesionario oficial o autorizado";
      txt_medidas = "medidas";
      break;
    default:
      txt_aviso = "It has added products to your garage workshop.\nIf you continue to be deleted and you will need to add.\nCONTINUE?";
      txt_borrar = "Double-click to delete this product.";
      txt_unidades = "unit / s";
      txt_modelo = "Official or Authorized Dealer";
      txt_medidas = "measures";
  }
  tallerIniciar("mTaller5-1",txt_modelo+"");
  //Cuando pulso en un taller, reinicio el taller con este fondo
  jQuery.each($("#modelos-taller p img"), function() {
    $(this).css({cursor:"pointer"}).click(function(){
      if (numProductosEnTaller>0){
        if (confirm(txt_aviso)){
          tallerIniciar($(this).attr("id"),$(this).parent().find("strong").html())
        }
      }else tallerIniciar($(this).attr("id"),$(this).parent().find("strong").html());
    });
  });
  
  //Programación para el funcionamiento de las capas de los productos.
  $("h3").css({cursor:"pointer"}).click(function(){
    $("#productos-elevadores").css({display:"none"});
    $("#productos-lubricacion").css({display:"none"});
    $("#productos-ruedas").css({display:"none"});
    $("#productos-vehiculos").css({display:"none"});
    $(this).next().css({display:"block"});
  });
  $(".cerrar").css({cursor:"pointer"}).click(function(){
    $(this).parent().parent().css({display:"none"});
  });
  $("#borrar_productos").css({cursor:"pointer"}).click(function(){
    tallerProductosBorrar();
  });
  $(".lista-productos-taller li").hover(
    function () {
      $(this).find("div.fotos").css({'display':'block'})
    }, 
    function () {
      $(this).find("div.fotos").css({'display':'none'})
    }
  );
  
  $(".lista-productos-taller .fotos img").css({cursor:"pointer"}).click(function(){
    var lista = $(this).parent().parent().parent().parent().parent().parent().attr("id");
    $("#"+lista).css({display:"none"});
    var productoImg = $(this).attr("src").replace("/taller/images/","");
    tallerProductoAnyadir(productoImg);
  });      
});


function tallerIniciar(nombreTaller,descripcion)
{
  $("#taller").css({background:"#ffffff url('/taller/images/txt_cargando.gif') no-repeat 0 0"});
  var fondo = nombreTaller.replace("mTaller","taller");
  $("#taller").css({background:"#ffffff url('/taller/images/"+fondo+".png') no-repeat 0 0"});
  //Pongo el nombre en su sitio
  $("#eleccion strong").html(descripcion);
  //borro los productos que hay hasta ahora
  tallerProductosBorrar();
  //poner el coeficiente de reducción.
  var numTaller = parseInt(fondo.replace("taller","").substring(0,1));
  switch(numTaller){
    case 1:
      coeficienteReduccion = 1;
      break;
    case 2:
      coeficienteReduccion = 0.40;
      break;
    case 3:
      coeficienteReduccion = 0.50;
      break;
    case 4:
      coeficienteReduccion = 0.35;
      break;
    case 5:
      coeficienteReduccion = 0.45;
      break;
    default:
      coeficienteReduccion = 1;
  }
}

function tallerProductosBorrar()
{
  $("#taller").find("div").remove();
  numProductosEnTaller=0;
  $("#lista-productos-presupuesto").html("");      
}

function tallerProductoAnyadir(producto)
{
  numProductosEnTaller = numProductosEnTaller+1;
  var productoNombre = producto.substring(0,producto.indexOf("-"));
  var width = Math.floor(productos[productoNombre][0]*coeficienteReduccion);
  var height = Math.floor(productos[productoNombre][1]*coeficienteReduccion);
  $("#taller").prepend("<div id='producto-"+numProductosEnTaller+"' style='width:"+width+"px;height:"+height+"px;z-index:"+(numProductosEnTaller+100)+";'><img src='/taller/images/"+producto+"' title='"+productoNombre+': '+txt_borrar+"' style='width:"+width+"px;height:"+height+"px;' /></div>");
  $("#producto-"+numProductosEnTaller).css({'border':'1px dotted black'});
  $("#producto-"+numProductosEnTaller).css({cursor:"pointer"}).draggable({ containment: '#taller', scroll: false, opacity:0.8,cursor:'move'});
  $("#producto-"+numProductosEnTaller).dblclick(function(){
    tallerProductoBorrar($(this),productoNombre);
  });
  $("#producto-"+numProductosEnTaller).hover(
    function () {
      $(this).css({'border':'1px dotted black'})
    }, 
    function () {
      $(this).css({'border':'none'})
    }
  );
  $("#producto-"+numProductosEnTaller).css({margin:"200px 0 0 400px"});
  $("#producto-"+numProductosEnTaller).animate({opacity: 0.2},150).animate({opacity: 0.9},150).animate({opacity: 0.2},150).animate({opacity: 1},150);
  //Si ya está en la lista de pedidos aumento la cantidad, si no lo añado
  //EL COCHE ESTÁ EXCLIDO DE LOS PEDIDOS
  if (productoNombre != "coche" && productoNombre !="car" && productoNombre != "camion" && productoNombre != "camión" && productoNombre !="truck"){
    var unidades = $("#unidades-"+productoNombre).find(".unidades").html();
    if (unidades && unidades!="" && unidades!="undefined"){
      var numUnidades = parseInt(unidades.substring(0,unidades.indexOf(" ")));
      $("#unidades-"+productoNombre).find(".unidades").html((numUnidades + 1)+" "+txt_unidades);
    }else{
      $("#lista-productos-presupuesto").append('<li id="unidades-'+productoNombre+'"><div class="foto"><img src="/taller/images/'+productoNombre+'-1.png" /></div><span class="producto">'+productoNombre+'</span><span class="unidades">1 '+txt_unidades+'</span></li>');
    }
    $("#producto-"+numProductosEnTaller).css({'border':'none'});
  }
  return true;
}

function tallerProductoBorrar(productoID,productoNombre)
{
  $(productoID).remove();
  numProductosEnTaller = numProductosEnTaller-1;
  var unidades = $("#unidades-"+productoNombre).find(".unidades").html();
  if (unidades && unidades!="" && unidades!="undefined"){
    var numUnidades = parseInt(unidades.substring(0,unidades.indexOf(" ")));
    if (numUnidades > 1){
      $("#unidades-"+productoNombre).find(".unidades").html((numUnidades-1)+" "+txt_unidades);
    }else{
      $("#unidades-"+productoNombre).remove();
    }
  }
  return true;
}

function tallerPresupuestoSolicitar()
{
  if (numProductosEnTaller<1){
    switch(idiomaPrincipal){
      case "es":
        alert("Antes de solicitar presupuesto tiene que añadir productos a su taller.");
        break;
      default:
        alert("Before budget request has to add products to your garage workshop");
    }
    return false;
  }
  //Lo primero es comprobar que ha introducido el nombre o la empresa
  if ($('#nombre').val()==""){
    switch(idiomaPrincipal){
      case "es":
        alert("Por favor, indique su nombre o el de su empresa.");
        break;
      default:
        alert("Please enter your name or your company.");
    }
    $('#nombre').val("");
    $('#nombre').css({border: "1px solid red"}).focus();
    return false;
  }else{$('#nombre').css({border: "1px solid #ff9627"});}
  
  //Email
  if ($('#email').val()==""){
    switch(idiomaPrincipal){
      case "es":
        alert("Por favor, indique el correo electrónico.");
        break;
      default:
        alert("Please indicate the e-mail.");
    }
    $('#email').val("");
    $('#email').css({border: "1px solid red"}).focus();
    return false;
  }else{$('#email').css({border: "1px solid #ff9627"});}
  
  //Teléfono
  if ($('#telefono').val()==""){
    switch(idiomaPrincipal){
      case "es":
        alert("Por favor, indique un teléfono de contacto.");
        break;
      default:
        alert("Please enter a contact phone number.");
    }
    $('#telefono').val("");
    $('#telefono').css({border: "1px solid red"}).focus();
    return false;
  }else{$('#telefono').css({border: "1px solid #ff9627"});}
  
  var listaProductos = "Taller seleccionado: "+$("#eleccion strong").html()+" -> ";
  jQuery.each($("#lista-productos-presupuesto li"), function() {
    listaProductos += $(this).find(".producto").html()+" ("+$(this).find(".unidades").html()+") | ";
  });
  
  //Ciudad
  if ($('#ciudad').val()==""){
    switch(idiomaPrincipal){
      case "es":
        alert("Por favor, indique su ciudad.");
        break;
      default:
        alert("Please enter your city.");
    }
    $('#ciudad').val("");
    $('#ciudad').css({border: "1px solid red"}).focus();
    return false;
  }else{$('#ciudad').css({border: "1px solid #ff9627"});}
  
  //País
  if ($('#pais').val()==""){
    switch(idiomaPrincipal){
      case "es":
        alert("Por favor, indique su país.");
        break;
      default:
        alert("Please enter your country.");
    }
    $('#pais').val("");
    $('#pais').css({border: "1px solid red"}).focus();
    return false;
  }else{$('#pais').css({border: "1px solid #ff9627"});}
  
  $.get("/php_lib/ajax.php", { accion: "tallerPresupuestoSolicitar", nombre: $('#nombre').val(), email:$('#email').val(), telefono:$('#telefono').val(), ciudad: $('#ciudad').val(), pais:$('#pais').val(), pedido:listaProductos },
  function(data){
    if (data != "error"){//Indicamos mensaje de OK
      switch(idiomaPrincipal){
        case "en":
          alert("Your request has been sent.\nWe will reply as soon as possible.");
          break;
        default:
          alert("Su solicitud se ha enviado correctamente.\nLe responderemos a la mayor brevedad posible.");
      }
      return true;
    }else{
      switch(idiomaPrincipal){
        case "es":
          alert("Error, inténtelo de nuevo en unos minutos.");
          break;
        default:
          alert("Error, try again in a few minutes.");
      }
      return false;
    }
  });
  return true;
}