/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */

(function($) {

var types = ['DOMMouseScroll', 'mousewheel'];

$.event.special.mousewheel = {
	setup: function() {
		if ( this.addEventListener )
			for ( var i=types.length; i; )
				this.addEventListener( types[--i], handler, false );
		else
			this.onmousewheel = handler;
	},
	
	teardown: function() {
		if ( this.removeEventListener )
			for ( var i=types.length; i; )
				this.removeEventListener( types[--i], handler, false );
		else
			this.onmousewheel = null;
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},
	
	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});


function handler(event) {
	var args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true;
	
	event = $.event.fix(event || window.event);
	event.type = "mousewheel";
	
	if ( event.wheelDelta ) delta = event.wheelDelta/120;
	if ( event.detail     ) delta = -event.detail/3;
	
	// Add events and delta to the front of the arguments
	args.unshift(event, delta);

	return $.event.handle.apply(this, args);
}

})(jQuery);


/* Copyright (c) 2009 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.js 86 2009-08-30 21:45:11Z kelvin.luck@gmail.com $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object	settings	hash with options, described below.
 *								scrollbarWidth	-	The width of the generated scrollbar in pixels
 *								scrollbarMargin	-	The amount of space to leave on the side of the scrollbar in pixels
 *								wheelSpeed		-	The speed the pane will scroll in response to the mouse wheel in pixels
 *								showArrows		-	Whether to display arrows for the user to scroll with
 *								arrowSize		-	The height of the arrow buttons if showArrows=true
 *								animateTo		-	Whether to animate when calling scrollTo and scrollBy
 *								dragMinHeight	-	The minimum height to allow the drag bar to be
 *								dragMaxHeight	-	The maximum height to allow the drag bar to be
 *								animateInterval	-	The interval in milliseconds to update an animating scrollPane (default 100)
 *								animateStep		-	The amount to divide the remaining scroll distance by when animating (default 3)
 *								maintainPosition-	Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *								tabIndex		-	The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *								enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *								animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *								scrollbarOnLeft	-	Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *								reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *								topCapHeight	-	The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *								bottomCapHeight	-	The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };
	
	return this.each(
		function()
		{
			var $this = $(this);
			var paneEle = this;
			var currentScrollPosition = 0;
			var paneWidth;
			var paneHeight;
			var trackHeight;
			var trackOffset = settings.topCapHeight;
			
			if ($(this).parent().is('.jScrollPaneContainer')) {
				currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				paneWidth = $c.innerWidth();
				paneHeight = $c.outerHeight();
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScollCap', $c).remove();
				$this.css({'top':0});
			} else {
				$this.data('originalStyleTag', $this.attr('style'));
				// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
				$this.css('overflow', 'hidden');
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				paneWidth = $this.innerWidth();
				paneHeight = $this.innerHeight();
				var $container = $('<div></div>')
					.attr({'className':'jScrollPaneContainer'})
					.css(
						{
							'height':paneHeight+'px', 
							'width':paneWidth+'px'
						}
					);
				if (settings.enableKeyboardNavigation) {
					$container.attr(
						'tabindex', 
						settings.tabIndex
					);
				}
				$this.wrap($container);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange', 
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);
				
			}
			trackHeight = paneHeight;
			
			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];
				
				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load readystatechange', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
								$this.jScrollPane(s2); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) { 
								//needed for potential cached images
								this.src = this.src; 
							} 
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;
			var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

			var cssToApply = {
				'height':'auto',
				'width': realPaneWidth + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					),
					$('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
				);
				
				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
				
				
				var currentArrowDirection;
				var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
				var currentArrowInc;
				var whileArrowButtonDown = function() 
				{
					if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
						positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
					}
					currentArrowInc++;
				};

				if (settings.enableKeyboardNavigation) {
					$container.bind(
						'keydown.jscrollpane',
						function(e) 
						{
							switch (e.keyCode) {
								case 38: //up
									currentArrowDirection = -1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 40: //down
									currentArrowDirection = 1;
									currentArrowInc = 0;
									whileArrowButtonDown();
									currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
									return false;
								case 33: // page up
								case 34: // page down
									// TODO
									return false;
								default:
							}
						}
					).bind(
						'keyup.jscrollpane',
						function(e) 
						{
							if (e.keyCode == 38 || e.keyCode == 40) {
								for (var i = 0; i < currentArrowTimerArr.length; i++) {
									clearInterval(currentArrowTimerArr[i]);
								}
								return false;
							}
						}
					);
				}

				if (settings.showArrows) {
					
					var currentArrowButton;
					var currentArrowInterval;

					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowUp', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'top':settings.topCapHeight + 'px'
									}
								)
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr(
									{
										'href':'javascript:;', 
										'className':'jScrollArrowDown', 
										'tabindex':-1
									}
								)
								.css(
									{
										'width':settings.scrollbarWidth+'px',
										'bottom':settings.bottomCapHeight + 'px'
									}
								)
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
				}
				
				if (settings.arrowSize) {
					trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
					trackOffset += settings.arrowSize;
				} else if ($upArrow) {
					var topArrowHeight = $upArrow.height();
					settings.arrowSize = topArrowHeight;
					trackHeight = paneHeight - topArrowHeight - $downArrow.height();
					trackOffset += topArrowHeight;
				}
				trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
				$track.css({'height': trackHeight+'px', top:trackOffset+'px'})
				
				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
				
				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;
				
				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};
				
				var ignoreNativeDrag = function() {	return false; };
				
				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};
				
				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					$container.scrollTop(0);
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};
				
				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);
				
				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);
				
				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
					return false;
				};
				
				$track.bind('mousedown', onTrackClick);
				
				$container.bind(
					'mousewheel',
					function (event, delta) {
						delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					ceaseAnimation();
					var maxScroll = contentHeight - paneHeight;
					pos = pos > maxScroll ? maxScroll : pos;
					$this.data('jScrollPaneMaxScroll', maxScroll);
					var destDragPosition = pos/maxScroll * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						$container.scrollTop(0);
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;
				
				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};
				
				initDrag();
				
				scrollTo(-currentScrollPosition, true);
			
				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);
						
						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;
						
						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}
						
						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)
				
				
				if (location.hash && location.hash.length > 1) {
					setTimeout(function() {scrollTo(location.hash);}, $.browser.safari ? 100 : 0);
				}
				
				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h && h.substr(0, 1) == '#' && h.length > 1) {
								setTimeout(function() {scrollTo(h, !settings.animateToInternalLinks);}, $.browser.safari ? 100 : 0);
							}
						}
					}
				); 
				
				// Deal with dragging and selecting text to make the scrollpane scroll...
				function onSelectScrollMouseDown(e)
				{
				   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
				   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
				  
				}
				
				var textDragDistanceAway;
				var textSelectionInterval;
				
				function onTextSelectionInterval()
				{
					direction = textDragDistanceAway < 0 ? -1 : 1;
					$this[0].scrollBy(textDragDistanceAway / 2);
				}

				function clearTextSelectionInterval()
				{
					if (textSelectionInterval) {
						clearInterval(textSelectionInterval);
						textSelectionInterval = undefined;
					}
				}
				
				function onTextSelectionScrollMouseMove(e)
				{
					var offset = $this.parent().offset().top;
					var maxOffset = offset + paneHeight;
					var mouseOffset = getPos(e, 'Y');
					textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
					if (textDragDistanceAway == 0) {
						clearTextSelectionInterval();
					} else {
						if (!textSelectionInterval) {
							textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
						}
					}
				}

				function onSelectScrollMouseUp(e)
				{
				   $(document)
					  .unbind('mousemove.jScrollPaneDragging')
					  .unbind('mouseup.jScrollPaneDragging');
				   clearTextSelectionInterval();
				}

				$container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

				
				$.jScrollPane.active.push($this[0]);
				
			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				$this[0].scrollTo = $this[0].scrollBy = function() {};
				// clean up listeners
				$this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
			}
			
		}
	)
};

$.fn.jScrollPaneRemove = function()
{
	$(this).each(function()
	{
		$this = $(this);
		var $c = $this.parent();
		if ($c.is('.jScrollPaneContainer')) {
			$this.css(
				{
					'top':'',
					'height':'',
					'width':'',
					'padding':'',
					'overflow':'',
					'position':''
				}
			);
			$this.attr('style', $this.data('originalStyleTag'));
			$c.after($this).remove();
		}
	});
}

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false,
	tabIndex : 0,
	enableKeyboardNavigation: true,
	animateToInternalLinks: false,
	topCapHeight: 0,
	bottomCapHeight: 0
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active; 
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);


 /*

	JQuery Curvy Corners by Mike Jolley
	http://blue-anvil.com
	http://code.google.com/p/jquerycurvycorners/
	------------ 
	Version 1.9	
	                                                        
	Origionaly by: Cameron Cooke and Tim Hutchison.
	Website: http://www.curvycorners.net
	
	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
  
(function($) {
$.fn.corner = function(options) {

	function BlendColour(Col1, Col2, Col1Fraction) {
		var red1 = parseInt(Col1.substr(1,2),16);
		var green1 = parseInt(Col1.substr(3,2),16);
		var blue1 = parseInt(Col1.substr(5,2),16);
		var red2 = parseInt(Col2.substr(1,2),16);
		var green2 = parseInt(Col2.substr(3,2),16);
		var blue2 = parseInt(Col2.substr(5,2),16);
		if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1;
		var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction)));
		if(endRed > 255) endRed = 255;
		if(endRed < 0) endRed = 0;
		var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction)));
		if(endGreen > 255) endGreen = 255;
		if(endGreen < 0) endGreen = 0;
		var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction)));
		if(endBlue > 255) endBlue = 255;
		if(endBlue < 0) endBlue = 0;
		return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);
	}
	
	function IntToHex(strNum) {
		base = strNum / 16;
		rem = strNum % 16;
		base = base - (rem / 16);
		baseS = MakeHex(base);
		remS = MakeHex(rem);
		return baseS + '' + remS;
	}
	
	function MakeHex(x) {
		if((x >= 0) && (x <= 9)) {
			return x; 
		} else {
			switch(x) {
				case 10: return "A";
				case 11: return "B";
				case 12: return "C";
				case 13: return "D";
				case 14: return "E";
				case 15: return "F";
			};
			return "F";
		};
	}
	
	function pixelFraction(x, y, r) {
		var pixelfraction = 0;
		var xvalues = new Array(1);
		var yvalues = new Array(1);
		var point = 0;
		var whatsides = "";
		var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2)));
		if ((intersect >= y) && (intersect < (y+1))) {
			whatsides = "Left";
			xvalues[point] = 0;
			yvalues[point] = intersect - y;
			point = point + 1;
		};
		var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2)));
		if ((intersect >= x) && (intersect < (x+1))) {
			whatsides = whatsides + "Top";
			xvalues[point] = intersect - x;
			yvalues[point] = 1;
			point = point + 1;
		};
		var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2)));
		if ((intersect >= y) && (intersect < (y+1))) {
			whatsides = whatsides + "Right";
			xvalues[point] = 1;
			yvalues[point] = intersect - y;
			point = point + 1;
		};
		var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2)));
		if ((intersect >= x) && (intersect < (x+1))) {
			whatsides = whatsides + "Bottom";
			xvalues[point] = intersect - x;
			yvalues[point] = 0;
		};
		switch (whatsides) {
			case "LeftRight":
			pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2);
			break;
			case "TopRight":
			pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2);
			break;
			case "TopBottom":
			pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2);
			break;
			case "LeftBottom":
			pixelfraction = (yvalues[0]*xvalues[1])/2;
			break;
			default:
			pixelfraction = 1;
		};
		return pixelfraction;
	}
	
	function rgb2Hex(rgbColour) {
		try {
			var rgbArray = rgb2Array(rgbColour);
			var red = parseInt(rgbArray[0]);
			var green = parseInt(rgbArray[1]);
			var blue = parseInt(rgbArray[2]);
			var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);
		} catch(e) {
			alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");
		};
		return hexColour;
	}
	
	function rgb2Array(rgbColour) {
		var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")"));
		var rgbArray = rgbValues.split(", ");
		return rgbArray;
	}
	
	function format_colour(colour) {
		var returnColour = "transparent";
		if(colour != "" && colour != "transparent")
		{
			if(colour.substr(0, 3) == "rgb" && colour.substr(0, 4) != "rgba")
			{
				returnColour = rgb2Hex(colour);
			}			
			else if(colour.length == 4)
			{
				returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);
			}
			else
			{
				returnColour = colour;
			};
		};
		return returnColour;
	};
	function strip_px(value) {
		return parseInt((( value != "auto" && value.indexOf("%") == -1 && value != "" && value.indexOf("px") !== -1)? value.slice(0, value.indexOf("px")) : 0))	
	}

    function drawPixel(box,intx, inty, colour, transAmount, height, newCorner, image, bgImage, cornerRadius, isBorder, borderWidth, boxWidth, settings) {
    	var $$ = $(box);
        var pixel = document.createElement("div");
        $(pixel).css({	height:height,width:"1px",position:"absolute","font-size":"1px",overflow:"hidden"	});
        //var topMaxRadius = Math.max(settings["tr"].radius, settings["tl"].radius);
        var topMaxRadius = Math.max(settings.tl ? settings.tl.radius : 0, settings.tr ? settings.tr.radius : 0);
        // Dont apply background image to border pixels
        if(image == -1 && bgImage != "") {
			if(topMaxRadius>0)
				$(pixel).css("background-position","-" + ((boxWidth - cornerRadius - borderWidth)+ intx) + "px -" + (($$.height() + topMaxRadius  - borderWidth )-inty) + "px");
			else 
				$(pixel).css("background-position","-" + ((boxWidth - cornerRadius - borderWidth)+ intx) + "px -" + (($$.height() )-inty) + "px");	
			$(pixel).css({
						 "background-image":bgImage,
						 "background-repeat":$$.css("background-repeat"),
						 "background-color":colour						 
			});
        }
        else
        {
			if (!isBorder) $(pixel).css("background-color",colour).addClass('hasBackgroundColor');
			else $(pixel).css("background-color",colour);
        };
        
        if (transAmount != 100)
        	setOpacity(pixel, transAmount);
        	//$(pixel).css('opacity',transAmount/100);
		$(pixel).css({top:inty + "px",left:intx + "px"});
        return pixel;
    };
    
	function setOpacity(obj, opacity) {
	  opacity = (opacity == 100)?99.999:opacity;
	
	  if($.browser.safari && obj.tagName != "IFRAME")
	  {
	      // Get array of RGB values
	      var rgbArray = rgb2Array(obj.style.backgroundColor);
	
	      // Get RGB values
	      var red   = parseInt(rgbArray[0]);
	      var green = parseInt(rgbArray[1]);
	      var blue  = parseInt(rgbArray[2]);
	
	      // Safari using RGBA support
	      obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";
	  }
	  else if(typeof(obj.style.opacity) != "undefined")
	  {
	      // W3C
	      obj.style.opacity = opacity/100;
	  }
	  else if(typeof(obj.style.MozOpacity) != "undefined")
	  {
	      // Older Mozilla
	      obj.style.MozOpacity = opacity/100;
	  }
	  else if(typeof(obj.style.filter) != "undefined")
	  {
	      // IE
	      obj.style.filter = "alpha(opacity:" + opacity + ")";
	  }
	  else if(typeof(obj.style.KHTMLOpacity) != "undefined")
	  {
	      // Older KHTML Based Browsers
	      obj.style.KHTMLOpacity = opacity/100;
	  }
	}
		
	// Apply the corners
	function applyCorners(box,settings) {
	
		var $$ = $(box); 

		// Get CSS of box and define vars
		var thebgImage 			= $$.css("backgroundImage");
		var topContainer = null;
		var bottomContainer = null;
		var masterCorners = new Array();
		var contentDIV = null;
		var boxHeight 			= strip_px($$.css("height")) ? strip_px($$.css("height")) : box.scrollHeight; 
		var boxWidth 			= strip_px($$.css("width")) ? strip_px($$.css("width")) : box.scrollWidth; 
		var borderWidth     	= strip_px($$.css("borderTopWidth")) ? strip_px($$.css("borderTopWidth")) : 0; 
		var boxPaddingTop 		= strip_px($$.css("paddingTop"));
		var boxPaddingBottom 	= strip_px($$.css("paddingBottom"));
		var boxPaddingLeft 	= strip_px($$.css("paddingLeft"));
		
		var boxPaddingRight 	= strip_px($$.css("paddingRight"));
		var boxColour 			= format_colour($$.css("backgroundColor"));
		var bgImage 			= (thebgImage != "none" && thebgImage!="initial") ? thebgImage : "";
		//var boxContent 		= $$.html();
		var borderColour 		= format_colour($$.css("borderTopColor")); 
		var borderString 		= borderWidth + "px" + " solid " + borderColour;
		
		var topMaxRadius = Math.max(settings.tl ? settings.tl.radius : 0, settings.tr ? settings.tr.radius : 0);
		var botMaxRadius = Math.max(settings.bl ? settings.bl.radius : 0, settings.br ? settings.br.radius : 0);
		
		$$.addClass('hasCorners').css({"padding":"0", "borderColor":box.style.borderColour, 'overflow':'visible'});
		if(box.style.position != "absolute") $$.css("position","relative");
		if(($.browser.msie)) {
			if($.browser.version==6 && box.style.width == "auto" && box.style.height == "auto") $$.css("width","100%");
			$$.css("zoom","1");
			$("*", $$).css("zoom","normal");
		}		
		
		for(var t = 0;t < 2;t++) {
			switch(t) {
				case 0:
				if(settings.tl || settings.tr) {
					var newMainContainer 	= document.createElement("div");
					topContainer		= box.appendChild(newMainContainer);
					$(topContainer).css({ width:"100%", "font-size":"1px", overflow:"hidden", position:"absolute", "padding-left":borderWidth, "padding-right":borderWidth, height:topMaxRadius + "px",top:0 - topMaxRadius + "px",left:0 - borderWidth + "px"}).addClass('topContainer');
				};
				break;
				case 1:
				if(settings.bl || settings.br) {
					var newMainContainer 	= document.createElement("div");
					bottomContainer	= box.appendChild(newMainContainer);
					$(bottomContainer).css({ width:"100%", "font-size":"1px", overflow:"hidden", position:"absolute", "padding-left":borderWidth, "padding-right":borderWidth, height:botMaxRadius,bottom:0 - botMaxRadius + "px",left:0 - borderWidth + "px"}).addClass('bottomContainer');
				};
				break;
			};
		};
		
		if(settings.autoPad == true) {
			//$$.html("");
			var contentContainer = document.createElement("div");
			var contentContainer2 = document.createElement("div");
			var clearDiv = document.createElement("div");
			
			$(contentContainer2).css({ margin:"0","padding-bottom":boxPaddingBottom,"padding-top":boxPaddingTop,"padding-left":boxPaddingLeft,"padding-right":boxPaddingRight, 'overflow':'visible'}).addClass('hasBackgroundColor content_container');

			$(contentContainer).css({position:"relative", 'float':"left",width:"100%", "margin-top":"-" + Math.abs(topMaxRadius-borderWidth) + "px", "margin-bottom":"-" + Math.abs(botMaxRadius-borderWidth) + "px"}).addClass = "autoPadDiv";
			
			$(clearDiv).css("clear","both");

			contentContainer2.appendChild(contentContainer);
			contentContainer2.appendChild(clearDiv);
			$$.wrapInner(contentContainer2);
		};
		
		if(topContainer) $$.css("border-top",0);
		if(bottomContainer) $$.css("border-bottom",0);
		var corners = ["tr", "tl", "br", "bl"];
		for(var i in corners) {
			if(i > -1 < 4) {
				var cc = corners[i];
				if(!settings[cc]) {

					if(((cc == "tr" || cc == "tl") && topContainer != null) || ((cc == "br" || cc == "bl") && bottomContainer != null)) {
						var newCorner = document.createElement("div");
						$(newCorner).css({position:"relative","font-size":"1px", overflow:"hidden"});
						
						if(bgImage == "")
							$(newCorner).css("background-color",boxColour);
						else
							$(newCorner).css("background-image",bgImage).css("background-color",boxColour);;

						switch(cc)
						{
							case "tl":							
								$(newCorner).css({height:topMaxRadius - borderWidth,"margin-right":settings.tr.radius - (borderWidth*2), "border-left":borderString,"border-top":borderString,left:-borderWidth + "px", "background-repeat":$$.css("background-repeat"), "background-position":borderWidth + "px 0px"});
							break;
							case "tr":
								$(newCorner).css({height:topMaxRadius - borderWidth,"margin-left":settings.tl.radius - (borderWidth*2), "border-right":borderString,"border-top":borderString,left:borderWidth + "px", "background-repeat":$$.css("background-repeat"), "background-position":"-" + (topMaxRadius + borderWidth) + "px 0px"});
							break;
							case "bl":
								if(topMaxRadius>0)
									$(newCorner).css({height:botMaxRadius - borderWidth,"margin-right":settings.br.radius - (borderWidth*2), "border-left":borderString,"border-bottom":borderString,left:-borderWidth + "px", "background-repeat":$$.css("background-repeat"), "background-position":"0px -" + ($$.height() + topMaxRadius  - borderWidth +1) + "px" });
								else
									$(newCorner).css({height:botMaxRadius - borderWidth,"margin-right":settings.br.radius - (borderWidth*2), "border-left":borderString,"border-bottom":borderString,left:-borderWidth + "px", "background-repeat":$$.css("background-repeat"), "background-position":"0px -" + ($$.height()) + "px" });
							break;
							case "br":
								if(topMaxRadius>0)
									$(newCorner).css({height:botMaxRadius - borderWidth,"margin-left":settings.bl.radius - (borderWidth*2), "border-right":borderString,"border-bottom":borderString,left:borderWidth + "px", "background-repeat":$$.css("background-repeat"),  "background-position":"-" + settings.bl.radius + borderWidth + "px -" + ($$.height() + topMaxRadius  - borderWidth + 1) + "px" });
								else
									$(newCorner).css({height:botMaxRadius - borderWidth,"margin-left":settings.bl.radius - (borderWidth*2), "border-right":borderString,"border-bottom":borderString,left:borderWidth + "px", "background-repeat":$$.css("background-repeat"),  "background-position":"-" + settings.bl.radius + borderWidth + "px -" + ($$.height()) + "px" });
							break;
						};
					};
				} else {
					if(masterCorners[settings[cc].radius]) {
						var newCorner = masterCorners[settings[cc].radius].cloneNode(true);
					} else {
						var newCorner = document.createElement("DIV");
						$(newCorner).css({	height:settings[cc].radius,width:settings[cc].radius,position:"absolute","font-size":"1px",overflow:"hidden"	});
						var borderRadius = parseInt(settings[cc].radius - borderWidth);
						for(var intx = 0, j = settings[cc].radius; intx < j; intx++) {
							if((intx +1) >= borderRadius)
								var y1 = -1;
							else
								var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1);
							if(borderRadius != j) {
								if((intx) >= borderRadius)
								var y2 = -1;
								else
								var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2)));
								if((intx+1) >= j)
								var y3 = -1;
								else
								var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);
							};
							if((intx) >= j)
								var y4 = -1;
							else
								var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2)));
							if(y1 > -1) newCorner.appendChild(drawPixel(box,intx, 0, boxColour, 100, (y1+1), newCorner, -1, bgImage, settings[cc].radius, 0, borderWidth, boxWidth, settings));
							if(borderRadius != j) {
								for(var inty = (y1 + 1); inty < y2; inty++) {
									if(settings.antiAlias) {
										if(bgImage != "") {
											var borderFract = (pixelFraction(intx, inty, borderRadius) * 100);
											if(borderFract < 30) {
												newCorner.appendChild(drawPixel(box,intx, inty, borderColour, 100, 1, newCorner, 0, bgImage, settings[cc].radius, 1, borderWidth, boxWidth, settings));
											} else {
												newCorner.appendChild(drawPixel(box,intx, inty, borderColour, 100, 1, newCorner, -1, bgImage, settings[cc].radius, 1, borderWidth, boxWidth, settings));
											};
										} else {
											var pixelcolour = BlendColour(boxColour, borderColour, pixelFraction(intx, inty, borderRadius));
											newCorner.appendChild(drawPixel(box,intx, inty, pixelcolour, 100, 1, newCorner, 0, bgImage, settings[cc].radius, cc, 1, borderWidth, boxWidth, settings));
										};
									};
								};
								if(settings.antiAlias) {
									  if(y3 >= y2)
									  {
										 if (y2 == -1) y2 = 0;
										 newCorner.appendChild(drawPixel(box,intx, y2, borderColour, 100, (y3 - y2 + 1), newCorner, 0,bgImage, 0, 1, borderWidth, boxWidth, settings));
									  }
								} else {
									  if(y3 >= y1)
									  {
										  newCorner.appendChild(drawPixel(box,intx, (y1 + 1), borderColour, 100, (y3 - y1), newCorner, 0,bgImage, 0, 1, borderWidth, boxWidth, settings));
									  }
								};
								var outsideColour = borderColour;
							} else {
								var outsideColour = boxColour;
								var y3 = y1;
							};
							if(settings.antiAlias) {
								for(var inty = (y3 + 1); inty < y4; inty++) {
									newCorner.appendChild(drawPixel(box,intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((borderWidth > 0)? 0 : -1),bgImage, settings[cc].radius, 1, borderWidth, boxWidth, settings));
								};                                
							};
						};
						masterCorners[settings[cc].radius] = newCorner.cloneNode(true);                                           
					};                    
					if(cc != "br") {
						for(var t = 0, k = newCorner.childNodes.length; t < k; t++) {
							var pixelBar 			= newCorner.childNodes[t];
							var pixelBarTop 		= strip_px($(pixelBar).css("top"));
							var pixelBarLeft 		= strip_px($(pixelBar).css("left"));
							var pixelBarHeight 		= strip_px($(pixelBar).css("height"));
							
							if(cc == "tl" || cc == "bl") {
								$(pixelBar).css("left",settings[cc].radius -pixelBarLeft -1 + "px");
							};
							
							if(cc == "tr" || cc == "tl") {
								$(pixelBar).css("top", settings[cc].radius -pixelBarHeight -pixelBarTop + "px");
							};
							
							switch(cc) {
								case "tr":
									$(pixelBar).css("background-position","-" + Math.abs((boxWidth - settings[cc].radius + borderWidth) + pixelBarLeft) + "px -" + Math.abs(settings[cc].radius -pixelBarHeight -pixelBarTop - borderWidth) + "px");
								break;
								case "tl":
									$(pixelBar).css("background-position","-" + Math.abs((settings[cc].radius -pixelBarLeft -1) - borderWidth) + "px -" + Math.abs(settings[cc].radius -pixelBarHeight -pixelBarTop - borderWidth) + "px");
								break;
								case "bl":
									if(topMaxRadius>0)
										$(pixelBar).css("background-position", "-" + Math.abs((settings[cc].radius -pixelBarLeft -1) - borderWidth) + "px -" + Math.abs(($$.height() + topMaxRadius - borderWidth + 1)) + "px");
									else
										$(pixelBar).css("background-position", "-" + Math.abs((settings[cc].radius -pixelBarLeft -1) - borderWidth) + "px -" + Math.abs(($$.height())) + "px");
								break;
							};
						};
					};
				};
				
				if(newCorner) {
					switch(cc) {
						case "tl":
						if($(newCorner).css("position") == "absolute") $(newCorner).css("top","0");
						if($(newCorner).css("position") == "absolute") $(newCorner).css("left","0");
						if(topContainer) topContainer.appendChild(newCorner);
						break;
						case "tr":
						if($(newCorner).css("position") == "absolute") $(newCorner).css("top","0");
						if($(newCorner).css("position") == "absolute") $(newCorner).css("right","0");
						if(topContainer) topContainer.appendChild(newCorner);
						break;
						case "bl":
						if($(newCorner).css("position") == "absolute") $(newCorner).css("bottom","0");
						if(newCorner.style.position == "absolute") $(newCorner).css("left","0");
						if(bottomContainer) bottomContainer.appendChild(newCorner);
						break;
						case "br":
						if($(newCorner).css("position") == "absolute") $(newCorner).css("bottom","0");
						if($(newCorner).css("position") == "absolute") $(newCorner).css("right","0");
						if(bottomContainer) bottomContainer.appendChild(newCorner);
						break;
					};                    
				};
			};
		};
		
		var radiusDiff = new Array();
		radiusDiff["t"] = Math.abs(settings.tl.radius - settings.tr.radius);
		radiusDiff["b"] = Math.abs(settings.bl.radius - settings.br.radius);
		for(z in radiusDiff) {
			if(z == "t" || z == "b") {
				if(radiusDiff[z]) {
					var smallerCornerType = ((settings[z + "l"].radius < settings[z + "r"].radius)? z +"l" : z +"r");
					var newFiller = document.createElement("div");
					$(newFiller).css({	height:radiusDiff[z],width:settings[smallerCornerType].radius+ "px",position:"absolute","font-size":"1px",overflow:"hidden","background-color":boxColour,"background-image":bgImage	});
				  switch(smallerCornerType)
				  {
					  case "tl":
						$(newFiller).css({"bottom":"0","left":"0","border-left":borderString,"background-position":"0px -" + (settings[smallerCornerType].radius - borderWidth )});
						topContainer.appendChild(newFiller);
						break;
	
					  case "tr":
						$(newFiller).css({"bottom":"0","right":"0","border-right":borderString,"background-position":"0px -" + (settings[smallerCornerType].radius - borderWidth ) + "px"});
						topContainer.appendChild(newFiller);
						break;
	
					  case "bl":
						$(newFiller).css({"top":"0","left":"0","border-left":borderString,"background-position":"0px -" + ($$.height() + settings[smallerCornerType].radius - borderWidth )});
						bottomContainer.appendChild(newFiller);
						break;
	
					  case "br":
						$(newFiller).css({"top":"0","right":"0","border-right":borderString,"background-position":"0px -" + ($$.height() + settings[smallerCornerType].radius - borderWidth )});
						bottomContainer.appendChild(newFiller);
						
						break;
				  }
			};
				
			var newFillerBar = document.createElement("div");
			$(newFillerBar).css({	position:"relative","font-size":"1px",overflow:"hidden","background-color":boxColour,"background-image":bgImage,"background-repeat":$$.css("background-repeat")});
			switch(z) {
					case "t":
					if(topContainer) {
						if(settings.tl.radius && settings.tr.radius) {
							$(newFillerBar).css({
												height:topMaxRadius - borderWidth + "px",
												"margin-left":settings.tl.radius - borderWidth  + "px",
												"margin-right":settings.tr.radius - borderWidth  + "px",
												"border-top":borderString
							}).addClass('hasBackgroundColor');
						
							if(bgImage != "")
								$(newFillerBar).css("background-position","-" + (topMaxRadius + borderWidth) + "px 0px");
							
							topContainer.appendChild(newFillerBar);
							
						}; 
						$$.css("background-position", "0px -" + (topMaxRadius - borderWidth +1) + "px"); 
					}; 
					break;
					case "b":
					if(bottomContainer) {
						if(settings.bl.radius && settings.br.radius) {
							$(newFillerBar).css({	
												height:botMaxRadius - borderWidth + "px",
												"margin-left":settings.bl.radius - borderWidth + "px",
												"margin-right":settings.br.radius - borderWidth + "px",
												"border-bottom":borderString
							});
						
							if(bgImage != "" && topMaxRadius>0)
								$(newFillerBar).css("background-position","-" + (settings.bl.radius - borderWidth) + "px -" + ($$.height() + topMaxRadius - borderWidth + 1) + "px");
							else
								$(newFillerBar).css("background-position","-" + (settings.bl.radius - borderWidth) + "px -" + ($$.height() ) + "px").addClass('hasBackgroundColor');
							
							bottomContainer.appendChild(newFillerBar);
						};
					};
					break;
				};
			};
		};
		$$.prepend(topContainer);
		$$.prepend(bottomContainer);
	}

	var settings = {
	  tl: { radius: 8 },
	  tr: { radius: 8 },
	  bl: { radius: 8 },
	  br: { radius: 8 },
	  antiAlias: true,
	  autoPad: true,
	  validTags: ["div"] };
	if ( options && typeof(options) != 'string' )
		$.extend(settings, options);
            
	return this.each(function() {
		if (!$(this).is('.hasCorners')) {
			applyCorners(this, settings);				
		}
		
	}); 
			
};
})(jQuery);


/*
 * yuga.js 0.7.1 - 優雅なWeb制作のためのJS
 *
 * Copyright (c) 2009 Kyosuke Nakamura (kyosuke.jp)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Since:     2006-10-30
 * Modified:  2009-01-27
 *
 * jQuery 1.3.1
 * ThickBox 3.1
 */

(function($) {

	$(function() {
		//$.yuga.selflink();
		$.yuga.rollover();
		//$.yuga.externalLink();
		//$.yuga.thickbox();
		$.yuga.scroll();
		//$.yuga.tab();
		//$.yuga.stripe();
		//$.yuga.css3class();
	});

	//---------------------------------------------------------------------

	$.yuga = {
		// URIを解析したオブジェクトを返すfunction
		Uri: function(path){
			var self = this;
			this.originalPath = path;
			//絶対パスを取得
			this.absolutePath = (function(){
				var e = document.createElement('span');
				e.innerHTML = '<a href="../photo_files/' + path + '" />';
				return e.firstChild.href;
			})();
			//絶対パスを分解
			var fields = {'schema' : 2, 'username' : 5, 'password' : 6, 'host' : 7, 'path' : 9, 'query' : 10, 'fragment' : 11};
			var r = /^((\w+):)?(\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/.exec(this.absolutePath);
			for (var field in fields) {
				this[field] = r[fields[field]];
			}
			this.querys = {};
			if(this.query){
				$.each(self.query.split('&'), function(){
					var a = this.split('=');
					if (a.length == 2) self.querys[a[0]] = a[1];
				});
			}
		},
		//現在のページと親ディレクトリへのリンク
		selflink: function (options) {
			var c = $.extend({
				selfLinkAreaSelector:'body',
				selfLinkClass:'current',
				parentsLinkClass:'parentsLink',
				postfix: '_cr',
				changeImgSelf:true,
				changeImgParents:true
			}, options);
			$(c.selfLinkAreaSelector+((c.selfLinkAreaSelector)?' ':'')+'a[href]').each(function(){
				var href = new $.yuga.Uri(this.getAttribute('href'));
				var setImgFlg = false;
				if ((href.absolutePath == location.href) && !href.fragment) {
					//同じ文書にリンク
					$(this).addClass(c.selfLinkClass);
					setImgFlg = c.changeImgSelf;
				} else if (0 <= location.href.search(href.absolutePath)) {
					//親ディレクトリリンク
					$(this).addClass(c.parentsLinkClass);
					setImgFlg = c.changeImgParents;
				}
				if (setImgFlg){
					//img要素が含まれていたら現在用画像（_cr）に設定
					$(this).find('img').each(function(){
						this.originalSrc = $(this).attr('src');
						this.currentSrc = this.originalSrc.replace(new RegExp('('+c.postfix+')?(\.gif|\.jpg|\.png)$'), c.postfix+"$2");
						$(this).attr('src',this.currentSrc);
					});
				}
			});
		},
		//ロールオーバー
		rollover: function(options) {
			var c = $.extend({
				hoverSelector: '.On, .navOn img',
				groupSelector: '.navGroup',
				postfix: '_on'
			}, options);
			//ロールオーバーするノードの初期化
			var rolloverImgs = $(c.hoverSelector).filter(isNotCurrent);
			rolloverImgs.each(function(){
				this.originalSrc = $(this).attr('src');
				this.rolloverSrc = this.originalSrc.replace(new RegExp('('+c.postfix+')?(\.gif|\.jpg|\.png)$'), c.postfix+"$2");
				this.rolloverImg = new Image;
				this.rolloverImg.src = this.rolloverSrc;
			});
			//グループ内のimg要素を指定するセレクタ生成
			var groupingImgs = $(c.groupSelector).find('img').filter(isRolloverImg);

			//通常ロールオーバー
			rolloverImgs.not(groupingImgs).hover(function(){
				$(this).attr('src',this.rolloverSrc);
			},function(){
				$(this).attr('src',this.originalSrc);
			});
			//グループ化されたロールオーバー
			$(c.groupSelector).hover(function(){
				$(this).find('img').filter(isRolloverImg).each(function(){
					$(this).attr('src',this.rolloverSrc);
				});
			},function(){
				$(this).find('img').filter(isRolloverImg).each(function(){
					$(this).attr('src',this.originalSrc);
				});
			});
			//フィルタ用function
			function isNotCurrent(i){
				return Boolean(!this.currentSrc);
			}
			function isRolloverImg(i){
				return Boolean(this.rolloverSrc);
			}

		},
		//外部リンクは別ウインドウを設定
		externalLink: function(options) {
			var c = $.extend({
				windowOpen:true,
				externalClass: 'externalLink',
				addIconSrc: ''
			}, options);
			var uri = new $.yuga.Uri(location.href);
			var e = $('a[href^="http://"]').not('a[href^="' + uri.schema + '://' + uri.host + '/' + '"]');
			if (c.windowOpen) {
				e.click(function(){
					window.open(this.href, '_blank');
					return false;
				});
			}
			if (c.addIconSrc) e.not(':has(img)').after($('<img src="../photo_files/'+c.addIconSrc+'" class="externalIcon" />'));
			e.addClass(c.externalClass);
		},
		//画像へ直リンクするとthickboxで表示(thickbox.js利用)
		thickbox: function() {
			try {
				tb_init('a[href$=".jpg"]:not(.thickbox, a[href*="?"]), a[href$=".gif"][href!="?"]:not(.thickbox, a[href*="?"]), a[href$=".png"][href!="?"]:not(.thickbox, a[href*="?"])');
			} catch(e) {
			}	
		},
		//ページ内リンクはするするスクロール
		scroll: function(options) {
			//ドキュメントのスクロールを制御するオブジェクト
			var scroller = (function() {
				var c = $.extend({
					easing:100,
					step:30,
					fps:60,
					fragment:''
				}, options);
				c.ms = Math.floor(1000/c.fps);
				var timerId;
				var param = {
					stepCount:0,
					startY:0,
					endY:0,
					lastY:0
				};
				//スクロール中に実行されるfunction
				function move() {
					if (param.stepCount == c.step) {
						//スクロール終了時
						setFragment(param.hrefdata.absolutePath);
						window.scrollTo(getCurrentX(), param.endY);
					} else if (param.lastY == getCurrentY()) {
						//通常スクロール時
						param.stepCount++;
						window.scrollTo(getCurrentX(), getEasingY());
						param.lastY = getEasingY();
						timerId = setTimeout(move, c.ms); 
					} else {
						//キャンセル発生
						if (getCurrentY()+getViewportHeight() == getDocumentHeight()) {
							//画面下のためスクロール終了
							setFragment(param.hrefdata.absolutePath);
						}
					}
				}
				function setFragment(path){
					location.href = path
				}
				function getCurrentY() {
					return document.body.scrollTop  || document.documentElement.scrollTop;
				}
				function getCurrentX() {
					return document.body.scrollLeft  || document.documentElement.scrollLeft;
				}
				function getDocumentHeight(){
					return document.documentElement.scrollHeight || document.body.scrollHeight;
				}
				function getViewportHeight(){
					return (!$.browser.safari && !$.browser.opera) ? document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight : window.innerHeight;
				}
				function getEasingY() {
					return Math.floor(getEasing(param.startY, param.endY, param.stepCount, c.step, c.easing));
				}
				function getEasing(start, end, stepCount, step, easing) {
					var s = stepCount / step;
					return (end - start) * (s + easing / (100 * Math.PI) * Math.sin(Math.PI * s)) + start;
				}
				return {
					set: function(options) {
						this.stop();
						if (options.startY == undefined) options.startY = getCurrentY();
						param = $.extend(param, options);
						param.lastY = param.startY;
						timerId = setTimeout(move, c.ms); 
					},
					stop: function(){
						clearTimeout(timerId);
						param.stepCount = 0;
					}
				};
			})();
			$('a[href^=#], area[href^=#]').not('a[href=#], area[href=#]').each(function(){
				this.hrefdata = new $.yuga.Uri(this.getAttribute('href'));
			}).click(function(){
				var target = $('#'+this.hrefdata.fragment);
				if (target.length == 0) target = $('a[name='+this.hrefdata.fragment+']');
				if (target.length) {
					scroller.set({
						endY: target.offset().top,
						hrefdata: this.hrefdata
					});
					return false;
				}
			});
		},
		//タブ機能
		tab: function(options) {
			var c = $.extend({
				tabNavSelector:'.tabNav',
				activeTabClass:'active'
			}, options);
			$(c.tabNavSelector).each(function(){
				var tabNavList = $(this).find('a[href^=#], area[href^=#]');
				var tabBodyList;
				tabNavList.each(function(){
					this.hrefdata = new $.yuga.Uri(this.getAttribute('href'));
					var selecter = '#'+this.hrefdata.fragment;
					if (tabBodyList) {
						tabBodyList = tabBodyList.add(selecter);
					} else {
						tabBodyList = $(selecter);
					}
					$(this).unbind('click');
					$(this).click(function(){
						tabNavList.removeClass(c.activeTabClass);
						$(this).addClass(c.activeTabClass);
						tabBodyList.hide();
						$(selecter).show();
						return false;
					});
				});
				tabBodyList.hide()
				tabNavList.filter(':first').trigger('click');
			});
		},
		//奇数、偶数を自動追加
		stripe: function(options) {
			var c = $.extend({
				oddClass:'odd',
				evenClass:'even'
			}, options);
			$('ul, ol').each(function(){
				//JSでは0から数えるのでevenとaddを逆に指定
				$(this).children('li:odd').addClass(c.evenClass);
				$(this).children('li:even').addClass(c.oddClass);
			});
			$('table, tbody').each(function(){
				$(this).children('tr:odd').addClass(c.evenClass);
				$(this).children('tr:even').addClass(c.oddClass);
			});
		},
		//css3のクラスを追加
		css3class: function() {
			//:first-child, :last-childをクラスとして追加
			$('body :first-child').addClass('firstChild');
			$('body :last-child').addClass('lastChild');
			//css3の:emptyをクラスとして追加
			$('body :empty').addClass('empty');
		}
	};
})(jQuery);

//ROLL_OVER
$(function(){
	$("img.Over, .Over img").each(function(){
		$("<img>").attr("src",$(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2"));
	})

	if($.browser.msie && $.browser.version<7){
		$("img.Over, .Over img").each(function(){
		
			$(this)
				.data("src",$(this).attr("src"))
				.attr("src","image/common/transparent.gif")
				.css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$(this).data("src")+"',sizingMethod='scale')")
				
		}).mouseover(function(){
			$(this).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$(this).data("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2")+"',sizingMethod='scale')")
		}).mouseout(function(){
			$(this).css("filter","progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+$(this).data("src")+"',sizingMethod='scale')")
		})
		
	}else{
		$("img.Over, .Over img").mouseover(function(){
			$(this).attr("src",$(this).attr("src").replace(/^(.+)(\.[a-z]+)$/, "$1_on$2"));
		}).mouseout(function(){
			$(this).attr("src",$(this).attr("src").replace(/^(.+)_on(\.[a-z]+)$/, "$1$2"));
		})
	}
})
