$(document).ready(function() {
	
	//automatically resize search input to fit parent block element
	$('#nav #search input#query').width($('#nav #top').outerWidth() - $('ul#menu-navigation-menu').outerWidth()-14-2-30);
		
	//if #site-alert block element exists
	if( $("#site-alert").length ) { 
	
		var newsItemID = $('#site-alert .container div').attr('id');
				
		//if the box hasn't been shown before slide it down
		if( $.cookie(newsItemID) == null ) {  //'alert_box'
			$("#header").addClass("with-site-alert");
			$("#site-alert").slideDown('slow', function() {
			 	// Animation complete
				$.cookie(newsItemID, 'open', { expires: 1 }); //set cookie to store open state
			});
		} 
		/*else if( $.cookie(newsItemID) != 'closed' ) {
			$("#site-alert").show();
		}*/
		
		//alert($('#site-alert .container div').attr('id'));
		
		//if the close button is clicked close the box
		$("#site-alert .close").click(function() {
		  $("#site-alert").slideUp('slow', function(event) {
			  // Animation complete
			  $.cookie(newsItemID, 'closed', { expires: 1 }); //set cookie to store closed state
		  });
		});
		
	}
	
	/*$( ".box" ).tabs(
		{ fx: {opacity: 'toggle', duration: 'normal'} }
	);*/ 
	
	//Ensure home heading areas have first and last classes assigned
	$("body.home #heading-area p").first().addClass("first");
	$("body.home #heading-area p").last().addClass("last");
	

	//labelify input boxes
	$("#nav #search input#query, #search-category input#query-category-search, #signup input, #commentform input, #commentform textarea, .wpcf7 input, .wpcf7 textarea").labelify({
	  text: "label",
	  labelledClass: "highlight"
	});	
	
	//Apply pajinate functionality - moved to onpage to remove load delay
	/*$('#latest-posts-box').pajinate({
		items_per_page : 6,
		num_page_links_to_display : 3,
		nav_label_first : '&laquo;',
		nav_label_last : '&raquo;',
		nav_label_prev : '&laquo; Prev',
		nav_label_next : 'Next &raquo;'
	});*/
	/*$('#clinic-locations-box').pajinate({
		items_per_page : 2,
		num_page_links_to_display : 3,
		nav_label_first : '&laquo;',
		nav_label_last : '&raquo;',
		nav_label_prev : '&laquo; Prev',
		nav_label_next : 'Next &raquo;'
	});*/
	
	//Facebook like textarea auto grow
	$("#commentform textarea, .wpcf7-form textarea").autoGrow();
	
	//remove last vertical line separator in horizontal menus
	$('#top-menu ul li:last-child').addClass('last');
	
	$("#related_posts_thumbnails li:first-child").addClass("first");
	$("#related_posts_thumbnails li:last-child").addClass("last");
	
	
	//make homepage service grouping boxes clickable
	$("#service-groupings ul li").click(function() {
	  window.location = $(this).find("h3:first a:first").attr("href");
	});
	$("#service-groupings ul li").hover(
      function() {
        $(this).addClass("hover");
      },
      function() {
        $(this).removeClass("hover");
      }
    );
	 
	//make wo_bannerize ads clickable
	$(".wp_bannerize div").click(function() {
	  window.location = $(this).find(".more a").attr("href");
	});
	$(".wp_bannerize div").hover(
      function() {
        $(this).addClass("hover");
      },
      function() {
        $(this).removeClass("hover");
      }
    );
	
	//make subpage boxes clickable
	$(".subpage-list ul li").click(function() {
	  window.location = $(this).find("h3:first a:first").attr("href");
	});
	$(".subpage-list ul li").hover(
      function() {
        $(this).addClass("hover");
        $(this).append('<div class="learn-more">Learn more &raquo;</div>');
      },
      function() {
        $(this).removeClass("hover");
        $(".learn-more").remove();
      }
    );
	 
	 //wrap avatar
	$("img.avatar").each(function() {
		$(this).wrap(function(){
			return '<span class="' + $(this).attr('class') + '" style="background:url(' + $(this).attr('src') + ') no-repeat left top; width: ' + $(this).width() + 'px; height: ' + $(this).height() + 'px;" />';
		});
		$(this).removeClass('avatar')
		$(this).css("opacity","0");
	});
	
	//smooth anchor scroller
	$(".scroll").click(function(event){
		//prevent the default action for the click event
		event.preventDefault();
		
		//get the full url - like mysitecom/index.htm#home
		var full_url = this.href;
		
		//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
		var parts = full_url.split("#");
		var trgt = parts[1];
		
		//get the top offset of the target anchor
		var target_offset = $("#"+trgt).offset();
		var target_top = target_offset.top;
		
		//goto that anchor by setting the body scroll top to anchor top
		$('html, body').animate({scrollTop:target_top}, 500);
	});
	
	// animate to top
	$("#back-to-top").hide();
	$(function () {
		$(window).scroll(function () {
			if ($(this).scrollTop() > 100) {
				$('#back-to-top').fadeIn();
			} else {
				$('#back-to-top').fadeOut();
			}
		});
	});
	
	$("#posts-box table tr :first-child, #article-box table tr :first-child").addClass("first");
	$("#posts-box table tr:odd, #article-box table tr:odd").addClass("odd");
	
	//add .last to last paragraph in blockquote (the author), if one exists
	$("blockquote > p:last-child").not(":first-child").addClass("last");
	
	
	$("#posts-box table, #article-box table").wrapAll('<div class="table-wrap" />');
	
	//add .first class to the first paragraph in #article-box's .entry-content (if paragraph has > 100 chars)
	var firstParagraph = $("#article-box .post .entry-content p:first-child, #article-box .recipe .entry-content p:first-child");
	//if(firstParagraph.text().length > 100) {
		firstParagraph.addClass("first");
	//}
	
});


$.fn.clearForm = function() {
	return this.each(function() {
	  var type = this.type, tag = this.tagName.toLowerCase();
	  if (tag == 'form')
		 return $(':input',this).clearForm();
	  if (type == 'text' || type == 'password' || tag == 'textarea')
		 this.value = '';
	  else if (type == 'checkbox' || type == 'radio')
		 this.checked = false;
	  else if (tag == 'select')
		 this.selectedIndex = -1;
	});
};





/*!
 * Autogrow Textarea Plugin Version v2.0
 * http://www.technoreply.com/autogrow-textarea-plugin-version-2-0
 *
 * Copyright 2011, Jevin O. Sewaruth
 *
 * Date: March 13, 2011
 */
jQuery.fn.autoGrow = function(){
	return this.each(function(){
		// Variables
		var colsDefault = this.cols;
		var rowsDefault = this.rows;
		
		//Functions
		var grow = function() {
			growByRef(this);
		}
		
		var growByRef = function(obj) {
			var linesCount = 0;
			var lines = obj.value.split('\n');
			
			for (var i=lines.length-1; i>=0; --i)
			{
				linesCount += Math.floor((lines[i].length / colsDefault) + 1);
			}

			if (linesCount >= rowsDefault)
				obj.rows = linesCount + 1;
			else
				obj.rows = rowsDefault;
		}
		
		var characterWidth = function (obj){
			var characterWidth = 0;
			var temp1 = 0;
			var temp2 = 0;
			var tempCols = obj.cols;
			
			obj.cols = 1;
			temp1 = obj.offsetWidth;
			obj.cols = 2;
			temp2 = obj.offsetWidth;
			characterWidth = temp2 - temp1;
			obj.cols = tempCols;
			
			return characterWidth;
		}
		
		// Manipulations
		this.style.width = "auto";
		this.style.height = "auto";
		this.style.overflow = "hidden";
		this.style.width = ((characterWidth(this) * this.cols) + 6) + "px";
		this.onkeyup = grow;
		this.onfocus = grow;
		this.onblur = grow;
		growByRef(this);
	});
};



;(function($){
/*******************************************************************************************/	
// jquery.pajinate.js - version 0.2
// A jQuery plugin for paginating through any number of DOM elements
// 
// Copyright (c) 2010, Wes Nolte (http://wesnolte.com)
// Liscensed under the MIT License (MIT-LICENSE.txt)
// http://www.opensource.org/licenses/mit-license.php
// Created: 2010-04-16 | Updated: 2010-04-26
/*******************************************************************************************/

	$.fn.pajinate = function(options){
		// Set some state information
		var current_page = 'current_page';
		var items_per_page = 'items_per_page';
		
		var meta;
	
		// Setup default option values
		var defaults = {
			item_container_id : '.content',
			items_per_page : 10,			
			nav_panel_id : '.page-navigation',
			num_page_links_to_display : 20,			
			start_page : 0,
			nav_label_first : 'First',
			nav_label_prev : 'Prev',
			nav_label_next : 'Next',
			nav_label_last : 'Last'
		};
		var options = $.extend(defaults,options);
		var $item_container;
		var $page_container;
		var $items;
		var $nav_panels;
	
		return this.each(function(){
			$page_container = $(this);
			$item_container = $(this).find(options.item_container_id);
			$items = $page_container.find(options.item_container_id).children();
			meta = $page_container;
			
			// Initialise meta data
			meta.data(current_page,0);
			meta.data(items_per_page, options.items_per_page);
					
			// Get the total number of items
			var total_items = $item_container.children().size();
			
			// Added by JS - hide controls and exit if not needed (ie. few items in list)
			if(total_items <= options.items_per_page) { 
				return false;
			} else {
				$page_container.append('<div class="page-navigation"></div>');	 //add controls
			}
			
			// Calculate the number of pages needed
			var number_of_pages = Math.ceil(total_items/options.items_per_page);
			
			// Construct the nav bar
			var more = '<span class="ellipse more">...</span>';
			var less = '<span class="ellipse less">...</span>';
			
			var navigation_html = '<a class="first_link" href="">'+ options.nav_label_first +'</a>';
			navigation_html += '<a class="previous_link" href="">'+ options.nav_label_prev +'</a>'+ less;
			var current_link = 0;
			while(number_of_pages > current_link){
				navigation_html += '<a class="page_link" href="" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
				current_link++;
			}
			navigation_html += more + '<a class="next_link" href="">'+ options.nav_label_next +'</a>';
			navigation_html += '<a class="last_link" href="">'+ options.nav_label_last +'</a>';
			
			// And add it to the appropriate area of the DOM	
			$nav_panels = $page_container.find(options.nav_panel_id);			
			$nav_panels.html(navigation_html).each(function(){
			
				$(this).find('.page_link:first').addClass('first');
				$(this).find('.page_link:last').addClass('last');
				
			});
			
			// Hide the more/less indicators
			$nav_panels.children('.ellipse').hide();
			
			// Set the active page link styling
			$nav_panels.find('.previous_link').next().next().addClass('active_page');
			
			/* Setup Page Display */
			// And hide all pages
			$items.hide();
			// Show the first page			
			$items.slice(0, meta.data(items_per_page)).show();

			/* Setup Nav Menu Display */
			// Page number slices
			
			var total_page_no_links = $page_container.children(options.nav_panel_id+':first').children('.page_link').size();
			options.num_page_links_to_display = Math.min(options.num_page_links_to_display,total_page_no_links);

			$nav_panels.children('.page_link').hide(); // Hide all the page links
			
			// And only show the number we should be seeing
			$nav_panels.each(function(){
				$(this).children('.page_link').slice(0, options.num_page_links_to_display).show();			
			});
			
			/* Bind the actions to their respective links */
			 
			// Event handler for 'First' link
			$page_container.find('.first_link').click(function(e){
				e.preventDefault();
				
				movePageNumbersRight($(this),0);
				goto(0);				
			});			
			
			// Event handler for 'Last' link
			$page_container.find('.last_link').click(function(e){
				e.preventDefault();
				var lastPage = total_page_no_links - 1;
				movePageNumbersLeft($(this),lastPage);
				goto(lastPage);				
			});			
			
			// Event handler for 'Prev' link
			$page_container.find('.previous_link').click(function(e){
				e.preventDefault();
				showPrevPage($(this));
			});
			
			
			// Event handler for 'Next' link
			$page_container.find('.next_link').click(function(e){
				e.preventDefault();				
				showNextPage($(this));
			});
			
			// Event handler for each 'Page' link
			$page_container.find('.page_link').click(function(e){
				e.preventDefault();
				goto($(this).attr('longdesc'));
			});			
			
			// Goto the required page
			goto(parseInt(options.start_page));
			toggleMoreLess();
		});
		
		function showPrevPage(e){
			new_page = parseInt(meta.data(current_page)) - 1;						
			
			// Check that we aren't on a boundary link
			if($(e).siblings('.active_page').prev('.page_link').length==true){
				movePageNumbersRight(e,new_page);
				goto(new_page);
			}
				
		};
			
		function showNextPage(e){
			new_page = parseInt(meta.data(current_page)) + 1;
			
			// Check that we aren't on a boundary link
			if($(e).siblings('.active_page').next('.page_link').length==true){		
				movePageNumbersLeft(e,new_page);
				goto(new_page);
			}
				
		};
			
		function goto(page_num){
			
			var ipp = meta.data(items_per_page);
			
			var isLastPage = false;
			
			// Find the start of the next slice
			start_from = page_num * ipp;
			
			// Find the end of the next slice
			end_on = start_from + ipp;
			// Hide the current page	
			$items.hide()
					.slice(start_from, end_on)
					.show();
			
			// Reassign the active class
			$page_container.find(options.nav_panel_id).children('.page_link[longdesc=' + page_num +']').addClass('active_page')
													 .siblings('.active_page')
													 .removeClass('active_page');										 
			
			// Set the current page meta data							
			meta.data(current_page,page_num);
			
			// Hide the more and/or less indicators
			toggleMoreLess();
		};	
		
		// Methods to shift the diplayed index of page numbers to the left or right
		function movePageNumbersLeft(e, new_p){
			var new_page = new_p;
			
			var $current_active_link = $(e).siblings('.active_page');
		
			if($current_active_link.siblings('.page_link[longdesc=' + new_page +']').css('display') == 'none'){
				
				$nav_panels.each(function(){
							$(this).children('.page_link')
								.hide() // Hide all the page links
								.slice(parseInt(new_page - options.num_page_links_to_display + 1) , new_page + 1)
								.show();		
							});
			}
			
		} 
		
		function movePageNumbersRight(e, new_p){
			var new_page = new_p;
			
			var $current_active_link = $(e).siblings('.active_page');
			
			if($current_active_link.siblings('.page_link[longdesc=' + new_page +']').css('display') == 'none'){
												
				$nav_panels.each(function(){
							$(this).children('.page_link')
								.hide() // Hide all the page links
								.slice( new_page , new_page + parseInt(options.num_page_links_to_display))
								.show();
							});
			}
		}
		
		// Show or remove the ellipses that indicate that more page numbers exist in the page index than are currently shown
		function toggleMoreLess(){
													 
			if(!$nav_panels.children('.page_link:visible').hasClass('last')){					
				$nav_panels.children('.more').show();
			}else {
				$nav_panels.children('.more').hide();
			}
			
			if(!$nav_panels.children('.page_link:visible').hasClass('first')){
				$nav_panels.children('.less').show();
			}else {
				$nav_panels.children('.less').hide();
			}			
		}
		
	};
	
})(jQuery);

/**
 * jQuery.labelify - Display in-textbox hints
 * Stuart Langridge, http://www.kryogenix.org/
 * Released into the public domain
 * Date: 25th June 2008
 * @author Stuart Langridge
 * @version 1.3
 *
 *
 * Basic calling syntax: $("input").labelify();
 * Defaults to taking the in-field label from the field's title attribute
 *
 * You can also pass an options object with the following keys:
 *   text
 *     "title" to get the in-field label from the field's title attribute 
 *      (this is the default)
 *     "label" to get the in-field label from the inner text of the field's label
 *      (note that the label must be attached to the field with for="fieldid")
 *     a function which takes one parameter, the input field, and returns
 *      whatever text it likes
 *
 *   labelledClass
 *     a class that will be applied to the input field when it contains the
 *      label and removed when it contains user input. Defaults to blank.
 *  
 */
jQuery.fn.labelify = function(settings) {
	settings = jQuery.extend({
		text: "title",
		labelledClass: ""
		}, settings);
		var lookups = {
			title: function(input) {
			return $(input).attr("title");
		},
		label: function(input) {
		return $("label[for=" + input.id +"]").text();
		}
	};
	var lookup;
	var jQuery_labellified_elements = $(this);
	
	return $(this).each(function() {
			
		if (typeof settings.text === "string") {
			lookup = lookups[settings.text]; // what if not there?
		} else {
			lookup = settings.text; // what if not a fn?
		};
		// bail if lookup isn't a function or if it returns undefined
		if (typeof lookup !== "function") { return; }
		var lookupval = lookup(this);
		if (!lookupval) { return; }
		
		//added by JS to handle value being set after validation - won't show label again on delete though :(
		if($(this).val() != "") { return; } 
		
		// need to strip newlines because the browser strips them
		// if you set textbox.value to a string containing them    
		$(this).data("label",lookup(this).replace(/\n/g,''));
		
		$(this).focus(function() {
			if (this.value === $(this).data("label")) {
				this.value = this.defaultValue;
				$(this).removeClass(settings.labelledClass);
			}
		}).blur(function(){
			if (this.value === this.defaultValue) {
				this.value = $(this).data("label");
				$(this).addClass(settings.labelledClass);
			}
		});
		
		var removeValuesOnExit = function() {
			jQuery_labellified_elements.each(function(){
				if (this.value === $(this).data("label")) {
					this.value = this.defaultValue;
					$(this).removeClass(settings.labelledClass);
				}
			})
		};
		
		$(this).parents("form").submit(removeValuesOnExit);
		$(window).unload(removeValuesOnExit);
		
		if (this.value !== this.defaultValue) {
			// user already started typing; don't overwrite their work!
			return;
		}
		
		// actually set the value
		this.value = $(this).data("label");
		$(this).addClass(settings.labelledClass);
		
	});
};


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
