$(document).ready(function($) {
    $('#accommodationSearchBox').accommodationSearch();
});

(function( $ ) {
  $.fn.accommodationSearch = function() {
    var AS_SLIDETIME = 500;
    var AS_ROOT = this;
    
    AS_ROOT.find('.unit>.form').hide();    
    AS_ROOT.find('.unit').each(function(index) {
        var section = $(this);
        
        if(section.hasClass('enforced')) {
          ToggleSection(section, false);
        }
        else if(section.hasClass('active')) {
          ToggleSection(section, false);
        }
        
        section.find('.header').click(function(e) {
          e.preventDefault();
          ToggleSection(section, true);
        });
    });
    
    //ToggleSection
    function ToggleSection(elm, isClicked) {
      var isActive = elm.hasClass('active');
      var isEnforced = elm.hasClass('enforced');
      //Set forced sections to allways be opened
      if(isEnforced) {
        slideDown(elm.find('.form'));
      }
      
      //Actions for non forced
      if(!isEnforced) {
        if(isClicked) {
          //Slide up element
          if(isActive) {
            elm.removeClass('active');
            slideUp(elm.find('.form'));
          }

          //Slide down element
          if(!isActive) {
            //Clear other elements
            closeSections();
            elm.addClass('active');
            slideDown(elm.find('.form'));
          }
        }
        else {          
          slideDown(elm.find('.form'));
        }
      }
    }
    
    //close other sectons
    function closeSections() {
      AS_ROOT.find('.unit').each(function(index) {
        var section = $(this);
        if(section.hasClass('active')) {
          section.removeClass('active');
          slideUp(section.find('.form'));
        }
      });
    }
    //SlideDown
    function slideDown(elm) {
      elm.slideDown(AS_SLIDETIME);
    }
    //SlideUp 
    function slideUp(elm) {
      elm.slideUp(AS_SLIDETIME);
    }
  };
})( jQuery );
