function home_itemVisibleInCallback(carousel, item, i, state, evt)
{
    var idx = carousel.index(i, home_itemList.length);
    carousel.add(i, home_getItemHTML(home_itemList[idx - 1]));
};

function home_itemVisibleOutCallback(carousel, item, i, state, evt)
{
    carousel.remove(i);
};

/**
 * Item html creation helper.
 */
function home_getItemHTML(item)
{
    return '<img src="' + item.img + '" width="358" height="268" alt="' + item.tile + '" />';
};

function scrollBg(selector,step,restartPosition){
        if (typeof(current) == 'undefined') current = 0;
	//Go to next pixel row.
	current -= step;
	
	//If at the end of the image, then go to the top.
	if (current == restartPosition){
	  current = 0;
	}
	
	//Set the CSS of the header.
	$(selector).css("background-position","0 "+current+"px");
	
	
}
//Calls the scrolling function repeatedly
$(document).ready(function() {
  setInterval("scrollBg('.download-content.blog',1,-600)", 5);

  $('#mysupercarousel').jcarousel();
  $('#mycarousel').jcarousel();
  if ($('#home-carousel').length != 0 && typeof(home_itemList) != 'undefined')
    $('#home-carousel').jcarousel({
      auto: 2,
      scroll: 1,
      wrap: 'circular',
      itemVisibleInCallback: {onBeforeAnimation: home_itemVisibleInCallback},
      itemVisibleOutCallback: {onAfterAnimation: home_itemVisibleOutCallback},
      buttonNextHTML: null,
      buttonPrevHTML: null
    });
  $('#chantiercarousel').jcarousel({scroll: 1});
  $('.login-container').load('/users/logins');
  $("#project_limit_date_").datepicker({dateFormat:'yy-mm-dd', nextText: 'Suivant', prevText: 'Précédent', monthNames: ['Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Decembre'], dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa']});

  $('.tool-tip').live('click', function(){
    return false;
  });

  $('.tool-tip').each(function(){
    $(this).qtip({
      content: $(this).html(),
      show: 'mouseover',
      hide: 'mouseout',
      position: {
        corner: {
           target: 'topRight',
           tooltip: 'bottomLeft'
        }
      },
      style: {
        padding: 5,
        background: '#FFF',
        color: '#7B746E',
        fontSize: '1.1em',
        textAlign: 'center',
        border: {
           width: 1,
           radius: 5,
           color: '#FF4621'
        },
        tip: 'bottomLeft'
      }
    })
  });

  $('#realisations_filters').find('.children_cat').each(function(){
    if($(this).find('.current').length == 0){
      $(this).hide();
      $(this).find('span:first').addClass('open_me');
      $(this).find('span:first').removeClass('close_me');
    }
    else{
      $(this).parent().find('.open_me:first').each(function(){
        $(this).find('span:first').addClass('close_me');
        $(this).find('span:first').removeClass('open_me');
      });
    }
  });

  $('.open_me').live('click', function(){
    $(this).parent().children('.children_cat').show();
    $(this).addClass('close_me');
    $(this).removeClass('open_me');
  });

  $('.close_me').live('click', function(){
    $(this).parent().children('.children_cat').hide();
    $(this).addClass('open_me');
    $(this).removeClass('close_me');
  });

  $('#project_selection').blur(function(){
    window.location.replace(window.location.pathname+'?project_id='+$(this).val());
  });

  $('.image').find('a').lightBox({
    imageLoading: '/images/front/jquery.lightbox/lightbox-ico-loading.gif',
    imageBtnClose: '/images/front/jquery.lightbox/lightbox-btn-close.gif',
    imageBtnPrev: '/images/front/jquery.lightbox/lightbox-btn-prev.gif',
    imageBtnNext: '/images/front/jquery.lightbox/lightbox-btn-next.gif',
    imageBlank: '/images/front/jquery.lightbox/lightbox-blank.gif'
  });

  $('.question_link').bind('click',function(){
  $(".answers").children().hide();
  $('#answer_'+$(this).attr("id")).show();  
  return false;
  });

  $('.news_link').bind('click',function(){
  $('#actu_current').html($('#content_'+$(this).attr("id")).html())
  $('.news_link').removeClass('current');
  $(this).addClass('current');
  return false;
  });

  $('.pop_link').bind('click',function(){
    alert('Cette fonctionnalité sera bientôt disponible');
    return false;
  });

  if($('.project_types').find('li').length > 0){
    $('.estimate_submit_button').addClass('has_to_be_clicked');
  }
  
  $('.project_type_li').live('click',function(){
    $('#parent_id').val($(this).find('.project_type_id').val());
     $('.project_type_li').each(function(){
       $(this).removeClass('clicked');
       $(this).addClass('no_hover');
     })
    $(this).addClass('clicked');
    $(this).removeClass('no_hover');
    $('.estimate_submit_button').removeClass('has_to_be_clicked');
  });


  $('.standard_materials').live('click',function(){
    $('#standard_materials').val($(this).find('#estimate_materials').val());
     $('.standard_materials').each(function(){
       $(this).removeClass('clicked');
       $(this).addClass('no_hover');
     })
    $(this).addClass('clicked');
    $(this).removeClass('no_hover');
    $('.estimate_submit_button').removeClass('has_to_be_clicked');
  });

  $('#estimate_submit').live('click',function(){
    if($('#parent_id').length>0){
      if($('#parent_id').val()==""){
        alert('vous devez choisir une étape pour continuer');
        return false;
      }
    }
    else if($('#standard_materials').length>0){
      if($('#standard_materials').val()==""){
        alert('vous devez choisir une étape pour continuer');
        return false;
      }
    }
    else if($('#project_id').length>0){
      if($('#project_id').val()==""){
        alert('vous devez choisir une étape pour continuer');
        return false;
      }
    }

    if($('#estimate_measures_type_valuebuilding_permit').is(':checked')){
      if($('#estimate_shob').val()=="0" || $('#estimate_shon').val()=="0" || $('#estimate_shab').val()=="0"){
        alert('Merci de saisir toutes les valeurs');
        return false;
      }
    }
    else if ($('#estimate_measures_type_valueponderated').is(':checked')){
      if($('#estimate_shop').val()=="0" || $('#estimate_shap').val()=="0" || $('#estimate_vhap').val()=="0"){
        alert('Merci de saisir toutes les valeurs');
        return false;
      }
    }
  });


  $('.project_model').live('click',function(){
    $('#project_id').val($(this).find('.project_type_id').val());
     $('.project_model').each(function(){
       $(this).removeClass('clicked');
       $(this).addClass('no_hover');
     })
    $(this).addClass('clicked');
    $(this).removeClass('no_hover');
    $('.estimate_submit_button').removeClass('has_to_be_clicked');
  });


if($('#measures').length>0){
    function calc_shob(){
      var parse_int_value = parseFloat($('#estimate_surface_created').val());
      if(parse_int_value){
        $('#shob_value').html(parse_int_value.toFixed(2)+" m2");
        $('#estimate_shob').val(parse_int_value.toFixed(2));
      }
      else{
        $('#shob_value').html('0.00'+" m2");
        $('#estimate_shob').val('0.00');
      }
    }

    function calc_shon(){
      var shon = 0;
      var parse_int_1 = parseFloat($('#estimate_basement_non_convertible').val());
      if(parse_int_1){
        shon += parse_int_1
      }
      var parse_int_2 = parseFloat($('#estimate_roof_non_convertible').val());
      if(parse_int_2){
        shon += parse_int_2
      }
      var parse_int_3 = parseFloat($('#estimate_balcony').val());
      if(parse_int_3){
        shon += parse_int_3
      }
      var parse_int_4 = parseFloat($('#estimate_parking').val());
      if(parse_int_4){
        shon += parse_int_4
      }

      if(parseFloat($('#estimate_surface_created').val())){
       shon = (parseFloat($('#estimate_surface_created').val()) - shon)*0.95
       $('#shon_value').html(shon.toFixed(2)+" m2");
       $('#estimate_shon').val(shon.toFixed(2));
      }
      else{
        $('#shon_value').html('0.00'+" m2");
        $('#estimate_shon').val('0.00');
        $('#shop_value').html('0.00'+" m2");
        $('#estimate_shop').val('0.00');
      }
      return shon;
    }

    function calc_estimation_shab(){
      var shon = calc_shon();
      var estimation_shab = shon*0.85;
      $('#estimation').html(estimation_shab.toFixed(2)+" m2");
      return estimation_shab;
    }

    function calc_shab(){
      var shab = parseFloat($('#estimate_inner_spaces').val());
      var estimation_shab = calc_estimation_shab();
      if (shab){
        $('#shab_value').html(shab.toFixed(2)+" m2");
        $('#estimate_shab').val(shab.toFixed(2));
      }
      else{
         $('#shab_value').html(estimation_shab.toFixed(2)+" m2");
         $('#estimate_shab').val(estimation_shab.toFixed(2));
      }
    }

    function calc_shop(){
      var shop = 0;
      $('.shop_tr').each(function(){
        var parse_int = parseFloat($(this).find('input').val());
        var pond = $(this).find('.pond').html();
        if(parse_int){
          shop += parse_int*pond
        }
      });
      $('#shop_value').html(shop.toFixed(2)+" m2");
      $('#estimate_shop').val(shop.toFixed(2));
      return shop;
    }


    function calc_shap(){
      var shap = 0;
      $('.shap_tr').each(function(){
        var parse_int = parseFloat($(this).find('input').val());
        var pond = $(this).find('.pond').html();
        if(parse_int){
          shap += parse_int*pond
        }
      });
      $('#shap_value').html(shap.toFixed(2)+" m2");
      $('#estimate_shap').val(shap.toFixed(2));
      return shap;
    }

    function calc_vhap(){
      var vhap = 0;
      var parse_int_surface = parseFloat($('#estimate_vhap_inner_space').val());
      var parse_int_height = parseFloat($('#estimate_vhap_height_space').val());
      if(parse_int_surface && parse_int_height){
          vhap += parse_int_surface*parse_int_height
      }
      $('#vhap_value').html(vhap.toFixed(2)+" m3");
      $('#estimate_vhap').val(vhap.toFixed(2));
      return vhap;
    }

    //Calc system
    //Show the right table
    if($('#estimate_measures_type_valueponderated').is(':checked')){
      $('#ponderated').show();
      $('#building_permit').hide();
    }
    else if($('#estimate_measures_type_valuebuilding_permit').is(':checked')){
      $('#ponderated').hide();
      $('#building_permit').show();
    }
    else{
      $('#estimate_measures_type_valuebuilding_permit').click();
      $('#ponderated').hide();
      $('#building_permit').show();
    }

    $('#estimate_measures_type_valueponderated').click(function(){
      $('#ponderated').show();
      $('#building_permit').hide();
    });

    $('#estimate_measures_type_valuebuilding_permit').click(function(){
      $('#ponderated').hide();
      $('#building_permit').show();
    });



    if(parseInt($('#estimate_surface_created').val())){
      $('#shob_value').html(parseFloat($('#estimate_surface_created').val()).toFixed(2));
      $('#estimate_shob').val(parseFloat($('#estimate_surface_created').val()).toFixed(2));
    }

    $('#estimate_surface_created').keyup(function(){
      calc_shob();
      calc_shon();
      calc_estimation_shab();
      calc_shab();
    });

    $('#measures').find('input[type="text"]').keypress(function (e) {
      if(e.which > 57 || e.which == 44 ) {
        return false;
      }
    });


    $('#shob_value').html(calc_shob());
    $('#estimate_shob').val(calc_shob());
    $('#shon_value').html(calc_shon());
    $('#estimate_shon').val(calc_shon());
    calc_estimation_shab();
    calc_shab();


    $('#estimate_basement_non_convertible').keyup(function(){
      calc_shon();
      calc_estimation_shab();
      calc_shab();
    });
    $('#estimate_roof_non_convertible').keyup(function(){
      calc_shon();
      calc_estimation_shab()
      calc_shab();
    });
    $('#estimate_balcony').keyup(function(){
      calc_shon();
      calc_estimation_shab()
      calc_shab();
    });
    $('#estimate_parking').keyup(function(){
      calc_shon();
      calc_estimation_shab()
      calc_shab();
    });


    $('#estimate_inner_spaces').keyup(function(){
      calc_shab();
    });

    //Calcul for ponderated method
    $('.shop_tr').each(function(){
      $(this).find('input').keyup(function(){
        calc_shop();
      });
    });
    calc_shop();

    $('.shap_tr').each(function(){
      $(this).find('input').keyup(function(){
        calc_shap();
      });
    });
    calc_shap();

    $('.vhap_tr').each(function(){
      $(this).find('input').keyup(function(){
        calc_vhap();
      });
    });
    calc_vhap();
}

  if (jQuery().jqueryzoom) { 
 
    jqzoom_options = {
      xzoom: 300,
      yzoom: 300,
      title: 0, 
      lens: 0
    };
    $('.jqzoom').jqueryzoom(jqzoom_options);

    $('.other_views img').live('click',function(){
      var first_image = $('.jqzoom').find('img');
      var clicked_img = $(this);
      $('.jqzoom').html(clicked_img);
      $('.other_views').append(first_image);
    });
  }
  
  /* Fundings */
  $('#funding').dialog({
    autoOpen: false,
    modal: true,
    width: 900
  });

  $('.funding-link').live('click', function(){
    $('#funding').dialog('open');
    return false;
  });

  $('#funding input').live('keypress', function(e){
    if ((e.which != 8 && e.which != 0) && (e.which < 45 || e.which > 58)) {
      e.preventDefault();
      e.stopPropagation();
    }
  });

  $('#funding .project input').blur(function(){
    var sum = 0;
    $(this).parents('table:first').find('input').each(function(){
      var val = $(this).val();
      if (val != '' && !$(this).hasClass('final')) {
        sum += parseFloat(val);
      }
    });
    $(this).parents('table:first').find('input.final').val(sum.toFixed(2));
  });

  $('#funding .bre input').blur(function(){
    var sum = 0;
    $(this).parents('table:first').find('input.cost').each(function(){
      var val = $(this).val();
      if (val != '' && !$(this).hasClass('final') && !$(this).hasClass('bre')) {
        sum += parseFloat(val);
      }
    });
    $(this).parents('table:first').find('input.final.cost').val(sum.toFixed(2));
    
    var bre = 0;
    var capital = $(this).parents('tr').find('input.cost').val();
    var rate = $(this).parents('tr').find('input.tax').val() || '0.0';
    var month = $(this).parents('tr').find('input.month').val();

    if (capital != '' && month != '') {
      if (parseFloat(rate) != 0.0) {
        var total = (parseFloat(capital) * parseFloat(rate));
        var toto = Math.pow(1+(parseFloat(rate) / 1200),-parseInt(month));
        bre = ( total / 1200) / (1 - toto);
      } else {
        bre = parseFloat(capital) / parseFloat(month);
      }
    }

    $(this).parents('tr:first').find('input.bre').val(bre.toFixed(2));
    sum = 0;
    $(this).parents('table:first').find('input.bre').each(function(){
      var val = $(this).val();
      if (val != '' && !$(this).hasClass('final')) {
        sum += parseFloat(val);
      }
    });
    $(this).parents('table:first').find('input.final.bre').val(sum.toFixed(2));

  });

  $('#funding .bre input.bre').live('keypress', function(e){
    if (e.which != 0){
      e.preventDefault();
      e.stopPropagation();         
    }
  });
  $('#funding').find('input.bre').blur(function(){
    var sum = 0;
  });

  //description lightbox

  $('#dialog').dialog({
      bgiframe: true,
			height: 400,
      width: 400,
			modal: true,
      autoOpen: false,
      buttons:{
        Ok: function() {
					$(this).dialog('close');
        }
      }

  });

  $('.desc_link').live('click', function(){
    $('#dialog').html($(this).parent().find('.desc_hidden').html());
    $('#dialog').dialog('open');
    return false;
  });

  $('#command').dialog({
    autoOpen: false,
    modal: true,
    width: 600,
    title: 'Je commande en ligne'
  });
  
  $('#command-link').live('click', function(){
    $('#command').dialog('open');
    return false;
  });

  $('#video_bourse').live('click',function(){
    $('#video').dialog('open');
    return false;	
  });
 
  $('#video').dialog({
    autoOpen: false,
    modal: true,
    width: 500,
    title: 'Bourse aux travaux'
  });
  
  if($('#player').length > 0){
    $f('player',{src: "/flashes/flowplayer-3.1.4.swf"}) 
  }

  $('#demo').dialog({
    autoOpen: false,
    modal: true,
    width: 500,
    title: "Logique d'utilisation de la bourse aux travaux"
  });

  $('#demo-link').live('click',function(){
	$('#demo').dialog('open');
	return false;
  });
});
