jQuery(document).ready(function() {
	box = new jbox();
});

// set up our jbox
function jbox() {
	this.overlay = '#Overlay';
	this.overlayLiner = '#OverlayLiner';
	this.currentContent = false;
	this.visible = false;
	this.mouseIn = false;
	this.fadeSpeed = 300;
	this.jboxGroups = Array();
	
	if (jQuery('a[rel^=jbox]').length) {
		this.buildOverlay();
	}

	this.addJboxHandler();
	this.addCloseHandler();
	this.addWindowHandler();
}

// build overlay
jbox.method('buildOverlay', function() {
	jQuery('body').append(
		jQuery('<div></div>').attr({ 'id': 'Overlay'}).css({ display: 'none', position: 'absolute', top: '0', left: '0', 'z-index': '25', opacity: .7, "background-color": 'white', padding: '0', margin: '0' }),
		jQuery('<div></div>').attr({ 'id': 'OverlayLiner' }).css({ display: 'none', position: 'absolute', top: '0', left: '0', 'z-index': '26', width: this.overlayWidth, height: this.overlayHeight, padding: '0', margin: '0' }).append(
			jQuery('<div></div>').attr({ 'id': 'OverlayContentHolder' }).css({ position: 'relative','z-index': '50', margin: '80px auto 0 auto', width: '636px' })
		)
	);
});

// display the overlay
jbox.method('showOverlay', function() {
	this.resizeOverlay();
	if (!this.visible) {
		//jQuery(this.overlay).css({ display: 'block' });
		//jQuery(this.overlayLiner).css({ display: 'block' });
		jQuery(this.overlay).fadeIn(this.fadeSpeed);
		jQuery(this.overlayLiner).fadeIn(this.fadeSpeed);
		this.visible = true;
	}
});

// hide the overlay
jbox.method('hideOverlay', function() {
	if (this.visible) {
		//jQuery(this.overlay).css({ display: 'none' });
		//jQuery(this.overlayLiner).css({ display: 'none' });
		jQuery(this.overlay).fadeOut(this.fadeSpeed);
		jQuery(this.overlayLiner).fadeOut(this.fadeSpeed);
		this.visible = false;
	}
});

// load content into the overlay (ajax request if doesn't exist, just display if already loaded)
jbox.method('loadContent', function(href, group) {
	httpRegExp = /^(http:)/;
	if (httpRegExp.test(href)) {
		pos = href.indexOf("/");
		var count = 0;
		while (count < 3) {
			count++;
			href = href.substr(pos + 1);
			pos = href.indexOf("/");
		}
	}
	hrefRegExp = /(.jpg)$/;
	gifRegExp  = /(.gif)$/;
	if (hrefRegExp.test(href) || gifRegExp.test(href)) {
		pos = href.indexOf("/");
		var loadID = href;
		while (pos != -1) {
			loadID = loadID.substr(pos + 1);
			pos    = loadID.indexOf("/");
		}
		pos = loadID.indexOf(".");
		loadID = loadID.substr(0, pos);
		if (jQuery('#' + loadID).length) {
			if (this.currentContent != loadID) {
				jQuery('#' + this.currentContent).fadeOut(400);
				this.currentContent = loadID;
				jQuery('#' + this.currentContent).fadeIn(400);
			}
		} else {
			jQuery('#OverlayContentHolder').prepend(
				// create div with loadID to hold new content
				jQuery('<div></div>').attr({ 'id': loadID, className: 'overlayContent imageContent' }).css({ background: 'transparent url(' + href + ') no-repeat center center' }).fadeIn(400)
			);
			if (this.currentContent) {
				jQuery('#' + this.currentContent).fadeOut(400);
			}
			this.currentContent = loadID;
			jQuery('#' + this.currentContent).fadeIn(400);
		}
	} else {
		hrefRegExp = /(.html)$/;
		if (hrefRegExp.test(href)) {
			var loadID = href.substr(0, href.length-4);
		} else {
			pos = href.indexOf("/");
			var loadID = href;
			var count = 0;
			var temp = '';
			var sep = '';
			while (pos != -1 && pos != loadID.length-1) {
				count++;
				loadID = loadID.substr(pos + 1);
				pos    = loadID.indexOf("/");
				if (count >= 2) {
					temp = temp + sep + loadID.substr(0, pos);
					sep = '-';
				}
			}
			loadID = temp + loadID;
			if (loadID.charAt(loadID.length-1) == "/") {
				loadID = loadID.substr(0, loadID.length-1);
			}
		}
		var _this  = this;
		// check to see if this content is part of a group
		if (group && _this.jboxGroups[group.group].length > 1) {
			// display next/prev buttons and add new click events
			jQuery('#next').css({ display: 'block' });
			jQuery('#prev').css({ display: 'block' });
			// unbind any current click events
			jQuery('#next').unbind('click');
			jQuery('#prev').unbind('click');
			// bind new click events
			jQuery('#next').bind('click', function() {
				var next = group.current+1;
				if (next > _this.jboxGroups[group.group].length-1) {
					next = 0;
				}
				_this.loadContent(_this.jboxGroups[group.group][next], { group: group.group, current: next });
			});
			jQuery('#prev').bind('click', function() {
				var prev = group.current-1;
				if (prev < 0) {
					prev = _this.jboxGroups[group.group].length-1;
				}
				_this.loadContent(_this.jboxGroups[group.group][prev], { group: group.group, current: prev });
			});
		} else {
			// make sure next/prev buttons are hidden
			jQuery('#next').css({ display: 'none' });
			jQuery('#prev').css({ display: 'none' });
		}
		
		// check to see if this content has already been loaded
		if (jQuery('#' + loadID).length) {
			// check to see if this content is already the current content
			if (this.currentContent != loadID) {
				// show loading animation
				jQuery('#loader').css({ display: 'block' });
				// hide current content
				jQuery('#' + this.currentContent).fadeOut(400);
				// show new content
				jQuery('#' + loadID).fadeIn(200);
				// hide loading animation
				jQuery('#loader').css({ display: 'none' });
				// store new current content id
				this.currentContent = loadID;
			}
			jQuery('#' + loadID).css({ display: 'block' });
		} else {
			// load content using ajax
			jQuery.get(href, function(data) {
				jQuery('#loader').css({ display: 'none' });
				jQuery('#OverlayContentHolder').prepend(
					// create div with loadID to hold new content
					jQuery('<div></div>').attr({ 'id': loadID, className: 'overlayContent' }).css({display: "none"}).append(data).fadeIn(200)
				);
				if (_this.currentContent) {
					jQuery('#' + _this.currentContent).fadeOut(400);
				}
				_this.currentContent = loadID;
				_this.addJboxHandler();
				_this.addCloseHandler();
			});
		}
	}
});

// add click events to all anchor tags with rel = 'jbox'
jbox.method('addJboxHandler', function() {
	var _this = this;
	jQuery("a[rel^='jbox']").each(function(i) {
		var rel = jQuery(this).attr('rel');
		var href = jQuery(this).attr('href');
		var position = href.indexOf("/");
		/*
		var found = 0;
		while (found < 3) {
			found++;
			// If url exists as http://something/name.php remove http://something/ and return name.php
			href = href.substr(position + 1, href.length);
			position = href.indexOf("/");
		}
		*/
		// check for groups (if length of rel is > 4 it means we have 'jbox[...]' which means it is in a group
		if (rel.length > 4) {
			// get the group name (the string between the [ ])
			rel = rel.substr(5, (rel.length-6));
			// create a new entry in the group array if it isn't already there
			if (!_this.jboxGroups[rel]) {
				_this.jboxGroups[rel] = Array();
			}
			if (jQuery.inArray(href, _this.jboxGroups[rel]) == -1) {
				// add this link to the group
				_this.jboxGroups[rel].push(href);
			}
			// store group and current info for loadContent() call
			rel = { group: rel, current: jQuery.inArray(href, _this.jboxGroups[rel]) };
		} else {
			// not part of a group so set rel to false
			rel = false;
		}
		// add click event
		jQuery(this).unbind("click");
		jQuery(this).bind("click", function(event) {
			event.preventDefault();
			box.showOverlay();
			box.loadContent(href, rel);
		});
	});
});

// add events to handle closing the overlay
jbox.method('addCloseHandler', function() {
	_this = this;
	jQuery('#OverlayContentHolder').unbind('mouseenter');
	jQuery('#OverlayContentHolder').unbind('mouseleave');
	jQuery('#OverlayContentHolder').bind('mouseenter', function() {
		_this.mouseIn = true;
	}).bind('mouseleave', function() {
		_this.mouseIn = false;
	});
	jQuery('ul.galleryNav li.close').unbind('click');
	jQuery('ul.galleryNav li.close').bind('click', function() {
		_this.hideOverlay();
	});
	jQuery(this.overlayLiner).unbind('click');
	jQuery(this.overlayLiner).bind('click', function() {
		if (!_this.mouseIn) {
			_this.hideOverlay();
		}
	});
});

// add a resize event to the window so the overlay stays the right size
jbox.method('addWindowHandler', function() {
	var _this = this;
	jQuery(window).resize(function() {
		_this.resizeOverlay(true);
	});
});

// get the current width and height of the window/document and apply this to the overlay and liner
jbox.method('resizeOverlay', function(windowChange) {
	var newWidth = this.getViewWidth(windowChange);
	var newHeight = this.getViewHeight();

	// check that the new height and width is different to the current
	if (this.overlayWidth != newWidth || this.overlayHeight != newHeight) {
		// set the new heights and widths
		
		// take into account the scrollbar in IE 6
		if(jQuery.browser.msie && jQuery.browser.version == "6.0"){
			newWidth = newWidth - 17;
		}
		
		jQuery(this.overlay).css({ width: newWidth, height: newHeight });
		jQuery(this.overlayLiner).css({ width: newWidth, height: newHeight });
		
		// store the new height and widths
		this.overlayWidth = newWidth;
		this.overlayHeight = newHeight;
	}
});

// get width of the view
jbox.method('getViewWidth', function(windowChange) {
	if (windowChange) {
		return jQuery(window).width();
	}
	return jQuery(document).width();
});

// get height of the view
jbox.method('getViewHeight', function() {
	return jQuery(document).height();
});
