function decodeUTF8(s){
  try {
    return decodeURIComponent(escape(s));
  }
  catch(e){
    return s;
  }
}
function toggleStatusMessage(msg){
  //Comun
  var psm = jq('#kssPortalMessage');
  if (msg!=''){
    psm.children('dd').html(msg);
    psm.attr('style','');
  }
  else {
    psm.children('dd').html('');
    psm.attr('style','display:none');
  }
}
function intersect(arr1,arr2){
  var temp = [];
  for (var i =0; i< arr1.length; i++){
    for (var j=0; j< arr2.length; j++){
      if (arr1[i]==arr2[j]){
        temp.add(arr1[i]);
      }
    }
  }
  return temp;
}
function retocaSelects(){
  var diccio = jq('input#diccio_selects').val();
  var r = eval('(' + diccio + ')');
  /*PROVISIONAL PER TREURE ELS ACCENTS*/    
  jq('select#numero_uno').attr('value','');
  jq('select#numero_dos option').attr('disabled','disabled').hide();
  jq('select#numero_tres option').attr('disabled','disabled').hide();
  jq('select#numero_cuatro option').attr('disabled','disabled').hide();
  jq('select#numero_cinco option').attr('disabled','disabled').hide();  

  jq('select#numero_uno').change(function(){
    var valor_1 = jq('select#numero_uno').attr('value');
    jq('select#numero_dos option').attr('disabled','disabled').hide();
    dic = r[valor_1];

    if (dic){
			for (var item=0; item < dic.length; item++){
			  jq('select#numero_dos option[value='+dic[item]+']').show().removeAttr('disabled');
      }
    }
    jq('select#numero_dos').attr('value','');
    jq('select#numero_tres').attr('value','');
    jq('select#numero_cuatro').attr('value','');
    jq('select#numero_cinco').attr('value','');
    jq('select#numero_tres option').attr('disabled','disabled').hide();
    jq('select#numero_cuatro option').attr('disabled','disabled').hide();
    jq('select#numero_cinco option').attr('disabled','disabled').hide();
    reformulaOpcions();
  });
  jq('select#numero_dos').change(function(){
    var valor_1 = jq('select#numero_uno').attr('value');
    var valor_2 = jq('select#numero_dos').attr('value');
    dic = r[valor_1+'#gc_sep#'+valor_2];
    jq('select#numero_tres option').attr('disabled','disabled').hide();
    if (dic){
			for (var item=0; item < dic.length; item++){
			  jq('select#numero_tres option[value='+dic[item]+']').show().removeAttr('disabled');
      }
    }
    jq('select#numero_tres').attr('value','');
    jq('select#numero_cuatro').attr('value','');
    jq('select#numero_cinco').attr('value','');
    jq('select#numero_cuatro option').attr('disabled','disabled').hide();
    jq('select#numero_cinco option').attr('disabled','disabled').hide();
    reformulaOpcions();
  });
  jq('select#numero_tres').change(function(){
    var valor_1 = jq('select#numero_uno').attr('value');
    var valor_2 = jq('select#numero_dos').attr('value');
    var valor_3 = jq('select#numero_tres').attr('value');
    dic = r[valor_1+'#gc_sep#'+valor_2+'#gc_sep#'+valor_3];
    jq('select#numero_cuatro option').attr('disabled','disabled').hide();
    if (dic){
			for (var item=0; item < dic.length; item++){
			  jq('select#numero_cuatro option[value='+dic[item]+']').show().removeAttr('disabled');
      }
    }
    jq('select#numero_cuatro').attr('value','');
    jq('select#numero_cinco').attr('value','');
    jq('select#numero_cinco option').attr('disabled','disabled').hide();
    reformulaOpcions();
  });
  jq('select#numero_cuatro').change(function(){
    var valor_1 = jq('select#numero_uno').attr('value');
    var valor_2 = jq('select#numero_dos').attr('value');
    var valor_3 = jq('select#numero_tres').attr('value');
    var valor_4 = jq('select#numero_cuatro').attr('value');
    dic = r[valor_1+'#gc_sep#'+valor_2+'#gc_sep#'+valor_3+'#gc_sep#'+valor_4];
    jq('select#numero_cinco option').attr('disabled','disabled').hide();
    if (dic){
			for (var item=0; item < dic.length; item++){
			  jq('select#numero_cinco option[value='+dic[item]+']').show().removeAttr('disabled');
      }
    }
    jq('select#numero_cinco').attr('value','');
    reformulaOpcions();
  });
  jq('select#numero_cinco').change(function(){
    reformulaOpcions();
  });
  posarOpcioPerDefecte();
}
function posarOpcioPerDefecte(){
  if (jq('select#numero_uno').length){
    jq('select#numero_uno').attr('value',jq('select#numero_uno option:not([disabled]):first').attr('value'));
    var diccio = jq('input#diccio_selects').attr('value');
    var r = eval('(' + diccio + ')');
    var valor_1 = jq('select#numero_uno').attr('value');
    
    if (jq('select#numero_dos').length){
			jq('select#numero_dos option').attr('disabled','disabled').hide();
			dic = r[valor_1];
			if (dic){
			  for (var item=0; item < dic.length; item++){
			    jq('select#numero_dos option[value='+dic[item]+']').show().removeAttr('disabled');
        }
			}
			jq('select#numero_dos').attr('value',jq('select#numero_dos option:not([disabled]):first').attr('value'));
    }
    if (jq('select#numero_tres').length){
      var valor_2 = jq('select#numero_dos').attr('value');
			jq('select#numero_tres option').attr('disabled','disabled').hide();
			dic = r[valor_1+'#gc_sep#'+valor_2];
			if (dic){
			  for (var item=0; item < dic.length; item++){
			    jq('select#numero_tres option[value='+dic[item]+']').show().removeAttr('disabled');
        }
			}
			jq('select#numero_tres').attr('value',jq('select#numero_tres option:not([disabled]):first').attr('value'));
    }
    if (jq('select#numero_cuatro').length){
      var valor_3 = jq('select#numero_tres').attr('value');
			jq('select#numero_cuatro option').attr('disabled','disabled').hide();
			dic = r[valor_1+'#gc_sep#'+valor_2+'#gc_sep#'+valor_3];
			if (dic){
			  for (var item=0; item < dic.length; item++){
			    jq('select#numero_cuatro option[value='+dic[item]+']').show().removeAttr('disabled');
        }
			}
			jq('select#numero_cuatro').attr('value',jq('select#numero_cuatro option:not([disabled]):first').attr('value'));
    }
    if (jq('select#numero_cinco').length){
      var valor_4 = jq('select#numero_cuatro').attr('value');
			jq('select#numero_cinco option').attr('disabled','disabled').hide();
			dic = r[valor_1+'#gc_sep#'+valor_2+'#gc_sep#'+valor_3+'#gc_sep#'+valor_4];
			if (dic){
			  for (var item=0; item < dic.length; item++){
			    jq('select#numero_cinco option[value='+dic[item]+']').show().removeAttr('disabled');
        }
			}
			jq('select#numero_cinco').attr('value',jq('select#numero_cinco option:not([disabled]):first').attr('value'));
    }
    reformulaOpcions();
  }
}
function reformulaOpcions(){
  var valor_1 = jq('select#numero_uno').attr('value');
  var valor_2 = jq('select#numero_dos').attr('value');
  var valor_3 = jq('select#numero_tres').attr('value');
  var valor_4 = jq('select#numero_cuatro').attr('value');
  var valor_5 = jq('select#numero_cinco').attr('value');
  var diccio = jq('input#diccio_models').attr('value');
  var lang = jq('html').attr('lang');

  var r = eval('(' + diccio + ')');
  clau=''
  if (valor_1){
    clau=valor_1;
  }
  if (valor_2){
    clau=clau+'#gc_sep#'+valor_2;
  }
  if (valor_3){
    clau=clau+'#gc_sep#'+valor_3;
  }  
  if (valor_4){
    clau=clau+'#gc_sep#'+valor_4;
  }
  if (valor_5){
    clau=clau+'#gc_sep#'+valor_5;
  }
  if (valor_1 || valor_2 || valor_3 || valor_4 || valor_5){
    var producto = r[clau];
    if (producto){
      jq('input#uid_selects').attr('value',producto['uid']);
      if ('stock_msg' in producto){
        jq('#plazo_entrega').text(decodeUTF8(producto['stock_msg'][lang]));
      }
    }else{
      jq('input#uid_selects').attr('value','');
    }
  }else{
    jq('input#uid_selects').attr('value','');
  }
  if (jq('input#uid_selects').length){
    canviPreuDinamicAux(jq('input#uid_selects'));
  }else if (jq('#taula_models input#uid').length){
    canviPreuDinamicAux(jq('#taula_models input#uid'));
  }
}

function submitFormulario(){
  jq('.form_comprar').each(function(){
    jq(this).validate({
       rules: { cantidad: { required: true, digits: true, min: 1 }
              },
       messages: { cantidad: 'Cantidad incorrecta'
                  },
       errorElement: 'div',
       errorPlacement: function(error, element){
          error.appendTo(element.parent().parent().children(".jqValidatorMessage"));
       }
    });
  });
}

function submitFormularioTablaMultiple(){
  jq('form#form_comprar_tabla_multiple input[name="tm_cantidad"]').focus(function(){
    $this = jq(this);
    if ($this.attr('value')==0){
      $this.attr('value','');
    }
  });
  jq('form#form_comprar_tabla_multiple input[name="tm_cantidad"]').blur(function(){
    $this = jq(this);
    if ($this.attr('value')==''){
      $this.attr('value',0);
    }
  });  
  
  
  jq('form#form_comprar_tabla_multiple').each(function(){
    jq(this).validate({
      submitHandler: function(form) {
        var url = jq('form#form_comprar_tabla_multiple').attr('absolute_url');        
        var formInputs = '{';
        
        jq('form#form_comprar_tabla_multiple input[type=text]').each(function() {
          $this = jq(this);
          if ($this.attr('value') > 0) {
            formInputs = formInputs +'"' + $this.attr('uid') +'": ' + $this.attr('value') +',';
          }
        });
        formInputs = formInputs +  '}';
        
        if (formInputs == '{}'){
          return false;
        }
        
        jq.ajax({
				  type : 'POST',
				  url : url+'/anadirCarroMultiple',
				  data: 'formInputs='+formInputs,
				  beforeSend: function(){
					  jq('#kss-spinner').show();
				  },
				  success: function(json){
				    jq('#kss-spinner').hide();
				    var r = eval('(' + json + ')');
				    if (r.result=='nok'){
				      toggleStatusMessage(r.msg);
				      window.scrollTo(0,0);
				    }else{
				      window.location=r.url;
				    }
				  },
				  error: function (){
            jq('#kss-spinner').hide();
            window.scrollTo(0,0);
          }
        });
        return false;
      },
      rules: { tm_cantidad: { number: true }
      },
      messages: { tm_cantidad: 'Cantidad incorrecta'
      },
      errorElement: 'div',
      errorPlacement: function(error, element){
         error.appendTo(element.parent().parent().children(".jqValidatorMessage"));
      }
    });
  });
}

function canviPreuDinamicAux(element){
  var uid = jq(element).val();
  var pvp = '';
  var pvp_oferta = '';
  var outlet ='';
  var cantidad_minima = '';
  var plazo_entrega = '';
  if (jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_pvp').length){
    pvp = jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_pvp').val();
  }
  if (jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_pvp_oferta').length){
    pvp_oferta = jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_pvp_oferta').val();
  }
  if (jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_es_outlet').attr('value')==1){
    jq('div#info_preus div#outlet').show();
  }
  else{
    jq('div#info_preus div#outlet').hide();
  }
  if (jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_cantidad_minima').length){
    cantidad_minima = jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_cantidad_minima').val();
  }
  if (jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_plazo_entrega').length){
    plazo_entrega = jq('#capsa_preus_gran input[type=hidden]#'+ uid +'_plazo_entrega').val();
  }
  if (pvp_oferta){
    jq('div#info_preus div#info_preus_oferta div.oferta span.importe').text(pvp_oferta);
    jq('div#info_preus div#info_preus_oferta div.precio span.importe').text(pvp);
    if (!jq('div#info_preus div#info_preus_oferta').is(':visible')){
      jq('div#info_preus div#info_preus_oferta').show();
      jq('div#info_preus div#info_preus_normal').hide();
    }
  }
  else if (pvp){
    jq('div#info_preus div#info_preus_normal div.precio span.importe').text(pvp);
    if (!jq('div#info_preus div#info_preus_normal').is(':visible')){
      jq('div#info_preus div#info_preus_normal').show();
      jq('div#info_preus div#info_preus_oferta').hide();
    }
  } else{
      jq('div#info_preus div#info_preus_normal').hide();
      jq('div#info_preus div#info_preus_oferta').hide();    
  }
  if (cantidad_minima){
    jq('div#info_cantidad_minima span.cantidad').text(cantidad_minima);
    jq('div input#cantidad').attr('value',cantidad_minima);
    if (cantidad_minima!=1){
      jq('div#info_cantidad_minima').show();
    }
    else{
      jq('div#info_cantidad_minima').hide();
    }
  }
  if (plazo_entrega){
    jq('div.llistat span#plazo_entrega').text(decodeUTF8(plazo_entrega));
  }
}
function canviPreuDinamicPetitAux(element){
    uid = jq(element).val();
    if (jq('#capsa_preus input[type=hidden]#'+ uid +'_cantidad_minima').length){
      cantidad_minima = jq('#capsa_preus input[type=hidden]#'+ uid +'_cantidad_minima').val();
    }
    if (jq('#capsa_preus input[type=hidden]#'+ uid +'_plazo_entrega').length){
      plazo_entrega = jq('#capsa_preus input[type=hidden]#'+ uid +'_plazo_entrega').val();
    }
    jq('div input#cantidad').attr('value',cantidad_minima);
    jq('div.llistat span#plazo_entrega').text(decodeUTF8(plazo_entrega));
}
function canviValorModel(){
  reformulaOpcions();
}
function canviPreuDinamic(){
  jq('select#uid').change(function(){ 
    canviPreuDinamicAux(jq(this));
  });
  jq('#taula_models input').click(function(){
    canviPreuDinamicAux(jq(this));
  });
}
function canviPreuDinamicPetit(){
  jq('#capsa_preus input').click(function(){
    canviPreuDinamicPetitAux(jq(this));
  });
}

jq(document).ready(function(){
  jq('span.fecha_fin').each(function(){
    var fecha_fin = jq(this).attr('fecha_fin');
    fecha_fin = fecha_fin.split('/');
    var date_future = new Date(fecha_fin[0],fecha_fin[1]-1,fecha_fin[2]);
    date_future.setHours(23);
    date_future.setMinutes(59);
    date_future.setSeconds(59);
    jq(this).countdown({until: date_future, compact: true});
  });
  submitFormulario();
  submitFormularioTablaMultiple();
  if (jq('#capsa_preus_gran').length){
    canviPreuDinamic();
    canviPreuDinamicAux(jq('select#uid option:first'));
    if (jq('#taula_models').length){
      canviPreuDinamicAux(jq('#taula_models input:first'));
    }
  }else if(jq('#capsa_preus').length){
    canviPreuDinamicPetit();
    canviPreuDinamicPetitAux(jq('#capsa_preus input#uid'));
  }  
  canviValorModel();
  retocaSelects();
  jq('.coleccio_imatges div').click(function(){
    var $this = jq(this);
    var id = $this.attr('id');
    jq('a#link_full').addClass('hidden');
    jq('a#link_full').attr('id','');
    var dest = jq('a.'+id);
    var url = $this.attr('url');
    dest.removeClass('hidden');
    dest.attr('id','link_full');
    jq('a.'+id+' img:first').attr('src',url);
  });
  jq('form#form_formulario input#uid:first').attr('checked','True');
});
