/**
 * @file
 * Contains jQuery-based javascript to be loaded on all theme pages
 *
 * See documentation on jQuery and Drupal at http://drupal.org/node/171213
 */

(function ($) {

  Drupal.behaviors.nszero = {
    attach: function(context, settings) {
    
    
    }  
  };
})(jQuery);    ;
/**
 * 
 * <a [options]>Text</a>
 * 
 * options
 * data-yt-user = Your youtube username
 * data-yt-layout = 'horizontal' | 'vertical'
 * data-yt-widget = 'subscribe'
 */
(function($, document, window, undefined){
  
$(document).ready(function(){
  // The shared data object
  var dataStore = {
    data: {},
    watching: {},
    
    /**
     * Check if has a value
     */
    has: function(key) {
      return !!this.data[key];
    },
    
    /**
     * Get
     */
    get: function(key) {
      return this.data[key];
    },
    
    /**
     * Set
     */
    set: function(key, value) {
      // Already has the key, handle this case for checking if values are updated
      if(this.has(key)) {
        var oldValue = this.data[key];
        this.data[key] = value;
        
        var ov, nv; // old value and new value
        for(var path in this.watching[key]) {
          ov = this._getPathValue(oldValue, path);
          nv = this._getPathValue(this.data[key], path);
          
          // If value changed, then call the callback
          if(ov != nv) {
            for(var i=0; i<this.watching[key][path].length; ++i) {
              this.watching[key][path][i](nv, ov);
            }
          }
        }
        
      // New value, go ahead and call all callbacks
      } else {
        this.data[key] = value;
        var o;
        for(var path in this.watching[key]) {
          o = this._getPathValue(this.data[key], path);
          for(var i=0; i<this.watching[key][path].length; ++i) {
            this.watching[key][path][i](o);
          }
        }
      }
    },
    
    /**
     * Start watching a value
     * 
     */
    watch: function(key, path, callback) {
      if($.isArray(path)) {
        path = path.join(',');  
      }
      if(!path) {
        path = '-'; 
      }
      
      if(!this.watching[key]) {
         this.watching[key] = {};
      }
      if(!this.watching[key][path]) {
        this.watching[key][path] = [];
      }
      
      this.watching[key][path].push(callback);
    },
    
    _getPathValue: function(value, path) {
      // null path
      if(path == '-') {
        return value; 
      }
      
      // work through the path
      path = path.split(',');
      var o = value;
      var i = 0;
      while(i<path.length && o[path[i]]) {
        o = o[path[i]]; 
        i = i+1;
      }
      
      // check that we got to end of the path for what to return
      if(i==path.length) {
        return o; 
      } else {
        return null; 
      }
    }
  };
  
  // The widget handlers
  var widgetHandlers = {
    'subscribe': function(t) {
      var username = t.attr('data-yt-user');
      // We need a username
      if(!username) {
        return;
      }
      
      // Setup the button elements
      var layout = t.attr('data-yt-layout') || 'horizontal';
      layout = layout in {'horizontal': 1} ? layout : 'horizontal';
      
      var buttonText = t.attr('data-yt-button-text') || 'Subscribe';
      
      t.addClass('yt-widget').addClass('yt-widget-subscribe').addClass('yt-layout-'+layout);
      var count = $('<span class="yt-count"></span>');
      t.html('<span class="yt-subscribe-button yt-button"><span class="yt-icon"></span> '+buttonText+'</span>');
      if(layout in {'vertical':1}) {
        t.prepend(count);
      } else {
        t.append(count);
      }
      
      var updateCount = function(c) {
        c = c-0;
        if(c>1000) {
          c = Math.floor(c/1000)+'k'; 
        }
        count.text(c);
      };
      dataStore.watch('users/'+username, ['entry','yt$statistics','subscriberCount'], updateCount);
      
      
      // Get the data
      if(dataStore.has('users/'+username)) {
        updateCount(dataStore.get('users/'+username).entry.yt$statistics.subscriberCount);
      } else {
        $.getJSON('//gdata.youtube.com/feeds/api/users/audotorg?v=2&alt=json&callback=?', function(data) {
          dataStore.set('users/'+username, data);
        });
      }
     
      
      // Setup the click action
      t.click(function(e){
        window.open('//www.youtube.com/subscription_center?add_user='+username, 'youtube-widget', 'height=300,width=500,status=no');
        
        // Push to Google Analytics if we can
        if(window._gaq) {
          window._gaq.push(['_trackSocial', 'youtube', 'subscribe', username]);
        }
        
        return false;
      });
    }
      
  };
  
  // Create the widgets
  var widgets = $('a[data-yt-widget]');
  if(widgets.length > 0) { // Don't bother if no widgets are on the page
    widgets.each(function(){ 
      var t = $(this);
      var widgetType = t.attr('data-yt-widget') || 'subscribe';
      if(widgetHandlers[widgetType]) {
        widgetHandlers[widgetType](t);
      }
    });
  }
  
});
  
})(jQuery, document, window);;
/*
  Formalize - version 1.1

  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 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.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();
});;
/* Column v1.0
 *
 * Copyright (c) 2011 Martijn W. van der Lee
 * Licensed under the MIT.
 *
 * Emulate CSS3 style column on browsers that don't support it.
 */
 
//TODO Split on hyphens, &shy;, and others.
//TODO Configurable splitter, using regex patterns. ('syllables', 'words', 'sentences', 'punctuation', function)
//TODO Add classes to different columns; 'column', 'last-column', 'first-column', use inner-div's so stuff can be layed out with CSS.
//TODO Accept "em" as measurement. Also other measurements: px, % (why?), in, mm(=in), cm(=cm), ex, pt(=in), pc(=in)
	//TODO Use $.px() if available (but keep overwriting %)
//TODO Iterative balancing
//TODO Experiment with normalizing... doesn't seem to work well. Is this even wanted?
//TODO Make balancing into strategy pattern.
//TODO Adjust strategy for column width calculation; does not match chrome strategy.
//TODO Postprocess: Top-of-column == h1? margin-top: 0;
//TODO Split strategies for lists and others (different node types).

//TODO Just do this inside the strategies; not worth the namespace polution.
if (String.prototype.indexOfRegExp == null) {
	String.prototype.indexOfRegExp = function(pattern, modifiers) {
		var re = new RegExp(pattern, modifiers);	// cached?
		var m = re.exec(this.valueOf());	
		return (m == null? -1 : m.index);
	}
}

(function( $ ){
	$.fn.column = function(options) {
		var settings = {
			'width':		'auto',
			'count':		'auto',
			'gap':			'normal',
			'rule_color':	'',
			'rule_style':	'none',
			'rule_width':	'medium',
			'split':		'word'	
		};
		
		var border_widths	= {	thin:	_measure_border_width('thin'),
								medium: _measure_border_width('medium'),
								thick:	_measure_border_width('thick')
							};		
		
		function _measure_em(scope) {
			var element = jQuery('<div style="display:none;height:10em;margin:0;padding:0;border:0;"></div>').appendTo(scope);
			var px = element.height() / 10;
			element.remove();
			return px;
		}

		function _measure_border_width(type) {
			var element = jQuery('<div style="border:'+type+' solid transparent;height:0px;"></div>').appendTo('body');
			var width = element.outerHeight() / 2;
			element.remove();
			return width;
		}

		var split_strategies = {
			word: 		function(node) {
							var contents = new Array;
							do {
								contents.push(node);
								if (split = node.nodeValue.indexOfRegExp('\\s+') + 1) {
									node = node.splitText(split);
								}
							} while (split);
							return contents;			
						},
			sentence: 	function(node) {
							var contents = new Array;
							do {
								contents.push(node);
								if (split = node.nodeValue.indexOfRegExp('[.:!?]+') + 1) {
									node = node.splitText(split);
								}
							} while (split);
							return contents;			
						}
		}
		
		function _split(parent) {
			var contents = new Array;
			$(parent).contents().each( function(index, value) {
				if (value.nodeType == 3) {						// Node.TEXT_NODE
					contents = contents.concat(split_strategies[settings.split](value));
				} else {
					contents.push(value);
				}
			});			
			return contents;			
		}
				
		return this.each( function() {
			// Merge options
			if (options) { 
				$.extend(settings, options);
			}			
			
			// per-instance settings
			var element			= this;
			var content			= $(this).html();	// entire bulk
			var contents		= _split(this);
			var gap_normal		= _measure_em(this);						
			
			// the active part
			_resize();	// do once pre-load so we atleast have columns
			$(window).resize(_resize).load(_resize);
			
			// worker
			function _resize() {
				// Clear columns
				$(element).empty();
			
				var column_gap		= (settings.gap == parseFloat(settings.gap))? settings.gap : gap_normal;
				
				if (settings.rule_style != 'none') {
					var rule_color = (settings.rule_color? settings.rule_color : $(element).css('color'));
					var rule_width = (settings.rule_width == parseFloat(settings.rule_width)? settings.rule_width : border_widths[settings.rule_width]);				
					column_gap		-= rule_width;
				}				
				
				if (settings.width != 'auto') {
					var column_count = Math.floor(($(element).width() + rule_width) / (settings.width + column_gap));
				} else if (settings.count != 'auto') {
					var column_count = settings.count;
				} else {
					return;
				}
				
				var width			= $(element).width() - ((column_count - 1) * column_gap);
				var column_width	= Math.floor(width / column_count);
																
				// Setup columns
				var left = 0;
				for (var c = 0; c < column_count; ++c) {
					var style	= 'position:absolute;'
								+ (c > 0?				 'left:'+left+'px;' : '')
								+ 'width:'+column_width+'px;'
								+ (c > 0?				 'padding-left:'+Math.ceil(column_gap / 2)+'px;' : '')
								+ (c < column_count - 1? 'padding-right:'+Math.floor(column_gap / 2)+'px;' : '')
								+ 'overflow:hidden;'
								;
					left += column_width;
					left += column_gap;
					if (c > 0 && settings.rule_style != 'none') {
						style	+= 'border-left:'+rule_width+'px '+settings.rule_style+' '+rule_color+';';
						left	+= rule_width;
					}
					$(element).append('<div style="'+style+'" class="column"></div>');
				}							
				
				// Determine height of total content in a single column
				var first = $('div.column', element).first();
				var height = first.html(content).height();
				first.empty();
				var height_step = Math.ceil(height / column_count);
				
				// Fill columns
				var contents_length = contents.length;
				var max_height = 0;
				var i = 0;
				for (var c = 0; c < column_count; ++c) {
					var div = $('div.column', element).eq(c);
					
					//hack to actually just do 2 each...
					if (c < column_count - 1) {
						// detect overflow
						while (i < contents_length && div.height() <= height_step) {
							div.append(contents[i++]);
						}
						
						// fill up rest of div
						var div_height = div.height();
						// 4 was contents_length, hack					
						while (i < 3 && div.height() == div_height) {
							div.append(contents[i++]);
						}
					
						// retract last part of content
						div.contents().last().remove();
						--i;
					} else {
						// dump remaining content in the last column
						while (i < contents_length) {
							div.append(contents[i++]);
						}
					}
					
					max_height = Math.max(max_height, div.height());
				}

				// Set all to the same height
				$('div.column', element).css('height', max_height);
				$(element).css('height', max_height);
			}		
		});
	};
})( jQuery );;
/**
 * @file
 * Contains jQuery-based javascript to be loaded on all theme pages
 *
 * See documentation on jQuery and Drupal at http://drupal.org/node/171213
 */

(function ($) {

  Drupal.behaviors.americansunitedtheme = {
    attach: function(context, settings) {
      //move the feed icon
      $(".view-blogs").siblings("a.feed-icon").insertAfter(".view-blogs .view-header");
    
      //active menu item hack for blog posts
      $(".menu-name-menu-utility-menu li").each(function() {
        this_path = window.location.pathname;
        link_path = $(this).children('a').attr('href');
        if ( this_path.indexOf(link_path) === 0) {
          $(this).addClass("active-trail").children("a").addClass("active-trail");
        }
      });
      
      
      // Drop down menu
      $('ul.drop-down-menu li')
        .hover(
          function() {
            var ul = $(this).children('ul').eq(0);
            ul.show().parent().addClass('hovering');
          },
          function() {
            var ul = $(this).children('ul').eq(0);
            ul.hide().parent().removeClass('hovering');
          }
        )
        .find('ul')
          .hide();
      
      //hack fix for menus
      $(".block-menu-block:not(.alterMenuBlock-processed)", context).each(function () {
        $(this).addClass('alterMenuBlock-processed').find("ul.menu li.expanded").each(function(){
          if ( ! $(this).hasClass('active-trail') ) {
            $(this).removeClass('expanded').addClass('collapsed').children().remove('ul.menu');
  	       }
        });	  
      }); 
      
      //external links
      $("a.external").attr("target","_blank");
      
      //two-column views (C&S, chapters)
      $(".lower .view-church-state-articles .view-content").column({count:2});
            
      $("#header-bg").prepend('<div class="before"/><div class="after"/>');
      
      //size the header extensions
      function resize_header( $h_width ) {
        diff = Math.ceil(($("#header-bg").width() - $h_width) / 2);
        if (diff > 1) $("#header-bg .before, #header-bg .after").width(diff);
      }
      resize_header(1152);
      $(window).resize(function() {
        resize_header(1152);
      });
      
      // Show the list of states with the map
      $('#select-state').each(function(){
        var stateList = $('.usmap-links').eq(0);
        stateList.clone().appendTo($(this).parent());
        $(this).parent().hover(
          function() {
            var ul = $(this).children('ul').eq(0);
            ul.show().parent().addClass('hovering');
          },
          function() {
            var ul = $(this).children('ul').eq(0);
            ul.hide().parent().removeClass('hovering');
          }
        )
        .children('a')
          .click(function() {
            return false;
          });
      });

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

Drupal.behaviors.initColorboxDefaultStyle = {
  attach: function (context, settings) {
    $(document).bind('cbox_complete', function () {
      // Only run if there is a title.
      if ($('#cboxTitle:empty', context).length == false) {
        setTimeout(function () { $('#cboxTitle', context).slideUp() }, 1500);
        $('#cboxLoadedContent img', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideDown();
        });
        $('#cboxOverlay', context).bind('mouseover', function () {
          $('#cboxTitle', context).slideUp();
        });
      }
      else {
        $('#cboxTitle', context).hide();
      }
      
      var close = $('#cboxClose');
      if(close.find('.icon').length == 0) {
        close.append('<span class="icon"></span>');
      }
    });
  }
};

})(jQuery);
;

