/**
 *  SLC Gov accordion handler.  This attaches a ui.accordion to a field_collection item
 *
 *	Most of this is taken from the views_accordion module
 *	Except we're not using views...these are fields
*/
(function ($) {
	$(function() { 
	  /* Our view settings */
	  var usegroupheader = false;
	  var viewname = 'accordion';
	  var display = 'page';

	  /* the selectors we have to play with */
	  
	  //var displaySelector = '.field-name-field-test-collection .field-items';
	  var displaySelector = '.field-collection-item-field-accordion-container .content';

	  var headerSelector = '.field-name-field-accordion-item-title';
	  var subtitleSelector = '.field-name-field-accordion-item-sub-title';
	  
	  //Relative to current item
      var iconSrc = '.field-name-field-accordion-item-icon .field-item';
	
	
	  $(displaySelector + ' ' + headerSelector+':not(.ui-accordion-header)').each(function() {
			var $this = $(this);
			
			var iconUrl = $this.parent().find(iconSrc).text();

			var subTitle = $this.parent().find(subtitleSelector);
			$this.append(subTitle.text());
			subTitle.remove();
			 $this.wrapInner('<a href="javascript:void(0);"></a>');
			 $this.siblings().wrapAll('<div></div>');
			 
			//Add the icon to the left
			$this.css({
				'background-image'		: 'url(' + iconUrl + ')', 
				'min-height'				:	72,
				'background-repeat'		: 'no-repeat', 
				'background-position'	: 'left top'
			});
			 
		});
	
	  /* jQuery UI accordion call */

	  $(displaySelector +':not(.ui-accordion)').accordion({
		  header: headerSelector,
		  active : false,
		  collapsible : true, 
		  autoHeight : false
	  });
	  
	  
	  });
})(jQuery);
;
/** 
 *	jCookieBookmarks v1.0.9
 *
 *	Version log:
 *	v1.0.9  - Added external_links_open_new_window option
 *  v1.0.8  - Fixed script error when using this.disableSelection, instead of obj.disableSelection
 *  v1.0.7  - Changed images, added 'add' functionality so it's not an external dependancy (this is how it should've always worked...)
 *  v1.0.6  - Added 'last' class for last item link, fixed for drupal compat
 *	v1.0.5	- Made text button links image-based
 *	v1.0.4	- Fixed centering of control link anchors, moved stylesheet to separate file
 *	v1.0.3	- Fixed bug: Restoring to defaults after all links are removed is not working, proper opts jq object instead of global var
 *	v1.0.2	- Fixed cookies not saving after browser is closed - added $.fn.jcookiebookmarks.opts.cookie_opts for passing options to cookie plugin
 *	v1.0.1	- Updated css styles, fixed sortable being sortable after cancel & proper cancellation of sortable changes
 *
 *	Known Bugs:
 *		none
*/
;
(function($) {
	//var opts;

	$.fn.jcookiebookmarks = function(config) { 
		$.fn.jcookiebookmarks.opts = $.extend({
				'store'					:	'jcookiebookmarks',
				'max'					:	15,
				'notice_position'		:	'left',
				'control_link_margin'	:	20,
				'external_links_open_new_window' :	true,
				'target'				:	'',
				'def'					:	[],
				'bookmarks_name'		:	'Quick Links',
				'cookie_opts'			:	{'path':'/', 'expires' : 4096},
				'title_delimiter'		:	'|', 
				'title_offset'			:	0,
				'use_title_formatter'	:	true,
				'current_storage_version'		:	20120126,	//Changing this will reset all bookmarks to defaults, custom links will be lost
				title_formatter			:	function(title) { 
												var offset = this.title_offset; 
												var count, offset_position;
												
												if ( offset > 0 ) { 
													while( count <= offset ) {
														offset_position = title.indexOf( $.fn.jcookiebookmarks.opts.title_delimiter, offset_position); 
														count++; 
													}
													offset = offset_position; 
												}
												
												var end = title.indexOf( $.fn.jcookiebookmarks.opts.title_delimiter, offset);
												
												if ( end == -1 ) {
													//Not found, use the whole title
													return title;
												}

												title = title.substring(0, end);
												
												//ltrim / rtrim
												title = title.replace(/^\s+|\s+$/g,"");

												return title;
											}
										
				
		}, config);
		
		/*********************************
		 *	Internal methods
		*********************************/
		
		/** 
		 *	Make the currently nested anchors default
		 *	This should only be called during initialization
		 *	Added external_links_open_new_window option - this only happens on defaults, so we only need to modify this here
		 *	@param container The bookmark container
		*/
		
		function save_defaults(container) { 
			var c = 0; 
			
			var def = $.fn.jcookiebookmarks.get('bookmarks-default');
			
			//Prevent multiple containers from being duplicated
			if ( def.length > 0 ||  $(container).hasClass('jcb-init') ) 
				return false;

			$('a', container).each(function() {
				if ( def.length >= $.fn.jcookiebookmarks.opts.max ) {
					return true;
				}
				def.unshift({
					'url' : $(this).attr('href'), 
					'title' : $(this).text()
				});
				return true;
			}); 
			$.fn.jcookiebookmarks.set('bookmarks-default', def);

			return true;

		}

		return this.each(function() {

			//If we can't store data reliable, just exit & leave the container alone
			if ( $.fn.jcookiebookmarks.verify_storage_engine() === true ) { 
			
				//Clear old defaults
				$.fn.jcookiebookmarks.set('bookmarks-default', [] );			
				
				//Get current version
				var ver = $.fn.jcookiebookmarks.get('bookmarks-version');
				//Clear old bookmarks if we're on a new version
				if ( ver != $.fn.jcookiebookmarks.opts.current_storage_version ) {
					$.fn.jcookiebookmarks.set('bookmarks-version', $.fn.jcookiebookmarks.opts.current_storage_version )
					$.fn.jcookiebookmarks.set('bookmarks', [] )
				}

				
				save_defaults(this);
				
				$.fn.jcookiebookmarks.attach_view(this); 
				$(this).addClass('jcb-init');		
				
			}


			
		}); 
	};
	
	/**********************************
	 *	Properties
	**********************************/
	$.fn.jcookiebookmarks.opts = {};
	
	/**********************************
	 *	Public methods
	**********************************/
	
	/** 
	 *	Retreieve data from the local storage
	 *	@param id		The key of the data to locate
	 *	@return mixed	False on failure, JSON Object on success
	*/
	$.fn.jcookiebookmarks.get = function(id) { 
		var key = $.fn.jcookiebookmarks.opts.store + '['+id+']';
		var d = $.fn.jcookiebookmarks.cookie(key);
		if ( d != undefined ) { 
			d = $.evalJSON(d);
			return d;
		}
		return false; 
	}
	
	/** 
	 *	Add data to the local storage
	 *	@param id  		The key used to store data
	 *	@param value	The data to set
	 *	@return bool	True on success, false on failure
	*/
	$.fn.jcookiebookmarks.set = function(id,value) { 
		var key = $.fn.jcookiebookmarks.opts.store + '['+id+']';
		try { 
			if ( $.fn.jcookiebookmarks.cookie(key, $.toJSON(value), $.fn.jcookiebookmarks.opts.cookie_opts ) ) {
				return true;
			}
		} catch(e){}
		
		return false;
	};
	
	
	/** 
	 *	Test the storage engine & make sure we can get/set data
	 *	If cookies are disabled & the page is loaded, we're thrown into an infite loop trying to get data
	 *	This function is checked during init to verify cookies, otherwise we'll leave items at default
	 *
	*/
	$.fn.jcookiebookmarks.verify_storage_engine = function() { 
		var r = Math.random(); 
		$.fn.jcookiebookmarks.set('test-engine', r); 
		
		var test = $.fn.jcookiebookmarks.get('test-engine'); 

		if ( r != test ) {
			return false; 
		}
		$.fn.jcookiebookmarks.set('test-engine', null); 
		
		return true;
	};	
	
	
	
	/** 
	 *	Add an 'Edit' link to the end of bookmark container
	 *	@param container The bookmark container
	*/
	$.fn.jcookiebookmarks.append_edit_link = function(container) { 
		//Add the edit button
		$('<a/>').attr({
				'href'	:	'javascript:void(0);',
				'class'	:	'jcb-edit-button jcb-edit-link jcb-button',
				'style'	:	''
			})
			.html('')
			.click(function() {
				$.fn.jcookiebookmarks.edit( container );								
			})
			.appendTo(container)
		;

		//Add the new button
		$('<a/>')
			.attr({
				'href'	:	'javascript:void(0);',
				'class'	:	'jcb-add-button jcb-edit-link jcb-button',
				'style'	:	''
			})
			.html('')
			.click(function() {
				$.fn.jcookiebookmarks.add();
				//$.fn.jcookiebookmarks.edit( container );								
			})
			.appendTo(container)
		;		
		
		

		return true;
	}; 

	/** 
	 *	Attach bookmark view to container.  All contents of container will be reset
	 *	@param container The bookmark container object
	*/
	$.fn.jcookiebookmarks.attach_view = function(container) { 
		var d = $.fn.jcookiebookmarks.get('bookmarks');
		var html; 
		$(container).html('');
		
		if ( d  != false ) {
			if ( d.length > 0 ) { 
				for( i = 0; i < d.length; i++ ) { 
					if ( d[i].url && d[i].title ) { 
						//Build the anchor

						//Items are built from bottom up, so index 0 is the 'last' item
						var cls = ( i == 0 ) ? 'last' : '';
						
						var a = $('<a/>');
									a.attr({
										'href'		:	d[i].url,
										'title' 	:	d[i].title, 
										'target'	:	$.fn.jcookiebookmarks.opts.target, 
										'class'		:	cls
									
									})
									.html( d[i].title )
						;
						$(a).prependTo(container);
						
					}
				}

				$.fn.jcookiebookmarks.append_edit_link(container);
				
				$.fn.jcookiebookmarks.attach_external_links(container);
				
				return true;
			}
		}
		else {
			
			var def = $.fn.jcookiebookmarks.get('bookmarks-default');			
			
			if ( def.length > 0 ) {

				if ( $(container).hasClass('jcb-init') ) { 
					//Links have been restored to default AFTER initilization, display a message
					$.fn.jcookiebookmarks.notice( $.fn.jcookiebookmarks.opts.bookmarks_name + ' have been restored to default settings.');
				}

				$.fn.jcookiebookmarks.set('bookmarks', def);
				//return $.fn.jcookiebookmarks.update_all_views();
				return $.fn.jcookiebookmarks.attach_view(container);
			} else {
				//This should not happen unless there were no links in static page
				return false;
			}
		}
					
	};

	/**
	 *	Make external links open in new window if requested
	*/
	$.fn.jcookiebookmarks.attach_external_links = function(container) {
		if ( !$.fn.jcookiebookmarks.opts.external_links_open_new_window )
			return;
		
		var url = document.location.protocol + '//' + document.location.host;
		
		//Find external links
		var $extlinks = $(container)
			.find('a')
				.not('[href^="' + url + '"]')
					.not('.jcb-button')
						.not('[href^="javascript"]');
		
		$extlinks.attr('target', '_blank');
		
	}

	/** 
	 *	Mark a link for removal
	 *	@param a The Anchor Object to be removed
	 *
	*/
	$.fn.jcookiebookmarks.remove = function(a) { 
		$(a).css({
				'text-decoration':'line-through'
			})
			.fadeTo(300,0.5)
			.addClass('jcb-pending-removal')
		;
		
		$(a)
			.data('control-link')
			.css({'font-size' : '14px'})
			.html('x')
			.attr({
				'title'	:	'Restore Link',
				'class'	:	'jcb-edit-link jcb-control-link ui-icon ui-icon-arrowreturnthick-1-w'
				
			})
			.unbind('click')
			.data('link' , $(a) )
			.click(function() {
				$.fn.jcookiebookmarks.cancel_pending_removal(this);
			})
		;
		return true;
		
	};
	
	/** 
	 *	Cancel removing a specific link
	 *	@param that The jcb-edit-link control anchor
	*/
	$.fn.jcookiebookmarks.cancel_pending_removal = function(that) {
		if ( $(that).data('link').hasClass('jcb-pending-removal') ) {
			$(that)
				.html('-')
				.css({ 'font-size' : '22px' })
				.unbind('click')
				.attr({
					'title' :	'Remove Link',
					'class'	:	'jcb-edit-link jcb-control-link ui-icon ui-icon-circle-minus'
				})
				.bind('click', function() {
					$.fn.jcookiebookmarks.remove( $(that).data('link') );
				})
				.data('link')
				.removeClass('jcb-pending-removal')
				.css({ 'text-decoration' : '' })
				.fadeTo(200,1)
			;
		}
	};
	
	/** 
	 *	Commit all pending changes & exit editor mode
	 *	@param container The bookmark container
	*/
	$.fn.jcookiebookmarks.save = function(container) {
		if ( $.fn.jcookiebookmarks.verify_storage_engine() == false ) { 
			//Cannot reliably save information, but add button has been clicked. Display a message for the user. 
			$.fn.jcookiebookmarks.notice('Could not save '+$.fn.jcookiebookmarks.opts.bookmarks_name+'.  Cookies do not appear to be working properly.');
			return false;
		}

		var d = []; 

		$('.jcb-pending-removal', container).remove(); 
		
		$('a', container).not('.jcb-edit-link').each(function() {
			var item = {
				'url'	: $(this).attr('href').toString(), 
				'title' : $(this).html().toString()
			}; 
			d.push(item);			
		});

		//IE Has no unshift support
		d.reverse(); 
		
		if ( d ) { 
			$.fn.jcookiebookmarks.set('bookmarks', d);
		}
		$(container).removeClass('jcb-edit');
		
		$.fn.jcookiebookmarks.notice('Changes Saved');


		//$.fn.jcookiebookmarks.attach_view(container);
		$.fn.jcookiebookmarks.update_all_views();
		
		
	};

	/**
	 *	Add teh control links (Save/Cancel)
	 *	@param that The Bookmarks Container
	*/
	$.fn.jcookiebookmarks.attach_control_link = function(that) { 
		var icon = ( $(that).hasClass('jcb-pending-removal') ) ? 'ui-icon-arrowreturnthick-1-w' : 'ui-icon-circle-minus';
		var a = $('<a />')
			.attr({
				'class'	:	'jcb-edit-link jcb-control-link ui-icon ' + icon,
				'href' 	: 	'javascript:void(0);', 
				//'style' :	'float:left;text-decoration:none;margin-right:5px;line-height:13px;font-size:22px;padding-top:1px;', 
				'title'	:	'Remove Link'
			})
			.html('')
			.click(function() {
				$.fn.jcookiebookmarks.remove( $(this).data('link') );
			})
			.css({
				'position'	:	'absolute',
				'top'		:	$(that).offset().top + ($(that).height()/2),
				'left'		:	$(that).offset().left - $.fn.jcookiebookmarks.opts.control_link_margin
				
			})
			.data('link' , $(that) )
		;
		$(that).data('control-link', a);
		
		return $(a).appendTo('body');
		
		
	};

	/** 
	 *	Enable bookmark editing mode
	 *	@param that The bookmark container
	*/
	$.fn.jcookiebookmarks.edit = function(that) { 
	
		if ( $(that).hasClass('jcb-init') && !$(that).hasClass('jcb-edit') ) { 
			$(that).addClass('jcb-edit');
			$('a', that).not('.jcb-edit-link').each(function() {
				//Setup the delete link
				$.fn.jcookiebookmarks.attach_control_link( this );
			});

			//Change the Edit button to Save
			$('.jcb-edit-button', that)
				.html('')
				.addClass('jcb-save-button')
				.unbind('click')
				.bind('click', function() {
					$.fn.jcookiebookmarks.save( $(this).parents('.jcb-edit') );
				})
			;
			
			//Remove the add link
			$('.jcb-add-button', that).remove();
			
			//Create the cancel button
			$('<a/>')
				.attr({
					'class'	:	'jcb-edit-link jcb-cancel-button jcb-button', 
					'href'	:	'javascript:void(0);',
					'style' :	'',
					'title'	:	'Cancel Changes'
				})
				.html('')
				.click(function() {
					//Cancel pending changes
					var container = $(this).parents('.jcb-edit');
					$.fn.jcookiebookmarks.cancel();
				})
				.appendTo( that ) 
			;
			
			//Enable drag/drop sorting
			$(that).sortable({
				update: function(event,ui) { 
					//Update the control links
					$('a', $(ui.item).parents('.jcb-init') ).not('.jcb-edit.link').each(function() {

						$(this).data('control-link').remove(); 
						var a = $.fn.jcookiebookmarks.attach_control_link(this);
					}); 
				}
			});
		
			$(that).disableSelection();
		
		}

		return true;	
	};
	
	/** 
	 *	Cancel pending updates & restore container
	*/
	$.fn.jcookiebookmarks.cancel = function() { 

			//These are attached to body
			$('.jcb-control-link').remove();

			$('.jcb-init').each(function() { 
				//Disable sortable links

				$('.jcb-pending-removal', this ).css({ 'text-decoration' : '' }).fadeTo(200,1).removeClass('jcb-pending-removal');
				$('.jcb-edit-link', this).remove();
				$(this).removeClass('jcb-edit');

				//Restores the bookmarks from saved cookies
				$.fn.jcookiebookmarks.attach_view(this);
				$(this).sortable('destroy');
	
				//$(this).remove(); 
				//$.fn.jcookiebookmarks.append_edit_link(this);					
				
				
			});
			
			
		
	};
	
	/** 
	 *	Add a new link to the bookmarks
	 *	@param config Config Object
	 *	Config Options
	 *	---------------
	 *	url - The URL to link (default: current page)
	 *	title - The title of the page ( default: current page)
	 *	
	 *	@return bool True on success, false if link was not added
	 *	
	*/
	$.fn.jcookiebookmarks.add = function(config) { 


		if ( $.fn.jcookiebookmarks.verify_storage_engine() == false ) { 
			//Cannot reliably save information, but add button has been clicked. Display a message for the user. 
			$.fn.jcookiebookmarks.notice('Could not save '+$.fn.jcookiebookmarks.opts.bookmarks_name+'.  Cookies do not appear to be working properly.');
			return false;
		}
		

		var item = $.extend({
			'url' 		: 	document.location.toString(), 
			'title' 	: 	document.title.toString(), 
			'target'	:	$.fn.jcookiebookmarks.opts.target 
		}, config);	
		
		if ( $.fn.jcookiebookmarks.opts.title_formatter && $.fn.jcookiebookmarks.opts.use_title_formatter == true ) { 
			item.title = $.fn.jcookiebookmarks.opts.title_formatter(item.title);
		}
		
		var d = $.fn.jcookiebookmarks.get('bookmarks');
		
		//Check if maximum links reached
		if ( d.length >= $.fn.jcookiebookmarks.opts.max ) { 
			$.fn.jcookiebookmarks.notice('Sorry, you\'ve reached the maximum number of '+$.fn.jcookiebookmarks.opts.bookmarks_name+' (' + $.fn.jcookiebookmarks.opts.max + ').  Please remove an item to continue.');
			return false;
		}
		
		//Check for duplicated links
		if ( $.fn.jcookiebookmarks.check_for_dupe(item) == true ) { 
			$.fn.jcookiebookmarks.notice('This link has already been added.');
			return false;
		}

		//Add the item to the beginning of the list
		d.push({
			'url' : item.url, 
			'title' : item.title
		}); 

		//Save data
		$.fn.jcookiebookmarks.set('bookmarks', d);

		//Update all the containers
		$.fn.jcookiebookmarks.update_all_views();
		
		
		$.fn.jcookiebookmarks.notice($.fn.jcookiebookmarks.opts.bookmarks_name + ' updated.');
		
		//return true;
	};
	
	/** 
	 *	run attach_view for each initialized bookmark container
	 *	This will syncronize multiple bookmark containers on one page
	*/
	$.fn.jcookiebookmarks.update_all_views = function() {
		
		$.fn.jcookiebookmarks.cancel();
		
		$('.jcb-init').each(function() { 
			//Cancel editing mode if active
			$.fn.jcookiebookmarks.attach_view(this);
		}); 
	};
	
	
	/** 
	 *	Create a notification using jQuery notify
	 *	@param msg string		The message to display
	 *	@param config object	The notify config object (may be omitted)
	 *	@return	mixed jquery notify response
	*/
	$.fn.jcookiebookmarks.notice = function(msg, config) { 
		var notice = $.extend({
			'position'	:	$.fn.jcookiebookmarks.opts.notice_position, 
			'stay'		:	false, 
			'text'		:	msg
		}, config);
		
		if ( !notice.text ) {
			return false;
		}
		
		return $.noticeAdd( notice );
		
	};
	
	/** 
	 *	Check for a duplicated link
	 *	@param item Link object to check
	 *	@return bool true if duplicate, false otherwise
	*/
	$.fn.jcookiebookmarks.check_for_dupe = function(item) { 
		var d = $.fn.jcookiebookmarks.get('bookmarks');
		for( i=0; i < d.length; i++ ) { 
			if ( item.url == d[i].url ) {
				return true;
			}
		}
		return false;
	
	};
	
	/** 
	 * jQuery cookie from
	 * http://plugins.jquery.com/files/jquery.cookie.js.txt
	*
	 * 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
	 *
	 */
	$.fn.jcookiebookmarks.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;
		}
	};	//end cookie

	
})(jQuery);


/** 
 *	jquery.json.min.js 
 *	
*/

(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);



/** 
 *		jQuery notice
 *		modified to use scrollTop() to position the thing properly if we're scrolled down
 *		Also added left/right positioning option and side_margin
*/
/**
*       jQuery.noticeAdd() and jQuery.noticeRemove()
*       These functions create and remove growl-like notices
*
*   Copyright (c) 2009 Tim Benniks
*
*       Permission is hereby granted, free of charge, to any person obtaining a copy
*       of this software and associated documentation files (the "Software"), to deal
*       in the Software without restriction, including without limitation the rights
*       to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*       copies of the Software, and to permit persons to whom the Software is
*       furnished to do so, subject to the following conditions:
*
*       The above copyright notice and this permission notice shall be included in
*       all copies or substantial portions of the Software.
*
*       THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*       IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*       FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*       AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*       LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*       OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*       THE SOFTWARE.
*
*       @author         Tim Benniks <tim@timbenniks.com>
*       @copyright  2009 timbenniks.com
*       @version    $Id: jquery.notice.js 1 2009-01-24 12:24:18Z timbenniks $
**/
(function(jQuery)
{
        jQuery.extend({
                noticeAdd: function(options)
                {
                        var defaults = {
                                inEffect:                       {opacity: 'show'},      // in effect
                                inEffectDuration:       600,                            // in effect duration in miliseconds
                                stayTime:                       3000,                           // time in miliseconds before the item has to disappear
                                text:                           '',                                     // content of the item
                                stay:                           false,                          // should the notice item stay or not?
                                type:                           'notice',                        // could also be error, succes
                                side_margin:					'20px',
                                position:						'right'
                        }

                        // declare varaibles
                        var options, noticeWrapAll, noticeItemOuter, noticeItemInner, noticeItemClose;

                        options                 = jQuery.extend({}, defaults, options);
                        noticeWrapAll   = (!jQuery('.notice-wrap').length) ? jQuery('<div></div>').addClass('notice-wrap').appendTo('body') : jQuery('.notice-wrap');
                        noticeItemOuter = jQuery('<div></div>').addClass('notice-item-wrapper');
                        noticeItemInner = jQuery('<div></div>').hide().addClass('notice-item ' + options.type).appendTo(noticeWrapAll).html('<p>'+options.text+'</p>').animate(options.inEffect, options.inEffectDuration).wrap(noticeItemOuter);
                        noticeItemClose = jQuery('<div></div>').addClass('notice-item-close').prependTo(noticeItemInner).html('x').click(function() { jQuery.noticeRemove(noticeItemInner) });

						
						var css = ( options.position == 'right' ) ? 
							{ 'right': options.side_margin, 'left': ''} : 
							{ 'left' : options.side_margin, 'right': ''}
						;
						
						css.top = jQuery(window).scrollTop()+10 ;
						
						
                        // hmmmz, zucht
                        // Uh, why only IE?
                        /*
                        if(navigator.userAgent.match(/MSIE 6/i)) 
                        {
	                        noticeWrapAll.css({top: document.documentElement.scrollTop});
    	                }
    	                */
    	                
    	                noticeWrapAll.css(css);
                        if(!options.stay) {
                                setTimeout(function() {
                                        jQuery.noticeRemove(noticeItemInner);
                                }, options.stayTime);
                        }
                },

                noticeRemove: function(obj)
                {
                        obj.animate({opacity: '0'}, 600, function()
                        {
                                obj.parent().animate({height: '0px'}, 300, function()
                                {
                                        obj.parent().remove();
                                });
                        });
                }
        });
})(jQuery);


;
/*
 *	Modiifeid by PPBH
*/
/**************************************************************************
 * Name:   EmbedPicasaGallery
 * Author: Tobias Oetiker <tobi@oetiker.ch>
 * Demo:   http://tobi.oetiker.ch/photo/
 * $Id: jquery.EmbedPicasaGallery.js 422 2010-06-20 11:01:01Z oetiker $
 **************************************************************************
 Description:
 
 This little script asks picasa web for a list of albums and for a list
 of pictures in the album. It then emits a series of <div class="pic-thumb"/>
 elements containing thumbnail images. The divs are inserted inside the element
 marked with a particular id. Clicking on an album will display thumbnails of the
 images in the album and clicking on a thumbnail will show the image itself
 using slimbox.
 
 The script itself uses jQuery (http://www.jquery.org) and slimbox2
 (http://www.digitalia.be/software/slimbox2) to work. So you have to load
 these two guys before loading the gallery script. You can load them in the
 header or the body of the document, this does not matter.
 
  <script type="text/javascript" src="js/jquery.js"></script>
  <link rel="stylesheet" href="css/slimbox2.css" type="text/css" media="screen" />
  <script type="text/javascript" src="slimbox2.js"></script>
  <script type="text/javascript" src="js/jquery.EmbedPicasaGallery.js"></script>

 Once loaded, call the picasaGallery function. This activates the
 code. With the id argument you tell it, where to put the gallery.

  <script type="text/javascript">
  jQuery(document).ready(function() {
  jQuery("#images").EmbedPicasaGallery('oetiker',{
      matcher:            /./,         // string or regexp to match album title
      size:               '72',        // thumbnail size (32, 48, 64, 72, 144, 160)
      msg_loading_list :  'Loading album list from PicasaWeb',
      msg_back :          'Back',
      authkey :           'optional-picasa-authkey',
      albumid :           'go-directly-to-this-album-ignore-matcher',
      album_title_tag:    '<h2/>',
      thumb_id_prefix:    'pThumb_',
      loading_animation: 'css/loading.gif',
      thumb_finalizer:    function(){var $a = jQuery(this); ... use this to do something to the anchor AFTER slimbox got there },
      thumb_tuner:        function($div,entry,i){ ... $div is the div of the thumbnail, entry is the picasa image info ...}
      link_mapper: function(el){  // see http://code.google.com/p/slimbox/wiki/jQueryAPI#The_linkMapper_function
            return [
                     el.href,
                     '<a href="'+el.href+'">'+el.title+'</a>'
                   ]
            }
   });
  });
  </script>

 Finally inside the document, add a div tag with the id set to the name
 chosen above.
 
 <div id="images"></div>

**********************************************************************************/

(function($) {
    // setup a namespace for us
    var nsp = 'EmbedPicasaGallery', authkey;

    // Private Variables and Functions in the _ object
    // note that this will refer to _ unless you
    // call using the call or apply methods

    // Public Variables and Methods
    $[nsp] = {
        defaultOptions: {
            matcher : RegExp('.+'),
            size    : 72,
            msg_loading_list : 'Loading album list from PicasaWeb',
            msg_back : 'Back',
            album_title_tag: '<h2/>',
            thumb_id_prefix: 'pThumb_',
            back_button : 'css/back_btn.gif',
            thumb_tuner: null,
            thumb_finalizer: null,
            loading_animation: null,
            slimbox : true,
            link_mapper: function(el){
                    return [
                        el.href,
                        '<a href="'+el.href+'">'+el.title+'</a>'
                    ]
                }
        } 
    };
    $.fn[nsp] = function(user,opts) {
        var localOpts,
            Cache = {};

        localOpts = $.extend( 
            {}, // start with an empty map
            $[nsp].defaultOptions, // add defaults
            opts // add options
        );

        function showOverview() {
            var $this,
                meta_opts,
                albumCount,
                $album_list,
                authkey = '';

            if ( Cache.__overview ){
                 Cache.__overview.show();
                 return;
            }
            $this = $(this);
            $this.empty();
            $this.append($('<br/>').css('clear','left'));
            meta_opts = localOpts;
            if ($.meta){
                meta_opts = $.extend({}, localOpts, $this.data());
            }
            albumCount = 0;
            $album_list = $('<div/>')
                .addClass('album-list')
                .append($('<div/>').text(meta_opts.msg_loading_list));


            function appendImage(i,item){
                var title,$div,$img;
                title = item.media$group.media$title.$t;
                if (title.match(meta_opts.matcher)){
                    albumCount++;
                    $img = $('<img/>')
                        .attr('title',title)
                        .attr('src',item.media$group.media$thumbnail[0].url)
                    $div = $('<div/>')
                        .addClass('album-cover')
                        .css({
                            'float': 'left',
                            marginRight: '16px',
                            marginBottom: '16px'
                        })
                        .click(function () {
                           $album_list.hide();
                           showAlbum($this,meta_opts,item.gphoto$id.$t,title,item.gphoto$numphotos.$t);
                        })
                        .hover(
                            function () { $(this).css("cursor","pointer")},
                            function () { $(this).css("cursor","default")}
                        )
                        .append( $img )
                        .append(
                            $('<div/>')
                            .addClass('album-title')
                            .css({
                                'font-size': '10px'
                            })
                            .text(title)
                            .width( meta_opts.size )
                        )                    
                    $album_list.append($div);
                };
            }
            
            function renderAlbumList(data){
                var $albums,maxHeight=0;
                $album_list.empty();
        		if (data.feed && data.feed.entry){
    	            $.each(data.feed.entry,appendImage);
        		} else {
          		    $this.text('Warning: No picasa albums found for user ' + user);
		        }
                Cache.__overview = $album_list;
                $albums = $album_list.children();


                if (albumCount == 1){
                    $albums.eq(0).click();
                    return;
                }
                $('.album-title',$album_list)
                .each(function(){                        
                     var h = $(this).outerHeight();
                     if (h > maxHeight){
                        maxHeight = h
                     }
                })
                .each(function(){
                    $(this).height(maxHeight)
                });

            }


            if (meta_opts.authkey){
                authkey = '&authkey=' + meta_opts.authkey;
            }
 
    	    if (meta_opts.albumid) {
       	       showAlbum($this,meta_opts,meta_opts.albumid,'')
    	    }
	        else {
                $this.prepend($album_list);
                $.getJSON('http://picasaweb.google.com/data/feed/api/user/' 
                    + user + '?kind=album&access=visible' + authkey 
                    + '&alt=json-in-script&thumbsize=' + meta_opts.size + 'c&callback=?',
                    renderAlbumList
               );
	        }
        };

        function showAlbum($this,meta_opts,album,title,photoCount){                        
            if ( Cache[album] ){
               Cache[album].show();
               return;
            };
            var i,$album,albumPics=[],$albumDiv;

            $album = $('<div/>').addClass('album');

            if (title){
                $album.append($(meta_opts.album_title_tag).text(title))
            }

            function makeDiv(){
               var $div = $('<div/>')
                   .width(meta_opts.size)
                   .height(meta_opts.size)
                   .css({
                        'float': 'left',
                        marginRight: '16px',
                        marginBottom: '16px'
                    });
               if (meta_opts.loading_animation){
                   $div.css('background','url(' + meta_opts.loading_animation + ') no-repeat center center');            
               }
               return $div;
            }

            if (Cache.__overview){
                $album.append($("<div/>")
                    .addClass("pic-thumb")
                    .width(meta_opts.size)
                    .height(meta_opts.size)
                    .css({'border-width': '0px',
                         'float' : 'left',
                         marginRight: '16px',
                         marginBottom: '16px'
                     })
                    .append($("<div/>")
                       	.html('<img src="'+meta_opts.back_button+'" border="0" />')
                        .click(function(){$album.hide();showOverview()})
                        .css({'cursor': 'pointer'})
/*
                        .html('<br/>'+meta_opts.msg_back)
                        .click(function(){$album.hide();showOverview()})
                        .css({'border-style':'outset',
                              'border-width':'1px',
                              'text-align'  :'center',
                              'width'       : (meta_opts.size - 2) + 'px',
                              'height'      : (meta_opts.size - 2) + 'px'
                        })
*/
                    )
                 );
             }
            
            if (photoCount){
                for (i=0;i<photoCount;i++) {
                    $albumDiv = makeDiv();
                    $album.append($albumDiv);
                    albumPics.push($albumDiv);
                }
            }

            function appendImage(i,item){
               var title, $img, $div, $a;
               title = item.media$group.media$description.$t || item.media$group.media$title.$t;  
               $img = $(new Image());
               $img.load(function(){                   
                    if (meta_opts.thumb_tuner){
                        meta_opts.thumb_tuner($div,item);
                    }
                    $img.show();
               })
               .css('border-width','0px')
               .hide();



//http://video.google.com/googleplayer.swf?videoUrl=
//&autoplay=yes&speedcontrol=0
//http%3A%2F%2Fv1.nonxt3.googlevideo.com%2Fvideoplayback%3Fid%3D7f153e0419e9c32f%26itag%3D5%26begin%3D0%26len%3D2147483647%26app%3Dpicasa%26et%3DINVALID%26el%3DINVALID%26ip%3D0.0.0.0%26ipbits%3D0%26expire%3D2857754015%26sparams%3Did%2Citag%2Cip%2Cipbits%2Cexpire%26signature%3D64FF3293765EB0708CE6375F3972F422C75864DF.3A4269A0706F38419ADA4EE8445B22C0B4CE586E%26key%3Dck1

               
               var link_href = item.content.src; 
               if ( item.media$group.media$content[1] && item.media$group.media$content[1].medium == 'video' ) { 
               		if ( item.media$group.media$content[1].url ) { 
               		
						link_href = item.media$group.media$content[1].url;
						link_href = 'http://video.google.com/googleplayer.swf?videoUrl=' + escape(link_href) + '&autoplay=yes&speedcontrol=0';
					   $a = $("<a/>")
							.attr({
								'href': link_href, 
								'title':title,
								'video_width': item.media$group.media$content[0].width, 
								'video_height': item.media$group.media$content[0].height,
								'rel': item.media$group.media$content[0].width + ' ' + item.media$group.media$content[0].height
							})
						   .addClass('flash')
						   .append($img);
						
					}

               }  else {
				   $a = $("<a/>")
					   //.attr("href",item.content.src)
					   .attr("href",link_href)
					   .attr("title",title)
					   .append($img);
				}
               
               


               

               if (($div = albumPics[i]) == undefined){
                    $div = makeDiv();  
                    $album.append($div);
               }

               $div
                   .attr("id", meta_opts.thumb_id_prefix + item.gphoto$id.$t )
                   .append($a)
               $img.attr("src", item.media$group.media$thumbnail[0].url);                
            }

            function renderAlbum(data){
                $.each(data.feed.entry,appendImage);
	
				//Clear any old objects
				$('#lbCenter #lbImage').css('background-image', '');

				flash_padding = 20;
                if ($.fn.slimbox && meta_opts.slimbox == true ){
                    $('a',$album).not('.flash').slimbox({},meta_opts.link_mapper);
                    
  
                    $('a.flash',$album).each(function() {
                    	var w = parseInt($(this).attr('video_width'));
                    	var h = parseInt($(this).attr('video_height'));
                    	$(this).slimbox({
                    		initialWidth:w+flash_padding,
                    		initialHeight:h+flash_padding
                    	},meta_opts.link_mapper)
                    	.click(function() {
                    		$('#lbCenter #lbImage div').css({ 'width':w, 'height':h }).show();
							$('<div class="picasa-video-container" />').appendTo('#lbCenter #lbImage div')
								.css({
									'width': w,
									'height': h
								})
								.show()
								.flash({
									swf: 	$(this).attr('href'),
									width: 	w, 
									height: h
								});	
							$('#lbCenter #lbImage').show();
							return false;
	                   	});
                    	
                    });
  
                    
/*                   
                   $('a.flash',$album).slimbox({initialWidth:640,initialHeight:480},meta_opts.link_mapper).click(function() {
                   			$('#lbCenter div')
								.show()
								.flash({
									swf: 	$(this).attr('href'),
									width: 	640, 
									height: 480
								});	
							return false;
                   
                    }); 
*/
                }
                if (meta_opts.thumb_callback){
                    $('a',$album).each(meta_opts.thumb_callback);
                }
                Cache[album] = $album;
            }
            authkey = '';
            if (meta_opts.authkey){
               authkey = '&authkey=' + meta_opts.authkey;
            }
            $.getJSON('http://picasaweb.google.com/data/feed/api/user/' 
                + user + '/albumid/' 
                + album + '?kind=photo&access=visible' + authkey + '&alt=json-in-script&thumbsize='+meta_opts.size+'c&imgmax=800&callback=?',
                renderAlbum
            );
            $this.prepend($album);
        };

        return this.each(showOverview);
    };
})(jQuery);
;
/**
 *	Modified by PPBH
 *	added this line to remove flash objects & container div, in close() around line #236
		//Remove flash objects while the lightbox is closing
		$('#lbCenter #lbImage object, .picasa-video-container').remove();		
	
 	Removes embedded flash
*/
/*!
	Slimbox v2.04 - The ultimate lightweight Lightbox clone for jQuery
	(c) 2007-2010 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/

(function($) {

	// Global variables, accessible to Slimbox only
	var win = $(window), options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,
		ie6 = !window.XMLHttpRequest, hiddenElements = [], documentElement = document.documentElement,

	// Preload images
	preload = {}, preloadPrev = new Image(), preloadNext = new Image(),

	// DOM elements
	overlay, center, image, sizer, prevLink, nextLink, bottomContainer, bottom, caption, number;

	/*
		Initialization
	*/

	$(function() {
		// Append the Slimbox HTML code at the bottom of the document
		$("body").append(
			$([
				overlay = $('<div id="lbOverlay" />')[0],
				center = $('<div id="lbCenter" />')[0],
				bottomContainer = $('<div id="lbBottomContainer" />')[0]
			]).css("display", "none")
		);

		image = $('<div id="lbImage" />').appendTo(center).append(
			sizer = $('<div style="position: relative;" />').append([
				prevLink = $('<a id="lbPrevLink" href="#" />').click(previous)[0],
				nextLink = $('<a id="lbNextLink" href="#" />').click(next)[0]
			])[0]
		)[0];

		bottom = $('<div id="lbBottom" />').appendTo(bottomContainer).append([
			$('<a id="lbCloseLink" href="#" />').add(overlay).click(close)[0],
			caption = $('<div id="lbCaption" />')[0],
			number = $('<div id="lbNumber" />')[0],
			$('<div style="clear: both;" />')[0]
		])[0];
	});


	/*
		API
	*/

	// Open Slimbox with the specified parameters
	$.slimbox = function(_images, startImage, _options) {
		options = $.extend({
			loop: false,				// Allows to navigate between first and last images
			overlayOpacity: 0.8,			// 1 is opaque, 0 is completely transparent (change the color in the CSS file)
			overlayFadeDuration: 400,		// Duration of the overlay fade-in and fade-out animations (in milliseconds)
			resizeDuration: 400,			// Duration of each of the box resize animations (in milliseconds)
			resizeEasing: "swing",			// "swing" is jQuery's default easing
			initialWidth: 250,			// Initial width of the box (in pixels)
			initialHeight: 250,			// Initial height of the box (in pixels)
			imageFadeDuration: 400,			// Duration of the image fade-in animation (in milliseconds)
			captionAnimationDuration: 400,		// Duration of the caption animation (in milliseconds)
			counterText: "Image {x} of {y}",	// Translate or change as you wish, or set it to false to disable counter text for image groups
			closeKeys: [27, 88, 67],		// Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
			previousKeys: [37, 80],			// Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
			nextKeys: [39, 78]			// Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
		}, _options);

		// The function is called for a single image, with URL and Title as first two arguments
		if (typeof _images == "string") {
			_images = [[_images, startImage]];
			startImage = 0;
		}

		middle = win.scrollTop() + (win.height() / 2);
		centerWidth = options.initialWidth;
		centerHeight = options.initialHeight;
		$(center).css({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2}).show();
		compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
		if (compatibleOverlay) overlay.style.position = "absolute";
		$(overlay).css("opacity", options.overlayOpacity).fadeIn(options.overlayFadeDuration);
		position();
		setup(1);

		images = _images;
		options.loop = options.loop && (images.length > 1);
		return changeImage(startImage);
	};

	/*
		options:	Optional options object, see jQuery.slimbox()
		linkMapper:	Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
				the image URL and the image caption (may contain HTML)
		linksFilter:	Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
				the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
				This function must always return true when the DOM element argument is "this".
	*/
	$.fn.slimbox = function(_options, linkMapper, linksFilter) {
		linkMapper = linkMapper || function(el) {
			return [el.href, el.title];
		};

		linksFilter = linksFilter || function() {
			return true;
		};

		var links = this;

		return links.unbind("click").click(function() {
			// Build the list of images that will be displayed
			var link = this, startIndex = 0, filteredLinks, i = 0, length;
			filteredLinks = $.grep(links, function(el, i) {
				return linksFilter.call(link, el, i);
			});

			// We cannot use jQuery.map() because it flattens the returned array
			for (length = filteredLinks.length; i < length; ++i) {
				if (filteredLinks[i] == link) startIndex = i;
				filteredLinks[i] = linkMapper(filteredLinks[i], i);
			}

			return $.slimbox(filteredLinks, startIndex, _options);
		});
	};


	/*
		Internal functions
	*/

	function position() {
		var l = win.scrollLeft(), w = win.width();
		$([center, bottomContainer]).css("left", l + (w / 2));
		if (compatibleOverlay) $(overlay).css({left: l, top: win.scrollTop(), width: w, height: win.height()});
	}

	function setup(open) {
		if (open) {
			$("object").add(ie6 ? "select" : "embed").each(function(index, el) {
				hiddenElements[index] = [el, el.style.visibility];
				el.style.visibility = "hidden";
			});
		} else {
			$.each(hiddenElements, function(index, el) {
				el[0].style.visibility = el[1];
			});
			hiddenElements = [];
		}
		var fn = open ? "bind" : "unbind";
		win[fn]("scroll resize", position);
		$(document)[fn]("keydown", keyDown);
	}

	function keyDown(event) {
		var code = event.keyCode, fn = $.inArray;
		// Prevent default keyboard action (like navigating inside the page)
		return (fn(code, options.closeKeys) >= 0) ? close()
			: (fn(code, options.nextKeys) >= 0) ? next()
			: (fn(code, options.previousKeys) >= 0) ? previous()
			: false;
	}

	function previous() {
		return changeImage(prevImage);
	}

	function next() {
		return changeImage(nextImage);
	}

	function changeImage(imageIndex) {
		if (imageIndex >= 0) {
			activeImage = imageIndex;
			activeURL = images[activeImage][0];
			prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
			nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);

			stop();
			center.className = "lbLoading";

			preload = new Image();
			preload.onload = animateBox;
			preload.src = activeURL;
		}

		return false;
	}

	function animateBox() {
		center.className = "";
		$(image).css({backgroundImage: "url(" + activeURL + ")", visibility: "hidden", display: ""});
		$(sizer).width(preload.width);
		$([sizer, prevLink, nextLink]).height(preload.height);

		$(caption).html(images[activeImage][1] || "");
		$(number).html((((images.length > 1) && options.counterText) || "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));

		if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
		if (nextImage >= 0) preloadNext.src = images[nextImage][0];

		centerWidth = image.offsetWidth;
		centerHeight = image.offsetHeight;
		var top = Math.max(0, middle - (centerHeight / 2));
		if (center.offsetHeight != centerHeight) {
			$(center).animate({height: centerHeight, top: top}, options.resizeDuration, options.resizeEasing);
		}
		if (center.offsetWidth != centerWidth) {
			$(center).animate({width: centerWidth, marginLeft: -centerWidth/2}, options.resizeDuration, options.resizeEasing);
		}
		$(center).queue(function() {
			$(bottomContainer).css({width: centerWidth, top: top + centerHeight, marginLeft: -centerWidth/2, visibility: "hidden", display: ""});
			$(image).css({display: "none", visibility: "", opacity: ""}).fadeIn(options.imageFadeDuration, animateCaption);
		});
	}

	function animateCaption() {
		if (prevImage >= 0) $(prevLink).show();
		if (nextImage >= 0) $(nextLink).show();
		$(bottom).css("marginTop", -bottom.offsetHeight).animate({marginTop: 0}, options.captionAnimationDuration);
		bottomContainer.style.visibility = "";
	}

	function stop() {
		preload.onload = null;
		preload.src = preloadPrev.src = preloadNext.src = activeURL;
		$([center, image, bottom]).stop(true);
		$([prevLink, nextLink, image, bottomContainer]).hide();
		
		//Remove flash objects while the lightbox is closing
		$('#lbCenter #lbImage object, .picasa-video-container').remove();		

	}

	function close() {
		if (activeImage >= 0) {
			stop();
			activeImage = prevImage = nextImage = -1;
			$(center).hide();
			$(overlay).stop().fadeOut(options.overlayFadeDuration, setup);
		}

		return false;
	}

})(jQuery);;
/**
 *	Embed youtube videos
 *	Matches a div like <div class='embed-youtube' data-video-id='{$video_id}'></div>
 *	Replaced with an embedded youtube video
 *
 *	//object width="425" height="350" data="http://www.youtube.com/v/Ahg6qcgoay4" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/Ahg6qcgoay4" /></object>
*/
jQuery(function($) { 

	$('.embed-youtube').each(function() {
		var t = $(this), 
			vid = t.attr('data-video-id');
		
		var obj = '<object width="425" height="350" data="http://www.youtube.com/v/'+vid+'" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/'+vid+'" /></object>';
		t.replaceWith(obj);		
		

	});
});
;
/**
 *	Embed picasa gallery with jquery.EmbedPicasaGallery
*/
jQuery(function($) { 

	var s = Drupal.settings.slcgov_settings, 
		path = s.module_path, 
		loading_image = '/' + path + '/js/EmbedPicasaGallery/loading.gif', 
		back_button = '/' + path + '/js/EmbedPicasaGallery/back_btn.gif';
		
		$('.embed-picasa').each(function() {
			var t = $(this), 
				user = t.attr('data-picasa-user'),
				album = t.attr('data-picasa-album');
			
			if ( album == '' ) 
				album = '.';
			
			//Regex
			album = new RegExp(album, 'i');
			
			t.EmbedPicasaGallery(user, {
				matcher : album,
				size: 104, 
				loading_animation: loading_image, 
				back_button : back_button
			}); 
		});	
});
;
(function ($) {

$(document).ready(function() {

  // Accepts a string; returns the string with regex metacharacters escaped. The returned string
  // can safely be used at any point within a regex to match the provided literal string. Escaped
  // characters are [ ] { } ( ) * + ? - . , \ ^ $ # and whitespace. The character | is excluded
  // in this function as it's used to separate the domains names.
  RegExp.escapeDomains = function(text) {
    return (text) ? text.replace(/[-[\]{}()*+?.,\\^$#\s]/g, "\\$&") : '';
  }

  // Attach onclick event to document only and catch clicks on all elements.
  $(document.body).click(function(event) {
    // Catch the closest surrounding link of a clicked element.
    $(event.target).closest("a,area").each(function() {

      var ga = Drupal.settings.googleanalytics;
      // Expression to check for absolute internal links.
      var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
      // Expression to check for special links like gotwo.module /go/* links.
      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
      // Expression to check for download links.
      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
      // Expression to check for the sites cross domains.
      var isCrossDomain = new RegExp("^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\/.*(" + RegExp.escapeDomains(ga.trackCrossDomains) + ")", "i");

      // Is the clicked URL internal?
      if (isInternal.test(this.href)) {
        // Is download tracking activated and the file extension configured for download tracking?
        if (ga.trackDownload && isDownload.test(this.href)) {
          // Download link clicked.
          var extension = isDownload.exec(this.href);
          _gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
        }
        else if (isInternalSpecial.test(this.href)) {
          // Keep the internal URL for Google Analytics website overlay intact.
          _gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
        }
      }
      else {
        if (ga.trackMailto && $(this).is("a[href^=mailto:],area[href^=mailto:]")) {
          // Mailto link clicked.
          _gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
        }
        else if (ga.trackOutbound && this.href) {
          if (ga.trackDomainMode == 2 && isCrossDomain.test(this.href)) {
            // Top-level cross domain clicked. document.location is handled by _link internally.
            _gaq.push(["_link", this.href]);
          }
          else {
            // External link clicked.
            _gaq.push(["_trackEvent", "Outbound links", "Click", this.href]);
          }
        }
      }
    });
  });
});

})(jQuery);
;

