/*
  JAVASCRIPT IN COMMON TO ALL SITE (FRONT SIDE)

  Only add the javascript common to this .js
  If there is some specific function, it should be in his own .js file
  @raulbarroso

*/

function pulsar(e) {
  tecla = (document.all) ? e.keyCode :e.which;
  return (tecla!=13);
}

function mas_consejos()
{
  if( parseInt($('#cont_consejos').text()) < parseInt($('#total_consejos').text()) )
    $('#cont_consejos').text( parseInt($('#cont_consejos').text()) + 1);
}

function menos_consejos()
{
  if( parseInt($('#cont_consejos').text()) > 1 )
    $('#cont_consejos').text( parseInt($('#cont_consejos').text()) - 1);
}

var addthis_config = {
  username: "ideup",
  services_compact: 'email, print, favorites, facebook, twitter, blogger, delicious, fresqui, google, meneame, digg, live, more'
}


function ir_ancla()
{
  document.location.href = "#ancla";
}

function mainmenu(){
  $("#navegacion ul ul").css({display:"none"});
  $("#navegacion ul li").hoverIntent(
  function(){
    $(this).find('ul:first:hidden').css({visibility: "visible",display: "none"}).slideDown(400);
  },
  function(){
    $(this).find("ul:first").fadeOut(400);
  })
}
function loginTop() {
  if($('#entrar_desplegable').css('display') != 'block') {
    $('#entrar_desplegable').toggle("fast", function(){
      $("#entrar").toggleClass('desplegado');
      $('#entrar_desplegable').seekAttention({pulse: false});
    });
  }

  return false;
}


$(document).ready(function (){

  // Llamada a la función que carga el menú con desplegables
  mainmenu();

  // Destacados de la home
  $('#destacados_wrapper').before('<div class="botonera_destacados">').cycle({
    speed: '500',
    timeout: 10000,
    random: true,
    pager: '.botonera_destacados'
  });

  // Hogar eficiente
  $('#hogareficiente_destacado').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast', fxAutoHeight: true });

  // Contenedor de tabs genérico
  $('#container-tabs').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });

  // Electrodomésticos eficientes - Tipos de electrodomésticos - Grandes
  $('#tab-frigorificos').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
  $('#tab-congeladores').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
  $('#tab-lavadoras').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
  $('#tab-secadoras').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
  $('#tab-lavavajillas').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
  $('#tab-hornos').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });
  $('#tab-cocinas').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });

  //tabs noticias eficientes
  $('#container-tabs-noticias').tabs({ fxSlide: true, fxFade: true, fxSpeed: 'fast' });

  //filtro desplegable noticias eficientes
  $('#btn_fechas a').click(function(){
    $('#fechas_desplegable').toggle('fast');
    $('#filtro_fechas').toggleClass('desplegado');
  });

  // Hogar eficiente - Consejos - Aislamiento - Fachadas y cubiertas
  $("#acordeon-fachycubi").accordion({
    alwaysOpen: false,
    autoheight: false,
    header: 'a.encabezado_acordeon',
    clearStyle: true
  });

  // Ilumina tu hogar - Tipos de lámpara
  $("#acordeon-ilumina_tipos").accordion({
    alwaysOpen: false,
    autoheight: false,
    header: 'a.encabezado_acordeon',
    clearStyle: true
  });

  // Función que carga los acordeones de Climatización eficiente
  $('#menu_climatizacion a').click(function(){
    var frag = $(this).parent().attr('class').substr(4).split(' ');
    $('.contenido_acordeon > ul:visible').fadeOut('normal', function() {
      $('#'+frag[0]).fadeIn();
    });
    $('#menu_climatizacion a.activo').removeClass('activo');
    $(this).addClass('activo');
    return false;
  });

  // Acordeones de Climatización eficiente
  $(".contenido_acordeon > ul").accordion({
    alwaysOpen: false,
    autoheight: false,
    header: 'a.encabezado_acordeon',
    clearStyle: true
  });

  // Carrusel vertical de Climatización eficiente
  jQuery('#menu_climatizacion').jcarousel({
    scroll:1,
    vertical:true
  });

  // Carrusel horizontal de consejos de la barra lateral
  jQuery('#consejos').jcarousel({scroll:1});

  // Carrusel horizontal de consejos de la barra lateral
  jQuery('#fondos').jcarousel({scroll:1});

  // Carrusel horizontal de consejos de la barra lateral
  jQuery('#pintaycolorea').jcarousel({scroll:1});

  // Carrusel peques parque
  jQuery('#parque').jcarousel({scroll:1});

  // Tooltip genérico
  $('.tooltipito, .tooltipito_validar').tooltip({
    track: true,
    top: -15,
    fade: 250
  });

  // Lightbox genérico
  $("a.iframe").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true
  });

  // Lightbox eliminar vivienda
  $("a.eliminar_vivienda").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameHeight' : 400,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox eliminar perfil
  $("a.eliminar_perfil").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameHeight' : 290,
    'frameWidth' : 490,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox tabla iluminación
  $("a.tabla_ilumina_comparativa").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 840,
    'frameHeight' : 610,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox canal peques
  $("a.pintasycoloreas").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 620,
    'frameHeight' : 490,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox canal peques
  $("a.rincon_ninos").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 620,
    'frameHeight' : 440,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox para terminos legales
  $("a.terminos_condiciones").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 600,
    'frameHeight' : 600,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox para terminos legales
  $("a.terminos_condiciones_registro").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 600,
    'frameHeight' : 400,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  // Lightbox para bases legales (promos)
  $(".promo_bbll").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 700,
    'frameHeight' : 600,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  $("a.iframe_asesor").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 500,
    'frameHeight' : 400,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });
  $("a#mensaje_bienvenida").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 400,
    'frameHeight' : 360,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  $(".send_guide_home").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 545,
    'frameHeight' : 510,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  $(".open_lightbox").fancybox({
			'hideOnContentClick': false,
			'overlayShow' : true,
			'frameWidth' : 300,
			'frameHeight' : 100,
			'easingIn' : 'easeOutBack',
			'easingOut' : 'easeInBack'
		});



  // Menú lateral de Tu canal eficiente
  $("h4#tus_datos").click(function () {
    $("ul#tus_datos_ul").slideToggle("slow");
    $("#tus_datos span").toggleClass("plegado");
  });
  $("h4#tus_viviendas").click(function () {
    $("ul#tus_viviendas_ul").slideToggle("slow");
    $("#tus_viviendas span").toggleClass("plegado");
  });

  $("a#asesor_video").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 820,
    'frameHeight' : 500,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack',
    'callbackOnClose': function(){ $('#fancy_content').html(''); }
  });

  $("#modalWindowButton").fancybox({
    'hideOnContentClick': false,
    'overlayShow' : true,
    'frameWidth' : 545,
    'frameHeight' : 320,
    'easingIn' : 'easeOutBack',
    'easingOut' : 'easeInBack'
  });

  //cuando se selecciona una provincia, cargamos la lista de municipios
  $('#provincia').change(function() {
    $.get("/ajax/municipios.php", { id: $('#provincia').val() }, function(e) {
      if(e) {
        $('#municipios').html(e);
      }
    } );
  });


  // Formulario de login
  $('#entrar_form input').keypress(function(event){
	  var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	    if (keyCode == 13) {
	        $('#registro_crearcuenta').click();
	        return false;
	    }
  });

  $('#registro_crearcuenta').click(function() {
    $('#login_incorrecto').html('');
    $.post("/ajax/comprobar_login_hogar.php", { mail: $('#mail').val() , pass: $('#pass').val() }, function(e) {
      if(e == "NO_USER"){
        $('#login_incorrecto').html("<span id='span_login_incorrecto'>Usuario no existe</span>");
      }
      else if(e == "OV_USER"){
        $('#login_incorrecto').html("<span id='span_login_incorrecto'>Debe acceder su cuenta desde su oficina virtual.</span>");
        $('.abre-lightbox').click();
      }
      else if(e == "INVALID_PASSWORD"){
          $("#login_incorrecto").html("<span id='span_login_incorrecto'>Password inválido.</span>");
      }
      else{
        $('#entrar_form').submit();
      }
    });
  });



  $('#sesion_caducada').click();


  // FONT SHADOW
  // if (('#claim_hogar').length > 0){
  //
  //   // textshadow plugin get automatically this property in his own css parameter
  //   // if ($("#claim_hogar").find("h3").length > 0) $("#claim_hogar").find("h3").textShadow();
  // }


   // CHANGING BETWEEN MODULES
  if ($('#choose_channel').length > 0) {

      $("#other_el").click(function(e) {
        $(".ui-slider-handle").stop(true,false).animate({left: 0}, 200, function(){
    	    window.location="/es/usuario";
    	  });

    	  $("#other_el").animate({opacity: 0}, 200);

    	});

      $('#choose_channel').slider({
    	     animate:true,
    	     values:[100],
    	     slide: function(e,ui)
    	     {
    	       $("#other_el").css("opacity", ($(".ui-slider-handle").position().left + 34)/100 );
    	     },
    	     stop: function(e,ui)
    	     {
    	       if($(".ui-slider-handle").position().left == 0)
              {
                window.location="/es/usuario";
              }
              else
              {
                $(".ui-slider-handle").animate({left: 66}, 200 );
                $("#other_el").animate({opacity: 1}, 200 );
              }
    	     }

    	     }
    	);
  }

  if (('#claim_hogar').length > 0){
    // textshadow plugin get automatically this property in his own css parameter
    $("#claim_hogar h3").textShadow();
  }


  // Handle click event to delay the stylish customizing actions
  if($('.send_guide_home').length > 0) {
    $('.send_guide_home').click(function(event) {
      setTimeout('$(\'.custom_select\').sSelect({ddMaxHeight: \'160px\'})',750)
    });
  }

}); // DOCUMENT READY

