/*
 * Some JS for gratis_immo.ch
 * Autor: Simon Perdrisat from cloud33.com for hallion.net
 * Please feel free to read it and use this code
 */


if (Drupal.jsEnabled) {
  $(document).ready(function() {
    initialise();
    function initialise(){
      ///////PAGE ADD OR EDIT
	$('#edit-field-property-agent-name-0-value-wrapper').hide();
	$('#edit-field-property-agent-phone-0-value-wrapper').hide();
	$('#edit-field-property-agent-email-0-value-wrapper').hide();

      if($('#edit-field-property-street-nbr-0-value').length){
        nbrPieceSlide()
        priceChargeSlide();
        //cache ville + computed field
        $('#edit-field-computed-address-0-value-wrapper').hide();
        $('#edit-field-property-country-0-value').attr("disabled", true);
        computedAddress();
        //ROOMS
        $('#edit-field-property-type-value').change(function(){
          nbrPieceSlide();
        });
        //CHARGE
        $('#edit-field-property-contract-value-23').change(function(){
          priceChargeSlide();
        });
        $('#edit-field-property-contract-value-22').change(function(){
          priceChargeSlide();
        });
      }
      
      //////PAGE SEARCH BOX
      if($('#block-gratis_search').length){
        //Center content
        content_auto_center();
        //Event clic on each bloc
        $('#content div.view-content div.views-row:not(.inline-ads)').each(function (i) {
          $(this).bind('click.openajax',function(event){
            node_click(event,$(this));
          });
        });
        //HASH redirection or opening
        var hash = window.location.hash;
        if(hash.length){
          hash = hash.substr(6, hash.length);
          if($('#' + hash).length){
            $('#' + hash).parent().parent().parent().parent().trigger('click.openajax');
          }else{
            //redirection directement sur le node
            hash = hash.replace("-", "/");
            window.location.replace(Drupal.settings.basePath + hash);
          }
        }
        
        //Auto center compatible with IE...
        var resizeTimer = null;
        $(window).bind('resize', function() {
          if (resizeTimer) clearTimeout(resizeTimer);
          resizeTimer = setTimeout(windows_rezizzze, 120);
        });
      }
    }
    //Center content
    function windows_rezizzze(){
      content_auto_center();
    //ajax_node_close();
    }
    function content_auto_center(){
      $('#content').css('margin','auto');
      var page_with = $('#page').width();
      var block_widht = 256;
      var content_width = page_with - (page_with % block_widht);
      $('#content').width(content_width);
      $('#content').css('position','relative');
    }
    //NODE AJAX LOAD
    function node_click(event,element){
      event.preventDefault();
      var element_node_id = $('.views-field-title span.field-content a span',element).attr('id');
      window.location.hash = 'view-' + element_node_id;
      if(element.attr('id') != 'ajax-processed'){ //Ce node n'est pas déjà ouvert'
        ajax_node_close();
        ajax_node_open(element);
        //Google analitics
        var element_path = element_node_id.replace("-", "/");
        element_path = '/' + element_path;
        pageTracker._trackPageview(element_path);
      }
    }

    function ajax_node_open(element){
      element.unbind('click.openajax');
      element.attr("id", "ajax-processed"); 
      element.wrapInner("<div id='teaser_content'></div>");
      $('#teaser_content').fadeOut();
      var node_path = $('div.views-field-title a',element).attr('href');
      node_path = node_path + '?ajax=1';
      $.get(node_path,
        function(data){
          $('#teaser_content').hide();
          $('#ajax-processed').append(data);
          $('#ajax-processed').css('position','absolute').after('<div id="spacer" class="views-row hidden">&nbsp;</div>');
          
          $('#spacer').css( 'visibility', 'hidden');
          var spacer_position = $('#spacer').position();
          $('#ajax-processed').css('top',spacer_position.top + 'px').css('z-index',1000);
          //ouverture à gauche ou à droite
          if((spacer_position.left + $('#spacer').outerWidth(true)) >= $('#content').width()){
            $('#ajax-processed').css('right','0');
          }else{
            $('#ajax-processed').css('left',spacer_position.left + 'px');
          }
          //run gmap setup if we have a gmap
          //Drupal.auto1map.behavior.nomousezoom = 'true';
          ///Drupal.behaviors.GMap take more time so we directly use gmap setup
          if($('#ajax-processed .gmap-control').length){
            $('#ajax-processed .gmap-control:not(.gmap-processed)').addClass('gmap-processed').each(Drupal.gmap.setup);
          }

          var ajax_content_height = $('#ajax_content').height();
          
          $('#ajax_content').hide();
          $('#ajax_content').fadeIn();
          $("#ajax-processed").animate({
            width: '464px',
            height: ajax_content_height
          }, 180,'swing',content_height_adjust );
          //
          //Scroll
          var target = $('#ajax_content');
          if (target.length){
            var top = target.offset().top - 40;
            $('html,body').animate({
              scrollTop: top
            }, 200,'swing');
          }
          //
          //
          //close button
          $('#ajax_content div.ajax_content_close_window').click(function(){
            ajax_node_close();
          });
          //Run ajax
          Drupal.Ajax.init();
          
        });

    }

    function content_height_adjust(){
      $('#content div.view-content').height($(document).height()-550);
    }
    function ajax_node_close(){
      if($("#ajax-processed").length){ //il y a quelque chose à fermer?
        //unload gmap
        if($('#ajax-processed .gmap-control').length){
          var mapdomid = $('#ajax_content .gmap-control').attr("id");
          var mapid = 'auto1map';
          delete Drupal.settings.gmap[mapid];
          Drupal.gmap.unloadMap(mapid); // This makes gmap forget the map state.
          $('#' + mapdomid).removeClass('gmap-processed').empty(); // This should reset the DOM hopefully
          $('#' + mapdomid).removeAttr('id');
        }
        $('#ajax_content').remove();
        $('#teaser_content').replaceWith($('#teaser_content').html());
        $("#ajax-processed").animate({
          width: '208px',
          height: '340px'
        }, 180,'swing', function(){
          $('#spacer').remove();
          //$(this).css('position','relative').css('z-index','').css('width','').css('height','');
          $(this).removeAttr('style');
          $(this).bind('click.openajax',function(event){
            node_click(event,$(this));
          });
          $('#content div.view-content').height('auto');
        });
        $('#ajax-processed').removeAttr('id');
      }
    }


    /**
   * Ajax Forms plugin for contactNodeAuthor
   *
   * @param {String} hook
   * @param {Object} args
   * @return {Bool}
   */
    Drupal.Ajax.plugins.contactNodeAuthor = function(hook, args) {
      // var tb_init_original;
      if (hook === 'scrollFind') {
        return false;
      }
      if (hook === 'message') {
        $('#contact-node-author-form-inwrap').fadeOut("slow");
      }
      return true;
    }
    /* --END-- Search */

    /* --START-- ADD and EDIT form */
    function nbrPieceSlide(){
      var idTypeNoRooms = ['27','42','43','52','28','44','46','47','48','49'];
      var value = $("#edit-field-property-type-value option:selected").val();
      if(jQuery.inArray(value,idTypeNoRooms) != -1){
        //cache
        $('#edit-field-property-rooms-nbr-value-wrapper').slideUp(300);
        $('#edit-field-property-rooms-nbr-value option:eq(24)').show();
        $('#edit-field-property-rooms-nbr-value option:eq(24)').attr("selected", "selected");
      }else{
        //montre
        if($("#edit-field-property-rooms-nbr-value option:eq(24):selected").val()){
          $("#edit-field-property-rooms-nbr-value option:eq(0)").attr("selected", "selected");
        }
        //cache 20 pièces
        $('#edit-field-property-rooms-nbr-value option:eq(24)').hide();
        $('#edit-field-property-rooms-nbr-value-wrapper').slideDown(300);
      }
    }

    function priceChargeSlide(){
      //23=rent 22= sell
      if($('#edit-field-property-contract-value-23:checked').val()){
        $('#edit-field-property-charges-0-value-wrapper').slideDown(300);
      }else{
        $('#edit-field-property-charges-0-value-wrapper').slideUp(300);
        $('#edit-field-property-charges-0-value').val('0.00');
      }
    }

    /*Compute address into one texfield so geocode can use it (yes durty)*/
    function computedAddress(){
      $('#node-form').submit(function() {
        if($("#edit-field-computed-address-0-value").length){
          $('#edit-field-property-country-0-value').attr("disabled", false);
          //compute!
          var concatenedAddress = '';
          $("#node-form fieldset.group-address input").each(function(){
            if($(this).val() != ''){
              concatenedAddress += $(this).val() + ', ';
            }
          });
          $("input#edit-field-computed-address-0-value").val(concatenedAddress);
        }
        return true;
      });
    }
  /* --END-- add and edit form */

  });
}
