var GirlMeta = ['vitals', 'hair', 'eyes', 'height'];

function tGalleryInit(jsonUrl, currentPage, perPage) {
	perPage = perPage || 8;
	currentPage = currentPage || 1;

jQuery(function($){

	function onClickLoadRecord(e) {
		$.getJSON(
			jsonUrl,
			{cat_name: 'totties', 'id': this.rel, 'width':324, 'height':431, crop:1, resize:1 },
			function(data) {
				var img = $('#totty-image img')[0];

				img.src = data.meta.resized_picture_url;
				img.alt = data.post_title;
				img.rel = data.ID;
				img.parentNode.href = data.meta.picture_url;

				$('#totty-info h2').html(data.post_title);
				$('#totty-info .content').html(data.post_content);

				for(i in GirlMeta) {
					if (data.meta[GirlMeta[i]]) {
						$('dd.info-' + GirlMeta[i]).html( data.meta[GirlMeta[i]] );
						$('.info-' + GirlMeta[i]).show();
					} else {
						$('.info-' + GirlMeta[i]).hide();
					}

				}
			}
		);
		e.preventDefault();
	}

	var GalleryLinkHandler = function(el) {
		this.elRef = el;		// as passed
		this.jEl = $(el);		// jquery'ed element
		this.el = this.jEl[0];	// actual element

		this.urlStore = [];
		if (!this.el.rel) { this.el.rel = 0; }

		if (this.el.href != '#' && this.el.href) {
			this._storeRelUrl();
		}
	}
	GalleryLinkHandler.prototype = {
		_storeRelUrl: function() {
			if (!this.jEl.hasClass('inactive'))
				this.urlStore[ parseInt(this.el.rel) ] = this.el.href;
		},

		/* always trust response from the json data - to be called on new reassignment */
		setNewLink: function(newUrl, direction) {
			this.el.rel = parseInt(this.el.rel) + parseInt(direction);

			if (newUrl) {
				this.jEl.removeClass('inactive');
				this._storeRelUrl();
				this.el.href = newUrl;
			} else {
				this.jEl.addClass('inactive');
				this.el.href = '#';
			}
		},

		/* following two methods reinstate URLs and rels from the urlcache */
		setLinkByDirection: function(direction) {
			this.setLinkByRel( parseInt(this.el.rel) + parseInt(direction) );
		},

		setLinkByRel: function(num) {
			if (this.urlStore[num]) {
				this.jEl.removeClass('inactive');
				this.el.href = this.urlStore[num];
			} else {
				this.el.href = '#';
				this.jEl.addClass('inactive');
			}
			this.el.rel = num;
		}
	}

	function calibratePalette() {
		var regexp = /t\-page\-([0-9]+)/;
		var active = 0;
		$('#main ul.gallery').each(function() {
			var matches = regexp.exec(this.id);
			if (matches[1]) {
				$(this).css('left', ((parseInt(matches[1])-1) * 260) + 'px');
				if ($(this).hasClass('active')) {
					active = parseInt(matches[1]);
				}
			}
		});

		if (active > 0) {
			$('#palette').css('left', 0- (260 * (parseInt(active)-1))).show();
		}
	}

	function handleClick(e, el, direction) {
		if (el.rel && el.rel > 0 && !$(el).hasClass('inactive')) {

			if (document.getElementById('t-page-' + el.rel)) {
				// scroll this in, scroll old out

				if ($.browser.mozilla) {
					// scrolling is far too jerky in firefox, so we use the alternative
					$('#main ul.active').removeClass('active').hide();
					$('#palette').css('left', 0- (260 * (parseInt(el.rel)-1)));
					$('#t-page-' + el.rel).addClass('active').show();

				} else {
					$('#palette').animate({left: 0- (260 * (parseInt(el.rel)-1))}, 500);
					$('#main ul.active').removeClass('active');
					$('#t-page-' + el.rel).addClass('active');
				}

				gNext.setLinkByDirection(direction);
				gPrev.setLinkByDirection(direction);

			} else {

				var lastGallery = $('#main ul.active')
				$(el).addClass('loading');

				if ($.browser.mozilla) {
					lastGallery.fadeOut(300, function(){
						$('#t-loading').show();
						$('#palette').hide();
					});
				}

				$.getJSON(
					jsonUrl,
					{cat_name: 'totties', mode: 'list', limit:perPage, 'page': el.rel, 'width':50, 'height':50, crop:1, resize:1 },
					function(data) {
						// create
						var newGallery = $('<ul id="t-page-' + data.page + '" class="gallery"></ul>').css('left', ((parseInt(data.page)-1) * 260) + 'px');

						// do direction test
						// if scrolling left (-1), position it to the left
						// if scrolling right (1), position it to the right
						//ul.left = "273px";

						lastGallery.after(newGallery);

						for(var i=0; i<data.results.length; i++ ) {
							var item = data.results[i];
							newGallery.append('<li><a href="' + item.permalink + '" title="' + item.meta.name + '" rel="'+ item.ID + '"><img src="'+ item.meta.resized_picture_url + '" alt="' + item.post_title + '" /></a></li>');
						}

						// do the scroll in thing..

						// then reassign scroll
						$('a', newGallery).click(onClickLoadRecord);
						lastGallery.removeClass('active');
						$(newGallery).addClass('active');

						//
						//newGallery.show();
						if ($.browser.mozilla) {
							// scrolling is far too jerky in firefox, so we use the alternative
							$('#t-loading').fadeOut('fast');
							$('#palette').css('left', 0- (260 * (parseInt(data.page)-1))).show();
							lastGallery.hide();

						} else {
							$('#palette').animate({left: 0- (260 * (parseInt(data.page)-1))}, 500);
						}

						gNext.setNewLink(data.nextUrl, direction);
						gPrev.setNewLink(data.prevUrl, direction);
						$(el).removeClass('loading');
					}
				);
			}
		}
		e.preventDefault();
	}

	calibratePalette();

	var gNext = new GalleryLinkHandler('#g-next');
	var gPrev = new GalleryLinkHandler('#g-prev');

	$('#g-next').click(function(e){ handleClick(e, this, 1); });
	$('#g-prev').click(function(e){ handleClick(e, this, -1); });

	$('#main .gallery a').click(onClickLoadRecord);



});
}