
/**
 * JavaScript behaviors for the front-end display of webforms.
 */

(function ($) {

Drupal.behaviors.webform = Drupal.behaviors.webform || {};

Drupal.behaviors.webform.attach = function(context) {
  // Calendar datepicker behavior.
  Drupal.webform.datepicker(context);
};

Drupal.webform = Drupal.webform || {};

Drupal.webform.datepicker = function(context) {
  $('div.webform-datepicker').each(function() {
    var $webformDatepicker = $(this);
    var $calendar = $webformDatepicker.find('input.webform-calendar');
    var startDate = $calendar[0].className.replace(/.*webform-calendar-start-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-');
    var endDate = $calendar[0].className.replace(/.*webform-calendar-end-(\d{4}-\d{2}-\d{2}).*/, '$1').split('-');
    var firstDay = $calendar[0].className.replace(/.*webform-calendar-day-(\d).*/, '$1');
console.log(startDate);
    // Convert date strings into actual Date objects.
    startDate = new Date(startDate[0], startDate[1] - 1, startDate[2]);
    endDate = new Date(endDate[0], endDate[1] - 1, endDate[2]);

    // Ensure that start comes before end for datepicker.
    if (startDate > endDate) {
      var laterDate = startDate;
      startDate = endDate;
      endDate = laterDate;
    }

    var startYear = startDate.getFullYear();
    var endYear = endDate.getFullYear();

    console.log(startDate);
    console.log(endDate);
    // Set up the jQuery datepicker element.
    $calendar.datepicker({
      dateFormat: 'yy-mm-dd',
      yearRange: startYear + ':' + endYear,
      firstDay: parseInt(firstDay),
      minDate: startDate,
      maxDate: endDate,
      onSelect: function(dateText, inst) {
        var date = dateText.split('-');
        $webformDatepicker.find('select.year, input.year').val(+date[0]);
        $webformDatepicker.find('select.month').val(+date[1]);
        $webformDatepicker.find('select.day').val(+date[2]);
      },
      beforeShow: function(input, inst) {
        // Get the select list values.
        var year = $webformDatepicker.find('select.year, input.year').val();
        var month = $webformDatepicker.find('select.month').val();
        var day = $webformDatepicker.find('select.day').val();

        // If empty, default to the current year/month/day in the popup.
        var today = new Date();
        year = year ? year : today.getFullYear();
        month = month ? month : today.getMonth() + 1;
        day = day ? day : today.getDate();

        // Make sure that the default year fits in the available options.
        year = (year < startYear || year > endYear) ? startYear : year;

        // jQuery UI Datepicker will read the input field and base its date off
        // of that, even though in our case the input field is a button.
        $(input).val(year + '-' + month + '-' + day);
      }
    });

    // Prevent the calendar button from submitting the form.
    $calendar.click(function(event) {
      $(this).focus();
      event.preventDefault();
    });
  });
}

})(jQuery);;
(function ($) {
  function ctm_hide_loader(element) {
    $(element).next('.ctm-ajax-loader').hide();
  }

  function ctm_show_loader(element) {
    $(element).next('.ctm-ajax-loader').show();
  }

  function ctm_add_loader(element) {
    var $e = $(element);

    // Check for an existing loader...
    if ($e.next('.ctm-ajax-loader').size() == 1) {
      return;
    }

    // Create the loader
    var $loader = $('<img src="' + Drupal.settings.ctm_ajax_loader + '" class="ctm-ajax-loader" />');
    
    // Find the position...
    var eOffset = $e.position();
    var eWidth = $e.width();
    var eHeight = $e.height();

    // Position the spinner
    $loader.css({
      top: eOffset.top + ((eHeight - 32) / 2),
      left: eOffset.left + ((eWidth - 32) / 2)
    });

    // Insert the loader...
    $loader.hide().insertAfter($e);
  }

  Drupal.behaviors.checkout_theme_module = {
    attach: function (context, settings) {
      $(':input[readonly=readonly]').css('color', '#666');
      
      $('.edit-basket-contents a').click(function(event) {
        event.preventDefault();

        // Wrap the block so we can replace its contents if needed...
        var wrapper_id = 'checkout-theme-module-cart-summary-ajax';
        if ($('#' + wrapper_id).size() == 0) {
          $wrapper = $('<div id="checkout-theme-module-cart-summary-ajax"></div>');
          $('#block-checkout-theme-module-cart-summary').wrap($wrapper);
        }

        // Add the loader here so it goes next to the wrapper
        ctm_add_loader($('#' + wrapper_id));

        // We want to track this...
        if (typeof(_gaq) != 'undefined') {
          _gaq.push(['_trackEvent', 'EditBasketContents', 'Click']);
        }

        // Open the cart page in Shadowbox... onClose we refresh the block
        // so that the cart contents is up to date
        Shadowbox.open({
          content: Drupal.settings.basePath + 'cart_summary',
          player: 'iframe',
          height: 540,
          width: 900,
          title: Drupal.t('Edit basket contents'),
          options: {
            onClose: function(ele) {
              // Show the loader
              ctm_show_loader($('#' + wrapper_id));

              $('#' + wrapper_id).css('opacity', 0.25).load(Drupal.settings.basePath + 'checkout_theme_module/cart_summary_ajax', function() {
                // Hide the loader + restore opacity
                ctm_hide_loader($('#' + wrapper_id));
                $('#' + wrapper_id).css('opacity', 1);

                Drupal.attachBehaviors($('#' + wrapper_id));
              });
            }
          }
        });
      });

      $('input.password-field', context).once('checkout-password', function () {
        var passwordInput = $(this);
      
        // Remove the keyup/focus/blur event handlers
        passwordInput.unbind('keyup').unbind('focus').unbind('blur');

        // Remove the password strength stuff
        $('.password-strength').remove();
      });

      // Add some 'next' buttons to the fieldsets...
      var i = 1;
      $('form[id^="commerce-checkout-form-checkout"] > div > fieldset.collapsible').once('checkout-theme', function() {
        var $fieldset = $(this);

        // Add the next button if it's not the last fieldset...
        if ($fieldset.next('fieldset.collapsible').size() != 0) {
          var $next = $('<span class="checkout-next-fieldset">' + Drupal.t('Next') + '</span>');
          $fieldset.find('> .fieldset-wrapper').append($next);
        }

        // Collapse the fieldset if it's not the first... and it has no errors
        if (i == 1 && $fieldset.is('.collapsed')) {
          $('> .fieldset-wrapper', $fieldset).show();
          $fieldset.removeClass('collapsed')
                   .trigger({ type: 'collapsed', value: false })
                   .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide'));
        }
        else if (i > 1 && !$fieldset.is('.collapsed')) {
          if ($fieldset.find('.error').size() == 0) {
            Drupal.toggleFieldset($fieldset);
          }
        }

        // Remove the invisible elements
        $fieldset.find('> legend .element-invisible').remove();

        // Number the legends...
        var $title = $fieldset.find('> legend .fieldset-title');
        $title.text(i + ". " + $title.text());

        // Add the up/down chevron
        $chevron = $('<span class="up-down-chevron"></span>');
        $chevron.click(function(event) {
          event.preventDefault();
          $(this).parent().find('.fieldset-title').click();
        })
        $fieldset.find('> legend').append($chevron);

        i++;
      });

      // Add the click handler for the next buttons
      $('form#commerce-checkout-form-checkout span.checkout-next-fieldset').once('checkout-theme', function() {
        $(this).click(function(event) {
          event.preventDefault();

          $my_fieldset = $(this).parents('fieldset.collapsible');
          $next_fieldset = $my_fieldset.next('fieldset.collapsible');
        
          Drupal.toggleFieldset($my_fieldset);
          if ($next_fieldset.is('.collapsed')) {
            Drupal.toggleFieldset($next_fieldset);
          }
        });
      });
    }
  }
})(jQuery);
;

