/* Prototypes */
function rand(l,u) { // lower bound and upper bound
  return Math.floor((Math.random() * (u-l+1))+l);
};

var errors = "";
var type_elem = false;
var postalCodeNumber = "";

/**
 * Deshabilitar elemento tipo boton o input (compatible con todos los navegadores)
 */

function disableElement(elem){
  if (jQuery.browser.msie){
    $(elem).hide();
  }
  else {
    $(elem).attr('disabled', 'disabled').addClass("opacity40");
  }
}

/**
 * Habilitar elemento tipo boton o input (compatible con todos los navegadores)
 */

function enableElement(elem){
  if (jQuery.browser.msie){
    $(elem).show();
  }
  else {
    $(elem).attr('disabled', '').removeClass("opacity40");
  }
}

function init_gen(){

  /* selector de pais/ciudad
   * al clickar en la ciudad actual desplega el selector de ciudades principales
   * cambia el icono y oculta la politica de privacidad
   */
  $(".selector #change_city").click(function() {
    // se desplega el selector de ciudad
        $("#cities").slideToggle();
        // cambia el icono de down a up
        $("#change_city #iconhead").toggleClass("down").toggleClass("up");
        // muestra las ciudades primarias
        $("#cities .primary").show();
        // oculta las ciudades primarias/secundarias
        $("#cities #viewallcities").hide();
        // si el selector de ciudades primarias/secundarias esta oculto...
        if ( $("#cities #viewallcities").hide() ) {
      $(".tab").addClass("closed");
    } else {
      $(".tab").removeClass("closed");
    }

  });

  /* selector de primarias + satelites
   * al clickar en ver todas las ciudades se desplega el selector de ciudades primarias+satelites
   */
  $(".tab .viewmorecities").click(function() {
    $(".tab #icon").toggleClass("up").toggleClass("down");
    $("#viewallcities").slideToggle();
    $("#cities .primary").slideToggle();
    $(".tab").toggleClass("closed");

  });


    /*     Preview home     */
  $('#combo_num_offers').change(
         function () {
             var url = $(this).val();
             document.location = url;
         }
   );

    $('#closePreview').click(function () {
           $('#barraPreview').hide();
           return false;
    });


    $("#loginSubmit").click(function() {
    var quantity = $("#quantity").val();
        $("form#accessOrderForm input[name=quantity]").val(quantity);
  });

    $("form#travellersForm").submit(function(){
        var ret = true;
        var oblig = true;
        var msg = "";
        $(".requerido").each(function(){
            $(this).removeClass("validateError");
            $(this).val($.trim($(this).val()));
            if($(this).val()=="" || $(this).val()==$(this).parent().attr("title")) {
                $(this).addClass("validateError");
                ret = false;
                oblig = false;
            }
        });

        $(".email").each(function(){
            if( $(this).hasClass('requerido') &&
                !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($(this).val())) ) {
                ret = false;
                msg = msg + ( "Campo E-mail incorrecto\n" );
                $(this).addClass("validateError");
            }
            else
                $(this).removeClass("validateError");
        });

        $(".numeric").each(function(){
            if( $(this).hasClass('requerido') &&
                !(/^[0-9]+$/.test($(this).val())) ) {
                ret = false;
                msg = msg + ( "El campo "  + $(this).attr("title") + " solo puede contener números\n" );
                $(this).addClass("validateError");
            }
            else
                $(this).removeClass("validateError");
        });

        if(!oblig) {
            alert("Rellena los campos obligatorios" + "\n" );
        } else if(!ret) {
            alert(msg);
        }
        return ret;
    });

    // Section recommend: show account create
    $('#accountCreateRecommend').click(function (e) {
        $('#accountCreateRecommend p').toggleClass('hidden');
        $('.ico-rounded_arrow').toggleClass('down');
        $('#newUser').slideToggle("fast");
      }
    );



    $('#news_unsuscribe').click(function() {
       var answer_news = $('input[name=answer]:checked').val();
       if( answer_news == 0){
           $('#newsletter_unsuscribe').attr('action','confirmation');
       }
    });

    errors = copyErrors;
    loadScript("/js/letsbonus.validations.js", function(){});

//    /* paymentMethods Visa - cuotas (AR) */
//    $("label[for=banc_visa_split]").click(function(e) {
//      // marcamos el radio de la opcion escogida
//      $('label input[id=banc_tpv_split]:eq(0)').attr('checked','checked');
//    });
//
//    /* paymentMethods Visa Nativa - cuotas (AR) */
//    $("label[for=banc_visa_native]").click(function(e) {
//      // marcamos el radio de la opcion escogida
//      $('label input[id=banc_tpv_native]:eq(0)').attr('checked','checked');
//    });
//
    /* paymentMethods Visa - cuotas (AR) */
    $("label[for=banc_visa_hipotecario], label[for=banc_visa_hipotecario] img").click(function(e) {
      // marcamos el radio de la opcion escogida
      $('label input[id=banc_visa_hipotecario]:eq(0)').attr('checked','checked');
    });

    /* paymentoptionCard Visa Mastercard */
    $("label[for=banc_tpv] span, label[for=banc_tpv] input").click(function(e) {
      // mostramos y ocultamos las capas
      $('.paymentoptionshowCard').slideDown();
      $('.paymentoptionshowPaypal').slideUp();
      // si existe pago de espectaculos
      if($('.paymentoptionShows').length > 0){
        $('.paymentoptionShows').slideUp();
      }
      // marcamos el radio de la opcion escogida
    $('label input[id=banc_tpv]:eq(0)').attr('checked','checked');

    if (e.currentTarget.id == 'banc_tpv'){
      // flag para saber si se ha recogido un evento en el elemento input
      type_elem = true;
    }
    });

    $("label[for=storedCards], #stored_card_radio_true").click(function(e) {
      // mostramos y ocultamos las capas
      $('#paymentFormGroup').slideUp();
      $('#savedCardsFormGroup').slideDown();
        $('#stored_card_radio_false').removeAttr('checked');
        $('#stored_card_radio_true').attr('checked','checked');
      $('#banco').val(CC_VISA);
        $('#paymentForm').removeData('validator');
        $('#paymentAuthorize').hide();
        $('label[for=storedCards] > span').addClass('up');
        $('label[for=newCards] > span').removeClass('up');
      $('label[for=storedCards] > a').removeClass('underline');
      $('label[for=newCards] > a').addClass('underline');
        paymentSavedCardsFormValidate();
    });

    $("label[for=newCards], #stored_card_radio_false").click(function(e) {
      // mostramos y ocultamos las capas
      $('#paymentFormGroup').slideDown();
      $('#savedCardsFormGroup').slideUp();
      $('#stored_card_radio_true').removeAttr('checked');
      $('#stored_card_radio_falsepaymentAuthorize').attr('checked','checked');
      $('#paymentForm').removeData('validator');
      $('#paymentAuthorize').show();
      $('label[for=storedCards] > span').removeClass('up');
      $('label[for=newCards] > span').addClass('up');
      $('label[for=storedCards] > a').addClass('underline');
      $('label[for=newCards] > a').removeClass('underline');
      paymentFullFormValidate();
    });

    /* paymentoptionPaypal */
    $("label[for=banc_paypal] span, label[for=banc_paypal] input").click(function(e) {
      // mostramos y ocultamos las capas
      $('.paymentoptionshowPaypal').slideDown();
      $('.paymentoptionshowCard').slideUp();
      // si existe pago de espectaculos
      if($('.paymentoptionShows').length > 0){
        $('.paymentoptionShows').slideUp();
      }
      // marcamos el radio de la opcion escogida
      $('label input[id=banc_paypal]:eq(0)').attr('checked','checked');

      if (e.currentTarget.id == 'banc_paypal'){
      // flag para saber si se ha recogido un evento en el elemento input
      type_elem = true;
    }
    });

    /* paymentoptionShows */
    $("label[for=banc_ticket] span, label[for=banc_ticket] input").click(function(e) {
      // mostramos y ocultamos las capas
      $('.paymentoptionshowPaypal').slideUp();
      $('.paymentoptionshowCard').slideUp();
      $('.paymentoptionShows').slideDown();
      // marcamos el radio de la opcion escogida
      $('label input[id=banc_ticket]:eq(0)').attr('checked','checked');

      if (e.currentTarget.id == 'banc_ticket'){
      // flag para saber si se ha recogido un evento en el elemento input
      type_elem = true;
    }
    });

    /* transPayment */
    $("label[for=banc_transfer] span, label[for=banc_transfer] input").click(function(e) {
      // mostramos y ocultamos las capas
      $('.paymentoptionshowPaypal').slideUp();
      $('.paymentoptionshowCard').slideUp();
      // si existe pago de espectaculos
      if($('.paymentoptionShows').length > 0){
        $('.paymentoptionShows').slideUp();
      }
      // marcamos el radio de la opcion escogida
      $('label input[id=banc_transfer]:eq(0)').attr('checked','checked');

      if (e.currentTarget.id == 'banc_transfer'){
      // flag para saber si se ha recogido un evento en el elemento input
      type_elem = true;
    }
    });

    // que no haga nada al clickar en el label de la opcion de pago pero si en caso de recoger un input
    $("label[for=banc_tpv], label[for=banc_paypal], label[for=banc_ticket], label[for=banc_transfer]").click(function(e) {
      // si el evento click tambien recoge accion en el input
      if (!type_elem){
        return false;
      }
      else{
        // inicializamos el flag
        type_elem = false;
      }

    });

  //Rellena hidden para validación de fecha de nacimiento
  $('select[name="client.birthDay"]').change(refillBithdayHidden);
  $('select[name="client.birthMonth"]').change(refillBithdayHidden);
  $('select[name="client.birthYear"]').change(refillBithdayHidden);

  //Rellena hidden para validación de sexo
  $('input[name="client.gender"]').change(function(){
    $('input[name="client.genderHidden"]').val($(this).val());
  });

  $('input[name="acceptLegalTerms"]').change(function(){
    if($(this).is(':checked')){
      $('input[name="acceptLegalTermsHidden"]').val('yes');
    }else{
      $('input[name="acceptLegalTermsHidden"]').val('');
    }
    //$('input[name="acceptLegalTermsHidden"]').val($(this).is(':checked'));
  });

  //Rellena hidden para validación de sexo
  $('input[name="salepostal.gender"]').change(function(){
    $('input[name="salepostal.genderHidden"]').val($(this).val());
  });

  $('#sel_clientpostal').live('change', function() {
    var url = window.location.host;
    if ( url.indexOf('secure') != -1 ) {
      var protocol = 'https://';
    }else {
      var protocol = 'http://';
    }
    if ($('#sel_clientpostal').val() > 0){
      var postalData = $.ajax({
        type: 'POST',
                    data: 'idPostal=' + $('#sel_clientpostal').val(),
        url: protocol + url + '/account/postal/getpostalclient' ,
        async: false,
        dataType : "json",
            success: function( obj ) {
          if (obj != false){
            $.each(obj,function (key, elm) {
              if (key != "gender"){
                if ($('#'+key) != undefined){
                  $('#'+key).val(elm);
                }
              } else {
                $('input[name="salepostal.gender"][value="'+elm+'"]').attr('checked',true);
                $('#genderHidden').val(elm);
              }
            });
          }
        }
      });
      $('input[name="saveClientpostal"]').attr("disabled",false);
    } else {
      $('#salepostalForm :input[type!="submit"][type!="radio"][type!="checkbox"][type!="hidden"]').val("");
      $('#salepostalForm :input[type="radio"]').attr("checked",false);
      $('#salepostalForm :input[type="checkbox"]').attr("checked",false);
      if ($('#sel_clientpostal option').length < 4){
        $('input[name="saveClientpostal"]').attr("disabled",false);
      } else {
        $('input[name="saveClientpostal"]').attr("disabled",true);
      }
    }
    // comprobamos si existe el combo de provincias
    if($("select#province").length){
        // inicializamos el listener para el combo de provincias
        onChangeCombo("#province", true);
        // inicializamos el tooltip de la tabla de gastos de envio
        shipmentTooltip(true);
    }
  });
}

function refillBithdayHidden(){
  birthDay=$('select[name="client.birthDay"]').val();
  birthMonth=$('select[name="client.birthMonth"]').val();
  birthYear=$('select[name="client.birthYear"]').val();
  if(birthDay!='' && birthMonth!='' && birthYear!=''){
    $('input[name="client.birthDate"]').val(birthMonth+'/'+birthDay+'/'+birthYear);
  }else{
    $('input[name="client.birthDate"]').val('');
  }
}

$(document).ready(init_gen);

/**
 * Muestra el formulario para modificar datos personales
 */
function showDataForm()
{
  $(".infoData").slideUp();
  $("#dataform").fadeIn("slow");
}

/**
 * Oculta el formulario para modificar datos personales
 */
function hideDataForm(){
  $(".infoData").fadeIn("slow");
  $("#dataform").slideUp();
}

/**
 * Muestra el formulario para escoger la ciudad de las newsletters
 */
function showNewslettersDataForm(){
  $(".infoNewsletters").slideUp();
  $("#newslettersForm").fadeIn("slow");
}

/**
 * Oculta el formulario para escoger la ciudad de las newsletters
 */
function hideNewslettersDataForm(){
  $(".infoNewsletters").fadeIn("slow");
  $("#newslettersForm").slideUp();
}

/**
 * Muestra el formulario para escoger la ciudad de las newsletters
 */
function showBillingDataForm(){
  $(".billingAddressForm").slideUp();
  $(".infoBillingAddress").fadeIn("slow");
}

/**
 * Oculta el formulario para escoger la ciudad de las newsletters
 */
function hideBillingDataForm(){
  $(".infoNewsletters").fadeIn("slow");
  $("#newslettersForm").slideUp();
}

/* GO LETSBOX */
$(document).ready(function(){
    $('a.openLetsbox').bind('click', function(){
        $.letsbox(this);
        return false;
    });
});

function doFormPost() {

   // data to send
    var name 		= $("form#formmail input[name='share.name']").val();
    var friendName  = $("form#formmail input[name='share.friendName']").val();
    var subject  	= $("form#formmail input[name='share.subject']").val();
    var text		= $("form#formmail textarea[name='share.text']").val();
   var urlm		= $("form#formmail input[name='url']").val();
    var friendMail = new Array();
    $("form#formmail input[name='share.friendMail[]']").each(function(i){
       friendMail[i] = this.value;
    });
   var dataToSend  =
   {
     name: name,
     friendName: friendName,
     friendMail: friendMail,
     subject: subject,
     text: text,
     url : urlm
   };

   // set the Url to be called
   var url = window.location.protocol + "//" + window.location.host + "/sharefriend/" ;
   //alert(url);


  // @todo attach the standard LB validator
  var error = false;
  var lang = $("form#formmail input[name='currentCountryIsoCode']").val();

  if($("form#formmail").valid()) {
     if(!error)
     {
         $.ajax({
             type: "POST",
             url: url,
             data: dataToSend,
             dataType: "text",
             success: function(resp)
             {
               $('#modal-container').empty();
               //alert(resp);
               $('#modal-container').append(resp);
               setTimeout(function(){
                   $("#modal-content").fadeOut('slow', function(){
                     $(".reveal-modal-bg").fadeOut('slow', function(){
                       $('#modal-container').empty();
                     });
                   });

                   $('#modal-container').empty().trigger('reveal:close');

                   // OnClick, load the form and set his event handlers
                   $('.basic-modal a.mail').click(function (e)
                   {
                     e.preventDefault();
                     $(".reveal-modal-bg").fadeIn('slow', function(){
                       $("#modal-content").fadeIn('slow');
                     });

                   });
                 }, 1000 );
             }
         });

     }
  }

}

/**
 * Atribuye estilo para destacar las opciones que salen en el modal al pasar el puntero por encima
 */
function hoverSelection(elem){
  // cuando el puntero este encima
  $(elem).live('mouseover',function(){
    // comprobamos que no este seleccionada
    if($(this).hasClass('option_selected') == false ){
      // aplicamos estilo
      $(this).addClass('option_hover');
    }
  });
  // cuando el puntero ya no este encima
  $(elem).live('mouseout',function(){
    // comprobamos que no sea una variacion seleccionada
    if($(this).hasClass('option_selected') == false){
      // aplicamos estilo
      $(this).removeClass('option_hover');
    }
  });
}

/**
 * Retorna al estilo original a una opcion deseleccionada
 */
function noSelectedOptionsStyle(elem){
  // por cada uno de las options
  $('.survey .option').each(function(){
    var s = $(this);
    // si no es el elemento seleccionado
    if( elem != s[0].id ){
      // quitamos la clase que indica la seleccion de la opcion
      s.removeClass('option_selected');
      $(this).removeClass('option_hover');
    }
  });
}

function surveyMessageSent(){
  // al enviar la encuesta la ocultamos
  $('.content-survey').fadeOut("slow");
   setTimeout(function(){
     // y se muestra un mensaje de confirmacion de envio
     $('.survey-response').fadeIn("slow");
  }, 800 );
}

/* END LIGTHBOX FUCNTIONS */

$(function(){
  $("a[rel^=external]").attr("target","_blank");

  $("form input[type=text], form textarea, .formtitle input[type=text], .formtitle textarea").each(function() {
    if($(this).attr("title") == "") {
      $(this).attr("title", $(this).parent().attr("title"));
    }
    $(this).focus(function() {
      if(!$(this).hasClass("date")) {
        if($(this).val() == $(this).attr("title")) {
          $(this).val("");
        }
      }
    }).blur(function() {
      if($(this).val() == "") {
        $(this).val($(this).attr("title"));
      }
    });
  });

  $("form").submit(function() {
    $("input[type=text], textarea", this).each(function() {
      if(!$(this).hasClass("date") && $(this).val() == $(this).attr("title")) {
        $(this).val("");
      }
    });
  });
});

function loadScript(url, callback){

     var script = document.createElement("script");
     script.type = "text/javascript";

     if (script.readyState){  //IE
        script.onreadystatechange = function(){
         if (script.readyState == "loaded" || script.readyState == "complete"){
               script.onreadystatechange = null;
               callback();
            }
         };
     } else {  //Others
       script.onload = function(){
         callback();
       };
     }

     script.src = url;
     document.getElementsByTagName("head")[0].appendChild(script);
}

function stripTags(srcString){
  if (srcString === '') {return '';}
  srcString = srcString.replace('\&nbsp;','');
  return srcString.replace(new RegExp('(<[\\s\\S]+?>)', 'g'), '');
}

function trim(str, chars) {
  return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/* qtip cvv2 paymentmethods */
$(document).ready(function() {

  $.fn.qtip.styles.styleCVV = { // Last part is the name of the style
     width: 230,
     background: '#E4DDD6',
     color: 'black',
     textAlign: 'center',
     border: {
        width: 7,
        radius: 5,
        color: '#E4DDD6'
     },
     tip: 'leftMiddle',
     name: 'dark' // Inherit the rest of the attributes from the preset dark style
  };

  $.fn.qtip.styles.shipmentCostsTable = { // Last part is the name of the style
     background: '#E4DDD6',
     color: 'black',
     textAlign: 'center',
     border: {
        width: 7,
        radius: 5,
        color: '#E4DDD6'
     },
     tip: 'topRight',
     name: 'dark' // Inherit the rest of the attributes from the preset dark style
  };

  $.fn.qtip.styles.styleFAQ = { // Last part is the name of the style
     width: 230,
     background: '#E4DDD6',
     color: 'black',
     textAlign: 'center',
     border: {
        width: 7,
        radius: 5,
        color: '#E4DDD6'
     },
     tip: 'leftTop',
     name: 'dark' // Inherit the rest of the attributes from the preset dark style
  };

  $.fn.qtip.styles.styleCreditCards = { // Last part is the name of the style
             width: 400,
             background: '#E4DDD6',
             color: 'black',
             textAlign: 'center',
             border: {
                width: 7,
                radius: 5,
                color: '#E4DDD6'
             },
             tip: 'leftTop',
             name: 'dark' // Inherit the rest of the attributes from the preset dark style
          };

  $.fn.qtip.styles.styleFlashFAQ = { // Last part is the name of the style
      width: 300,
      background: '#CEC8C3',
      color: 'black',
      textAlign: 'left',
      border: {
        width: 7,
        radius: 5,
        color: '#CEC8C3'
      },
      tip: 'topLeft',
      name: 'dark' // Inherit the rest of the attributes from the preset dark style
  };
      $.fn.qtip.styles.styleLetsMagic = {
          width: 320
        ,background: 'none'
        ,border: 'none'
        ,padding: '0'
      };
  $.fn.qtip.styles.styleLetsSurprise = { // Last part is the name of the style
          width: 300,
          background: '#CEC8C3',
          color: 'black',
          textAlign: 'left',
          border: {
              width: 7,
              radius: 5,
              color: '#CEC8C3'
          },
          tip: 'topLeft',
          name: 'dark' // Inherit the rest of the attributes from the preset dark style
  };

  $.fn.qtip.styles.faqSurpriseCard = { // Last part is the name of the style
          width: 300,
          background: '#CEC8C3',
          color: 'black',
          textAlign: 'left',
          border: {
              width: 7,
              radius: 5,
              color: '#CEC8C3'
          },
          tip: 'leftBottom',
          name: 'dark' // Inherit the rest of the attributes from the preset dark style
  };

  if($('#letsmagic').length){
  $('#letsmagic').qtip({
      content: $(".letsmagicImg").html()
      ,style: 'styleLetsMagic'
      ,position: {
          corner: {
              tooltip: 'topRight',
              target: 'bottomLeft'
          }
              ,target: $('#letsMagicTooltipTarget')
          ,adjust: {
                  x: 30
                  ,y: -5
          }
      }
      ,show: 'mouseover'
      ,hide: 'mouseout'
   });
  }
  if($('.ecardSend.detail').length){
        $('.ecardSend.detail').qtip({
           content: $("#ecardSendContent").html(),
           style: 'styleLetsSurprise',
           position: {
               corner: {
                   tooltip: 'topLeft',
                   target: 'topLeft'
               },
               target: $('.ecardSendContent'),
               adjust: {
                   x: 320,
                   y: 50
               }
           },
           show: 'mouseover',
           hide: 'mouseout'
        });
  }
  if($('#authorise_display').length){
    $('#help_authorize').qtip({
       content: $("#authorise_tooltip_content").html(),
       style: 'styleCVV',
       position: {
           corner: {
               tooltip: 'topLeft',
               target: 'topLeft'
           },
           target: $('.authorize_tooltip_target'),
           adjust: {
               x: 15,
               y: -70
           }
       },
       show: 'mouseover',
       hide: 'mouseout'
    });
  }

  if($('.help_cvv').length){
    $('.help_cvv').qtip({
       content: $("#tooltip_cvv2").html(),
       style: 'styleCVV',
       position: {
           corner: {
               tooltip: 'topLeft',
               target: 'topLeft'
           },
           target: $('.cvv_tooltip_target'),
           adjust: {
               x: 15,
               y: -70
           }
       },
       show: 'mouseover',
       hide: 'mouseout'
    });
  }

  if($('.shipmentInfo.shipmentText').length){
    $('.shipmentInfo.shipmentText').qtip({
       content: $(".shipmentCopy").html(),
       style: 'shipmentCostsTable',
       position: {
           corner: {
               tooltip: 'topRight',
               target: 'bottomLeft'
           },
           target: $('.shipmentTextTooltipTarget'),
           adjust: {
               x: 0,
               y: 15
           }
       },
       show: 'mouseover',
       hide: 'mouseout'
    });
  }

  if($('.pyamentFaqs').length){
    // controla los tooltips de preguntas frecuentas
    $('.pyamentFaqs .faq').each(function(){
      // recogemos las clases de cada pregunta
      var res = $(this).attr('class');
      // separamos las clases
      res = res.split(" ");
      // recogemos la segunda
      res = res[1];
      $(this).qtip({
          // concatenamos para recoger el contenido a mostrar
          content:$('.content_' + res),
          // aplicamos estilo de tooltip
          style: 'styleFAQ',
          position: {
               corner: {
                   tooltip: 'topLeft',
                   target: 'topLeft'
               },
               target: $('.faq_tooltip_target_' + res),
               adjust: {
                   x: 15,
                   y: -10
               }
           },
          // mostramos solo cuando no exista otro tooltip
          show: {solo: true, ready: false, when: 'mouseover'},
          hide: { when: 'mouseout', fixed: true }
      });
    });
  }

  if($('.cardsFormContent').length){
        // controla los tooltips de preguntas frecuentas
        $('.cardsFormContent .cardTooltip').each(function(){
          // recogemos las clases de cada pregunta
          var res = $(this).attr('class');
          // separamos las clases
          res = res.split(" ");
          // recogemos la segunda
          res = res[1];
          $(this).qtip({
              // concatenamos para recoger el contenido a mostrar
              content:$('.cardContent_' + res),
              // aplicamos estilo de tooltip
              style: 'styleCreditCards',
              position: {
                   corner: {
                       tooltip: 'topLeft',
                       target: 'topLeft'
                   },
                   target: $('.card_tooltip_target_' + res),
                   adjust: {
                       x: 15,
                       y: -10
                   }
               },
              // mostramos solo cuando no exista otro tooltip
              show: {solo: true, ready: false, when: 'mouseover'},
              hide: { when: 'mouseout', fixed: true }
          });
        });
      }

  if($('.faqFlashOffers ').length){
    // controla los tooltips de preguntas frecuentas
    $('.faqFlashOffers .faq').each(function(){
      // recogemos las clases de cada pregunta
      var res = $(this).attr('class');
      // separamos las clases
      res = res.split(" ");
      // recogemos la segunda
      res = res[1];
      $(this).qtip({
          // concatenamos para recoger el contenido a mostrar
          content:$('.content_' + res),
          // aplicamos estilo de tooltip
          style: 'styleFlashFAQ',
          position: {
               corner: {
                   tooltip: 'topMiddle',
                   target: 'leftMiddle'
               },
               target: $('.faq_tooltip_target_' + res),
               adjust: {
                   x: 200,
                   y: 7
               }
           },
          // mostramos solo cuando no exista otro tooltip
          show: {solo: true, ready: false, when: 'mouseover'},
          hide: { when: 'mouseout', fixed: false }
      });
    });
  }
  $('.eCardFaq').qtip({
       content: $("#eCardFaqContent"),
       style: 'faqSurpriseCard',
       position: {
           corner: {
               tooltip: 'topLeft',
               target: 'topLeft'
           },
           target: $('.eCardFaq'),
           adjust: {
               x: 15,
               y: -55
           }
       },
       // mostramos solo cuando no exista otro tooltip
      show: {solo: true, ready: false, when: 'mouseover'},
      hide: { when: 'mouseout', fixed: true }
    });
  $('.surpriseFaq').qtip({
      content: $("#surpriseFaqContent"),
      style: 'faqSurpriseCard',
      position: {
          corner: {
              tooltip: 'topLeft',
              target: 'topLeft'
          },
          target: $('.surpriseFaq'),
          adjust: {
              x: 15,
              y: -90
          }
      },
      // mostramos solo cuando no exista otro tooltip
      show: {solo: true, ready: false, when: 'mouseover'},
      hide: { when: 'mouseout', fixed: true }
  });

});

/**
 * Slide cities auxiliar
 * */
$(document).ready(function() {
  if($('#slides').length){
    $('#slides').slides({
      start: 1,
      container: 'slides_container_aux',
      next: 'next_city_aux',
      currentClass: 'current',
      generatePagination: false

    });
  }
});

/**
 * Controla el modal a desplegar con google maps como contenido
 */
function showGoogleMap(zoom, latitude, longitude, title, frontitle, affiliate ){

  var geocoder = new google.maps.Geocoder();

  var latLng = new google.maps.LatLng(latitude, longitude)
  var map = new google.maps.Map(document.getElementById('GoogleMap'), {
      zoom: zoom,
      center: latLng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  var mLatLin = new google.maps.LatLng(latitude, longitude);

  if(affiliate == 1){
    var icono = new google.maps.MarkerImage("/media/img/vivirvip/vivirvip_google-maps-marker.png", null, null, new google.maps.Point(13, 32), new google.maps.Size(26, 32));
  }
  else{
    var icono = new google.maps.MarkerImage("/media/img/main/google-maps-marker.png", null, null, new google.maps.Point(13, 32), new google.maps.Size(26, 32));
  }
  var infowindow = new google.maps.InfoWindow({
      content: title
    });

  var marker = new google.maps.Marker({
      position: mLatLin,
      title: frontitle,
      map: map,
      popup:false,
      draggable: false,
      icon: icono
  });

  var geocodePosition = function (pos) {
      geocoder.geocode({
        latLng: pos
      }, function(responses) {
        if (responses && responses.length > 0) {
          var address = responses[0].formatted_address;
            $('#DireccionMasCercana').text(address);
        } else {
          $('#DireccionMasCercana').text('Error en la carga de datos de Google Maps.');
        }
      });
    }

  $('#linkGoogleMap').attr('href','http://maps.google.com/maps?z='+zoom+'&q=loc:'+latitude+'+'+longitude);

//	//geocodePosition(mLatLin);
//
//	//ventana popup del marker
//	//infowindow.open(map, marker);
};

/**
 * Anyadimos al prototipo de array una nueva funcion que elimina valores
 * duplicados de un Array
 */
Array.prototype.uniqueRank = function(a) {
    return function() {
        return this.filter(a)
    }
}(function(a, b, c) {
    return c.indexOf(a, b + 1) < 0
});

/**
 * Devuelve una array ordenada de forma ascendente si se utiliza con el metodo
 * sort()
 *
 * @param a
 * @param b
 * @returns {Number}
 */
function sortNumber(a, b) {
    return a - b;
}

/**
 * Recoge copys pasados por parametro
 *
 * @param copy
 * @returns {getCopy}
 */
function getCopy(copy) {
    this.copy = copy;
}

/**
 * Devuelve el contenido de los copys pasados
 *
 * @returns
 */
function setCopy() {
    return this.copy;
}

/**
 * Modificacion en el formulario salepostal IT, para una oferta en concreto (43739)
 */
function submitProcess() {
  // recogemos el valor de los dos campos
    var address1 = $('#address_via').val();
    var address2 = $('#address_nr').val();

    // controlamos que no se envie el codigo postal de ejemplo
    var postalAddress = $('#extraAddress1').val();
    if(postalCodeNumber == postalAddress){
      $('#extraAddress1').val("");
    }

    // si se han introducido los valores necesarios
    if(address1 != '' && address2 != ''){
      // concatenamos el valor
      var address = address1 + " " + address2;
      // anyadimos el valor a un input oculto
      $('#address').val(address);
      // enviamos la info
      $('#salepostalForm').submit();
    }
}

/**
 * Introduce un codigo postal de ejemplo en el formulario
 */
function exampleCap(postalCode){
  postalCodeNumber = postalCode;
  // recogemos el valor del campo correspondiente al codigo postal
    var address1 = $('#extraAddress1').val();
    // si esta vacio introducimos el ejemplo
    if(address1 == ''){
      // asignamos el valor pasado por parametro al campo
      $('#extraAddress1').val(postalCode);
      // aplicamos un estilo diferente
      $('#extraAddress1').css('color','#777');
    }
    // vaciamos el campo en cuanto se haga click en el
    $('#extraAddress1').click(function(){
      $('#extraAddress1').val("");
    })
    // al hacer click en la pagina
    $(document).click(function(e){
      // si el elemento donde se ha hecho click es diferente al campo
      if(e.target.id != 'extraAddress1'){
        // recogemos el valor del campo
        address1 = $('#extraAddress1').val();
        // si esta vacio o esta lleno y es igual al valor de la variable pasada por parametro
        if(address1 == '' || address1 != '' && address1 == postalCode){
            // asignamos el valor pasado por parametro al campo
            $('#extraAddress1').val(postalCode);
            $('#extraAddress1').css('color','#777');
          }
        else {
          // aplicamos el estilo correspondiente al resto de datos introducidos por el user
          $('#extraAddress1').css('color','#333333');
        }
      }
    });
}

/**
 * Previene la introduccion de numeros en un campo de un formulario
 */
function noAlphanumeric(input){
    $('#' + input).keyup(function(){
      if ($(this).val() != ""){
        $(this).val($(this).val().replace(/[^0-9\.]/g, ""));
      }
    });
}

/**
 *	Muestra un banner en el caso de que el usuario se conecte via movil
 */
function loadbnr_mobile(){
    //android
    var ua = navigator.userAgent.toLowerCase();
    var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
    if(isAndroid) {
        //add banner
        $('.loadbnr_mobile').after('<a href="http://ad.letsbonus.com/es/mobile"><img src="/media/img/countries/es/bnr_app_mobile.jpg" width="990" height="139" /></a>');
    }

    // iphone/ipod
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
       if (document.cookie.indexOf("iphone_redirect=false") == -1)
           //add banner
        $('.loadbnr_mobile').after('<a href="http://ad.letsbonus.com/es/mobile"><img src="/media/img/countries/es/bnr_app_mobile.jpg" width="990" height="139" /></a>');
    }
}
$(document).ready(function() {
/**
 *	Si existe la id sidebar y no es una promo especial se anyade una clase al content para mostrar el fondo del sidebar
 *  y se cambia la imagen de fondo del menu
 */
  if ( ($("#sidebar").length > 0) && ($("#offersSpecialPromo").length == 0 ) ) {
    $("#content").addClass('bg');
    $(".menu-bg-right").addClass('bg');
  }

/**
 *	Si es el lightbox de paypal se oculta la frase "ya estoy registrado"
 */
  if ($("#promo-content").length > 0) {
    $(".registered p").hide();
  }

});

/**
 * ------------------ Script to activate content tabs on ------------------
 * ------------------- General Terms & Conditions Section  ----------------
 */

$(function() {

  //When page loads...
  $(".tab_content").hide(); //Hide all content
  $("#tabs a:first").addClass("active").show(); //Activate first tab
  $(".tab_content:first").show(); //Show first tab content

  var tabContainers = $('.tab_content');

      $('#tabs a').click(function () {

          $('#tabs a').removeClass('active');
          $(this).addClass('active');
          tabContainers.hide().filter(this.hash).fadeIn(500); //Find hash value which corrensponds to the id of the needed text container

          return false;
      });

});

// Function for going instantly to the fisrt tab, scrolls to top
function conditionsFirstTabNow(){
    $(".tab_content").hide(); //Hide all content
    $('#tabs a').removeClass('active'); //Deactivate all tabs
    $("#tabs a:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
    scroll(0,0); // Scroll to top
}

/**
 * ------------------ Script to make Commerce Poll a ------------------
 * ------------------------ Two Step Form  ---------------------
 */

$(function() {

  var poll_form = $('#formspoll'),
    first_step = $('#first-step'),
    second_step = $('#second-step'),
    send_button = $('#poll_input'),
    pagination = $('#form-pagination');
    stopSubmit = true;

    send_button.click(function(e) {
      if (stopSubmit == true) {
       first_step.fadeOut(500, function() {
          second_step.fadeIn(500, function() {
            pagination.text('2/2');
          });
      });
       e.preventDefault();
       stopSubmit = false;
      } else {
        poll_form.submit();
      }
    });
});



/**
 * Anyade un borde sombreado al elemento pasado por parametro al pasar el mouse por encima
 * @param elem: elemento hover
 */
function addBorderShadow(elem){
    $(elem).mouseover(function(e){
        $(this).addClass('borderShadow');
    });
    $(elem).mouseout(function(e){
        $(this).removeClass('borderShadow');
    });
}

/**
 * Funcion genérica para option que muestra contenido con un efecto slide
 * param1: id sobre el que se hace click
 * param2: id que se ve afectado al aplicar la funcion
 */
function optionSlide(param1,param2) {
    $('#' + param1).click(function(){
        if($(this).is(':checked')){
            $('#' + param2).slideDown();
        }else{
            $('#' + param2).slideUp();
        }
    });
}

/**
 * Funcion genérica para option que muestra/oculta contenido
 * param1: id sobre el que se hace click
 * param2: id que se ve afectado al aplicar la funcion
 */
function optionShow(param1,param2) {
    $('#' + param1).click(function(){
        if($(this).is(':checked')){
            $('#' + param2).slideDown();
        }else{
            $('#' + param2).slideUp();
        }
    });
}

/**
 * Recoge un flag para poder enviar el formulario
 * @param formValidated: flag boleano
 */
function sendFamilyNewsletterForm(formValidated){
    // si es true
    if(formValidated){
        // enviamos el formulario por ajax
        sendFamilyNewsletterDataFromSidebarRegister();
    }
}

function getClientStatus(isLogged, isSubscribed, isClient){
    // recogemos las variables de estado y las guardamos en una array
    this.clientStatus = {
            'isLogged':isLogged,
            'isSubscribed':isSubscribed,
            'isClient':isClient
    };
}
/**
 * Devuelve una array de estados del cliente
 * @returns: array
 */
function setClientStatus(){
    return this.clientStatus;
}

/**
 * Monta el formulario de registro de la newsletter de family & kids segun el estado del cliente
 */
function putFamilyNews(){
    // recogemos toda la capa donde esta el formulario de registro a la news de family & kids
    var form = $(".sidebarNewsRegister");
    // si el usuario esta logueado
    if(setClientStatus().isLogged){
        // si el usuario ya esta inscrito en la newsletter
        if(setClientStatus().isSubscribed){
            // ocultamos el formulario de registro
            form.hide();
        }
        else{
            // mostramos el formulario
            form.show();
            // procesamos los elementos a mostrar
            $(".sidebarNewsRegister .second").hide();
            $(".sidebarNewsRegisterButton").insertAfter(".sidebarNewsRegisterForm");
            $(".sidebarNewsRegister .first").show();

            // datos a enviar cuando el usuario se quiere apuntar a la news
            var dataToSend = {
                prevSection: $("#prevSection").val(),
                utm_source: $("#utm_source").val()
            };

            // al apuntarse a la news
            $("input.first").bind('click', function(){
                $.ajax({
                       type: "post",
                       url: window.location.protocol + "//" + window.location.host + "/newsletter/familyplanform/insert",
                       dataType : "json",
                       data: dataToSend,
                       success: function(response){
                           // ocultamos todos los elementos
                           $(".sidebarNewsRegisterTitles, .sidebarNewsRegisterForm, .sidebarNewsRegisterButton").fadeOut("slow", function(){
                               // mostramos el mensaje de exito en la peticion
                               $(".sidebarNewsSuccessMsg").fadeIn("fast");
                               // si no es cliente
                               if(!response.isClient){
                                   // mostramos el boton de registro
                                   showRegisterButtonInSidebarNewsletterBanner();
                                   // al clickar redirigir a la pagina de registro
                                   redirectToRegisterPage();
                               }
                           });
                       },
                       error: function(){
                           $(".sidebarNewsRegister .sendError.validateError").insertAfter(".sidebarNewsRegisterButton").fadeIn("fast");
                       }
                });
            });
        }
    }
    else{
        // mostramos el formulario de registro a la newsletter
        form.show();
        $(".sidebarNewsRegisterButton").removeClass("marleft30");
        $(".sidebarNewsRegisterButton").addClass("marleft5");
        $(".sidebarNewsRegisterButton").insertAfter(".sidebarNewsRegisterForm fieldset");
        $(".sidebarNewsRegisterTxt .second").show();
        $(".sidebarNewsRegisterForm, .sidebarNewsRegisterButton input.second").show();
        $(".sidebarNewsRegister .first, .sidebarNewsSuccessMsg").hide();

        // al apuntarse a la news
        $(".sidebarNewsRegisterButton input.second").bind('click', function(){
            // validamos el formulario
            familyNewsletterRegisterValidate();
        });

    }
}

function showRegisterButtonInSidebarNewsletterBanner(){
   // ocultamos todos los botones menos el de regitro
   $(".sidebarNewsRegisterButton .first, .sidebarNewsRegisterButton .second").hide();
   $(".sidebarNewsRegisterButton").insertAfter(".sidebarNewsSuccessMsg");
   $(".sidebarNewsRegisterButton").addClass("marleft30");
   $(".sidebarNewsRegisterButton, .sidebarNewsRegisterButton .registerAccountButton").fadeIn("fast");
}

/**
 * Redirige al usuario a la pagina de registro
 */
function redirectToRegisterPage(){
    $(".sidebarNewsRegisterButton .registerAccountButton").bind('click', function(e){
        e.preventDefault();
        // redirigimos al usuario a la pagina de registro
        window.location = window.location.protocol + "//" + window.location.host + "/account/create";
    })
}

/**
 * Envia por ajax los datos del usuario al apuntarse a la newsletter de Family&Kids
 */
function sendFamilyNewsletterDataFromSidebarRegister(){
    // datos a enviar cuando el usuario se quiere apuntar a la news sin estar logueado
    var dataToSend = {
        'newsletter.mail': $(".sidebarNewsRegister input[name='newsletter.mail']").val(),
        'newsletter.idCity': $(".sidebarNewsRegister select[name='newsletter.idCity']").val(),
        acceptLegalTermsHidden: $(".sidebarNewsRegister #acceptLegalTermsHidden").val(),
        prevSection: $("#prevSection").val(),
        utm_source: $("#utm_source").val()
    };
    // realizamos el envio por ajax
    $.ajax({
        type: "post",
        url: window.location.protocol + "//" + window.location.host + "/newsletter/familyplanform/insert",
        dataType : "json",
        data: dataToSend,
        success: function(response){
            // ocultamos todos los elementos
            $(".sidebarNewsRegisterTitles, .sidebarNewsRegisterForm, .sidebarNewsRegisterButton").fadeOut("slow", function(){
                // mostramos el mensaje de exito en la peticion
                $(".sidebarNewsSuccessMsg, .sidebarNewsSuccessMsg .first").fadeIn("fast");
                // si no es cliente
                   if(!response.isClient){
                       // mostramos el boton de registro
                       showRegisterButtonInSidebarNewsletterBanner();
                       // al clickar redirigir a la pagina de registro
                       redirectToRegisterPage();
                   }
            });
        },
        error: function(){
            $(".sidebarNewsRegister .sendError.validateError").insertAfter(".sidebarNewsRegisterButton").fadeIn("fast");
        }
    });
}

/**
 * Devuelve el numero de pestanyas existentes en el menu de navegacion
 * @returns
 */
function setMenuTabsQuantity(){
    // recoge la cantidad de pestanyas existentes en el menu de navegacion
    var tabs = $(".menulist li").length;
    return tabs;
}

/**
 * Aplica/Quita el borde derecho a las pestanyas siempre que el numero de estas sea menor/mayor a lo indicado por parametro
 * @param maxTabsNumber: parametro que indica el numero de pestanyas maximas
 */
function controlBorderRightForLastTabOfTheMenu(maxTabsNumber){
    // si el numero de pestanyas es menor al maximo permitido
    if(setMenuTabsQuantity() < maxTabsNumber){
        // aplicamos el borde derecho para delimitar el area clickable
        $(".menulist li a:last").addClass("applyBorderRightForMenuTab");
    }
    // sino
    else{
        // eliminamos el borde derecho
        $(".menulist li a:last").addClass("removeBorderRightForMenuTab");
    }
}

/**
 * Recoge los formularios a mostrar de newsletters family&kids en la pagina de confirmacion de compra
 * @param currentCityForm: boolean
 * @param newCityForm: boolean
 */
function setFkNewslettersForms(currentCityForm, newCityForm){
    // flag para saber que formularios mostrar
    var forms = false;
    if(currentCityForm && newCityForm){
        forms = true;
    }
    // objeto que contiene los parametros recogidos
    this.fkNewsData = {
            currentCityForm: currentCityForm,
            newCityForm: newCityForm,
            forms: forms
    }
}
/**
 * Devuelve los formularios a mostrar de newsletters family&kids en la pagina de confirmacion de compra
 * @returns object
 */
function getFkNewslettersForms(){
    return this.fkNewsData;
}

/**
 * Muestra en la vista de la pagina de confirmacion de compra los formularios de newsletters family&kids
 */
function showFkNewslettersForms(){
    // se recoge los forms a mostrar
    var data = getFkNewslettersForms();
    // primer formulario
    if(data.currentCityForm){
        // si es el unico formulario, que ocupe todo el ancho
        if(!data.forms){
            $("#currentCityForm").removeClass("width50");
            $("#currentCityForm").addClass("width90 borderRightNone");
        }
        // se muestra form
        $("#currentCityForm").fadeIn("slow");;
        // aplica el listener para el envio del formulario por ajax
        sendFamilyNewsletterData('currentCityForm');
    }
    if(data.newCityForm){
        // si es el unico formulario, que ocupe todo el ancho
        if(!data.forms){
            $("#newCityForm").addClass("width90");
        }
        // se muestra form
        $("#newCityForm").fadeIn("slow");
        // aplica el listener para el envio del formulario por ajax
        sendFamilyNewsletterData('newCityForm');
    }
}

/**
 * Envia por ajax los datos del usuario al apuntarse a la newsletter de Family&Kids en la pagina de confirmacion de compra
 */
function sendFamilyNewsletterData(form){
    $("#" + form + " .submitBtn").bind('click', function(e){
        e.preventDefault();
        // ocultamos el icono loading
        $("#" + form + " .spinningWheel").removeClass("hidden");
        // variable que almacenara la url a enviar por ajax
        var url = '';
        // recogemos el valor del input del formulario
        var inputChecked = $("#" + form + " input[type='radio']:checked").val();
        // dependiendo del formulario atribuimos un valor a la variable url e idSale
        if(form == 'currentCityForm'){
            var idSale = '';
            url = window.location.protocol + "//" + window.location.host + '/newsletter/afterpaymentfamilyplansubscribe';
        }
        else{
            // variable que almacenara la id de la venta
            var idSale = {'idSale': $('input[name=saleId]').val()};
            url = window.location.protocol + "//" + window.location.host + '/newsletter/afterpaymentchangecity';
        }
        if(inputChecked != 0){
            // realizamos el envio por ajax
            $.ajax({
                type: "post",
                url: url,
                dataType : "json",
                data: idSale,
                success: function(response){
                    // se oculta icono loading
                    $("#" + form + " .spinningWheel").addClass("hidden");
                    // se oculta el formulario y se muestra un texto
                    showFamilyNewsMessage(form, inputChecked);
                }
            });
        }
        else{
            showFamilyNewsMessage(form);
        }
    })
}

/**
 * Segun la opcion escogida en la suscripcion en la pagina de confirmacion de compra a Family&Kids se muestra un tipo de texto
 * @param form: id del formulario
 * @param inputChecked: boolean
 */
function showFamilyNewsMessage(form, inputChecked){
    $("#" + form + " form").fadeOut("slow", function(){
        // mostramos el mensaje de exito en la suscripcion
        $("#" + form + " .rounded_box").fadeIn("fast");
        if(inputChecked && inputChecked == 1){
            $("#" + form + " .rounded_box .suscribedText").fadeIn("fast");
        }
        // mostramos el mensaje de no suscrito
        else{
            $("#" + form + " .rounded_box .notSuscribedText").fadeIn("fast");
        }
    });
}
