// Contains cloud-zoom, colorbox, idTabs, and kwicks

//////////////////////////////////////////////////////////////////////////////////
// Cloud Zoom V1.0.2
// (c) 2010 by R Cecco. <http://www.professorcloud.com>
// MIT License
//
// Please retain this copyright header in all versions of the software
//////////////////////////////////////////////////////////////////////////////////
(function ($) {

    $(document).ready(function () {
        $('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
    });

    function format(str) {
        for (var i = 1; i < arguments.length; i++) {
            str = str.replace('%' + (i - 1), arguments[i]);
        }
        return str;
    }

    function CloudZoom(jWin, opts) {
        var sImg = $('img', jWin);
		var	img1;
		var	img2;
        var zoomDiv = null;
		var	$mouseTrap = null;
		var	lens = null;
		var	$tint = null;
		var	softFocus = null;
		var	$ie6Fix = null;
		var	zoomImage;
        var controlTimer = 0;      
        var cw, ch;
        var destU = 0;
		var	destV = 0;
        var currV = 0;
        var currU = 0;      
        var filesLoaded = 0;
        var mx,
            my; 
        var ctx = this, zw;
        // Display an image loading message. This message gets deleted when the images have loaded and the zoom init function is called.
        // We add a small delay before the message is displayed to avoid the message flicking on then off again virtually immediately if the
        // images load really fast, e.g. from the cache. 
        //var	ctx = this;
        setTimeout(function () {
            //						 <img src="/images/loading.gif"/>
            if ($mouseTrap === null && !($.browser.msie && $.browser.version < 7)) {
                var w = jWin.parent().width();
                jWin.parent().append(format('<div style="width:%0px;position:absolute;top:75%;left:%1px;text-align:center" class="cloud-zoom-loading" >Loading...</div>', w / 3, (w / 2) - (w / 6))).find(':last').css('opacity', 0.5);
            }
        }, 200);


        var ie6FixRemove = function () {

            if ($ie6Fix !== null) {
                $ie6Fix.remove();
                $ie6Fix = null;
            }
        };

        // Removes cursor, tint layer, blur layer etc.
        this.removeBits = function () {
            //$mouseTrap.unbind();
            if (lens) {
                lens.remove();
                lens = null;             
            }
            if ($tint) {
                $tint.remove();
                $tint = null;
            }
            if (softFocus) {
                softFocus.remove();
                softFocus = null;
            }
            ie6FixRemove();

            $('.cloud-zoom-loading', jWin.parent()).remove();
        };


        this.destroy = function () {
            jWin.data('zoom', null);

            if ($mouseTrap) {
                $mouseTrap.unbind();
                $mouseTrap.remove();
                $mouseTrap = null;
            }
            if (zoomDiv) {
                zoomDiv.remove();
                zoomDiv = null;
            }
            //ie6FixRemove();
            this.removeBits();
            // DON'T FORGET TO REMOVE JQUERY 'DATA' VALUES
        };


        // This is called when the zoom window has faded out so it can be removed.
        this.fadedOut = function () {
            
			if (zoomDiv) {
                zoomDiv.remove();
                zoomDiv = null;
            }
			 this.removeBits();
            //ie6FixRemove();
        };

        this.controlLoop = function () {
            if (lens) {
				var z =	$('#primaryimage').offset().left-$('#zoom1').offset().left;
                var x = (z+mx - sImg.offset().left - (cw * 0.5)) >> 0;
                var y = (my - sImg.offset().top - (ch * 0.5)) >> 0;
               
                if (x < z) {
                    x = z;
                }
                else if (x > (z+sImg.outerWidth() - cw)) {
                    x = (z+sImg.outerWidth() - cw);
                }
                if (y < 0) {
                    y = 0;
                }
                else if (y > (sImg.outerHeight() - ch)) {
                    y = (sImg.outerHeight() - ch);
                }

                lens.css({
                    left: x,
                    top: y
                });
                lens.css('background-position', (-x) + 'px ' + (-y) + 'px');

                destU = (((x-z) / sImg.outerWidth()) * zoomImage.width) >> 0;
                destV = (((y) / sImg.outerHeight()) * zoomImage.height) >> 0;
                currU += (destU - currU) / opts.smoothMove;
                currV += (destV - currV) / opts.smoothMove;

                zoomDiv.css('background-position', (-(currU >> 0) + 'px ') + (-(currV >> 0) + 'px'));              
            }
            controlTimer = setTimeout(function () {
                ctx.controlLoop();
            }, 30);
        };

        this.init2 = function (img, id) {

            filesLoaded++;
            //console.log(img.src + ' ' + id + ' ' + img.width);	
            if (id === 1) {
                zoomImage = img;
            }
            //this.images[id] = img;
            if (filesLoaded === 2) {
                this.init();
            }
        };

        /* Init function start.  */
        this.init = function () {
            // Remove loading message (if present);
            $('.cloud-zoom-loading', jWin.parent()).remove();


/* Add a box (mouseTrap) over the small image to trap mouse events.
		It has priority over zoom window to avoid issues with inner zoom.
		We need the dummy background image as IE does not trap mouse events on
		transparent parts of a div.
		*/
            $mouseTrap = jWin.parent().append(format("<div class='mousetrap' style='background-image:url(\".\");z-index:999;position:absolute;width:%0px;height:%1px;left:%2px;top:%3px;padding-left:20px;padding-right:20px;\'></div>", sImg.outerWidth(), sImg.outerHeight(), ($('#wrap').width() - sImg.outerWidth() - 40) / 2, 0)).find(':last');
			
			$mouseTrap.bind('click',this,function(event){
				if (window.getSelection && document.createRange) {
					window.getSelection().removeAllRanges()
				}
				if (opts.clickThrough) {
					window.open(zoomImage.src);
				}
				return false
			});
            if (!($.browser.msie && $.browser.version < 7)) { 
                //////////////////////////////////////////////////////////////////////			
                /* Do as little as possible in mousemove event to prevent slowdown. */
                $mouseTrap.bind('mousemove', this, function (event) {
                    // Just update the mouse position
                    mx = event.pageX;
                    my = event.pageY;
                });
                //////////////////////////////////////////////////////////////////////					
                $mouseTrap.bind('mouseleave', this, function (event) {
                    clearTimeout(controlTimer);
                    //event.data.removeBits();                
    				if(lens) { lens.fadeOut(299); }
    				if($tint) { $tint.fadeOut(299); }
    				if(softFocus) { softFocus.fadeOut(299); }
    				zoomDiv.fadeOut(100, function () {
                        ctx.fadedOut();
                    });	
    				$('#' + opts.position).css('zIndex',-99);				
                    return false;
                });
                //////////////////////////////////////////////////////////////////////			
                $mouseTrap.bind('mouseenter', this, function (event) {
    				mx = event.pageX;
                    my = event.pageY;
                    zw = event.data;
                    if (zoomDiv) {
                        zoomDiv.stop(true, false);
                        zoomDiv.remove();
                    }

                    var xPos = opts.adjustX,
                        yPos = opts.adjustY;
                                 
                    var siw = sImg.outerWidth();
                    var sih = sImg.outerHeight();

                    var w = opts.zoomWidth;
                    var h = opts.zoomHeight;
                    if (opts.zoomWidth == 'auto') {
                        w = siw;
                    }
                    if (opts.zoomHeight == 'auto') {
                        h = sih;
                    }
                    //$('#info').text( xPos + ' ' + yPos + ' ' + siw + ' ' + sih );
                    var appendTo = jWin.parent(); // attach to the wrapper			
                    switch (opts.position) {
                    case 'top':
                        yPos -= h; // + opts.adjustY;
                        break;
                    case 'right':
                        xPos += siw; // + opts.adjustX;					
                        break;
                    case 'bottom':
                        yPos += sih; // + opts.adjustY;
                        break;
                    case 'left':
                        xPos -= w; // + opts.adjustX;					
                        break;
                    case 'inside':
                        w = siw;
                        h = sih;
                        break;
                        // All other values, try and find an id in the dom to attach to.
                    default:
                        appendTo = $('#' + opts.position);
                        // If dom element doesn't exit, just use 'right' position as default.
                        if (!appendTo.length) {
                            appendTo = jWin;
                            xPos += siw; //+ opts.adjustX;
                            yPos += sih; // + opts.adjustY;	
                        } else {
                            w = appendTo.innerWidth();
                            h = appendTo.innerHeight();
                        }
                    }

                    zoomDiv = appendTo.append(format('<div id="cloud-zoom-big" class="cloud-zoom-big" style="display:none;position:absolute;left:%0px;top:%1px;width:%2px;height:%3px;background-image:url(\'%4\');z-index:99;"></div>', xPos, yPos, w, h, zoomImage.src)).find(':last');
    				appendTo.css('zIndex',98);
    				
                    // Add the title from title tag.
                    if (sImg.attr('title') && opts.showTitle) {
                        zoomDiv.append(format('<div class="cloud-zoom-title">%0</div>', sImg.attr('title'))).find(':last').css('opacity', opts.titleOpacity);
                    }

                    // Fix ie6 select elements wrong z-index bug. Placing an iFrame over the select element solves the issue...		
                    if ($.browser.msie && $.browser.version < 7) {
                        $ie6Fix = $('<iframe frameborder="0" src="#"></iframe>').css({
                            position: "absolute",
                            left: xPos,
                            top: yPos,
                            zIndex: 99,
                            width: w,
                            height: h
                        }).insertBefore(zoomDiv);
                    }

                    zoomDiv.fadeIn(500);

                    if (lens) {
                        lens.remove();
                        lens = null;
                    } /* Work out size of cursor */
                    cw = (sImg.outerWidth() / zoomImage.width) * zoomDiv.width();
                    ch = (sImg.outerHeight() / zoomImage.height) * zoomDiv.height();

                    // Attach mouse, initially invisible to prevent first frame glitch
                    lens = jWin.append(format("<div class = 'cloud-zoom-lens' style='display:none;z-index:98;position:absolute;width:%0px;height:%1px;'></div>", cw, ch)).find(':last');

                    $mouseTrap.css('cursor', lens.css('cursor'));

                    var noTrans = false;

                    // Init tint layer if needed. (Not relevant if using inside mode)			
                    if (opts.tint) {
                        lens.css('background', 'url("' + sImg.attr('src') + '")');
                        $tint = jWin.append(format('<div style="display:none;position:absolute; left:0px; top:0px; width:%0px; height:%1px; background-color:%2;" />', sImg.outerWidth(), sImg.outerHeight(), opts.tint)).find(':last');
                        $tint.css('opacity', opts.tintOpacity);                    
    					noTrans = true;
    					$tint.fadeIn(500);

                    }
                    if (opts.softFocus) {
                        lens.css('background', 'url("' + sImg.attr('src') + '")');
                        softFocus = jWin.append(format('<div style="position:absolute;display:none;top:2px; left:2px; width:%0px; height:%1px;" />', sImg.outerWidth() - 2, sImg.outerHeight() - 2, opts.tint)).find(':last');
                        softFocus.css('background', 'url("' + sImg.attr('src') + '")');
                        softFocus.css('opacity', 0.5);
                        noTrans = true;
                        softFocus.fadeIn(500);
                    }

                    if (!noTrans) {
                        lens.css('opacity', opts.lensOpacity);										
                    }
    				if ( opts.position !== 'inside' ) { lens.fadeIn(500); }

                    // Start processing. 
                    zw.controlLoop();

                    return; // Don't return false here otherwise opera will not detect change of the mouse pointer type.
                });
            }
        };

        if (!($.browser.msie && $.browser.version < 7)) {
            img1 = new Image();
            $(img1).load(function () {
                ctx.init2(this, 0);
            });
            img1.src = sImg.attr('src');

            img2 = new Image();
            $(img2).load(function () {
                ctx.init2(this, 1);
            });
            img2.src = jWin.attr('href');
        }
    }

    $.fn.CloudZoom = function (options) {
        // IE6 background image flicker fix
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } catch (e) {}
        this.each(function () {
			var	relOpts, opts;
			// Hmm...eval...slap on wrist.
			eval('var	a = {' + $(this).attr('rel') + '}');
			relOpts = a;
            if ($(this).is('.cloud-zoom')) {
                $(this).css({
                    'position': 'relative',
                    'display': 'block'
                });
                $('img', $(this)).css({
                    'display': 'block'
                });
                // Wrap an outer div around the link so we can attach things without them becoming part of the link.
                // But not if wrap already exists.
                if ($(this).parent().attr('id') != 'wrap') {
                    $(this).wrap('<div id="wrap" style="top:0px;z-index:9999;position:relative;"></div>');
                }
                opts = $.extend({}, $.fn.CloudZoom.defaults, options);
                opts = $.extend({}, opts, relOpts);
                $(this).data('zoom', new CloudZoom($(this), opts));

            } else if ($(this).is('.cloud-zoom-gallery')) {
                opts = $.extend({}, relOpts, options);
                $(this).data('relOpts', opts);
                $(this).bind('click', $(this), function (event) {
                    var data = event.data.data('relOpts');
                    // Destroy the previous zoom
                    $('#' + data.useZoom).data('zoom').destroy();
                    // Change the biglink to point to the new big image.
                    $('#' + data.useZoom).attr('href', event.data.attr('href'));
                    // Change the small image to point to the new small image.
                    $('#' + data.useZoom + ' img').attr('src', event.data.data('relOpts').smallImage);
                    // Init a new zoom with the new images.				
                    $('#' + event.data.data('relOpts').useZoom).CloudZoom();
                    return false;
                });
            }
        });
        return this;
    };

    $.fn.CloudZoom.defaults = {
        zoomWidth: 'auto',
        zoomHeight: 'auto',
        position: 'right',
        tint: false,
        tintOpacity: 0.5,
        lensOpacity: 0.5,
        softFocus: false,
        smoothMove: 3,
        showTitle: true,
        titleOpacity: 0.5,
        adjustX: 0,
        adjustY: 0
    };

})(jQuery);



// ColorBox v1.3.15 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
// Copyright (c) 2010 Jack Moore - jack@colorpowered.com
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function ($, window) {
	
	var
	// ColorBox Default Settings.	
	// See http://colorpowered.com/colorbox for details.
	defaults = {
		transition: "elastic",
		speed: 300,
		width: false,
		initialWidth: "600",
		innerWidth: false,
		maxWidth: false,
		height: false,
		initialHeight: "450",
		innerHeight: false,
		maxHeight: false,
		scalePhotos: true,
		scrolling: true,
		inline: false,
		html: false,
		iframe: false,
		photo: false,
		href: false,
		title: false,
		rel: false,
		opacity: 0.9,
		preloading: true,
		current: "image {current} of {total}",
		previous: "previous",
		next: "next",
		close: "close",
		open: false,
		returnFocus: true,
		loop: true,
		slideshow: false,
		slideshowAuto: true,
		slideshowSpeed: 2500,
		slideshowStart: "start slideshow",
		slideshowStop: "stop slideshow",
		onOpen: false,
		onLoad: false,
		onComplete: false,
		onCleanup: false,
		onClosed: false,
		overlayClose: true,		
		escKey: true,
		arrowKey: true
	},
	
	// Abstracting the HTML and event identifiers for easy rebranding
	colorbox = 'colorbox',
	prefix = 'cbox',
	
	// Events	
	event_open = prefix + '_open',
	event_load = prefix + '_load',
	event_complete = prefix + '_complete',
	event_cleanup = prefix + '_cleanup',
	event_closed = prefix + '_closed',
	event_purge = prefix + '_purge',
	event_loaded = prefix + '_loaded',
	
	// Special Handling for IE
	isIE = $.browser.msie && !$.support.opacity, // feature detection alone gave a false positive on at least one phone browser and on some development versions of Chrome.
	isIE6 = isIE && $.browser.version < 7,
	event_ie6 = prefix + '_IE6',

	// Cached jQuery Object Variables
	$overlay,
	$box,
	$wrap,
	$content,
	$topBorder,
	$leftBorder,
	$rightBorder,
	$bottomBorder,
	$related,
	$window,
	$loaded,
	$loadingBay,
	$loadingOverlay,
	$title,
	$current,
	$slideshow,
	$next,
	$prev,
	$close,

	// Variables for cached values or use across multiple functions
	interfaceHeight,
	interfaceWidth,
	loadedHeight,
	loadedWidth,
	element,
	index,
	settings,
	open,
	active,
	closing = false,
	
	publicMethod,
	boxElement = prefix + 'Element';
	
	// ****************
	// HELPER FUNCTIONS
	// ****************

	// jQuery object generator to reduce code size
	function $div(id, css) { 
		id = id ? ' id="' + prefix + id + '"' : '';
		css = css ? ' style="' + css + '"' : '';
		return $('<div' + id + css + '/>');
	}

	// Convert % values to pixels
	function setSize(size, dimension) {
		dimension = dimension === 'x' ? $window.width() : $window.height();
		return (typeof size === 'string') ? Math.round((/%/.test(size) ? (dimension / 100) * parseInt(size, 10) : parseInt(size, 10))) : size;
	}
	
	// Checks an href to see if it is a photo.
	// There is a force photo option (photo: true) for hrefs that cannot be matched by this regex.
	function isImage(url) {
		return settings.photo || /\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(url);
	}
	
	// Assigns function results to their respective settings.  This allows functions to be used as values.
	function process(settings) {
		for (var i in settings) {
			if ($.isFunction(settings[i]) && i.substring(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time.
			    settings[i] = settings[i].call(element);
			}
		}
		settings.rel = settings.rel || element.rel || 'nofollow';
		settings.href = settings.href || $(element).attr('href');
		settings.title = settings.title || element.title;
		return settings;
	}

	function trigger(event, callback) {
		if (callback) {
			callback.call(element);
		}
		$.event.trigger(event);
	}

	// Slideshow functionality
	function slideshow() {
		var
		timeOut,
		className = prefix + "Slideshow_",
		click = "click." + prefix,
		start,
		stop,
		clear;
		
		if (settings.slideshow && $related[1]) {
			start = function () {
				$slideshow
					.text(settings.slideshowStop)
					.unbind(click)
					.bind(event_complete, function () {
						if (index < $related.length - 1 || settings.loop) {
							timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
						}
					})
					.bind(event_load, function () {
						clearTimeout(timeOut);
					})
					.one(click + ' ' + event_cleanup, stop);
				$box.removeClass(className + "off").addClass(className + "on");
				timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed);
			};
			
			stop = function () {
				clearTimeout(timeOut);
				$slideshow
					.text(settings.slideshowStart)
					.unbind([event_complete, event_load, event_cleanup, click].join(' '))
					.one(click, start);
				$box.removeClass(className + "on").addClass(className + "off");
			};
			
			if (settings.slideshowAuto) {
				start();
			} else {
				stop();
			}
		}
	}

	function launch(elem) {
		if (!closing) {
			
			element = elem;
			
			settings = process($.extend({}, $.data(element, colorbox)));
			
			$related = $(element);
			
			index = 0;
			
			if (settings.rel !== 'nofollow') {
				$related = $('.' + boxElement).filter(function () {
					var relRelated = $.data(this, colorbox).rel || this.rel;
					return (relRelated === settings.rel);
				});
				index = $related.index(element);
				
				// Check direct calls to ColorBox.
				if (index === -1) {
					$related = $related.add(element);
					index = $related.length - 1;
				}
			}
			
			if (!open) {
				open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys.
				
				$box.show();
				
				if (settings.returnFocus) {
					try {
						element.blur();
						$(element).one(event_closed, function () {
							try {
								this.focus();
							} catch (e) {
								// do nothing
							}
						});
					} catch (e) {
						// do nothing
					}
				}
				
				// +settings.opacity avoids a problem in IE when using non-zero-prefixed-string-values, like '.5'
				$overlay.css({"opacity": +settings.opacity, "cursor": settings.overlayClose ? "pointer" : "auto"}).show();
				
				// Opens inital empty ColorBox prior to content being loaded.
				settings.w = setSize(settings.initialWidth, 'x');
				settings.h = setSize(settings.initialHeight, 'y');
				publicMethod.position(0);
				
				if (isIE6) {
					$window.bind('resize.' + event_ie6 + ' scroll.' + event_ie6, function () {
						$overlay.css({width: $window.width(), height: $window.height(), top: $window.scrollTop(), left: $window.scrollLeft()});
					}).trigger('scroll.' + event_ie6);
				}
				
				trigger(event_open, settings.onOpen);
				
				$current.add($prev).add($next).add($slideshow).add($title).hide();
				
				$close.html(settings.close).show();
			}
			
			publicMethod.load(true);
		}
	}

	// ****************
	// PUBLIC FUNCTIONS
	// Usage format: $.fn.colorbox.close();
	// Usage from within an iframe: parent.$.fn.colorbox.close();
	// ****************
	
	publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
		var $this = this, autoOpen;
		
		if (!$this[0] && $this.selector) { // if a selector was given and it didn't match any elements, go ahead and exit.
			return $this;
		}
		
		options = options || {};
		
		if (callback) {
			options.onComplete = callback;
		}
		
		if (!$this[0] || $this.selector === undefined) { // detects $.colorbox() and $.fn.colorbox()
			$this = $('<a/>');
			options.open = true; // assume an immediate open
		}
		
		$this.each(function () {
			$.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options));
			$(this).addClass(boxElement);
		});
		
		autoOpen = options.open;
		
		if ($.isFunction(autoOpen)) {
			autoOpen = autoOpen.call($this);
		}
		
		if (autoOpen) {
			launch($this[0]);
		}
		
		return $this;
	};

	// Initialize ColorBox: store common calculations, preload the interface graphics, append the html.
	// This preps colorbox for a speedy open when clicked, and lightens the burdon on the browser by only
	// having to run once, instead of each time colorbox is opened.
	publicMethod.init = function () {
		// Create & Append jQuery Objects
		$window = $(window);
		$box = $div().attr({id: colorbox, 'class': isIE ? prefix + 'IE' : ''});
		$overlay = $div("Overlay", isIE6 ? 'position:absolute' : '').hide();
		
		$wrap = $div("Wrapper");
		$content = $div("Content").append(
			$loaded = $div("LoadedContent", 'width:0; height:0; overflow:hidden'),
			$loadingOverlay = $div("LoadingOverlay").add($div("LoadingGraphic")),
			$title = $div("Title"),
			$current = $div("Current"),
			$next = $div("Next"),
			$prev = $div("Previous"),
			$slideshow = $div("Slideshow").bind(event_open, slideshow),
			$close = $div("Close")
		);
		$wrap.append( // The 3x3 Grid that makes up ColorBox
			$div().append(
				$div("TopLeft"),
				$topBorder = $div("TopCenter"),
				$div("TopRight")
			),
			$div(false, 'clear:left').append(
				$leftBorder = $div("MiddleLeft"),
				$content,
				$rightBorder = $div("MiddleRight")
			),
			$div(false, 'clear:left').append(
				$div("BottomLeft"),
				$bottomBorder = $div("BottomCenter"),
				$div("BottomRight")
			)
		).children().children().css({'float': 'left'});
		
		$loadingBay = $div(false, 'position:absolute; width:9999px; visibility:hidden; display:none');
		
		$('body').prepend($overlay, $box.append($wrap, $loadingBay));
		
		$content.children()
		.hover(function () {
			$(this).addClass('hover');
		}, function () {
			$(this).removeClass('hover');
		}).addClass('hover');
		
		// Cache values needed for size calculations
		interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();//Subtraction needed for IE6
		interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
		loadedHeight = $loaded.outerHeight(true);
		loadedWidth = $loaded.outerWidth(true);
		
		// Setting padding to remove the need to do size conversions during the animation step.
		$box.css({"padding-bottom": interfaceHeight, "padding-right": interfaceWidth}).hide();
		
		// Setup button events.
		$next.click(publicMethod.next);
		$prev.click(publicMethod.prev);
		$close.click(publicMethod.close);
		
		// Adding the 'hover' class allowed the browser to load the hover-state
		// background graphics.  The class can now can be removed.
		$content.children().removeClass('hover');
		
		$('.' + boxElement).live('click', function (e) {
			// checks to see if it was a non-left mouse-click and for clicks modified with ctrl, shift, or alt.
			if (!((e.button !== 0 && typeof e.button !== 'undefined') || e.ctrlKey || e.shiftKey || e.altKey)) {
				e.preventDefault();
				launch(this);
			}
		});
		
		$overlay.click(function () {
			if (settings.overlayClose) {
				publicMethod.close();
			}
		});
		
		// Set Navigation Key Bindings
		$(document).bind("keydown", function (e) {
			if (open && settings.escKey && e.keyCode === 27) {
				e.preventDefault();
				publicMethod.close();
			}
			if (open && settings.arrowKey && !active && $related[1]) {
				if (e.keyCode === 37 && (index || settings.loop)) {
					e.preventDefault();
					$prev.click();
				} else if (e.keyCode === 39 && (index < $related.length - 1 || settings.loop)) {
					e.preventDefault();
					$next.click();
				}
			}
		});
	};
	
	publicMethod.remove = function () {
		$box.add($overlay).remove();
		$('.' + boxElement).die('click').removeData(colorbox).removeClass(boxElement);
	};

	publicMethod.position = function (speed, loadedCallback) {
		var
		animate_speed,
		// keeps the top and left positions within the browser's viewport.
		posTop = Math.max(document.documentElement.clientHeight - settings.h - loadedHeight - interfaceHeight, 0) / 2 + $window.scrollTop(),
		posLeft = Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2 + $window.scrollLeft();
		
		// setting the speed to 0 to reduce the delay between same-sized content.
		animate_speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed;
		
		// this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly,
		// but it has to be shrank down around the size of div#colorbox when it's done.  If not,
		// it can invoke an obscure IE bug when using iframes.
		$wrap[0].style.width = $wrap[0].style.height = "9999px";
		
		function modalDimensions(that) {
			// loading overlay height has to be explicitly set for IE6.
			$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = that.style.width;
			$loadingOverlay[0].style.height = $loadingOverlay[1].style.height = $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = that.style.height;
		}
		
		$box.dequeue().animate({width: settings.w + loadedWidth, height: settings.h + loadedHeight, top: posTop, left: posLeft}, {
			duration: animate_speed,
			complete: function () {
				modalDimensions(this);
				
				active = false;
				
				// shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation.
				$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
				$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
				
				if (loadedCallback) {
					loadedCallback();
				}
			},
			step: function () {
				modalDimensions(this);
			}
		});
	};

	publicMethod.resize = function (options) {
		if (open) {
			options = options || {};
			
			if (options.width) {
				settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
			}
			if (options.innerWidth) {
				settings.w = setSize(options.innerWidth, 'x');
			}
			$loaded.css({width: settings.w});
			
			if (options.height) {
				settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
			}
			if (options.innerHeight) {
				settings.h = setSize(options.innerHeight, 'y');
			}
			if (!options.innerHeight && !options.height) {				
				var $child = $loaded.wrapInner("<div style='overflow:auto'></div>").children(); // temporary wrapper to get an accurate estimate of just how high the total content should be.
				settings.h = $child.height();
				$child.replaceWith($child.children()); // ditch the temporary wrapper div used in height calculation
			}
			$loaded.css({height: settings.h});
			
			publicMethod.position(settings.transition === "none" ? 0 : settings.speed);
		}
	};

	publicMethod.prep = function (object) {
		if (!open) {
			return;
		}
		
		var photo,
		speed = settings.transition === "none" ? 0 : settings.speed;
		
		$window.unbind('resize.' + prefix);
		$loaded.remove();
		$loaded = $div('LoadedContent').html(object);
		
		function getWidth() {
			settings.w = settings.w || $loaded.width();
			settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
			return settings.w;
		}
		function getHeight() {
			settings.h = settings.h || $loaded.height();
			settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
			return settings.h;
		}
		
		$loaded.hide()
		.appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations.
		.css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'})
		.css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height.
		.prependTo($content);
		
		$loadingBay.hide();
		
		// floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width.
		$('#' + prefix + 'Photo').css({cssFloat: 'none', marginLeft: 'auto', marginRight: 'auto'});
		
		// Hides SELECT elements in IE6 because they would otherwise sit on top of the overlay.
		if (isIE6) {
			$('select').not($box.find('select')).filter(function () {
				return this.style.visibility !== 'hidden';
			}).css({'visibility': 'hidden'}).one(event_cleanup, function () {
				this.style.visibility = 'inherit';
			});
		}
				
		function setPosition(s) {
			var prev, prevSrc, next, nextSrc, total = $related.length, loop = settings.loop;
			publicMethod.position(s, function () {
				function defilter() {
					if (isIE) {
						//IE adds a filter when ColorBox fades in and out that can cause problems if the loaded content contains transparent pngs.
						$box[0].style.removeAttribute("filter"); 
					}
				}
				
				if (!open) {
					return;
				}
				
				if (isIE) {
					//This fadeIn helps the bicubic resampling to kick-in.
					if (photo) {
						$loaded.fadeIn(100);
					}
				}
				
				$loaded.show();
				
				trigger(event_loaded);
				
				$title.show().html(settings.title);
				
				if (total > 1) { // handle grouping
					if (typeof settings.current === "string") {
						$current.html(settings.current.replace(/\{current\}/, index + 1).replace(/\{total\}/, total)).show();
					}
					
					$next[(loop || index < total - 1) ? "show" : "hide"]().html(settings.next);
					$prev[(loop || index) ? "show" : "hide"]().html(settings.previous);
					
					prev = index ? $related[index - 1] : $related[total - 1];
					next = index < total - 1 ? $related[index + 1] : $related[0];
					
					if (settings.slideshow) {
						$slideshow.show();
					}
					
					// Preloads images within a rel group
					if (settings.preloading) {
						nextSrc = $.data(next, colorbox).href || next.href;
						prevSrc = $.data(prev, colorbox).href || prev.href;
						
						nextSrc = $.isFunction(nextSrc) ? nextSrc.call(next) : nextSrc;
						prevSrc = $.isFunction(prevSrc) ? prevSrc.call(prev) : prevSrc;
						
						if (isImage(nextSrc)) {
							$('<img/>')[0].src = nextSrc;
						}
						
						if (isImage(prevSrc)) {
							$('<img/>')[0].src = prevSrc;
						}
					}
				}
				
				$loadingOverlay.hide();
				
				if (settings.transition === 'fade') {
					$box.fadeTo(speed, 1, function () {
						defilter();
					});
				} else {
					defilter();
				}
				
				$window.bind('resize.' + prefix, function () {
					publicMethod.position(0);
				});
				
				trigger(event_complete, settings.onComplete);
			});
		}
		
		if (settings.transition === 'fade') {
			$box.fadeTo(speed, 0, function () {
				setPosition(0);
			});
		} else {
			setPosition(speed);
		}
	};

	publicMethod.load = function (launched) {
		var href, img, setResize, prep = publicMethod.prep;
		
		active = true;
		element = $related[index];
		
		if (!launched) {
			settings = process($.extend({}, $.data(element, colorbox)));
		}
		
		trigger(event_purge);
		
		trigger(event_load, settings.onLoad);
		
		settings.h = settings.height ?
				setSize(settings.height, 'y') - loadedHeight - interfaceHeight :
				settings.innerHeight && setSize(settings.innerHeight, 'y');
		
		settings.w = settings.width ?
				setSize(settings.width, 'x') - loadedWidth - interfaceWidth :
				settings.innerWidth && setSize(settings.innerWidth, 'x');
		
		// Sets the minimum dimensions for use in image scaling
		settings.mw = settings.w;
		settings.mh = settings.h;
		
		// Re-evaluate the minimum width and height based on maxWidth and maxHeight values.
		// If the width or height exceed the maxWidth or maxHeight, use the maximum values instead.
		if (settings.maxWidth) {
			settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth;
			settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
		}
		if (settings.maxHeight) {
			settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight;
			settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
		}
		
		href = settings.href;
		
		$loadingOverlay.show();

		if (settings.inline) {
			// Inserts an empty placeholder where inline content is being pulled from.
			// An event is bound to put inline content back when ColorBox closes or loads new content.
			$div().hide().insertBefore($(href)[0]).one(event_purge, function () {
				$(this).replaceWith($loaded.children());
			});
			prep($(href));
		} else if (settings.iframe) {
			// IFrame element won't be added to the DOM until it is ready to be displayed,
			// to avoid problems with DOM-ready JS that might be trying to run in that iframe.
			$box.one(event_loaded, function () {
				var iframe = $("<iframe frameborder='0' style='width:100%; height:100%; border:0; display:block'/>")[0];
				iframe.name = +new Date();
				iframe.src = settings.href;
				
				if(!settings.scrolling){
					iframe.scrolling = "no";
				}
				
				if(isIE){
					iframe.allowtransparency="true";
				}
				
				$(iframe).appendTo($loaded).one(event_purge, function () {
					//iframe.src = "//about:blank";
				});
			});
			
			prep(" ");
		} else if (settings.html) {
			prep(settings.html);
		} else if (isImage(href)) {
			img = new Image();
			img.onload = function () {
				var percent;
				img.onload = null;
				img.id = prefix + 'Photo';
				$(img).css({border: 'none', display: 'block', cssFloat: 'left'});
				if (settings.scalePhotos) {
					setResize = function () {
						img.height -= img.height * percent;
						img.width -= img.width * percent;	
					};
					if (settings.mw && img.width > settings.mw) {
						percent = (img.width - settings.mw) / img.width;
						setResize();
					}
					if (settings.mh && img.height > settings.mh) {
						percent = (img.height - settings.mh) / img.height;
						setResize();
					}
				}
				
				if (settings.h) {
					img.style.marginTop = Math.max(settings.h - img.height, 0) / 2 + 'px';
				}
				
				if ($related[1] && (index < $related.length - 1 || settings.loop)) {
					$(img).css({cursor: 'pointer'}).click(publicMethod.next);
				}
				
				if (isIE) {
					img.style.msInterpolationMode = 'bicubic';
				}
				
				setTimeout(function () { // Chrome will sometimes report a 0 by 0 size if there isn't pause in execution
					prep(img);
				}, 1);
			};
			
			setTimeout(function () { // Opera 10.6+ will sometimes load the src before the onload function is set
				img.src = href;
			}, 1);	
		} else if (href) {
			$loadingBay.load(href, function (data, status, xhr) {
				prep(status === 'error' ? 'Request unsuccessful: ' + xhr.statusText : $(this).children());
			});
		}
	};

	// Navigates to the next page/image in a set.
	publicMethod.next = function () {
		if (!active) {
			index = index < $related.length - 1 ? index + 1 : 0;
			publicMethod.load();
		}
	};
	
	publicMethod.prev = function () {
		if (!active) {
			index = index ? index - 1 : $related.length - 1;
			publicMethod.load();
		}
	};

	// Note: to use this within an iframe use the following format: parent.$.fn.colorbox.close();
	publicMethod.close = function () {
		if (open && !closing) {
			closing = true;
			
			open = false;
			
			trigger(event_cleanup, settings.onCleanup);
			
			$window.unbind('.' + prefix + ' .' + event_ie6);
			
			$overlay.fadeTo('fast', 0);
			
			$box.stop().fadeTo('fast', 0, function () {
				
				trigger(event_purge);
				
				$loaded.remove();
				
				$box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide();
				
				setTimeout(function () {
					closing = false;
					trigger(event_closed, settings.onClosed);
				}, 1);
			});
		}
	};

	// A method for fetching the current element ColorBox is referencing.
	// returns a jQuery object.
	publicMethod.element = function () {
		return $(element);
	};

	publicMethod.settings = defaults;

	// Initializes ColorBox when the DOM has loaded
	$(publicMethod.init);

}(jQuery, this));




/* idTabs ~ Sean Catchpole - Version 2.2 - MIT/GPL */ 
(function(){ 
var dep = {}; 
var init = function(){  
 
/* Options (in any order): 
 
 start (number|string) 
    Index number of default tab. ex: $(...).idTabs(0) 
    String of id of default tab. ex: $(...).idTabs("tab1") 
    default: class "selected" or index 0 
    Passing null will force it to not select a default tab 
 
 change (boolean) 
    True - Url will change. ex: $(...).idTabs(true) 
    False - Url will not change. ex: $(...).idTabs(false) 
    default: false 
 
 click (function) 
    Function will be called when a tab is clicked. ex: $(...).idTabs(foo) 
    If the function returns true, idTabs will show/hide content (as usual). 
    If the function returns false, idTabs will not take any action. 
    The function is passed four variables: 
      The id of the element to be shown 
      an array of all id's that can be shown 
      the element containing the tabs 
      and the current settings 
 
 selected (string) 
    Class to use for selected. ex: $(...).idTabs(".current") 
    default: ".selected" 
 
 event (string) 
    Event to trigger idTabs on. ex: $(...).idTabs("!mouseover") 
    default: "!click" 
    To bind multiple event, call idTabs multiple times 
      ex: $(...).idTabs("!click").idTabs("!focus") 
 
*/ 
(function($){ 
 
  $.fn.idTabs = function(){ 
    //Loop Arguments matching options 
    var s = {}; 
    for(var i=0; i<arguments.length; ++i) { 
      var a=arguments[i]; 
      switch(a.constructor){ 
        case Object: $.extend(s,a); break; 
        case Boolean: s.change = a; break; 
        case Number: s.start = a; break; 
        case Function: s.click = a; break; 
        case String: 
          if(a.charAt(0)=='.') s.selected = a; 
          else if(a.charAt(0)=='!') s.event = a; 
          else s.start = a; 
        break; 
      } 
    } 
 
    if(typeof s['return'] == "function") //backwards compatible 
      s.change = s['return']; 
     
    return this.each(function(){ $.idTabs(this,s); }); //Chainable 
  } 
 
  $.idTabs = function(tabs,options) { 
    //Settings 
    var meta = ($.metadata)?$(tabs).metadata():{}; 
    var s = $.extend({},$.idTabs.settings,meta,options); 
 
    //Play nice 
    if(s.selected.charAt(0)=='.') s.selected=s.selected.substr(1); 
    if(s.event.charAt(0)=='!') s.event=s.event.substr(1); 
    if(s.start==null) s.start=-1; //no tab selected 
     
    //Setup Tabs 
    var showId = function(){ 
      if($(this).is('.'+s.selected)) 
        return s.change; //return if already selected 
      var id = "#"+this.href.split('#')[1]; 
      var aList = []; //save tabs 
      var idList = []; //save possible elements 
      $("a",tabs).each(function(){ 
        if(this.href.match(/#/)) { 
          aList.push(this); 
          idList.push("#"+this.href.split('#')[1]); 
        } 
      }); 
      if(s.click && !s.click.apply(this,[id,idList,tabs,s])) return s.change; 
      //Clear tabs, and hide all 
      for(i in aList) $(aList[i]).removeClass(s.selected); 
      for(i in idList) $(idList[i]).removeClass('visibleTab').addClass('invisibleTab'); 
      //Select clicked tab and show content 
      $(this).addClass(s.selected); 
      $(id).removeClass('invisibleTab').addClass('visibleTab'); 
      return s.change; //Option for changing url 
    } 
 
    //Bind idTabs 
    var list = $("a[href*='#']",tabs).unbind(s.event,showId).bind(s.event,showId); 
    list.each(function(){ $("#"+this.href.split('#')[1]).removeClass('visibleTab').addClass('invisibleTab'); }); 
 
    //Select default tab 
    var test=false; 
    if((test=list.filter('.'+s.selected)).length); //Select tab with selected class 
    else if(typeof s.start == "number" &&(test=list.eq(s.start)).length); //Select num tab 
    else if(typeof s.start == "string" //Select tab linking to id 
         &&(test=list.filter("[href*='#"+s.start+"']")).length); 
    if(test) { test.removeClass(s.selected); test.trigger(s.event); } //Select tab 
 
    return s; //return current settings (be creative) 
  } 
 
  //Defaults 
  $.idTabs.settings = { 
    start:0, 
    change:false, 
    click:null, 
    selected:".selected", 
    event:"!click" 
  }; 
 
  //Version 
  $.idTabs.version = "2.2"; 
 
  //Auto-run 
  $(function(){ $(".idTabs").idTabs(); }); 
 
})(jQuery); 
 
 
 
} //init 
 
// Check Dependencies 
var check = function(o,s){ 
  s = s.split('.'); 
  while(o && s.length) o = o[s.shift()]; 
  return o; 
} 
 
// Add Script 
var head = document.getElementsByTagName("head")[0]; 
var add = function(url){ 
  var s = document.createElement("script"); 
  s.type = "text/javascript"; s.src = url; 
  head.appendChild(s); 
} 
 
// Save Self 
var s = document.getElementsByTagName('script'); 
var src = s[s.length-1].src; 
 
// Load Dependencies 
var ok=true; 
for(d in dep) { 
  if(check(this,d)) continue; 
  ok=false; 
  add(dep[d]); 
} if(ok) return init(); 
 
// Reload Self 
add(src); 
 
})();



/*
	Kwicks for jQuery (version 1.5.1)
	Copyright (c) 2008 Jeremy Martin
	http://www.jeremymartin.name/projects.php?project=kwicks
	
	Licensed under the MIT license:
		http://www.opensource.org/licenses/mit-license.php

	Any and all use of this script must be accompanied by this copyright/license notice in its present form.
*/

(function($){
	$.fn.kwicks = function(options) {
		var defaults = {
			isVertical: false,
			sticky: false,
			defaultKwick: 0,
			event: 'mouseover',
			spacing: 0,
			duration: 500,
			fluid: false,
			showOnLoad: false
		};
		var o = $.extend(defaults, options);
		var WoH = (o.isVertical ? 'height' : 'width'); // WoH = Width or Height
		var LoT = (o.isVertical ? 'top' : 'left'); // LoT = Left or Top
		
		return this.each(function() {
			container = $(this);
			var kwicks = container.children('li').not('.cap');
			if (!o.fluid)
				var normWoH = kwicks.eq(0).css(WoH).replace(/px/,''); // normWoH = Normal Width or Height for fixed width or height
			else { //For fluid width
				var normWoH = container.width() / kwicks.size();
				o.max = container.width() * o.maxpercent;
			}
			if(!o.max) {
				o.max = (normWoH * kwicks.size()) - (o.min * (kwicks.size() - 1));
			} else {
				o.min = ((normWoH * kwicks.size()) - o.max) / (kwicks.size() - 1);
			}
			
			if (!o.fluid) { // set width of container ul
				if(o.isVertical) {
					container.css({
						width : kwicks.eq(0).css('width'),
						height : (normWoH * kwicks.size()) + (o.spacing * (kwicks.size() - 1)) + 'px'
					});				
				} else {
					container.css({
						width : (normWoH * kwicks.size()) + (o.spacing * (kwicks.size() - 1)) + 'px',
						height : kwicks.eq(0).css('height')
					});				
				}
			} else {
				if(o.isVertical)
					container.css({	width : kwicks.eq(0).css('width') });	
				else
					container.css({	height : kwicks.eq(0).css('height') });	
			}

			// pre calculate left or top values for all kwicks but the first and last
			// i = index of currently hovered kwick, j = index of kwick we're calculating
			var preCalcLoTs = []; // preCalcLoTs = pre-calculated Left or Top's
			for(i = 0; i < kwicks.size(); i++) {
				preCalcLoTs[i] = [];
				// don't need to calculate values for first or last kwick
				for(j = 1; j < kwicks.size() - 1; j++) {
					if(i == j) {
						preCalcLoTs[i][j] = o.isVertical ? j * o.min + (j * o.spacing) : j * o.min + (j * o.spacing);
					} else {
						preCalcLoTs[i][j] = (j <= i ? (j * o.min) : (j-1) * o.min + o.max) + (j * o.spacing);
					}
				}
			}
			
			if (o.fluid) {
				$(window).bind('resize',function(){
					o.max = container.width() * o.maxpercent;
					normWoH = container.width() / kwicks.size();
					o.min = ((normWoH * kwicks.size()) - o.max) / (kwicks.size() - 1);
					// pre calculate left or top values for all kwicks but the first and last
					// i = index of currently hovered kwick, j = index of kwick we're calculating
					preCalcLoTs = []; // preCalcLoTs = pre-calculated Left or Top's
					for(i = 0; i < kwicks.size(); i++) {
						preCalcLoTs[i] = [];
						// don't need to calculate values for first or last kwick
						for(j = 1; j < kwicks.size() - 1; j++) {
							if(i == j) {
								preCalcLoTs[i][j] = o.isVertical ? j * o.min + (j * o.spacing) : j * o.min + (j * o.spacing);
							} else {
								preCalcLoTs[i][j] = (j <= i ? (j * o.min) : (j-1) * o.min + o.max) + (j * o.spacing);
							}
						}
					}
					
					kwicks.each(function(i){
						var kwick = $(this);
						// set initial width or height and left or top values
						kwick.css(WoH, (100 / kwicks.size())+'%');
						// set first kwick
						if(i === 0) {
							kwick.css(LoT, '0px');
						} 
						// set last kwick
						else if(i == kwicks.size() - 1) {
							kwick.css(o.isVertical ? 'bottom' : 'right', '0px');
						}
						// set all other kwicks
						else {
							if(o.sticky) {
								kwick.css(LoT, preCalcLoTs[o.defaultKwick][i]);
							} else {
								kwick.css(LoT, (i * normWoH) + (i * o.spacing));
							}
						}
						// correct size in sticky mode
						if(o.sticky) {
							if(o.defaultKwick == i) {
								kwick.css(WoH, o.max + 'px');
								kwick.addClass('active');
							} else {
								kwick.css(WoH, o.min + 'px');
							}
						}
						kwick.css({
							margin: 0,
							position: 'absolute'});
					});
				});
			}
			
			// loop through all kwick elements
			kwicks.each(function(i) {
				var kwick = $(this);
				// set initial width or height and left or top values
				if (o.fluid)
					kwick.css(WoH, (100 / kwicks.size())+'%');
				// set first kwick
				if(i === 0) {
					kwick.css(LoT, '0px');
				} 
				// set last kwick
				else if(i == kwicks.size() - 1) {
					kwick.css(o.isVertical ? 'bottom' : 'right', '0px');
				}
				// set all other kwicks
				else {
					if(o.sticky && o.defaultKwick) {
						kwick.css(LoT, preCalcLoTs[o.defaultKwick][i]);
					} else {
						kwick.css(LoT, (i * normWoH) + (i * o.spacing));
					}
				}
				// correct size in sticky mode
				if(o.sticky && o.defaultKwick) {
					if(o.defaultKwick == i) {
						kwick.css(WoH, o.max + 'px');
						kwick.addClass('active');
					} else {
						kwick.css(WoH, o.min + 'px');
					}
				}
				kwick.css({
					margin: 0,
					position: 'absolute'
				});
				
				kwick.bind(o.event, function() {
					if (o.fluid) {
						o.max = container.width() * o.maxpercent;
						normWoH = container.width() / kwicks.size();
						o.min = ((normWoH * kwicks.size()) - o.max) / (kwicks.size() - 1);	
					}
					// calculate previous width or heights and left or top values
					var prevWoHs = []; // prevWoHs = previous Widths or Heights
					var prevLoTs = []; // prevLoTs = previous Left or Tops
					kwicks.stop().removeClass('active');
					for(j = 0; j < kwicks.size(); j++) {
						prevWoHs[j] = (!o.fluid) ? kwicks.eq(j).css(WoH).replace(/px/, '') : kwicks.eq(j).width();
						prevLoTs[j] = kwicks.eq(j).css(LoT).replace(/px/, '');
						//if (kwicks.eq(j)[0].getAttribute('id') != kwick[0].getAttribute('id')) {
							//$(kwicks.eq(j)[0].firstChild).stop().animate({opacity:0});
							//$(kwicks.eq(j)[0].firstChild.firstChild.nextSibling).stop().animate({opacity:0},250);
						//}
					}
					var aniObj = {};
					aniObj[WoH] = (!o.fluid) ? o.max : (100*o.maxpercent)+'%';
					var maxDif = o.max - prevWoHs[i];
					var prevWoHsMaxDifRatio = prevWoHs[i]/maxDif;
					kwick.addClass('active').animate(aniObj, {
						step: function(now) {
							// calculate animation completeness as percentage
							if (!o.fluid)
								var percentage = maxDif != 0 ? now/maxDif - prevWoHsMaxDifRatio : 1;								
							else
								var percentage = maxDif != 0 ? (container.width()*(now/100))/maxDif - prevWoHsMaxDifRatio : 1;
							// adjsut other elements based on percentage
							kwicks.each(function(j) {
								if(j != i) {
									if (!o.fluid)
										kwicks.eq(j).css(WoH, prevWoHs[j] - ((prevWoHs[j] - o.min) * percentage) + 'px');
									else {
										kwicks.eq(j).css(WoH, ((prevWoHs[j] - ((prevWoHs[j] - o.min) * percentage))*100)/container.width() + '%');
									}
								}
								if(j > 0 && j < kwicks.size() - 1) { // if not the first or last kwick
									kwicks.eq(j).css(LoT, prevLoTs[j] - ((prevLoTs[j] - preCalcLoTs[i][j]) * percentage) + 'px');
								}
							});
						},
						duration: o.duration,
						easing: o.easing
					});
					//$(kwick.context.firstChild).stop().animate({opacity:1},250,function () { $(kwick.context.firstChild.firstChild.nextSibling).stop().animate({opacity:1}) });
				});
			});
			if(!o.sticky) {
				container.bind("mouseleave", function() {
					var prevWoHs = [];
					var prevLoTs = [];
					kwicks.removeClass('active').stop();
					for(i = 0; i < kwicks.size(); i++) {
						prevWoHs[i] = (!o.fluid) ? kwicks.eq(i).css(WoH).replace(/px/, '') : kwicks.eq(i).width();
						prevLoTs[i] = kwicks.eq(i).css(LoT).replace(/px/, '');					
						//$(kwicks.eq(i)[0].firstChild).stop().animate({opacity:1});
						//$(kwicks.eq(i)[0].firstChild.firstChild.nextSibling).stop().animate({opacity:0},250);
					}
					var aniObj = {};
					aniObj[WoH] = (!o.fluid) ? normWoH : normWoH/container.width()*100 + '%';
					var normDif = (!o.fluid) ? normWoH - prevWoHs[0] : normWoH - prevWoHs[0];
					kwicks.eq(0).animate(aniObj, {
						step: function(now) {
							var percentage = normDif != 0 ? (container.width()*(now/100) - prevWoHs[0])/normDif : 1;
							for(i = 1; i < kwicks.size(); i++) {
								if (!o.fluid)
									kwicks.eq(i).css(WoH, prevWoHs[i] - ((prevWoHs[i] - normWoH) * percentage) + 'px');
								else
									kwicks.eq(i).css(WoH, (prevWoHs[i] - ((prevWoHs[i] - normWoH) * percentage))*100/container.width() + '%');
								if(i < kwicks.size() - 1) {
									kwicks.eq(i).css(LoT, prevLoTs[i] - ((prevLoTs[i] - ((i * normWoH) + (i * o.spacing))) * percentage) + 'px');
								}
							}
						},
						duration: o.duration,
						easing: o.easing
					});
				});
			}
			if (o.showOnLoad)
				container.css('visibility','visible');
		});
	};
})(jQuery);



/*
    newsTicker for jQuery (version 1.4.4)
    Copyright (c) 2011 Augustus Mayo
    http://www.augustuswm.com
    
    Licensed under the MIT license:
        http://www.opensource.org/licenses/mit-license.php

    Any and all use of this script must be accompanied by this copyright/license notice in its present form.
*/

(function($) {
    $.fn.newsTicker = function(options) {
        var defaults = {
            alignment: 'left',
            duration: 3000,
            moveDuration: 500,
            hideWhileLoad: false,
            arrowHTML: ">"
        };
        var o = $.extend(defaults, options);

        return this.each(function() {
            ul = $(this);

            if (o.redrawOnResize)
                ul.addClass("newsTicker-container");

            if (o.hideWhileLoad) {
                var displayState = ul.css("display");
                ul.css({display:"none"});
            }

            var li = ul.children('li');
            li.css({width:ul.width() - 40+"px"});
            li.addClass("newsTicker-story");

            var h = 0;
            li.each(function() { h = Math.max($(this).outerHeight(),h) });

            ul.css({height:h+"px"});
            li.each(function() {
                $(this).css({top:h+"px"});
            });
            li.eq(0).addClass('newsTicker-active').css({top:Math.round((h-li.eq(0).outerHeight())/2)+"px"});

            ul[0].showNext = function() {
                var cur = ul.children('.newsTicker-active');
                var next = cur.next().is(".newsTicker-expand") ? li.eq(0) : cur.next(".newsTicker-story");

                cur.animate({top:-1*h+"px"},o.moveDuration,function() { $(this).css({top:h+"px"}).removeClass('newsTicker-active'); });
                next.animate({top:Math.round((h-next.outerHeight())/2)+"px"},o.moveDuration,function() {
                    $(this).addClass('newsTicker-active');
                    ul.children(".newsTicker-arrow").css({top:$(this).position().top,height:$(this).outerHeight(),lineHeight:$(this).outerHeight()+"px"});
                });
            }

            var arrow = $("<li>").addClass("newsTicker-arrow");
            ul.prepend(arrow);
            arrow.css({height: h + "px",lineHeight: h + "px"});
            arrow.html(o.arrowHTML);

            if (li.size() > 1) {
                var expand = $("<li>").addClass("newsTicker-expand");
                ul.append(expand);
                expand.css({height: h + "px",lineHeight: h + "px"});
                expand.html("v");
                expand.attr("title","Expand List");

                expand.bind("click",function() {
                    eul = $(this).parent();
                    if (!eul[0].animating) {
                        eul[0].animating = true;
                        if (!eul[0].fullDisplay) {
                            var li = eul.children(".newsTicker-story"), sum = 0;
                            li.css({position:"static"});
                            li.each(function(q) { sum += $(this).outerHeight(); });
                            eul.animate({height:sum+"px"},function() { eul[0].animating = false; });
                            eul.children(".newsTicker-arrow").css({top:eul.children(".newsTicker-active").position().top});
                            $(this).html("^");
                            $(this).attr("title","Hide List");
                        } else {
                            var li = eul.children(".newsTicker-story");
                            var h = 0;
                            li.each(function() { h = Math.max($(this).outerHeight(),h) });
                            eul.animate({height:h+"px"},function() {
                                li.css({position:"absolute"});
                                eul.children(".newsTicker-arrow").css({top:eul.children(".newsTicker-active").position().top});
                                eul[0].animating = false;
                            });
                            $(this).html("v");
                            $(this).attr("title","Expand List");
                        }

                        eul[0].fullDisplay = !eul[0].fullDisplay;
                    }
                });

                ul[0].fullDisplay = false;
                ul[0].timer = setInterval(ul[0].showNext,o.duration);
            }

            if (o.hideWhileLoad)
                ul.css({display:displayState});
        });
    };
})(jQuery);


/*
    slideGallery for jQuery (version 1.4.4)
    Copyright (c) 2011 Augustus Mayo
    http://www.augustuswm.com
    
    Licensed under the MIT license:
        http://www.opensource.org/licenses/mit-license.php

    Any and all use of this script must be accompanied by this copyright/license notice in its present form.
*/

(function($) {
    $.fn.slideGallery = function(options) {
        var defaults = {
            alignment: 'left',
            duration: 3000,
            moveDuration: 500,
            hideWhileLoad: false,
            arrowHTML: ">",
            startIndex: 0,
            imagePositionX: "center",
            imagePositionY: "center"
        };
        var o = $.extend(defaults, options);

        return this.each(function() {
            var ul = $(this),
                li = $(this).children("li"),
                sCount = li.size(),
                container = $("<div>").addClass("slideGallery-container"),
                startImg = li.eq(o.startIndex).children("a").attr("rel"),
                img = $("<img>").attr({src:startImg}).addClass("slideGallery-image");
                
                oldParent = ul.parent();
                ul.addClass("slideGallery-itemList");
                li.addClass("slideGallery-item");
                li.eq(0).addClass("slideGallery-active");

                ul.css({width:Math.ceil(sCount/4)*60});
                
                li.each(function() {
                    var link = $(this).children("a"),
                        full = link.attr("rel"),
                        url = link.attr("href"),
                        thumb = link.children("img"),
                        thumbUrl = "url('"+thumb.attr("src")+"')";
                        
                    $(this).css({
                        backgroundImage: thumbUrl,
                        backgroundPositionX: o.imagePositionX,
                        backgroundPositionY: o.imagePositionY
                    });

                    link.css({display:"none"});

                    $(this)[0].fullImage = full;
                    $(this)[0].thumbImage = thumb.attr("src");
                    $(this)[0].followUrl = url;
                    $(this)[0].transitionIn = function (u) {
                        // Revealed by slide left
                    };
                    $(this)[0].transitionOut = function (u) {
                        u.animate({left:-1*container.outerWidth()},function() { u.remove(); });
                    };

                    $(this).bind("mouseover", function() {
                        ul[0].paused = true;
                        var cur = ul.children('.slideGallery-active');
                        var newImg = $("<img>").attr({src:$(this)[0].fullImage}).addClass("slideGallery-image");
                        container.prepend(newImg);

                        $(this)[0].transitionIn(newImg);
                        cur[0].transitionOut(img);
                        img = newImg;

                        cur.removeClass("slideGallery-active");
                        $(this).addClass("slideGallery-active");
                    });

                    $(this).bind("mouseout", function() {
                        ul[0].paused = false;
                    });
                });

                ul[0].timer = setInterval(function() {
                    if (!ul[0].paused) {
                        var cur = ul.children('.slideGallery-active');
                        var next = cur.is(":last-child") ? li.eq(0) : cur.next(".slideGallery-item");
                        var newImg = $("<img>").attr({src:next[0].fullImage}).addClass("slideGallery-image");
                        container.prepend(newImg);

                        next[0].transitionIn(newImg);
                        cur[0].transitionOut(img);
                        img = newImg;

                        cur.removeClass("slideGallery-active");
                        next.addClass("slideGallery-active");
                    }
                },5000);

                oldParent.append(container.append(img).append(ul));
                //parent.append(container.append(ul));*/
        });
    };
})(jQuery);








/************************************/
/*** LOGIN AND REGISTRATION BOXES ***/
/************************************/

var xwqlsxz = false;
var tjlhtls = 0;

function attachLoginBox(pattern) {
	$(pattern).colorbox({
		width:'400px',
		height:'290px',
		inline:true,
		href:'#generalloginBox',
		title:'Log In',
		rel:'nofollow',
		transition:"none",
		close:"Close"
	});
}

function applyDownloadInterface(pattern) {
	$(pattern).bind("click",function() {
       if ($(this).attr('rel').split('_')[0] == 'locked') {
            $(this).colorbox({
        		onOpen:function() {
        			if (xwqlsxz && ($(this).attr('rel').split('_')[0] == 'locked')) {
        				$('#reqAuthFileName').html($(this).closest('.download').find('div.middlecontent > a').html().split('<br>')[0]);
        				$('#reqEmail').attr('href',$('#reqEmail').attr('href')+$(this).closest('.download').find('div.middlecontent > a').html().split('<br>')[0]);
        				$('#restrictedFName').val($(this).closest('.download').find('div.middlecontent > a').html().split('<br>')[0]);
        				$('#restrictedFId').val($(this).closest('.download').find('div.middlecontent > a').attr('href').match(/file\?i=(\d+)/)[1]);
        				$('#loginFileMsg').html('Access to this file is restricted to authorized users only.');
        				$('#regLink').html('Request access to this file');
        			} else {
        				if ($(this).attr('rel').split('_')[1] != '7') {
        					if ($('#regLinkAuth').attr('href').search(/\?/) > -1)
        						$('#regLinkAuth').attr('href',$('#regLinkAuth').attr('href').substr(0,$('#regLinkAuth').attr('href').search(/\?/))+'?f='+$.trim($(this).closest('.download').find('div.middlecontent > a').html().split('<br>')[0]));
        					else
        						$('#regLinkAuth').attr('href',$('#regLinkAuth').attr('href')+'?f='+$.trim($(this).closest('.download').find('div.middlecontent > a').html().split('<br>')[0]));
        					$('#regLinkAuth').html('Register and request manual authorization.');
        					$('#loginFileMsg').html('');
        				} else {
        					$('#regLinkAuth').attr('href','http://'+document.domain+'/'+$.cookie('country')+'/'+$.cookie('line')+'/'+'account');
        					$('#regLinkAuth').html('I need to register');
        					$('#loginFileMsg').html('Users are required to register an account and log in before downloading this file');
        				}
        				//$('#regLink').html('I need to register');				
        			}
        		},
        		width:function() { return ($(this).attr('rel').split('_')[0] == 'locked') ? '420px' : '90%'; },
        		height:function() { return ($(this).attr('rel').split('_')[0] == 'locked') ? '290px' : '90%'; },
        		inline:function() { return ($(this).attr('rel').split('_')[0] == 'locked'); },
        		iframe:function() { return !($(this).attr('rel').split('_')[0] == 'locked'); },
        		href:function() { 
        			if (!($(this).attr('rel').split('_')[0] == 'locked'))
        				return $(this).attr('href');
        			else if (!xwqlsxz)
        				return '#loginBox';
        			else
        				return '#permissionBox';
        			},
        		title:function() {
        			if (!($(this).attr('rel').split('_')[0] == 'locked'))
        				return $(this).attr('title');
        			else if (!xwqlsxz && $(this).attr('rel').split('_')[1] != '7')
        				return 'Authorization Required';
        			else if (!xwqlsxz)
        				return 'Registration Required';
        			else
        				return '';
        		},
        		rel:'nofollow',
        		transition:"none",
        		close:"Close"
        	});
        }
    });
}
	
$().ready(function() {
	$('#generalloginBox form').bind('submit',function(e) { 
		e.preventDefault();
		$(this).find('.loginButton').click();
	});
	
	$('#loginBox form').bind('submit',function(e) { 
		e.preventDefault();
		$(this).find('.loginButton').click();
	});
	
	$('.loginButton').bind('click',function() {
        var l = $(this), u = l.parent().parent().find(".loginEmail"), p = l.parent().parent().find(".loginPassword");
		$('.errorMsg').remove();
		$(this).parent().css({'display':'none'});
		$('<img src="binary/mapLoadBar.gif" style="margin-top:15px;" />').insertAfter($(this).parent().prev());
		var domain = (document.domain.match('rts') > -1) ? document.domain : document.domain+'/site';
		$.ajax({
			type: 'POST',
			url: 'http://'+domain+'/jxLogin.php',
            data: 'e='+u.val()+'&p='+p.val(),
			dataType: 'xml',
			success: function(d,s,x) {
						if ($(d).find('status').eq(0).text() == '1') {
							xwqlsxz = true;
							tjlhtls = $(d).find('level').eq(0).text();
							$('.navitem a[rel="login"]').html("My Account");
							$('#navlogin').html("<a href='#'>Edit My Account</a> | <a href='#'>Logout</a>");
							/*$('.download a[rel*="locked"]').each(function() {
								var r = $(this).attr('rel');
								if (r.split('.')[1]/1 <= tjlhtls) {
									$(this).attr('rel','');
									if ($(this).prev().hasClass('lockContainer'))
										$(this).prev().find(":nth-child(1)").attr('src','binary/lockspriteopen.gif');	
								}
							});*/
							//$.colorbox.close();
							window.location = window.location;
						} else {
							l.parent().prev().remove();
							$('<div class="errorMsg" style="font-size:8pt; color:red;">Unable to log in. Incorrect email/password combination.</div>').insertAfter(l.parent().parent().prev());
							l.parent().css({'display':'block'});
						}
					 },
			error: function(x,s,t) {
						l.parent().prev().remove();
						$('<div class="errorMsg" style="font-size:8pt; color:red;">Unable to log in. Incorrect email/password combination.</div>').insertAfter(l.parent().parent().prev());
						l.parent().css({'display':'block'});
					 }
		});
	});
	
	$('#requestButton').bind('click',function() {
		var l = $(this);
		$('.errorMsg').remove();
		$(this).parent().css({'display':'none'});
		$('<div><img src="binary/mapLoadBar.gif" style="margin-top:15px;" /><br/>Your request is being sent. This may take up to a minute...</div>').insertAfter($(this).parent().prev());
		var domain = (document.domain.match('rts') > -1) ? document.domain : document.domain+'/site';
		$.ajax({
			type: 'POST',
			url: 'http://'+domain+'/jxAuthEmail.php',
			data: 'n='+$('#restrictedFName').val()+'&i='+$('#restrictedFId').val(),
			success: function(d,s,x) {
						l.parent().prev().remove();
						$('<div class="errorMsg" style="font-size:8pt; color:#007700;">'+d+'</div>').insertAfter(l.parent().prev());
			},
			error: function(x,s,t) {
						l.parent().prev().remove();
			}
		});
	});
});

$().ready(function() {
		attachLoginBox('.generalloginlink');
		$('.activesecondary').removeClass('activesecondary');
		$('#primarynav > div.navitem').mouseenter(function() {
				clearTimeout($('#navbar').data('clearcheck'));
				$('.activesection').css('backgroundImage',"").removeClass('activesection');
				$(this).addClass('activesection').css('backgroundImage',"url('binary/nav"+$(this).children('a').attr('rel')+".png')");
				$('.activesecondary').removeClass('activesecondary');
				var nW = $('#navbar').width();
				var nO = $('#navbar').offset().left;
				var mW = $('#nav'+$(this).children('a').attr('rel')).width();
				var oL = $(this).offset().left+8;
				var offL = (mW + oL >= nW + nO) ? nW - mW + $('#navbar').offset().left : oL;
				$('#nav'+$(this).children('a').attr('rel')).addClass('activesecondary').offset({top:$('#nav'+$(this).children('a').attr('rel')).offset().top,left:offL});
		});
		
		$('#navbar').mouseenter(function() { clearTimeout($(this).data('clearcheck')); });
		$('#navbar').mouseleave(function() { 
			var timeoutId = setTimeout(function() { $('.activesection').css('backgroundImage',"").removeClass('activesection'); $('.activesecondary').removeClass('activesecondary'); }, 1000);
			$('#navbar').data('clearcheck',timeoutId);			
		});

    function fixIE6() {
        //var start = (new Date()).getTime();
        if (!window.XMLHttpRequest) {

            if ($("#page").width() < 800)
                $("#page").css("width","800px");

            var imgs = document.getElementsByTagName('img');
            var imgsLength = imgs.length;
            //alert(imgsLength);
            
            for (var i = 0; i < imgsLength && imgsLength < 150; i++) {
                if (imgs[i].src.search(/\.(png)/i) > -1) {
                    (function(elm) {
                        $(elm).bind("load",function() {
                            $(elm).unbind("load");
                            var w = elm.offsetWidth, h = elm.offsetHeight;
                            elm.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='" + elm.src + "')";
                            elm.src = "binary/clear.gif";
                            elm.style.width = w + "px";
                            elm.style.height = h + "px";
                        });
                        elm.src = elm.src;
                    })(imgs[i]);
                    /*var w = imgs[i].offsetWidth,h = imgs[i].offsetHeight;
                    imgs[i].style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod='scale', src='" + imgs[i].src + "')";
                    imgs[i].src = "binary/clear.gif";
                    imgs[i].style.width = w + "px";
                    imgs[i].style.height = h + "px";*/
                }
            }
        }
        //alert (((new Date()).getTime()-start)/1000);
    }

    fixIE6();
});

$().ready(function() {
    if (window.XMLHttpRequest) {
        $(".downloadCategory").css({display:"none"});
        $(".downloadTitle").bind("click",function(e) {
           e.preventDefault();
           var cat = $(this).next(".downloadCategory")
           cat.slideToggle(250);
           var s = $(this).children("a").children("img").attr("src");
           if (s) s = s.search(/plus/i) > -1 ? "binary/minus.gif" : "binary/plus.gif";
           $(this).children("a").children("img").attr("src",s);
        });
    } else {
        $(".downloadTitle").bind("click",function(e) {
           e.preventDefault();
       });
    }
});

$().ready(function() { $('.modal').colorbox({width:"90%",height:"90%",iframe:true,transition:"none",close:"Close"}); });
