(function($, Mage) {

	$(document).ready(function(){
		//set the seach box label
		var term = "Botanical or Common Name";
		var q = decodeURIComponent(window.location.search).parseQuery();
		if(Object.keys(q).indexOf('name') > -1) {
			term = q.name.replace(/\+/ig, ' ');
			$('#gallery-search').val(term);
		}
		$('#gallery-search').focus(function() { if($('#gallery-search').val().toLowerCase() == term.toLowerCase()) { $('#gallery-search').val(""); } });
				

	}); // document.ready


	// ***** Functions for all dialog boxes *****
	var dialog_funcs = {
		// *** Close all open jqueryui dialog boxes
		closeAll: function() {
			for (i in dialogs) {
				// Check for jqueryui dialog instance
				if (typeof(dialogs[i].container.dialog) != 'function') { continue; }

				dialogs[i].container.dialog('close');
			}
		}, // closeAll()


		close: function(target_dialog) {
			target_dialog.container.dialog('close');
		}, // close()


		// *** Reset form data and validator
		reset: function(target_dialog) {
			if (target_dialog.form.length) {
				target_dialog.form.get(0).reset();
			}

			if (target_dialog.varien_form.validator) {
				target_dialog.varien_form.validator.reset();
			}
		},


		// *** Bind "open dialog" event to dialog trigger link
		bind: function(target_dialog) {
			$(target_dialog.trigger_selector).live('click', function() {
				dialog_funcs.closeAll();
				dialog_funcs.open(target_dialog);
				return(false);
			});
		}, // bind()


		// *** Open the target_dialog
		open: function(target_dialog) {
			if ((typeof(target_dialog.events) == 'object') && (typeof(target_dialog.events.before_open) == 'function')) {
				target_dialog.events.before_open(target_dialog);
			}

			target_dialog.container.dialog('open');
		}, // open()


		// *** Login/signup success
		loginSuccessfulEvent: function(target_dialog) {
			$(".imagelibrary .item-preview ul.downloads.logged_out").removeClass('logged_out').addClass('logged_in');

			dialog_funcs.closeAll();
			dialog_funcs.reset(target_dialog);
		}, // loginSuccessfulEvent()


		// *** Login/signup success
		logoutEvent: function(target_dialog) {
			$(".imagelibrary .item-preview ul.downloads.logged_in").removeClass('logged_in').addClass('logged_out');

			dialog_funcs.closeAll();
			if (typeof(target_dialog) != 'undefined') {
				dialog_funcs.reset(target_dialog);
			}
		}, // logoutEvent()


		// *** Set a dialog's "Ok" button either disabled or active
		setOkButtonStatus: function(target_dialog, disabled) {
			var $button = target_dialog.container.dialog('widget').find('.ui-dialog-buttonset button:contains("Ok")');
			$button.attr('disabled', disabled);

			if (disabled == 'disabled') {
				$button.addClass('ui-state-disabled');
			} else {
				$button.removeClass('ui-state-disabled');
			}
		}, // setOkButtonStatus


		// *** Dialog Submit button
		submit: function(target_dialog) {
			// Attempt to validate form data
			if (!(target_dialog.varien_form.validator && target_dialog.varien_form.validator.validate())) {
				return(false);
			}

			// Temporarily disable Ok button
			dialog_funcs.setOkButtonStatus(target_dialog, 'disabled');

			$.ajax({
				url: target_dialog.form.attr('action'),
				type: target_dialog.form.attr('method'),
				data: target_dialog.form.serialize(),
				dataType: 'json',
				success: function(data, status, xhr) {
					if (data.alert) {
						dialogs.status.actions.alert(data.alert, data.alert_title);
					}

					// Server-side can specify a target_dialog.actions.X function to call, by setting data.action='X'
					if (data.action && (typeof(target_dialog.actions[data.action]) == 'function')) {
						// Optionally data.action_args can also be passed to function X. Here we make sure data.action_args exists as an object, to avoid needing to use typeof() so much inside of function X
						if (typeof(data.action_args) == 'undefined') {
							data.action_args = {};
						}

						target_dialog.actions[data.action](target_dialog, data.action_args);
					}

					dialog_funcs.setOkButtonStatus(target_dialog, '');
				},
				error: function(xhr, status, error){
					dialogs.status.actions.alert(error, 'An error occurred');
				}
			});

			return(false);
		}, // submit()


		// *** Initialize dialog
		init: function(target_dialog) {
			if (target_dialog.trigger_selector && !$(target_dialog.trigger_selector).length) { return; }

			// Inject form into document body
			$.get(Mage.getBaseUrl() +target_dialog.template_path, function(data) {
				$('body').append(data);
				
				target_dialog.container = $(target_dialog.dialog_id);
				target_dialog.form = target_dialog.container.find('form');
				target_dialog.varien_form = new VarienForm(target_dialog.form.attr('id'), true);

				// Default options for jqueryui dialog
				var dialog_options = {
					resizable: false,
					modal: true,
					autoOpen: false,
					buttons: {
						'Ok': function() { dialog_funcs.submit(target_dialog); },
						'Cancel': function() { dialog_funcs.close(target_dialog); }
					},
					close: function() { dialog_funcs.reset(target_dialog); }
				}

				// Apply dialog specific options to the default
				$.extend(dialog_options, target_dialog.jqueryui_options);

				// Create jqueryui dialog
				target_dialog.container.dialog(dialog_options);

				dialog_funcs.bind(target_dialog);

				if ((typeof(target_dialog.events) == 'object') && (typeof(target_dialog.events.after_init) == 'function')) {
					target_dialog.events.after_init();
				}
			});

		}

	} // dialog_funcs



	// ***** Individual dialog specific data *****
	var dialogs = {
		// ************ Signup Dialog ************
		signup: {
			trigger_selector: '.media-signup-popup',
			dialog_id: '#media-signup-popup-dialog',
			form: $,
			container: $,
			varien_form: null,
			template_path: 'imagelibrary/dialog/signup',
			jqueryui_options: {
				width: 520,
				height: 520,
				title: 'Sign up'
			},
			actions: {
				success: function(target_dialog, args) {
					dialog_funcs.loginSuccessfulEvent(target_dialog);

					// On successful signup, server-side will pass:
					// args.show_new_acct_status = true
					seed.greenhouse.download_count = 0;
					seed.greenhouse.user_is_temporary = 1;
					dialogs.agreement.actions.update_amounts();

					if (args.show_new_acct_status == true) {
						dialogs.status.actions.set_section('new-account');
						dialog_funcs.open(dialogs.status);
					}
				}
			}
		},

		// ************ Login Dialog ************
		login: {
			trigger_selector: '.login-popup',
			dialog_id: '#login-popup-dialog',
			form: $,
			container: $,
			varien_form: null,
			template_path: 'imagelibrary/dialog/login',
			jqueryui_options: {
				width: 580,
				height: 340,
				title: 'Log In'
			},
			actions: {
				success: function(target_dialog) {
					seed.greenhouse.download_count = 0;
					seed.greenhouse.user_is_temporary = 0;
					dialogs.agreement.actions.update_amounts();

					dialog_funcs.loginSuccessfulEvent(target_dialog);
				},

				logout: function(target_dialog) {
					dialog_funcs.logoutEvent(target_dialog);
				}
			}
		},

		// ************ Status Dialog ************
		status: {
			dialog_id: '#status-popup-dialog',
			container: $,
			template_path: 'imagelibrary/dialog/status',
			jqueryui_options: {
				width: 600,
				height: 360,
				//title: 'New Account Status',
				buttons: {
					'Ok': function() { dialog_funcs.close(dialogs.status); }
				}
			},
			actions: {
				set_section: function(section, text) {
					dialogs.status.container
						.find('.status-section').hide().end()
						.find('#status-section-'+ section).show()
							.find('.window-title').each(function() {
								dialogs.status.container.dialog('option', 'title', $(this).text())
							});
				},

				alert: function(text, title) {
					dialogs.status.actions.set_section('generic-alert');
					dialogs.status.container.dialog('option', 'title', (title || 'Alert'));
					dialogs.status.container.find('.alert-text').text(text);

					dialog_funcs.open(dialogs.status);
				},

				update_amounts: function() {
					// seed.greenhouse.max_allowed_downloads should have been set in imagelibrary/gallery.phtml
					dialogs.status.container.find('span.num_downloads').text(seed.greenhouse.max_allowed_downloads);
				}
			},
			events: {
				after_init: function() {
					dialogs.status.actions.update_amounts();
				}
			}
		},

		// ************ Agreement Dialog ************
		agreement: {
			dialog_id: '#agreement-popup-dialog',
			container: $,
			template_path: 'imagelibrary/dialog/agreement',
			target_download_type: '',
			jqueryui_options: {
				width: 600,
				height: 600,
				title: 'Download Image',
				buttons: {
					'Ok': function() {
						dialog_funcs.closeAll();

						seed.greenhouse.download(dialogs.agreement.target_download_type);
					},
					'Cancel': function() { dialog_funcs.closeAll(); }
				}
			},
			actions: {
				update_amounts: function() {
					if (seed.greenhouse.user_is_temporary == 1) {
						var download_count_text = (seed.greenhouse.download_count+1) +' of '+ (seed.greenhouse.max_allowed_downloads);

						dialogs.agreement.container.dialog('widget').removeClass('user_is_confirmed').addClass('user_is_temporary')
							.find('.download_count').text(download_count_text);
					} else {
						dialogs.agreement.container.dialog('widget').removeClass('user_is_temporary').addClass('user_is_confirmed');
					}
				}
			},
			events: {
				before_open: function() {
					dialogs.agreement.actions.update_amounts();
					dialogs.agreement.container.find('input#agreement_confirm').removeAttr('checked');
					dialog_funcs.setOkButtonStatus(dialogs.agreement, 'disabled');
				},

				after_init: function() {
					dialogs.agreement.container.find('input#agreement_confirm').change(function() {
						dialog_funcs.setOkButtonStatus(dialogs.agreement, ($(this).is(':checked') ? '' : 'disabled'));
					})
				}
			}
		}
	} // var dialogs


	// Make data structures global
	window.dialog_funcs = dialog_funcs;
	window.dialogs = dialogs;


	/*
	$(document).ready(function() {
		dialog_funcs.init(dialogs.signup);
		dialog_funcs.init(dialogs.login);
		dialog_funcs.init(dialogs.status);
		dialog_funcs.init(dialogs.agreement);
	});
	*/

})(jQuery, Mage)


var showroom = Class.create({
	downloadurl: 'http://www.baileynurseries.com/imagelibrary/download/',
	currentimage: 0,
	totalimages: 0,
	pid: 0,
	effectview: null,
	cache: null,
	images: null,
	restricted_download_types: ['bw', 'press'], // Only these download types are restricted
	download_count: 0, // Number of restricted files downloaded so far this session
	user_is_temporary: 0, // Whether or not currently logged in user is still waiting approval (and can only download max_allowed_downloads of restricted files)
	max_allowed_downloads: 5, // Default to 5, but gets overwritten by value in backend. This is the max # of restricted files that can be downloaded by temp users
	
	initialize: function() {

		$('prev-item').observe('click', this.prevpage.bind(this));
		$('next-item').observe('click', this.nextpage.bind(this));
		//$('greenhouse-slides').on('click','a.wrap',function(ev) { ev.stop(); });
		if($('greenhouse-nav')) { $('greenhouse-nav').hide(); }
		if($('greenhouse-data')) { $('greenhouse-data').hide(); }

		if($('download-web')) { $('download-web').observe('click', this.download_callback.bind(this)); }
		if($('download-pdf')) { $('download-pdf').observe('click', this.download_callback.bind(this)); }
		if($('download-bw')) { $('download-bw').observe('click', this.download_callback.bind(this)); }
		if($('download-press')) { $('download-press').observe('click', this.download_callback.bind(this)); }

		this.currentimage = 0;
		this.totalimages = 0;
	},
	clean: function() {
		if($('greenhouse-nav')) { $('greenhouse-nav').hide(); }
		if($('greenhouse-data')) { $('greenhouse-data').hide(); }
		if($('greenhouse-images-count')) { $('greenhouse-images-count').update(''); }
		$$('span.wrap').each(function(el){ el.remove(); });
		this.currentimage = 0;
		this.totalimages = 0;
		this.images = null;
	},
	startview: function(imgs, pid) {
		this.pid = pid;
		this.totalimages = imgs.size();
		if(this.totalimages == 0) { this.updatecaption(); return; }
		this.images = imgs;
		
		//set the container to be the total width of all images
		$('greenhouse-slides').setStyle({'width':this.totalimages*420+'px', 'left':'0px'});

		//change the total number of images to zero for the caption if it's 'not available'
		if(this.totalimages == 1 && imgs[0].image.match(/image-not-available/i)) {
			this.totalimages = 0;
			if($('download-web')) { $('download-web').hide(); }
		} else {
			if($('download-web')) { $('download-web').show(); }
		}
		this.currentimage = 1;
		this.updatecaption();
		
		//show the nav
		$('prev-item').setStyle({'display': 'none'});
		$('next-item').setStyle({'display': (this.totalimages > 1 ? 'block':'none')});
		if(this.totalimages > 1) {
			if($('greenhouse-nav')) { $('greenhouse-nav').show(); }			
		} else {
			if($('greenhouse-nav')) { $('greenhouse-nav').hide(); }
		}

		if ($('greenhouse-data')) { $('greenhouse-data').show(); }
		//setup the downloads
		this.setupdownloads();
			
		//put the images in
		$A(imgs).each(function(img, cnt) {
			$('greenhouse-slides').insert({'bottom': new Element('span', {'href':'#','rel':pid, 'class':'wrap', 'style':'float:left;display:block;z-index:2'}).update(new Element('img',{'src':img.image,'border':'0'})) });				
		});
		//show the first image
		//this.view(1, 'goleft');
		
	},
	//the 'pager' - hide the current, show what we're told
	view: function(item, dir) {
		//finish the current effect if there is one
		if(this.effectview != null) {
			this.effectview.finishOn = (new Date).getTime();
			this.effectview = null;
		}
		this.currentimage = item;

		if(dir == 'goleft') {
			this.effectview = new Effect.Move('greenhouse-slides', { x:-420, y:0, mode:'relative',duration:1 });
		} else {
			this.effectview = new Effect.Move('greenhouse-slides', { x:420, y:0, mode:'relative',duration:1 });
		}		
		this.updatecaption();
	},
	//handles all slideshow paging
	nextpage: function(ev) {
		ev.stop();
		if(this.currentimage + 1 == this.totalimages) {
			$('next-item').hide();
		}
		if(this.currentimage == 1 && this.totalimages > 1) {
			$('prev-item').show();
		}
		this.view(this.currentimage + 1,'goleft');
		return false;
	},
	prevpage: function(ev) {
		ev.stop();
		if(this.currentimage - 1 == 1) {
			$('prev-item').hide();
		}
		if(this.currentimage - 1 < this.totalimages && this.totalimages > 1) {
			$('next-item').show();
		}
		this.view(this.currentimage - 1, 'goright');
		return false;
	},
	updatecaption: function() {
		if(this.totalimages == 0 ) {
			$('greenhouse-images-count').update("No images currently available");
		} else if(this.totalimages == 1) {
			$('greenhouse-images-count').update("One image available");
		} else {
			$('greenhouse-images-count').update("Viewing "+this.currentimage+" of "+this.totalimages+" available");
		}		
	},
	setupdownloads: function() {
	},
	download_callback: function(ev) {
		ev.stop();
		var download_type = ev.target.rel;

		if (this.restricted_download_types.indexOf(download_type) != -1) {
			this.download_restricted(download_type);
		} else {
			this.download(download_type);
		}
	},
	download_restricted: function(type) {
		// Show download-limit dialog if a temp user has used all of their allowed downloads
		if ((this.download_count >= this.max_allowed_downloads) && (this.user_is_temporary == 1)) {
			dialogs.status.actions.set_section('download-limit');
			dialog_funcs.open(dialogs.status);
		// Show the agreement box if it's the first download of the session (for all users) or if user is temporary
		} else if ((this.download_count == 0) || (this.user_is_temporary == 1)) {
			dialogs.agreement.target_download_type = type;
			dialog_funcs.open(dialogs.agreement);
		} else {
			this.download(type);
		}
	},
	download: function(type) {
		// If they're downloading a restricted file, increase the count
		if (this.restricted_download_types.indexOf(type) != -1) {
			this.download_count++;
		}

		this.dowindow(this.downloadurl + type + '/pid/' + this.pid + '/i/' + this.images[this.currentimage-1].id);
	},
	dowindow: function(url) {
		var nw = window.location.href = url;
	}
	
	
});

var plantae = Class.create({
	library : 'http://www.baileynurseries.com/imagelibrary/gallery/',
	maxleaf : 12, //how many thumbnails to show
	sprouts : 0, //total plants results
	chromosome : {}, // the search results - sort when planted... er created.
	leaves: 0,
	stem : [], //sorted plants - entity_id to chromosome
	imgsort : "B", //set by the select 
	tview : "T", //set by links
	currentpage : 1, //the current page
	conceivedpage: 1, //what page was the dataset started on
	term:'',
	greenhouse: null,
	firstload : true,
	loadingeffect: null,
	effectpage: null,
	ajaxqueue: [],
	pagewarning: -1, //the paging warning is not showing - what page is waiting for if positive
	
	initialize: function(data) {
		this.greenhouse = new showroom();
		$('next').observe('click', function(ev) { ev.stop(); seed.page('up'); } );
		$('prev').observe('click', function(ev) { ev.stop(); seed.page('down'); } );

		//thumbnail list changes
		$('view-thumb').observe('click', this.showthumbs.bind(this) );   
		$('view-list').observe('click', this.showlist.bind(this) );
		
		//name type sort
		if($('image-result-sort') ) {
			$('image-result-sort').observe('change', this.resort.bind(this) );
		}
		
		if(data) {
			this.plant(data);
		}
	},
	
	//set up from the passed information - first run
	plant : function(data) {

		if(!data) { return; }
		
		this.getoptions();
		this.stem = new Array(parseInt(data.count).isNaN ? 0 : parseInt(data.count));
		this.fertilize(data);
		this.conceivedpage = this.chromosome.current;
		this.library = data.baseurl + 'gallery/';
		this.greenhouse.downloadurl = data.baseurl + 'download/';
		this.searchuri = data.searchuri;
		this.sprouts = this.chromosome.count;
		//pages
		this.leaves = Object.keys(seed.chromosome.collection).length > 12 ? Math.ceil(this.sprouts/12) : data.pages; 
		
		//set the results label
		$('image-results-count').update(this.sprouts + " Results");
		if(this.sprouts == 0) {
			$($('greenhouse-message').childElements()[0]).update('No plants were found. Please search again.');
		}
		
		var thumb = null;
		//i don't like this
		for(var i = 0; i < this.sprouts; i++) {
			thumb = new Element('div', { 'id': '', 'title': '', 'class': 'thumb', 'style': '' });
			$('gallery-pot').insert({'bottom':thumb});
		}
		thumb = null;
		
		return true;
	},
	
	//add data for paging
	fertilize: function(data) {
		//check to see if data is a string or object
		if(Object.isString(data)) {
			data = data.evalJSON();
			Object.extend(this.chromosome.collection, data.collection);
		} else {
			Object.extend(this.chromosome, data);	
		}
		//what page these results are for
		this.searchpage = data.current;
		
		//the array index # and values should represent data we've gotten,
		// so the the index with the corresponding search result #
		var resultindex = (data.current -1 <= 0 ? 0 : data.current -1)*12;

		//add new to sorted array
		for(rna in data.collection) {
			this.stem[resultindex] = rna;
			resultindex++;
		}

		//do we need to resort with the new items?
		resultindex = null;
		return true;
	},
	
	//set the labels for the result set, conjure up the list and set the item
	germinate : function(showthisone) {
		if(!this.isalive()) { return false; } //stop if we don't have any data
		//$$('.thumb').each(function(el) { el.stopObserving(); el.remove(); })
		
		//create the list w/o images - will show when needed
		for(var placement = 0, len = this.stem.length; placement < len; ++placement) {
			if(typeof this.stem[placement] == 'undefined') { continue; }
			var species = this.stem[placement];

			//if it's already there, skip it;
			if($('id-'+species)) { continue; }
			
			var dna = this.chromosome.collection[species];
			if(dna == null) continue;
			
			//check for values before setting them out there ----
			dna.image = (dna.image ? dna.image : '/default.png');
			dna.thumbnail = (dna.thumbnail ? dna.thumbnail : '/default.png'); 

			//set the divs up ---- fetch the thumbnail only when we haven't shown it yet
			var imgthumb = new Element('div', {
				'style': 'background: transparent url('+dna.image+') no-repeat scroll center center; display: '+(this.tview == "T" ? 'block':'none')+';height:66px;width:91px',
				'class': 'view-thumb'
			});
			var txtthumb = new Element('div', {
				'class': 'view-list',
				'style': 'display: '+(this.tview != "T" ? 'block':'none')+'; height:27px; overflow: hidden;'
			}).update((this.imgsort == "B" ? dna.plant_botanical_name : dna.plant_common_name) + '<span>' + (this.imgsort == "B" ? dna.plant_common_name : dna.plant_botanical_name) + '</span>');
			
			var thumb = $$('div.thumb')[placement];
			$(thumb).writeAttribute({'id':'id-'+dna.entity_id,'title':(this.imgsort == "B" ? dna.plant_botanical_name : dna.plant_common_name)});
			var label = new Element('div', {
				'class':'thumb-label',
				'style':'display:none;'
			}).update("<span>"+(this.imgsort == "B" ? dna.plant_botanical_name : dna.plant_common_name)+"</span>");

			thumb.insert({'bottom':imgthumb});
			thumb.insert({'bottom':txtthumb});
			thumb.insert({'bottom':label});
			//thumb.observe('mouseover', this.thumbover);
			//thumb.observe('mouseout', this.thumbout);
			thumb.observe('click', this.view.bind(this, dna.entity_id));
			
			dna = imgthumb = txtthumb = thumb = label = null;			
		}
		$('gallery-pot').on('mouseover', 'div.thumb', this.thumbover);
		$('gallery-pot').on('mouseout', 'div.thumb', this.thumbout);
		//first thumbnail fetching
//		this.water();
		if(this.firstload) {
			//set the current page
			this.currentpage = this.chromosome.current;
			//show the first plant of the page
			if(!showthisone) { showthisone = this.stem[(((this.currentpage - 1)*12))]; }
			this.view(showthisone);
			//set the position if we aren't on page one
			if(this.currentpage > 1) {
				var j = new Effect.Move('gallery-pot',{'x':0, 'y':-420*(this.currentpage-1), mode:'relative', duration: 0});
			}
			this.firstload = false;
			//initial 3 page prefetching
			for(var i = 0; i < 1; ++i) {
				if(this.currentpage - i > 0) {
					this.fanfetchback(this.currentpage - i);
				}
				if(this.currentpage + i <= this.chromosome.pages) {
					this.fanfetchforward(this.currentpage + i);
				}
			}
		}
		//hide the warning if it's there
		if(this.pagewarning > -1 && (this.searchpage*this.maxleaf) - this.maxleaf == this.pagewarning) {
			this.pagewarning = -1;
			$('pagewarning').hide();
		}
	},
	
	//get the next 12 and/or previous 12 given an anchor page
	fanfetch: function(anchorpage) {
		var pajax = null;
		var najax = null;
		//if we have less than 12 results, don't do anything
		if(this.sprouts <= this.maxleaf) { return; }
		//our search
		this.fanfetchback(anchorpage);
		this.fanfetchforward(anchorpage);

	},
	fanfetchback: function(getpage) {
		var params = this.paramsfromquery();
		var queue_stern_page = (getpage - 1  < 0 ? 0 : getpage - 1);
		if(getpage != 1 && typeof this.stem[(queue_stern_page-1)*this.maxleaf] == 'undefined') {
			//get previous results
			params.page = queue_stern_page;
			pajax = new Ajax.Request(this.library+this.searchuri+'?'+Object.toQueryString(params), {
				onSuccess: this.updateajax.bind(this)
			});
		}		
	},
	fanfetchforward: function(getpage) {
		var params = this.paramsfromquery();
		if(getpage + 1 <= Math.ceil(this.sprouts/this.maxleaf) && typeof this.stem[getpage*this.maxleaf] == 'undefined') {
			//get next results
			params.page = getpage + 1;
			pajax = new Ajax.Request(this.library+this.searchuri+'?'+Object.toQueryString(params), {
				onSuccess: this.updateajax.bind(this)
			});
			
		}		
	},
	paramsfromquery: function() {
		var peanut = decodeURIComponent(window.location.search).toQueryParams();
		peanut.name = (peanut.name) ? peanut.name.replace(/\+/gi, ' ') : '';
		peanut.page = (peanut.page) ? peanut.page : this.currentpage;
		return peanut;
	},

	updateajax: function(obj) {
		if(this.ajaxqueue.size() > 0) { this.pageprefetchloop(); }
		this.fertilize(obj.responseText);
		this.germinate();
	},
	
	//paging
	page : function(dir) {
		if(this.effectpage != null) {
			//finish scrolling now
			this.effectpage.finishOn = (new Date).getTime();
			this.effectpage = null;
		}
		if(!this.passgo(dir)) { return; }
		
		//need better check
		if(dir == "up" && this.currentpage != this.leaves && Math.ceil(this.sprouts/this.maxleaf) > this.currentpage) {
			//send up warning if the results aren't back yet
			this.pageup();
			this.currentpage++;
		}
		if(dir == "down" && this.currentpage > 1) {
			this.pagedown();
			this.currentpage--;
		}
		this.fanfetch(this.currentpage);
	},	
	pageup: function() {
		this.effectpage = new Effect.Move('gallery-pot',{'x':0, 'y':'-420', mode:'relative'});
	},
	pagedown: function() {
		this.effectpage = new Effect.Move('gallery-pot',{'x':0, 'y':'420', mode:'relative'});
	},
	passgo: function(dir) {
		if(!this.isalive()) { return false; } //stop if we don't have any data
		if(this.sprouts < this.maxleaf) { return false; } // we don't need to page for less than twelve...?
		var showdown = (this.currentpage * this.maxleaf) - this.maxleaf;
		showdown = showdown < 0 ? 0 : showdown;
		var showup = this.currentpage * this.maxleaf;
		if(
			(dir == "up" && typeof this.stem[showup] == 'undefined' && showup < this.sprouts) ||
			(dir == "down" && typeof this.stem[showdown] == 'undefined')
		) {
			this.pagewarning = dir == "up" ? showup : showdown;
			$('pagewarning').update('Fetching results. Please wait.');
			$('pagewarning').show();
			return false;
		}
		return true;		
	},
	
	//catch to see if there is data
	isalive : function() {
		if(typeof this.chromosome.collection == undefined) { return false; }
		for(var i in this.chromosome.collection) { return true; }
		return false;
	},
	
	//get options for page load
	getoptions : function() {
		var opts, h = decodeURIComponent(window.location.hash);
		if(!h.match(/^#{.*}/)) { return; }

		h = h.replace(/^#/,'');
		opts = h.evalJSON(true);
		
		// sort by 'B'otanical or 'C'ommon
		this.imgsort = (opts && opts.s) ? opts.s : "B"; 
		if($('image-result-sort')) {
			$$('select#image-result-sort option')[(this.imgsort == "B" ? 0 : 1)].selected = true;
		}
		
		//show 'T'humbs or 'L'ist
		this.tview =  (opts && opts.t) ? opts.t : "T";
		this.updateview();
	},

	setoptions : function() {
		var opts = { 's': this.imgsort, 't':this.tview };
		window.location.hash = Object.toJSON(opts);
	},
	
	getwithit : function() {
		var rtn = window.location.protocol + "//" + window.location.host + window.location.pathname;
		var s = decodeURIComponent(window.location.search);
		s = s.replace(/^\?/, '');
		s = s.replace(/\+/gi, ' ');
		var out = s.toQueryParams();
		out.sort = this.imgsort;
		window.location = rtn + '?' + Object.toQueryString(out) + window.location.hash;
	},

	view: function(pid) {
		var aj = null;
		var plant = null;
		if(typeof pid != 'string') {
			plant = this.chromosome.collection[arguments[1]];
		} else {
			plant = this.chromosome.collection[pid];
		}

		if(this.loadingeffect) { 
			this.loadingeffect.finishOn = (new Date).getTime(); 
			this.loadingeffect = null;
		}
				
		//if we've already seen the plant, re-use it and forget fetching
		if(!Object.isUndefined(plant) && !Object.isUndefined(plant.features)) {
			this.viewupdate(plant);
			return;
		}
		
		//loading message
		this.loadingeffect = new Effect.SlideDown('greenhouse-message', {duration:.3});
		
		aj = new Ajax.Request(this.library+'plantdata?'+Object.toQueryString({'pid':pid}), {
			onSuccess: (function(resp) {
				//console.log(resp.responseText);
				var info = resp.responseText.evalJSON();
				//these aren't all always going to have data, even when we specify the exact set (instead of all)
				//need an order and hide/show as needed so the interface stays consistent
				if(Object.isUndefined(this.chromosome.collection[info.id])) {
					this.chromosome.collection[info.id] = {};
				}
				Object.extend(this.chromosome.collection[info.id], info);
				this.viewupdate(info);
				info = null;
			}).bind(this)
		});
		plant = null;
	},
	viewupdate: function(info) {
		
		$('greenhouse-botanical').update(this.chromosome.collection[info.id].plant_botanical_name);
		$('greenhouse-common').update(this.chromosome.collection[info.id].plant_common_name);
		$('greenhouse-description').update('');
		$('greenhouse-features').hide();
		$$('dl#greenhouse-features dd').each(function(el){ el.remove(); });
		$$('ul#greenhouse-attributes li').each(function(el){ el.remove(); });
		this.greenhouse.clean();
		
		for(var opt in info) {
			if(opt == 'images') {
				this.greenhouse.startview(info[opt], info.id);
			} else if(opt == 'features') {
				if((info[opt].uniq())[0] == "") { continue; }
				$('greenhouse-features').show();
				if(info[opt].toString().match(/frag/i)) { $('greenhouse-features').insert({'bottom':"<dd class='frag'>Fragrant</dd>"}); }
				if(info[opt].toString().match(/wet/i)) { $('greenhouse-features').insert({'bottom':"<dd class='wet'>Moist Location</dd>"}); }
				if(info[opt].toString().match(/but/i)) { $('greenhouse-features').insert({'bottom':"<dd class='but'>Attracts Butterflies</dd>"}); }
				if(info[opt].toString().match(/bird/i)) { $('greenhouse-features').insert({'bottom':"<dd class='bird'>Attracts Birds</dd>"}); }
				if(info[opt].toString().match(/scis/i)) { $('greenhouse-features').insert({'bottom':"<dd class='scis'>Good For Cutting</dd>"}); }
				if(info[opt].toString().match(/deer/i)) { $('greenhouse-features').insert({'bottom':"<dd class='deer'>Deer Resistant</dd>"}); }
				if(info[opt].toString().match(/drought/i)) { $('greenhouse-features').insert({'bottom':"<dd class='drought'>Drought Tolerant</dd>"}); }
			} else if(opt == 'description') {
				$('greenhouse-description').update(info.description);
			} else if(opt.toString().match(/height|shape|spread|foliage|exposure|zone/i)) {
				$('greenhouse-attributes').insert({'bottom':'<li><strong>'+opt+':&#160;</strong>&#160;'+(info[opt] != null ? info[opt] : '')+'</li>'});
			}
		}
		
		if(this.loadingeffect) {
			this.loadingeffect.finishOn = (new Date).getTime(); 
			this.loadingeffect = Effect.SlideUp('greenhouse-message', {duration:.3});
		}
		
		info = opt = null;
	},	
	showthumbs: function(ev) {
			ev.stop();
			this.tview = "T";
			this.setoptions();
			this.updateview();
	},
	showlist: function(ev) {
			ev.stop();
			this.tview = "L";
			this.setoptions();
			this.updateview();
	},
	thumbover: function(e, el) {
		if(!el.hasClassName('thumb')) { return; }
		if($(el).firstDescendant().getStyle('display') == 'block') {
			$(el).firstDescendant().addClassName('thumbhover');
			$(el).childElements()[2].show();
		} else {
			$(el).childElements()[1].addClassName('thumbhover');
		}
	},
	thumbout: function(e, el) {
		if(!$(el).hasClassName('thumb')) { return; }
		if($(el).firstDescendant().getStyle('display') == 'block') {
			$(el).firstDescendant().removeClassName('thumbhover');
			$(el).childElements()[2].hide();
		} else {
			$(el).childElements()[1].removeClassName('thumbhover');
		}
	},
	updateview: function() {
		if(this.tview == "T" && $('view-thumb')) {
  		$('view-thumb').addClassName('active');
  		$('view-thumb').next().removeClassName('active');
  		$$('div.view-thumb').invoke('setStyle',{'display':'block'});
  		$$('div.view-list').invoke('setStyle',{'display':'none'});
  	} else if(this.tview == "L" && $('view-thumb')) {
  		$('view-list').addClassName('active');
  		$('view-list').previous().removeClassName('active'); 
  		$$('div.view-thumb').invoke('setStyle',{'display':'none'});
  		$$('div.view-list').invoke('setStyle',{'display':'block'});
  	}
	},
	resort: function(ev) {
			this.imgsort = ev.element().options[ev.element().selectedIndex].value;
			//this.setsort(this.imgsort);
			this.setoptions();
			this.getwithit();
	},
	parseURL: function(url, what) {
    //save the unmodified url to href property
    //so that the object we get back contains
    //all the same properties as the built-in location object
    var loc = { 'href' : url };

    //split the URL by single-slashes to get the component parts
    var parts = url.replace('//', '/').split('/');

    //store the protocol and host
    loc.protocol = parts[0];
    loc.host = parts[1];

    //extract any port number from the host
    //from which we derive the port and hostname
    parts[1] = parts[1].split(':');
    loc.hostname = parts[1][0];
    loc.port = parts[1].length > 1 ? parts[1][1] : '';

    //splice and join the remainder to get the pathname
    parts.splice(0, 2);
    loc.pathname = '/' + parts.join('/');

    //extract any hash and remove from the pathname
    loc.pathname = loc.pathname.split('#');
    loc.hash = loc.pathname.length > 1 ? '#' + loc.pathname[1] : '';
    loc.pathname = loc.pathname[0];

    //extract any search query and remove from the pathname
    loc.pathname = loc.pathname.split('?');
    loc.search = loc.pathname.length > 1 ? '?' + loc.pathname[1] : '';
    loc.pathname = loc.pathname[0];

    //return the final object
    if(what) return loc[what];
    return loc;
}
	
});
var seed = null;

