$(document).ready(setupRoyalSelects);

function setupRoyalSelects() {
   //set SELECTED option if the corresponding formfield has a value
   $('.royal_selectbox').each(function () {
      var jThis = $(this);
      var jOptions = $('.rs_option', jThis);
      var jLabel = $('.rs_label', jThis);

      //get value
      var selectedVal = jThis.next().val();
      var selectedLabel = '';

      //loop options to match value and label the box accordingly
      if (selectedVal != '') {
         jOptions.each(function () {
            if (this.getAttribute('value') == selectedVal) {
               jLabel.html(this.innerHTML);
            }
         });
      }
   });

   // set click event for open/close
   $('.rs_field').click(royalSelectToggleOptions);

   // set click event for an option
   $('.rs_option').click(function () {
      var _val = this.getAttribute('value');
      var _label = this.innerHTML;
      var jInput = $(this).parent().parent().next();
      var royalForm;

      //set form field value and label
      jInput.val(_val);
      $('.rs_label', $(this).parent().prev()).html(_label);

      //trigger auto-submit when class 'rs_directsubmit' is present
      if ($(this).parent().parent().hasClass('rs_directsubmit')) {
         royalForm = jInput.get(0).form;
         if (royalForm) {
            royalForm.submit();
        //    return;
         } 
         else if (this.href != '') {
            location.href = this.href;
            return;
         }
      }

      //kill dropdown on click of option, in context of the rs_field div.
      royalSelectToggleOptions.apply( $(this).parent().prev().get(0) );

      //prevent link event
      return false;
   });

   //close (all) dropdowns on click anywhere.
   $(document).click(function () {
      $('.rs_options').hide();
      $('.rs_arrow').removeClass('rs_arrow_active');
      $('.rs_field').removeClass('rs_field_active');
   });
}
function royalSelectToggleOptions() {
   $(this).toggleClass('rs_field_active');
   $('.rs_arrow', this).toggleClass('rs_arrow_active');
   $(this).next().toggle();

   return false;
}

