
/**
 * 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');
    // 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();

    // 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 ($) {
Drupal.settings.views = Drupal.settings.views || {'ajax_path': '/views/ajax'};

Drupal.behaviors.quicktabs = {
  attach: function (context, settings) {
    $.extend(true, Drupal.settings, settings);
    $('.quicktabs_wrapper:not(.quicktabs-processed)', context).addClass('quicktabs-processed').each(function(){
      Drupal.quicktabs.prepare(this);
    });
  }
}

Drupal.quicktabs = Drupal.quicktabs || {};

// setting up the inital behaviours
Drupal.quicktabs.prepare = function(el) {
  // el.id format: "quicktabs-$name"
  var name = el.id.substring(el.id.indexOf('-') +1);
  var $ul = $(el).find('ul.quicktabs_tabs:first');
  $ul.find('li a').each(function(){this.name = name}).each(Drupal.quicktabs.initialiseLink);

  // Search for the active tab.
  //var $active_tab = $(el).children('.quicktabs_tabs').find('li.active a');
  //if ($active_tab.hasClass('qt_tab') || $active_tab.hasClass('qt_ajax_tab')) {
  //  $active_tab.trigger('click');
  //}
  //else {
  //  // Click on the first tab.
  //  $(el).children('.quicktabs_tabs').find('li.first a').trigger('click');
  //}
}

Drupal.quicktabs.initialiseLink = function(index, element, tab) {
  if (!element.myTabIndex) {
    element.myTabIndex = index;
  }
  if (!tab) {
    tab = new Drupal.quicktabs.tab(element);
  }
  if (tab.tabpage.hasClass('quicktabs_tabpage') || tab.tabObj.type != 'view') {
    $(element).bind('click', {tab: tab}, Drupal.quicktabs.clickHandler);
  }
  else {
    Drupal.quicktabs.ajaxView(tab, element);
  }
}

Drupal.quicktabs.clickHandler = function(event) {
  var tab = event.data.tab;

  // Set clicked tab to active.
  $(this).parents('li').siblings().removeClass('active');
  $(this).parents('li').addClass('active');

  // Hide all tabpages.
  tab.container.children().addClass('quicktabs-hide');

  // Show the active tabpage.
  if (tab.tabpage.hasClass('quicktabs_tabpage')) {
    tab.tabpage.removeClass('quicktabs-hide');
  }
  else {
    if ($(this).hasClass('qt_ajax_tab')) {
      // construct the ajax path to retrieve the content, depending on type
      var qtAjaxPath = Drupal.settings.basePath + 'quicktabs/ajax/' + tab.tabObj.type + '/';
      switch (tab.tabObj.type) {
        case 'node':
          qtAjaxPath +=  tab.tabObj.nid + '/' + tab.tabObj.teaser + '/' + tab.tabObj.hide_title;
          break;
        case 'block':
          qtAjaxPath +=  tab.name + '/' + tab.tabObj.bid + '/' + tab.tabObj.hide_title;
          break;
        case 'qtabs':
          qtAjaxPath +=  tab.tabObj.machine_name;
          break;
      }

      $.ajax({
        url: qtAjaxPath,
        type: 'GET',
        data: null,
        beforeSend: function (xmlhttprequest) {
          var $progress = $('<div class="ajax-progress ajax-progress-throbber"><div class="throbber">&nbsp;</div></div>');
          $(tab.element).after($progress);
        },
        success: tab.options.success,
        complete: tab.options.complete,
        dataType: 'json'
      });
    }
  }
  return false;
}

// constructor for an individual tab
Drupal.quicktabs.tab = function (el) {
  this.element = el;
  this.tabIndex = el.myTabIndex;
  this.name = el.name;
  var qtKey = 'qt_' + this.name;
  var i = 0;
  for (var key in Drupal.settings.quicktabs[qtKey].tabs) {
    if (i == this.tabIndex) {
      this.tabObj = Drupal.settings.quicktabs[qtKey].tabs[key];
      this.tabKey = key;
    }
    i++;
  }
  this.tabpage_id = 'quicktabs_tabpage_' + this.name + '_' + this.tabKey;
  this.container = $('#quicktabs_container_' + this.name);
  this.tabpage = this.container.find('#' + this.tabpage_id);
  // The 'this' variable will not persist inside of the options object.
  var tab = this;
  this.options = {
    success: function(response) {
      return tab.success(response);
    },
    complete: function(response) {
      return tab.complete();
    }
  }
}

// ajax callback for non-views tabs
Drupal.quicktabs.tab.prototype.success = function(response) {
  this.container.append(Drupal.theme('quicktabsResponse', this, response.data));
  this.tabpage = this.container.find('#' + this.tabpage_id);
  Drupal.attachBehaviors(this.container, response.settings);
}


Drupal.quicktabs.tab.prototype.complete = function() {
  $(this.element).parent().find('.ajax-progress').remove();
}

Drupal.quicktabs.view_dom_id = 0; // keeps track of ids to use for ajax-loaded views

Drupal.quicktabs.ajaxView = function(tab, element) {
  
  var ajax_path = Drupal.settings.views.ajax_path;
   //If there are multiple views this might've ended up showing up multiple times.
  if (ajax_path.constructor.toString().indexOf("Array") != -1) {
    ajax_path = ajax_path[0];
  }
  var args;
  if (tab.tabObj.args != '') {
    args = tab.tabObj.args.join('/');
  } else {
    args = '';
  }
  var dom_id = 0;
  if (Drupal.quicktabs.view_dom_id > 0) {
    dom_id = Drupal.quicktabs.view_dom_id;
  }
  else {
    $('div.view').each(function(){
      var classList = $(this).attr('class').split(/\s+/);
      $.each(classList, function(index, item){
        if (item.match(/^view\-dom-\id\-\d+/)) {
          var this_dom_id = item.split(/\-/)[3];
          if (this_dom_id > dom_id) {
            dom_id = this_dom_id;
          }
        }
      });
    });
  }

  dom_id++;
  Drupal.quicktabs.view_dom_id = dom_id;

  var viewData = {
    'view_name': tab.tabObj.vid,
    'view_display_id': tab.tabObj.display,
    'view_args': args,
    'view_dom_id': dom_id
  }
  tab.dom_id = dom_id;
  var element_settings = {};
  element_settings.url = ajax_path;
  element_settings.event = 'click';
  element_settings.progress = { 'type': 'throbber' };
  element_settings.submit = viewData;
  
  var ajax = new Drupal.ajax(false, element, element_settings);
  // Override HTTP method type and the beforeSerialize and success methods.
  ajax.options.type = 'GET';
  ajax.beforeSerialize = function(element_settings, options) { return; };
  ajax.old_success = ajax.success;
  ajax.success = function(response, status) {
    // Set clicked tab to active.
    $(element).parents('li').siblings().removeClass('active');
    $(element).parents('li').addClass('active');
    tab.container.children().addClass('quicktabs-hide');
    tab.container.append(Drupal.theme('quicktabsResponse', tab, null));
    tab.tabpage = tab.container.find('#' + tab.tabpage_id);
    $(element).unbind();
    this.old_success(response, status);
    Drupal.quicktabs.initialiseLink(element.myTabIndex, element, tab);
  }
}

// theme function for ajax response
Drupal.theme.prototype.quicktabsResponse = function(tab, new_content) {
  var newDiv = tab.tabObj.type == 'view' ? '<div id="' + tab.tabpage_id + '" class="quicktabs_tabpage"><div class="view-dom-id-' + tab.dom_id + '"></div></div>' : '<div id="' + tab.tabpage_id + '" class="quicktabs_tabpage">' + new_content + '</div>';
  return newDiv;
};
})(jQuery);
;
//
// Note: This file depends on the jQuery library.
//

// Module pattern:
// http://yuiblog.com/blog/2007/06/12/module-pattern/
var FORMALIZE = (function($, window, document, undefined) {
	// Private constants.
	var PLACEHOLDER_SUPPORTED = 'placeholder' in document.createElement('input');
	var AUTOFOCUS_SUPPORTED = 'autofocus' in document.createElement('input');
	var WEBKIT = 'webkitAppearance' in document.createElement('select').style;
	var IE6 = !!($.browser.msie && parseInt($.browser.version, 10) === 6);
	var IE7 = !!($.browser.msie && parseInt($.browser.version, 10) === 7);

	// Expose innards of FORMALIZE.
	return {
		// FORMALIZE.go
		go: function() {
			for (var i in FORMALIZE.init) {
				FORMALIZE.init[i]();
			}
		},
		// FORMALIZE.init
		init: {
			// FORMALIZE.init.detect_webkit
			detect_webkit: function() {
				if (!WEBKIT) {
					return;
				}

				// Tweaks for Safari + Chrome.
				$('html').addClass('is_webkit');
			},
			// FORMALIZE.init.full_input_size
			full_input_size: function() {
				if (!IE7 || !$('textarea, input.input_full').length) {
					return;
				}

				// This fixes width: 100% on <textarea> and class="input_full".
				// It ensures that form elements don't go wider than container.
				$('textarea, input.input_full').wrap('<span class="input_full_wrap"></span>');
			},
			// FORMALIZE.init.ie6_skin_inputs
			ie6_skin_inputs: function() {
				// Test for Internet Explorer 6.
				if (!IE6 || !$('input, select, textarea').length) {
					// Exit if the browser is not IE6,
					// or if no form elements exist.
					return;
				}

				// For <input type="submit" />, etc.
				var button_regex = /button|submit|reset/;

				// For <input type="text" />, etc.
				var type_regex = /date|datetime|datetime-local|email|month|number|password|range|search|tel|text|time|url|week/;

				$('input').each(function() {
					var el = $(this);

					// Is it a button?
					if (this.getAttribute('type').match(button_regex)) {
						el.addClass('ie6_button');

						/* Is it disabled? */
						if (this.disabled) {
							el.addClass('ie6_button_disabled');
						}
					}
					// Or is it a textual input?
					else if (this.getAttribute('type').match(type_regex)) {
						el.addClass('ie6_input');

						/* Is it disabled? */
						if (this.disabled) {
							el.addClass('ie6_input_disabled');
						}
					}
				});

				$('textarea, select').each(function() {
					/* Is it disabled? */
					if (this.disabled) {
						$(this).addClass('ie6_input_disabled');
					}
				});
			},
			// FORMALIZE.init.autofocus
			autofocus: function() {
				if (AUTOFOCUS_SUPPORTED || !$(':input[autofocus]').length) {
					return;
				}

				$(':input[autofocus]:visible:first').focus();
			},
			// FORMALIZE.init.placeholder
			placeholder: function() {
				if (PLACEHOLDER_SUPPORTED || !$(':input[placeholder]').length) {
					// Exit if placeholder is supported natively,
					// or if page does not have any placeholder.
					return;
				}

				FORMALIZE.misc.add_placeholder();

				$(':input[placeholder]').each(function() {
					var el = $(this);
					var text = el.attr('placeholder');

					el.focus(function() {
						if (el.val() === text) {
							el.val('').removeClass('placeholder_text');
						}
					}).blur(function() {
						FORMALIZE.misc.add_placeholder();
					});

					// Prevent <form> from accidentally
					// submitting the placeholder text.
					el.closest('form').submit(function() {
						if (el.val() === text) {
							el.val('').removeClass('placeholder_text');
						}
					}).bind('reset', function() {
						setTimeout(FORMALIZE.misc.add_placeholder, 50);
					});
				});
			}
		},
		// FORMALIZE.misc
		misc: {
			// FORMALIZE.misc.add_placeholder
			add_placeholder: function() {
				if (PLACEHOLDER_SUPPORTED || !$(':input[placeholder]').length) {
					// Exit if placeholder is supported natively,
					// or if page does not have any placeholder.
					return;
				}

				$(':input[placeholder]').each(function() {
					var el = $(this);
					var text = el.attr('placeholder');

					if (!el.val() || el.val() === text) {
						el.val(text).addClass('placeholder_text');
					}
				});
			}
		}
	};
// Alias jQuery, window, document.
})(jQuery, this, this.document);

// Automatically calls all functions in FORMALIZE.init
jQuery(document).ready(function() {
	FORMALIZE.go();
});;

