/*
 * jQuery Fraction Slider v0.6
 * http://fractionslider.jacksbox.de
 *
 * Author: Mario Jäckle
 * eMail: support@jacksbopx.de
 *
 * Copyright 2013, jacksbox.design
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 */


(function($) {
	
	/** ************************* **/
	/** SLDIER CLASS  **/
	/** ************************* **/
	
	// here happens all the fun
	var FractionSlider = function(element, options){
		
		var vars = {
			init: true, 			// initialised the first time
			running:false,			// currently running
			controlsActive:true,	// currently running
			currentSlide: 0,		// current slide number
			maxSlide: 0,			// max slide number
			currentStep: 0,			// current step number
			maxStep: 0,				// current slide number
			currentObj: 0,			// curent object number (in step)
			maxObjs: 0,				// max object number (in step)
			finishedObjs: 0			// finsihed objects (in step)
		};
		var timeouts = [];
		
		var fractionObjs = null; 	// objs for current step
		
		var	slider = $(element),
			pager = null; 	// the slider element
		
		vars.maxSlide = slider.children('.slide').length - 1;
		
		// some more needed vars
		var sliderWidth = slider.width();
		var bodyWidth = $('body').width();
		var offsetX = (bodyWidth-sliderWidth)/2;
		if(options['fullWidth']){
			sliderWidth = bodyWidth;
		}
		var sliderHeight = slider.height();
		
		init();
		
		/** ************************* **/
		/** FUNCTIONS **/
		/** ************************* **/
		
		function init(){
			// some basic stuff
			slider.addClass('fraction-slider');
			
			if(options['controls']){
				slider.append('<a href="#" class="prev"></a><a href="#" class="next" ></a>');
				
				slider.find('.next').bind('click', function(){return nextBtnPressed()
				})
				slider.find('.prev').bind('click', function(){return prevBtnPressed()});
			}
			
			if(options['pager']){
				pager = $('<div class="fs-pager-wrapper"></div>');
				slider.append(pager);
			}

			if(options['fullWidth']){
				slider.css({'overflow': 'visible'});
			}else{
				slider.css({'overflow': 'hidden'});
			}
			
			slider.children('.slide').each(function(index){
				var slide = $(this);
				slide.children().attr('rel', index);
				if(options['pager']){
					pager.append('<a rel="'+index+'" href="#"></a>');
				}	
			});
			
			if(options['pager']){
				pager = $(pager).children('a');
				pager.bind('click', function(){return pagerPressed(this)});
			}
			
			// all importent stuff is done, everybody has taken a shower, we can go
			// starts the slider and the slide rotation
			slideRotation();
		}
		
		function pagerPressed(el){
			if(vars.controlsActive){
				vars.controlsActive = false;
				stopTimeouts();
				slider.find('.slide *').stop(true, true);
			
				endSlide(vars.currentSlide);
				
				vars.currentSlide = $(el).attr('rel');
				
				vars.currentStep = 0;
				vars.maxStep = 0;
				vars.currentObj = 0;
				vars.maxObjs = 0;
				vars.finishedObjs = 0;
				
				// console.log('prev '+vars.currentSlide);
				startSlide();
			}
			
			return false;
		}
		
		function prevBtnPressed(){
			if(vars.controlsActive){
				vars.controlsActive = false;
				stopTimeouts();
				slider.find('.slide *').stop(true, true);
				
				endSlide(vars.currentSlide);
				
				vars.currentSlide--;
				
				vars.currentStep = 0;
				vars.maxStep = 0;
				vars.currentObj = 0;
				vars.maxObjs = 0;
				vars.finishedObjs = 0;
				
				if(vars.currentSlide < 0){
					vars.currentSlide = vars.maxSlide;
				}
				// console.log('prev '+vars.currentSlide);
				startSlide();
			}
			
			return false;
		}
		function nextBtnPressed(){
			if(vars.controlsActive){
				vars.controlsActive = false;
				stopTimeouts();
				slider.find('.slide *').stop(true, true);
				
				endSlide(vars.currentSlide);
				
				vars.currentSlide++;
			
				vars.currentStep = 0;
				vars.maxStep = 0;
				vars.currentObj = 0;
				vars.maxObjs = 0;
				vars.finishedObjs = 0;
				
				if(vars.currentSlide > vars.maxSlide){
					vars.currentSlide = 0;
				}
				// console.log('next '+vars.currentSlide);
				startSlide();
			}
			
			return false;
		}
		
		function stopTimeouts(){
			var length = timeouts.length;
			$.each(timeouts,function(index){
				clearTimeout(this);
				if(index == length-1){
					timeouts = [];
				}
			});
		}
		
		function slideRotation(){
			// set timeout | first slide instant start
			if(vars.init){
				var timeout = 0;
				vars.init = false;
			}else{
				var timeout = options['timeout'];
				vars.init = false;
			}
			
		    // console.log('TIMEOUT');
			// timeout after slide is complete	
			timeouts.push(setTimeout(function(){
					// console.log('slide change:');
					
					// stops the slider after first slide (only when slide count = 1)
					if(vars.maxSlide == 0 && vars.running == true){
						// TODO: better solution!
					}else{
						endSlide(vars.currentSlide-1);
						startSlide();
						vars.running = true;
					}
				}, 
				timeout
			));
		}
		
		// starts a slide
		function startSlide(){
			if(options['pager']){
				pager.removeClass('active');
				pager.eq(vars.currentSlide).addClass('active');
			};
			
			if(options['backgroundAnimation']){
				backgroundAnimation()
			};
			
			var slideObj = slider.children('.slide:eq('+vars.currentSlide+')');
			
			if(slideObj.length == 0){
				vars.currentSlide = 0;
				slideObj = slider.children('.slide:eq('+vars.currentSlide+')');
			}
			// console.log(' start slide: '+vars.currentSlide);
			
			getStepsForSlide();
			
			slideObj.show();
			slideObj.children().hide();
			
			vars.currentObj = 0;
			vars.maxObjs = 0;
			vars.finishedObjs = 0;
			
			iterateSteps();
		}
		
		// ends a slide
		function endSlide(slide){
			if(slide < 0){
				return;
			}
			var slideObj = slider.children('.slide:eq('+slide+')');
			
			// console.log(' end slide: '+slide);
			
			var objs = slideObj.children();
			
			objs.each(function(){
				var obj = $(this);
				var position = obj.position();
				var transition = obj.attr("data-out");
				var easing = obj.attr("data-ease-out");
				
				if(transition == null){
					transition = options['transitionOut'];
				}
				
				if(easing == null){
					easing = options['easeOut'];
				}
				
				moveObjectOut(obj, position, transition, easing);
			}).promise().done(function(){
				slideObj.hide(); 
				vars.controlsActive = true;
			});
		}
		
		// gets the maximum step for the current slide
		function getStepsForSlide(){
			var objs = slider.children('.slide:eq('+vars.currentSlide+')').children();
			var maximum = 0;
			
			objs.each(function() {
			  var value = parseFloat($(this).attr('data-step'));
			  maximum = (value > maximum) ? value : maximum;
			});
			
			vars.maxStep = maximum;
			// console.log('  max steps: '+ vars.maxStep);
		}
		
		/** SLIDE TIMELINE **/
		function iterateSteps(){
			
			if(vars.currentStep == 0){
				var objs = slider.children('.slide:eq('+vars.currentSlide+')').children('*:not([data-step]), *[data-step="'+vars.currentStep+'"]');
			}else{
				var objs = slider.children('.slide:eq('+vars.currentSlide+')').children('*[data-step="'+vars.currentStep+'"]');
			}
			
			vars.maxObjs = objs.length;
			
			fractionObjs = objs;
			
			if(vars.maxObjs > 0){
				
				vars.currentObj = 0;
				vars.finishedObjs = 0;
				
				iterateObjs();
			}else{	
				slider.trigger('fraction:stepFinished');
			}
		}
		
		function iterateObjs(){
			var obj = $(fractionObjs[vars.currentObj]);

			var position = obj.attr("data-position").split(',');
			var transition = obj.attr("data-in");
			var delay = obj.attr("data-delay");
			var speed = obj.attr('data-speed');
			var easing = obj.attr('data-ease-in');
			// check for special options
			var special = obj.attr("data-special");
			
			if(position == null){
				position = options['position'].split(',');
			}
			if(transition == null){
				transition = options['transitionIn'];
			}
			if(delay == null){
				delay = options['delay'];
			}
			if(easing == null){
				easing = options['easeIn'];
			}
			moveObjectIn(obj, position, transition, delay, speed, easing, special);
			
			vars.currentObj++;
			
			if(vars.currentObj < vars.maxObjs){
				iterateObjs();
			}else{
				vars.currentObj = 0;
			}
		}
		
		function objFinished(obj){
			if(obj.attr('rel') == vars.currentSlide){
				vars.finishedObjs++;

				//console.log('  finished: '+vars.finishedObjs +"/"+ vars.maxObjs + ' - ' + vars.currentSlide + "/"+obj.attr('rel'));
				//console.log($(obj));

				if(vars.finishedObjs == vars.maxObjs){
					slider.trigger('fraction:stepFinished');
				}	
			}
		}
		
		slider.bind('fraction:stepFinished', function(){
			vars.currentStep++
			if(vars.currentStep > vars.maxStep){
				if(options['autoChange']){
					vars.currentSlide++;
					vars.currentStep = 0;

					slideRotation();
				}
				
				return;
			}
			iterateSteps();
		});
		
		/** ************************* **/
		/** TRANSITIONS **/
		/** ************************* **/
		
		/** IN TRANSITION **/
		function moveObjectIn(obj, position, transition, delay, speed, easing, special){
			var startY = null;
			var startX = null;
			var targetY = null;
			var targetX = null;
			
			// set start position
			switch(transition){
				case 'left':
					startY = position[0];
					startX = sliderWidth;
					break;
				case 'bottomLeft':
					startY = sliderHeight;
					startX = sliderWidth;
					break;
				case 'topLeft':
					startY = obj.outerHeight()*-1;
					startX = sliderWidth;
					break;
				case 'top':
					startY = obj.outerHeight()*-1;
					startX = position[1];
					break;
				case 'bottom':
					startY = sliderHeight;
					startX = position[1];
					break;
				case 'right':
					startY = position[0];
					startX = 0 - offsetX- obj.outerWidth();
					break;
				case 'bottomRight':
					startY = sliderHeight;
					startX = 0 - offsetX- obj.outerWidth();
					break;
				case 'topRight':
					startY = obj.outerHeight()*-1;
					startX = 0 - offsetX- obj.outerWidth();
					break;
			}
			
			// set target position
			targetY = position[0];
			targetX = position[1];
			
			if(speed == null){
				speed =options['speedIn'];
			}else{
				speed = parseInt(speed);
			}
			
			// set the delay
			timeouts.push(setTimeout(function(){
				// for special=cylce 
				if(special == 'cycle' && obj.attr('rel') == vars.currentSlide){
					var tmp = obj.prev();
					if(tmp.length > 0){
						var tmpPosition = $(tmp).attr('data-position').split(',');
					    	tmpPosition = {'top':tmpPosition[0],'left':tmpPosition[1]};
						var tmpTransition = $(tmp).attr('data-out');
							if(tmpTransition == null){
								tmpTransition = options['transitionOut'];
							}
						moveObjectOut(tmp, tmpPosition, tmpTransition, speed);
					}
				}
				
				if(transition == 'fade'){
					 obj.css({"top": targetY+"px", "left": targetX+"px"})
						.fadeIn(speed, 
				   		 function(){
				   		 	objFinished(obj);
				   		 	}
						)
						.addClass('fs_obj_active');					
				}else if(transition == 'none'){
					// no animation
					 obj.css({"top": targetY+"px", "left": targetX+"px"})
						.show(0, 
				   		 function(){
				   		 	objFinished(obj);
				   		 	}
						)
						.addClass('fs_obj_active');
				}else{
					// animate
					obj.css({"top": startY+"px", "left": startX+"px"})
					   .show()
					   .animate({"top": targetY+"px", "left": targetX+"px"}, 
					   		 speed, 
					   		 easing, 
					   		 function(){
					   		 	objFinished(obj);
					   		 	}
					   		)
					   .addClass('fs_obj_active');	
				}
			},delay));
		}
		
		/** OUT TRANSITION **/
		function moveObjectOut(obj, position, transition, speed, easing){
			var targetY = null;
			var targetX = null;
			
			// set target position
			switch(transition){
				case 'left':
					targetY = position['top'];
					targetX = 0 - offsetX - 100 - obj.outerWidth();
					break;
				case 'bottomLeft':
					targetY = sliderHeight;
					targetX = 0 - offsetX - 100 - obj.outerWidth();
					break;
				case 'topLeft':
					targetY = obj.outerHeight()*-1;
					targetX = 0 - offsetX - 100 - obj.outerWidth();
					break;
				case 'top':
					targetY = obj.outerHeight()*-1;
					targetX = position['left'];
					break;
				case 'bottom':
					targetY = sliderHeight;
					targetX = position['left'];
					break;
				case 'right':
					targetY = position['top'];
					targetX = sliderWidth;
					break;
				case 'bottomRight':
					targetY = sliderHeight;
					targetX = sliderWidth;
					break;
				case 'topRight':
					targetY = obj.outerHeight()*-1;
					targetX = sliderWidth;
					break;
				default:
					break;
			}
			
			// get speed for the out transition
			if((speed == null && transition != 'fade') || (speed == null && transition != 'none')){
				if(position['left']>targetX){
					distX = Math.abs(position['left']-targetX);
				}else
				if(position['left']>targetX){
					distX = Math.abs(targetX-position['left']);
				}else{
					distX = 0;
				}
				
				if(position['top']>targetY){
					distY = Math.abs(position['top']-targetY);
				}else
				if(targetY>position['top']){
					distY = Math.abs(targetY-position['top']);
				}else{
					distY = 0;
				}
				
				dist = Math.sqrt((distX*distX)+(distY*distY));
				
				// calculate the speed for transition
				speed = (dist * (options['speedOut']/1000));	
			}else if(speed != null){
			}else{
				// calculate the speed for transition
				speed = options['speedOut'];
			}	
			
			if(transition == 'fade'){
				// fade
				obj.fadeOut(speed, 
							function(){
								obj.hide();
								}
					)
					.removeClass('fs_obj_active');				
			}else if(transition == 'none'){
				// animation
				obj.hide(0,
						function(){
							obj.hide();
							}
					)
					.removeClass('fs_obj_active');
			}else{
				// animation
				obj.animate({"top": targetY+"px", "left": targetX+"px"}, 
							speed, 
							easing, 
							function(){
								obj.hide();
								}
					)
					.removeClass('fs_obj_active');	
			}
		}
		
		function backgroundAnimation(){
			if(options['backgroundElement'] == null || options['backgroundElement'] == ""){
				var el = slider;
			}else{
				var el = $(options['backgroundElement']);
			}
			
			var oldPos = el.css('background-position');
			    oldPos = oldPos.split(' ');
			var moveX = options['backgroundX'];	
			var moveY = options['backgroundY'];
			var x = Number(oldPos[0].replace(/[px,%]/g, '')) + moveX;	
			var y = Number(oldPos[0].replace(/[px,%]/g, '')) + moveY;
			
			el.animate({backgroundPositionX: x+'px', backgroundPositionY: y+'px'}, options['backgroundSpeed'], options['backgroundEase']);
		}
	}
	
	/** ************************* **/
	/** PLUGIN  **/
	/** ************************* **/
	
  	$.fn.fractionSlider = function(options) {
	
		// defaults & options
		var options = $.extend( {
		  'position'					: '0,0',				// default position | should never be used
		  'transitionIn'        		: 'left',				// defaulöt in - transition
		  'transitionOut' 				: 'left',				// default out - transition
		  'fullWidth' 					: false,				// transition over the full width of the window
		  'delay' 						: 0,					// default delay for elements
		  'timeout'						: 2000,					// default timeout before switching slides
		  'speedIn'						: 2500,					// default in - transition speed
		  'speedOut'					: 1000,					// default out - transition speed
		  'easeIn'						: 'easeOutExpo',		// default easing in
		  'easeOut'						: 'easeOutCubic',		// default easing out
		
		  'controls'					: false,				// controls on/off
		  'pager'						: false,				// controls on/off
		  'autoChange'					: true,					// auto change slides
		
		  'backgroundAnimation'			: false,				// background animation
		  'backgroundElement'			: null,					// element to animate | default fractionSlider element
		  'backgroundX'					: 500,					// default x distance
		  'backgroundY'					: 500,					// default y distance
		  'backgroundSpeed'				: 2500,					// default background animation speed
		  'backgroundEase'				: 'easeOutCubic',		// default background animation easing
		}, options);
		
		// ready for take-off 
		var slider = new FractionSlider(this, options);
  	};

	/** ************************* **/
	/** EASING EXTEND  **/
	/** ************************* **/

	// based on jqueryui (http://jqueryui.com/)
	// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)

	var baseEasings = {};

	$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
		baseEasings[ name ] = function( p ) {
			return Math.pow( p, i + 2 );
		};
	});

	$.extend( baseEasings, {
		Sine: function ( p ) {
			return 1 - Math.cos( p * Math.PI / 2 );
		},
		Circ: function ( p ) {
			return 1 - Math.sqrt( 1 - p * p );
		},
		Elastic: function( p ) {
			return p === 0 || p === 1 ? p :
				-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
		},
		Back: function( p ) {
			return p * p * ( 3 * p - 2 );
		},
		Bounce: function ( p ) {
			var pow2,
				bounce = 4;

			while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
			return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
		}
	});

	$.each( baseEasings, function( name, easeIn ) {
		$.easing[ "easeIn" + name ] = easeIn;
		$.easing[ "easeOut" + name ] = function( p ) {
			return 1 - easeIn( 1 - p );
		};
		$.easing[ "easeInOut" + name ] = function( p ) {
			return p < 0.5 ?
				easeIn( p * 2 ) / 2 :
				1 - easeIn( p * -2 + 2 ) / 2;
		};
	}); // end easing
})( jQuery );;
/**
* @file
* Javascript, modifications of DOM.
*
* Manipulates links to include jquery load funciton
*/

(function ($) {
  Drupal.behaviors.jquery_ajax_load = {
    attach: function (context, settings) {
      jQuery.ajaxSetup ({
      // Disable caching of AJAX responses
        cache: false
      });

      var trigger = Drupal.settings.jquery_ajax_load.trigger;
      var target = Drupal.settings.jquery_ajax_load.target;
      // Puede ser más de un valor, hay que usar foreach()
      $(trigger).once(function() {
        var html_string = $(this).attr( 'href' );
        // Hay que validar si la ruta trae la URL del sitio
        $(this).attr( 'href' , target );
        var data_target = $(this).attr( 'data-target' );
        if (typeof data_target === 'undefined' ) {
          data_target = target;
        }
        else {
          data_target = '#' + data_target;
        }
        $(this).click(function(evt) {
          evt.preventDefault();
          jquery_ajax_load_load($(this), data_target, html_string);
        });
      });
      $(trigger).removeClass(trigger);
    }
  };  

// Handles link calls
  function jquery_ajax_load_load(el, target, url) {
    var module_path = Drupal.settings.jquery_ajax_load.module_path;
    var toggle = Drupal.settings.jquery_ajax_load.toggle;
    var base_path = Drupal.settings.jquery_ajax_load.base_path;
    var animation = Drupal.settings.jquery_ajax_load.animation;
    if( toggle && $(el).hasClass( "jquery_ajax_load_open" ) ) {
      $(el).removeClass( "jquery_ajax_load_open" );
      if ( animation ) {
        $(target).hide('slow', function() {
          $(target).empty();
        });
      }
      else {
        $(target).empty();
      }
    }
    else {
      var loading_html = Drupal.t('Loading'); 
      loading_html += '... <img src="/';
      loading_html += module_path;
      loading_html += '/jquery_ajax_load_loading.gif">';
      $(target).html(loading_html);
      $(target).load(base_path + 'jquery_ajax_load/get' + url, function( response, status, xhr ) {
        if ( status == "error" ) {
          var msg = "Sorry but there was an error: ";
          $(target).html( msg + xhr.status + " " + xhr.statusText );
        }
        else {
          if ( animation ) {
            $(target).hide();
            $(target).show('slow')
          }
//        Drupal.attachBehaviors(target);
        }
      });
      $(el).addClass( "jquery_ajax_load_open" );
    }
  }
}(jQuery));
;
(function ($) {

/**
* @file
* Javascript support files.
*
*/

Drupal.behaviors.twitter_bootstrap_modal = {
  attach: function (context, settings) {
    // Actions to make link Twitter Bootstrap Modal
    var TBtrigger = Drupal.settings.jquery_ajax_load.TBtrigger;
    // Puede ser más de un valor, hay que usar foreach()
    $(TBtrigger).once(function() {
      var html_string = $(this).attr( 'href' );
      // Hay que validar si la ruta trae la URL del sitio
      $(this).attr( 'href' , '/jquery_ajax_load/get' + html_string );
      $(this).attr( 'data-target' , '#jquery_ajax_load');
      $(this).attr( 'data-toggle' , 'modal' );
    });
    var TBmodaltrigger = Drupal.settings.jquery_ajax_load.TBmodaltrigger;
    $(TBmodaltrigger).once(function() {
      $(this).click(openDialog);
    });
  }
}

var openDialog = function() {
  var TBpath = Drupal.settings.jquery_ajax_load.TBpath;
  var html_string = TBpath + 'bs_modal' + $(this).attr( 'href' );
  $('#jquery_ajax_load').remove();
  twitter_bootstrap_modal_create_modal();
  $('#jquery_ajax_load').modal({
    remote: html_string
  });
  return false;
}

function twitter_bootstrap_modal_create_modal() {
  var modal_name = Drupal.settings.jquery_ajax_load.TBname;
  var modal_module = Drupal.settings.jquery_ajax_load.TBmodule;
  $('body').append('<div id="jquery_ajax_load" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">');
  $('#jquery_ajax_load').append('<div class="modal-dialog" />');
  $('#jquery_ajax_load .modal-dialog').append('<div class="modal-content" />');
  $('#jquery_ajax_load .modal-content').append('<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 class="modal_title">' + modal_name + '</h3></div>');
  $('#jquery_ajax_load .modal-content').append('<div class="modal-body"><span class="text-warning">' + Drupal.t('Loading') + '... </span><img src="/' + modal_module + '/twitter_bootstrap_modal_loading.gif"></div>');
  $('#jquery_ajax_load .modal-content').append('<div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">' + Drupal.t('Close') + '</button></div>');
}

}(jQuery));

;
(function ($) {

Drupal.behaviors.textarea = {
  attach: function (context, settings) {
    $('.form-textarea-wrapper.resizable', context).once('textarea', function () {
      var staticOffset = null;
      var textarea = $(this).addClass('resizable-textarea').find('textarea');
      var grippie = $('<div class="grippie"></div>').mousedown(startDrag);

      grippie.insertAfter(textarea);

      function startDrag(e) {
        staticOffset = textarea.height() - e.pageY;
        textarea.css('opacity', 0.25);
        $(document).mousemove(performDrag).mouseup(endDrag);
        return false;
      }

      function performDrag(e) {
        textarea.height(Math.max(32, staticOffset + e.pageY) + 'px');
        return false;
      }

      function endDrag(e) {
        $(document).unbind('mousemove', performDrag).unbind('mouseup', endDrag);
        textarea.css('opacity', 1);
      }
    });
  }
};

})(jQuery);
;
/**
 * @file
 * Provides dependent visibility for form items in CTools' ajax forms.
 *
 * To your $form item definition add:
 * - '#process' => array('ctools_process_dependency'),
 * - '#dependency' => array('id-of-form-item' => array(list, of, values, that,
 *   make, this, item, show),
 *
 * Special considerations:
 * - Radios are harder. Because Drupal doesn't give radio groups individual IDs,
 *   use 'radio:name-of-radio'.
 *
 * - Checkboxes don't have their own id, so you need to add one in a div
 *   around the checkboxes via #prefix and #suffix. You actually need to add TWO
 *   divs because it's the parent that gets hidden. Also be sure to retain the
 *   'expand_checkboxes' in the #process array, because the CTools process will
 *   override it.
 */

(function ($) {
  Drupal.CTools = Drupal.CTools || {};
  Drupal.CTools.dependent = {};

  Drupal.CTools.dependent.bindings = {};
  Drupal.CTools.dependent.activeBindings = {};
  Drupal.CTools.dependent.activeTriggers = [];

  Drupal.CTools.dependent.inArray = function(array, search_term) {
    var i = array.length;
    while (i--) {
      if (array[i] == search_term) {
         return true;
      }
    }
    return false;
  }


  Drupal.CTools.dependent.autoAttach = function() {
    // Clear active bindings and triggers.
    for (i in Drupal.CTools.dependent.activeTriggers) {
      $(Drupal.CTools.dependent.activeTriggers[i]).unbind('change.ctools-dependent');
    }
    Drupal.CTools.dependent.activeTriggers = [];
    Drupal.CTools.dependent.activeBindings = {};
    Drupal.CTools.dependent.bindings = {};

    if (!Drupal.settings.CTools) {
      return;
    }

    // Iterate through all relationships
    for (id in Drupal.settings.CTools.dependent) {
      // Test to make sure the id even exists; this helps clean up multiple
      // AJAX calls with multiple forms.

      // Drupal.CTools.dependent.activeBindings[id] is a boolean,
      // whether the binding is active or not.  Defaults to no.
      Drupal.CTools.dependent.activeBindings[id] = 0;
      // Iterate through all possible values
      for(bind_id in Drupal.settings.CTools.dependent[id].values) {
        // This creates a backward relationship.  The bind_id is the ID
        // of the element which needs to change in order for the id to hide or become shown.
        // The id is the ID of the item which will be conditionally hidden or shown.
        // Here we're setting the bindings for the bind
        // id to be an empty array if it doesn't already have bindings to it
        if (!Drupal.CTools.dependent.bindings[bind_id]) {
          Drupal.CTools.dependent.bindings[bind_id] = [];
        }
        // Add this ID
        Drupal.CTools.dependent.bindings[bind_id].push(id);
        // Big long if statement.
        // Drupal.settings.CTools.dependent[id].values[bind_id] holds the possible values

        if (bind_id.substring(0, 6) == 'radio:') {
          var trigger_id = "input[name='" + bind_id.substring(6) + "']";
        }
        else {
          var trigger_id = '#' + bind_id;
        }

        Drupal.CTools.dependent.activeTriggers.push(trigger_id);

        if ($(trigger_id).attr('type') == 'checkbox') {
          $(trigger_id).siblings('label').addClass('hidden-options');
        }

        var getValue = function(item, trigger) {
          if ($(trigger).size() == 0) {
            return null;
          }

          if (item.substring(0, 6) == 'radio:') {
            var val = $(trigger + ':checked').val();
          }
          else {
            switch ($(trigger).attr('type')) {
              case 'checkbox':
                var val = $(trigger).attr('checked') ? true : false;

                if (val) {
                  $(trigger).siblings('label').removeClass('hidden-options').addClass('expanded-options');
                }
                else {
                  $(trigger).siblings('label').removeClass('expanded-options').addClass('hidden-options');
                }

                break;
              default:
                var val = $(trigger).val();
            }
          }
          return val;
        }

        var setChangeTrigger = function(trigger_id, bind_id) {
          // Triggered when change() is clicked.
          var changeTrigger = function() {
            var val = getValue(bind_id, trigger_id);

            if (val == null) {
              return;
            }

            for (i in Drupal.CTools.dependent.bindings[bind_id]) {
              var id = Drupal.CTools.dependent.bindings[bind_id][i];
              // Fix numerous errors
              if (typeof id != 'string') {
                continue;
              }

              // This bit had to be rewritten a bit because two properties on the
              // same set caused the counter to go up and up and up.
              if (!Drupal.CTools.dependent.activeBindings[id]) {
                Drupal.CTools.dependent.activeBindings[id] = {};
              }

              if (val != null && Drupal.CTools.dependent.inArray(Drupal.settings.CTools.dependent[id].values[bind_id], val)) {
                Drupal.CTools.dependent.activeBindings[id][bind_id] = 'bind';
              }
              else {
                delete Drupal.CTools.dependent.activeBindings[id][bind_id];
              }

              var len = 0;
              for (i in Drupal.CTools.dependent.activeBindings[id]) {
                len++;
              }

              var object = $('#' + id + '-wrapper');
              if (!object.size()) {
                // Some elements can't use the parent() method or they can
                // damage things. They are guaranteed to have wrappers but
                // only if dependent.inc provided them. This check prevents
                // problems when multiple AJAX calls cause settings to build
                // up.
                var $original = $('#' + id);
                if ($original.is('fieldset') || $original.is('textarea')) {
                  continue;
                }

                object = $('#' + id).parent();
              }

              if (Drupal.settings.CTools.dependent[id].type == 'disable') {
                if (Drupal.settings.CTools.dependent[id].num <= len) {
                  // Show if the element if criteria is matched
                  object.attr('disabled', false);
                  object.addClass('dependent-options');
                  object.children().attr('disabled', false);
                }
                else {
                  // Otherwise hide. Use css rather than hide() because hide()
                  // does not work if the item is already hidden, for example,
                  // in a collapsed fieldset.
                  object.attr('disabled', true);
                  object.children().attr('disabled', true);
                }
              }
              else {
                if (Drupal.settings.CTools.dependent[id].num <= len) {
                  // Show if the element if criteria is matched
                  object.show(0);
                  object.addClass('dependent-options');
                }
                else {
                  // Otherwise hide. Use css rather than hide() because hide()
                  // does not work if the item is already hidden, for example,
                  // in a collapsed fieldset.
                  object.css('display', 'none');
                }
              }
            }
          }

          $(trigger_id).bind('change.ctools-dependent', function() {
            // Trigger the internal change function
            // the attr('id') is used because closures are more confusing
            changeTrigger(trigger_id, bind_id);
          });
          // Trigger initial reaction
          changeTrigger(trigger_id, bind_id);
        }
        setChangeTrigger(trigger_id, bind_id);
      }
    }
  }

  Drupal.behaviors.CToolsDependent = {
    attach: function (context) {
      Drupal.CTools.dependent.autoAttach();

      // Really large sets of fields are too slow with the above method, so this
      // is a sort of hacked one that's faster but much less flexible.
      $("select.ctools-master-dependent")
        .once('ctools-dependent')
        .bind('change.ctools-dependent', function() {
          var val = $(this).val();
          if (val == 'all') {
            $('.ctools-dependent-all').show(0);
          }
          else {
            $('.ctools-dependent-all').hide(0);
            $('.ctools-dependent-' + val).show(0);
          }
        })
        .trigger('change.ctools-dependent');
    }
  }
})(jQuery);
;
(function ($) {

/**
 * Attaches sticky table headers.
 */
Drupal.behaviors.tableHeader = {
  attach: function (context, settings) {
    if (!$.support.positionFixed) {
      return;
    }

    $('table.sticky-enabled', context).once('tableheader', function () {
      $(this).data("drupal-tableheader", new Drupal.tableHeader(this));
    });
  }
};

/**
 * Constructor for the tableHeader object. Provides sticky table headers.
 *
 * @param table
 *   DOM object for the table to add a sticky header to.
 */
Drupal.tableHeader = function (table) {
  var self = this;

  this.originalTable = $(table);
  this.originalHeader = $(table).children('thead');
  this.originalHeaderCells = this.originalHeader.find('> tr > th');
  this.displayWeight = null;

  // React to columns change to avoid making checks in the scroll callback.
  this.originalTable.bind('columnschange', function (e, display) {
    // This will force header size to be calculated on scroll.
    self.widthCalculated = (self.displayWeight !== null && self.displayWeight === display);
    self.displayWeight = display;
  });

  // Clone the table header so it inherits original jQuery properties. Hide
  // the table to avoid a flash of the header clone upon page load.
  this.stickyTable = $('<table class="sticky-header"/>')
    .insertBefore(this.originalTable)
    .css({ position: 'fixed', top: '0px' });
  this.stickyHeader = this.originalHeader.clone(true)
    .hide()
    .appendTo(this.stickyTable);
  this.stickyHeaderCells = this.stickyHeader.find('> tr > th');

  this.originalTable.addClass('sticky-table');
  $(window)
    .bind('scroll.drupal-tableheader', $.proxy(this, 'eventhandlerRecalculateStickyHeader'))
    .bind('resize.drupal-tableheader', { calculateWidth: true }, $.proxy(this, 'eventhandlerRecalculateStickyHeader'))
    // Make sure the anchor being scrolled into view is not hidden beneath the
    // sticky table header. Adjust the scrollTop if it does.
    .bind('drupalDisplaceAnchor.drupal-tableheader', function () {
      window.scrollBy(0, -self.stickyTable.outerHeight());
    })
    // Make sure the element being focused is not hidden beneath the sticky
    // table header. Adjust the scrollTop if it does.
    .bind('drupalDisplaceFocus.drupal-tableheader', function (event) {
      if (self.stickyVisible && event.clientY < (self.stickyOffsetTop + self.stickyTable.outerHeight()) && event.$target.closest('sticky-header').length === 0) {
        window.scrollBy(0, -self.stickyTable.outerHeight());
      }
    })
    .triggerHandler('resize.drupal-tableheader');

  // We hid the header to avoid it showing up erroneously on page load;
  // we need to unhide it now so that it will show up when expected.
  this.stickyHeader.show();
};

/**
 * Event handler: recalculates position of the sticky table header.
 *
 * @param event
 *   Event being triggered.
 */
Drupal.tableHeader.prototype.eventhandlerRecalculateStickyHeader = function (event) {
  var self = this;
  var calculateWidth = event.data && event.data.calculateWidth;

  // Reset top position of sticky table headers to the current top offset.
  this.stickyOffsetTop = Drupal.settings.tableHeaderOffset ? eval(Drupal.settings.tableHeaderOffset + '()') : 0;
  this.stickyTable.css('top', this.stickyOffsetTop + 'px');

  // Save positioning data.
  var viewHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
  if (calculateWidth || this.viewHeight !== viewHeight) {
    this.viewHeight = viewHeight;
    this.vPosition = this.originalTable.offset().top - 4 - this.stickyOffsetTop;
    this.hPosition = this.originalTable.offset().left;
    this.vLength = this.originalTable[0].clientHeight - 100;
    calculateWidth = true;
  }

  // Track horizontal positioning relative to the viewport and set visibility.
  var hScroll = document.documentElement.scrollLeft || document.body.scrollLeft;
  var vOffset = (document.documentElement.scrollTop || document.body.scrollTop) - this.vPosition;
  this.stickyVisible = vOffset > 0 && vOffset < this.vLength;
  this.stickyTable.css({ left: (-hScroll + this.hPosition) + 'px', visibility: this.stickyVisible ? 'visible' : 'hidden' });

  // Only perform expensive calculations if the sticky header is actually
  // visible or when forced.
  if (this.stickyVisible && (calculateWidth || !this.widthCalculated)) {
    this.widthCalculated = true;
    var $that = null;
    var $stickyCell = null;
    var display = null;
    var cellWidth = null;
    // Resize header and its cell widths.
    // Only apply width to visible table cells. This prevents the header from
    // displaying incorrectly when the sticky header is no longer visible.
    for (var i = 0, il = this.originalHeaderCells.length; i < il; i += 1) {
      $that = $(this.originalHeaderCells[i]);
      $stickyCell = this.stickyHeaderCells.eq($that.index());
      display = $that.css('display');
      if (display !== 'none') {
        cellWidth = $that.css('width');
        // Exception for IE7.
        if (cellWidth === 'auto') {
          cellWidth = $that[0].clientWidth + 'px';
        }
        $stickyCell.css({'width': cellWidth, 'display': display});
      }
      else {
        $stickyCell.css('display', 'none');
      }
    }
    this.stickyTable.css('width', this.originalTable.outerWidth());
  }
};

})(jQuery);
;
(function ($) {

/**
 * Toggle the visibility of a fieldset using smooth animations.
 */
Drupal.toggleFieldset = function (fieldset) {
  var $fieldset = $(fieldset);
  if ($fieldset.is('.collapsed')) {
    var $content = $('> .fieldset-wrapper', fieldset).hide();
    $fieldset
      .removeClass('collapsed')
      .trigger({ type: 'collapsed', value: false })
      .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide'));
    $content.slideDown({
      duration: 'fast',
      easing: 'linear',
      complete: function () {
        Drupal.collapseScrollIntoView(fieldset);
        fieldset.animating = false;
      },
      step: function () {
        // Scroll the fieldset into view.
        Drupal.collapseScrollIntoView(fieldset);
      }
    });
  }
  else {
    $fieldset.trigger({ type: 'collapsed', value: true });
    $('> .fieldset-wrapper', fieldset).slideUp('fast', function () {
      $fieldset
        .addClass('collapsed')
        .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show'));
      fieldset.animating = false;
    });
  }
};

/**
 * Scroll a given fieldset into view as much as possible.
 */
Drupal.collapseScrollIntoView = function (node) {
  var h = document.documentElement.clientHeight || document.body.clientHeight || 0;
  var offset = document.documentElement.scrollTop || document.body.scrollTop || 0;
  var posY = $(node).offset().top;
  var fudge = 55;
  if (posY + node.offsetHeight + fudge > h + offset) {
    if (node.offsetHeight > h) {
      window.scrollTo(0, posY);
    }
    else {
      window.scrollTo(0, posY + node.offsetHeight - h + fudge);
    }
  }
};

Drupal.behaviors.collapse = {
  attach: function (context, settings) {
    $('fieldset.collapsible', context).once('collapse', function () {
      var $fieldset = $(this);
      // Expand fieldset if there are errors inside, or if it contains an
      // element that is targeted by the URI fragment identifier.
      var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : '';
      if ($fieldset.find('.error' + anchor).length) {
        $fieldset.removeClass('collapsed');
      }

      var summary = $('<span class="summary"></span>');
      $fieldset.
        bind('summaryUpdated', function () {
          var text = $.trim($fieldset.drupalGetSummary());
          summary.html(text ? ' (' + text + ')' : '');
        })
        .trigger('summaryUpdated');

      // Turn the legend into a clickable link, but retain span.fieldset-legend
      // for CSS positioning.
      var $legend = $('> legend .fieldset-legend', this);

      $('<span class="fieldset-legend-prefix element-invisible"></span>')
        .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide'))
        .prependTo($legend)
        .after(' ');

      // .wrapInner() does not retain bound events.
      var $link = $('<a class="fieldset-title" href="#"></a>')
        .prepend($legend.contents())
        .appendTo($legend)
        .click(function () {
          var fieldset = $fieldset.get(0);
          // Don't animate multiple times.
          if (!fieldset.animating) {
            fieldset.animating = true;
            Drupal.toggleFieldset(fieldset);
          }
          return false;
        });

      $legend.append(summary);
    });
  }
};

})(jQuery);
;
(function ($) {

/**
 * Automatically display the guidelines of the selected text format.
 */
Drupal.behaviors.filterGuidelines = {
  attach: function (context) {
    $('.filter-guidelines', context).once('filter-guidelines')
      .find(':header').hide()
      .closest('.filter-wrapper').find('select.filter-list')
      .bind('change', function () {
        $(this).closest('.filter-wrapper')
          .find('.filter-guidelines-item').hide()
          .siblings('.filter-guidelines-' + this.value).show();
      })
      .change();
  }
};

})(jQuery);
;
