/*
Description: Scripts para el Canal de Eficiencia Energetica en la EMPRESA de Gas Natural Fenosa
*/



// Login header
function loginTop() {
  if($('#entrar_desplegable').css('display') != 'block') {
  	$('#entrar_desplegable').toggle("fast", function(){
  	  $("#entrar").toggleClass('desplegado');
  	  $('#entrar_desplegable').seekAttention({pulse: false});

      $(document).click(function(event) {

                // To change clicked style on country combo
                if (!$(event.target).closest('#entrar_desplegable').length) {
                  $("#entrar_desplegable").toggle('fast');
                  $("#entrar").toggleClass('desplegado');
                  $(document).unbind('click');
                };
              });

  	});
  }
  return false;
}

// Tooltips
function vertooltip(nombreCapa){
  document.getElementById(nombreCapa).style.display="block";
}
function ocultartooltip(nombreCapa){
  document.getElementById(nombreCapa).style.display="none";
}

// Toggle
function slide(obj) {
	$('#'+obj).slideToggle();
	return false;
}

// Notas de barra de estado
function notasDesplegable() {
	$('#mis_notas').toggle("fast", function(){
	  $("#mis_notas_container").toggleClass('desplegado');
	});
  return false;
}

$(document).ready(function () {

	// Desplegable del login de cabecera
	$("#btn_entrar a").click(function() {
		$('#entrar_desplegable').toggle("fast");
		$("#entrar").toggleClass('desplegado');

            $(document).click(function(event) {

              // To change clicked style on country combo
              if (!$(event.target).closest('#entrar_desplegable').length) {
                $("#entrar_desplegable").toggle('fast');
                $("#entrar").toggleClass('desplegado');
                $(document).unbind('click');
              };
            });


		return false;
	});


        //Submit action of login form by pressing enter. Handled by sfGuardAuth/signin
        $('#entrar_form').submit(function(ev) {
            ev.preventDefault();
            ev.stopPropagation();

            var signin = {
                    'username'      : $('#mail').val(),
                    'password'      : $('#pass').val(),
                    'remember'      : $('#remember').attr('checked'),
                    '_csrf_token'   : $('#signin__csrf_token').val()
            };

            $.post($('#entrar_form').attr('action'), { data: signin }, function(response) {
                //The form is not validated
                if (response.error == false){
                        window.location.href = $('#url').attr('innerHTML');
                }
                //User validation succesfuly
                else{
                    //TODO Mostrar estilos de error en el login
                    $('#login_incorrecto span').show();
                }
            });

        });

        //Submit action of login form by clicking on button image.
	$('#registro_crearcuenta').click(function(ev) {
            $('#entrar_form').submit();
	});

	// If user has not logged in, show login form
	if ($("a#comienza_sesion").length!=0) {
		if($('a#comienza_sesion').attr('href')=='') {
			$('a#comienza_sesion').click(function () {
				if($('#entrar_desplegable').css('display') != 'block') {
					$('#entrar_desplegable').toggle("fast", function(){
						$("#entrar").toggleClass('desplegado');
						$('#entrar_desplegable').seekAttention({pulse: false});
					});
				}
				return false;
			});
		}
	}

	// carrusel de destacados
	if ($(".custom_carousel").length!=0) {
		jQuery('.custom_carousel').jcarousel({
			scroll:1,
			auto:10,
	    wrap: 'last'
		});
	}

	$("#enviar_recuperar_pass").click(function() {
           $("#mensaje_recuperar_pass").html('');
           $.get($("#url_recordar_pass").text(), { email: $("#mail_pass").val() }, function(e) {
             if (e) {
               $('#mensaje_recuperar_pass').html("<span id='span_login_incorrecto'>"+e+"</div>");
             }
           });
      });

	//add bubbles
	if ($(".bubblewrap").length!=0) {
			$('ul#destacados').imgbubbles({factor:1.4
		});
	}

	// Acordeon
	if ($(".contenido_acordeon").length!=0) {
				$(".contenido_acordeon").accordion({
				alwaysOpen: false,
				autoheight: false,
				header: 'a.encabezado_acordeon',
				clearStyle: true
		 	});
	}

	// Abrimos lightbox en todos los enlaces con la clase .iframe
	$("a.iframe").fancybox({
            'hideOnContentClick': true,
            'overlayShow' : true,
            'frameWidth' : 900,
            'frameHeight' : 900,
            'onClosed': function() {
            parent.location.reload(true);
            }
	});

        //sesion caducada
        //TODO Control the existence of the link
        //if($("a#sesion_caducada").lenght > 1)

	if ($("a#sesion_caducada").length > 0) {
    $("a#sesion_caducada").fancybox({
     'hideOnContentClick': false,
     'overlayShow' : true,
     'frameWidth' : 600,
     'frameHeight' : 175,
     'easingIn' : 'easeOutBack',
     'easingOut' : 'easeInBack'
    });

    $("a#sesion_caducada").click();

	}

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

	// Lightbox para nuevo negocio
	$("a.nuevo_negocio").fancybox({
		'hideOnContentClick': false,
		'overlayShow' : true,
		'frameWidth' : 600,
		'frameHeight' : 580,
		'easingIn' : 'easeOutBack',
		'easingOut' : 'easeInBack'
	});

	// Lightbox para info auditoria
	$("a.info_auditoria").fancybox({
		'hideOnContentClick': true,
		'overlayShow' : true,
		'frameWidth' : 700,
		'frameHeight' : 580,
		'easingIn' : 'easeOutBack',
		'easingOut' : 'easeInBack'
	});

	// Lightbox para info documentacion
	$("a.info_documentacion").fancybox({
		'hideOnContentClick': true,
		'overlayShow' : true,
		'frameWidth' : 600,
		'frameHeight' : 380,
		'easingIn' : 'easeOutBack',
		'easingOut' : 'easeInBack'
	});

  $("a#asesor_video_link").fancybox({
		'hideOnContentClick': true,
		'overlayShow' : true,
		'frameWidth' : 600,
		'frameHeight' : 400,
		'easingIn' : 'easeOutBack',
		'easingOut' : 'easeInBack'  });

	// Lightbox para nueva industria
	if ($(".nueva_industria").length!=0) {
		$("a.nueva_industria").fancybox({
			'hideOnContentClick': false,
			'overlayShow' : true,
			'frameWidth' : 660,
			'frameHeight' : 570,
			'easingIn' : 'easeOutBack',
			'easingOut' : 'easeInBack'
		});
	}

	// Lightbox para nueva industria
	if ($(".miniicon_industria_mas").length!=0) {
		$("a.miniicon_industria_mas").fancybox({
			'hideOnContentClick': false,
			'overlayShow' : true,
			'frameWidth' : 660,
			'frameHeight' : 570,
			'easingIn' : 'easeOutBack',
			'easingOut' : 'easeInBack'
		});
	}

	// Lightbox for promo
	$(".promo_bbll").fancybox({
		'hideOnContentClick': false,
		'overlayShow' : true,
		'frameWidth' : 660,
		'frameHeight' : 500,
		'easingIn' : 'easeOutBack',
		'easingOut' : 'easeInBack'
	});

	//floating layer (process bar)
	if ($("#ghost").length!=0) {
			var pos=parseInt($(window).scrollTop())+parseInt($(window).height());
			$('#ghost').css("top",pos-60+"px");

			//scroll the ghost
			$(window).scroll(function()
			{
					 var pos=parseInt($(window).scrollTop())+parseInt($(window).height());
					$('#ghost').animate({top:pos-60+"px" },{queue: false, duration: 500});
			});
	}

	// Desplegable de la barra de estado
	if ($(".btn_notas").length!=0) {
		$(".btn_notas").click(function() {
			$('#mis_notas').toggle("fast");
			return false;
		});
	}

  //find all form and apply the select fix ie
	if ($("#tus_datos_form").length!=0) {
		$(function() {
			$("#tus_datos_form").jqTransform();
		});
	}

  //accion del select en herramientas/homeSuccess
	if ($("#selecciona_negocio").length!=0) {
		$("#selecciona_negocio").change(function() {
			this.form.submit();
		});
	}

  // List municipios for selected provincia
	if ($("#uf_hotel_provincia_id").length!=0) {
		$('#uf_hotel_provincia_id').change(function() {
			$.get("/tools/getMunicipios", { id: $('#uf_hotel_provincia_id').val() }, function(e) {
				if(e) {
					$('#uf_hotel_municipio_id').html(e);
					$('#uf_hotel_municipio_id').removeAttr('disabled');
				}
			});
		});
	}

  // sumas en las tablas del report
	if ($("#herramientas_report").length!=0) {
		IdeupMath.observeAndSum('[id^=uf_hotel_electricidad_consumo]', '#total_electricidad_consumo');
		IdeupMath.observeAndSum('[id^=uf_hotel_electricidad_coste]', '#total_electricidad_coste');
		IdeupMath.observeAndSum('[id^=uf_hotel_electricidad_pen_reactiva]', '#total_pen_reactiva');
		IdeupMath.observeAndSum('[id^=uf_hotel_electricidad_pen_potencia]', '#total_pen_potencia');
		IdeupMath.observeAndSum('[id^=uf_hotel_gas_natural_consumo]', '#total_gas_natural_consumo');
		IdeupMath.observeAndSum('[id^=uf_hotel_gas_natural_coste]', '#total_gas_natural_coste');
		IdeupMath.observeAndSum('[id^=uf_hotel_agua_cantidad]', '#total_agua_cantidad');
		IdeupMath.observeAndSum('[id^=uf_hotel_agua_coste]', '#total_agua_coste');
	}

  //dock menu JS options
	if ($("#dock").length!=0) {
					$('#dock').Fisheye(
				{
					maxWidth: 30,
					items: 'a',
					itemsText: 'span',
					container: '.dock-container',
					itemWidth: 175,
					proximity: 30,
					alignment : 'center',
					valign: 'top',
					halign : 'center'
				}
			);
	}


	//TABS
	if ($(".tabs").length!=0) {
	  $(".tab_content").hide();
	    $("ul.tabs li:first").addClass("active").show();
	    $(".tab_content:first").show();

	    $("ul.tabs li").click(function()
	      {
        $("ul.tabs li").removeClass("active");
        $(this).addClass("active");
        $(".tab_content").hide();

        var activeTab = $(this).find("a").attr("href");
        $(activeTab).fadeIn();
        return false;
    });
	}



	// toggled slides
	if ($(".slide").length > 0){

		$(".slide").click(function(){

			var ruta = $(this).find("a").attr("href");

			$(ruta).slideToggle("fast");

			$(this).toggleClass("active"); return false;

		});

	}

	if ($('a.login_request').length > 0){
	  $('a.login_request').click(function(ev){
      ev.preventDefault();
      if($('#entrar_desplegable').css('display') != 'block') {
        $('#entrar_desplegable').toggle("fast", function(){
          $("#entrar").toggleClass('desplegado');
          $('#entrar_desplegable').seekAttention({pulse: false});
          $('#mail').focus();

           $(document).click(function(event) {

              // To change clicked style on country combo
              if (!$(event.target).closest('#entrar_desplegable').length) {
                $("#entrar_desplegable").toggle('fast');
                $("#entrar").toggleClass('desplegado');
                $(document).unbind('click');
              };
            });

        });
      }

	  });
	}

});

$(window).resize(function () {

	//floating layer (process bar)
	if ($("#ghost").length!=0) {
			var pos=parseInt($(window).scrollTop())+parseInt($(window).height());
			$('#ghost').css("top",pos-60+"px");

			//scroll the ghost
			$(window).scroll(function()
			{
					 var pos=parseInt($(window).scrollTop())+parseInt($(window).height());
					$('#ghost').animate({top:pos-60+"px" },{queue: false, duration: 500});
			});
	}
});



