function EnableAjaxRecursive(element) {

    var aTags = jQuery(element).find("a");
    jQuery.each(aTags, function () {
        var link = jQuery(this).attr("href");
        if (link && IsInternalPageLink(link)) {
            jQuery(this).click(function () {
                var href = jQuery(this).attr("href");

                if (GetIdFromUrl(document.location.href) != GetIdFromUrl(href)) {
                    GetPageByUrl(href);
                }
                return false;
            });
        }
    });
}

function IsInternalLink(str) {
    return !StartsWith(str, "http://") && !StartsWith(str, "https://") && !StartsWith(str, "ftp://") && !StartsWith(str, "ftps://");
}

function IsInternalPageLink(str) {
    var lowStr = str.toLowerCase();
    return IsInternalLink(lowStr) && !StartsWith(lowStr, "/image/") && !StartsWith(lowStr, "/billede/") && !StartsWith(lowStr, "/file/") && !StartsWith(lowStr, "/fil/");
}

function StartsWith(str, lookFor) {
    return (str.indexOf(lookFor) === 0);
}

function GetIdFromUrl(url) {
    return GetLastPartFromCharacter(url, '-');
}
function GetLastPartFromCharacter(text, character) {
    for (i = text.length - 1; i >= 0; i--) {
        if (text.charAt(i) == character) {
            return text.substring(i + 1, text.length);
        }
    }
    return text;
}
function GetPageByHash(hash) {
    if (hash != "") {
        hash = hash.replace("#", "");
        GetPageByUrl(hash);
    }
}
function GetPageByUrl(url) {
    if (url != "") {
        if (url.match("/side/"))
            url = url.replace("/Side/", "/SideAjax/");
        else if (url.match("/webshop/") || url.match("/users/")) {
            
        }
        else {
            if (!StartsWith(url, "/"))
                url = "/" + url;
            url = "/SideAjax" + url;
        }
        jQuery(".fade").hide();
        GetPage(url);
    }
}
function GetPage(url) {
    var globalData;
    var hasAnimated = false;
    function loadPageData(json) {
        if (json.maincontent != null) {
            jQuery("#piranya-page").html(json.maincontent);
            EnableAjaxRecursive(jQuery("#piranya-page"));
        }

        if (json.subcontent != null) {
            jQuery("#piranya-subcontent-container").html(json.subcontent);
            EnableAjaxRecursive(jQuery("#piranya-subcontent-container"));
        }

        if (json.mainmenu != null) {
            jQuery("#piranya-mainmenu").html(json.mainmenu);
            EnableAjaxRecursive(jQuery("#piranya-mainmenu"));
        }

        if (json.submenu != null) {
            jQuery("#piranya-submenu").html(json.submenu);
            EnableAjaxRecursive(jQuery("#piranya-submenu"));
        }

        if (json.title != null)
            document.title = json.title;

        if (typeof window.InitializeScrollBars == 'function') {
            InitializeScrollBars();
        }

        if (typeof window.InitializeSlimbox == 'function') {
            InitializeSlimbox();
        }

        jQuery(".fade").hide().fadeIn(500, function () { });
    }
    var fade = jQuery(".fade");
    fade.fadeOut(500, function () {
        hasAnimated = true;
        if (globalData != null) {
            loadPageData(globalData);
        }
    });

    jQuery.ajaxSetup({ cache: false });
    jQuery.getJSON(url, null, function (data) {
        if (hasAnimated || fade.length == 0)
            loadPageData(data);
        else
            globalData = data;
    });


    document.location.hash = url.replace("/SideAjax/", "") //Set url in browser
}

/*
	Slimbox v2.04 - The ultimate lightweight Lightbox clone for jQuery
	(c) 2007-2010 Christophe Beyls <http://www.digitalia.be>
	MIT-style license.
*/
(function (w) { var E = w(window), u, f, F = -1, n, x, D, v, y, L, r, m = !window.XMLHttpRequest, s = [], l = document.documentElement, k = {}, t = new Image(), J = new Image(), H, a, g, p, I, d, G, c, A, K; w(function () { w("body").append(w([H = w('<div id="lbOverlay" />')[0], a = w('<div id="lbCenter" />')[0], G = w('<div id="lbBottomContainer" />')[0]]).css("display", "none")); g = w('<div id="lbImage" />').appendTo(a).append(p = w('<div style="position: relative;" />').append([I = w('<a id="lbPrevLink" href="#" />').click(B)[0], d = w('<a id="lbNextLink" href="#" />').click(e)[0]])[0])[0]; c = w('<div id="lbBottom" />').appendTo(G).append([w('<a id="lbCloseLink" href="#" />').add(H).click(C)[0], A = w('<div id="lbCaption" />')[0], K = w('<div id="lbNumber" />')[0], w('<div style="clear: both;" />')[0]])[0] }); w.slimbox = function (O, N, M) { u = w.extend({ loop: false, overlayOpacity: 0.8, overlayFadeDuration: 400, resizeDuration: 400, resizeEasing: "swing", initialWidth: 250, initialHeight: 250, imageFadeDuration: 400, captionAnimationDuration: 400, counterText: "Image {x} of {y}", closeKeys: [27, 88, 67], previousKeys: [37, 80], nextKeys: [39, 78] }, M); if (typeof O == "string") { O = [[O, N]]; N = 0 } y = E.scrollTop() + (E.height() / 2); L = u.initialWidth; r = u.initialHeight; w(a).css({ top: Math.max(0, y - (r / 2)), width: L, height: r, marginLeft: -L / 2 }).show(); v = m || (H.currentStyle && (H.currentStyle.position != "fixed")); if (v) { H.style.position = "absolute" } w(H).css("opacity", u.overlayOpacity).fadeIn(u.overlayFadeDuration); z(); j(1); f = O; u.loop = u.loop && (f.length > 1); return b(N) }; w.fn.slimbox = function (M, P, O) { P = P || function (Q) { return [Q.href, Q.title] }; O = O || function () { return true }; var N = this; return N.unbind("click").click(function () { var S = this, U = 0, T, Q = 0, R; T = w.grep(N, function (W, V) { return O.call(S, W, V) }); for (R = T.length; Q < R; ++Q) { if (T[Q] == S) { U = Q } T[Q] = P(T[Q], Q) } return w.slimbox(T, U, M) }) }; function z() { var N = E.scrollLeft(), M = E.width(); w([a, G]).css("left", N + (M / 2)); if (v) { w(H).css({ left: N, top: E.scrollTop(), width: M, height: E.height() }) } } function j(M) { if (M) { w("object").add(m ? "select" : "embed").each(function (O, P) { s[O] = [P, P.style.visibility]; P.style.visibility = "hidden" }) } else { w.each(s, function (O, P) { P[0].style.visibility = P[1] }); s = [] } var N = M ? "bind" : "unbind"; E[N]("scroll resize", z); w(document)[N]("keydown", o) } function o(O) { var N = O.keyCode, M = w.inArray; return (M(N, u.closeKeys) >= 0) ? C() : (M(N, u.nextKeys) >= 0) ? e() : (M(N, u.previousKeys) >= 0) ? B() : false } function B() { return b(x) } function e() { return b(D) } function b(M) { if (M >= 0) { F = M; n = f[F][0]; x = (F || (u.loop ? f.length : 0)) - 1; D = ((F + 1) % f.length) || (u.loop ? 0 : -1); q(); a.className = "lbLoading"; k = new Image(); k.onload = i; k.src = n } return false } function i() { a.className = ""; w(g).css({ backgroundImage: "url(" + n + ")", visibility: "hidden", display: "" }); w(p).width(k.width); w([p, I, d]).height(k.height); w(A).html(f[F][1] || ""); w(K).html((((f.length > 1) && u.counterText) || "").replace(/{x}/, F + 1).replace(/{y}/, f.length)); if (x >= 0) { t.src = f[x][0] } if (D >= 0) { J.src = f[D][0] } L = g.offsetWidth; r = g.offsetHeight; var M = Math.max(0, y - (r / 2)); if (a.offsetHeight != r) { w(a).animate({ height: r, top: M }, u.resizeDuration, u.resizeEasing) } if (a.offsetWidth != L) { w(a).animate({ width: L, marginLeft: -L / 2 }, u.resizeDuration, u.resizeEasing) } w(a).queue(function () { w(G).css({ width: L, top: M + r, marginLeft: -L / 2, visibility: "hidden", display: "" }); w(g).css({ display: "none", visibility: "", opacity: "" }).fadeIn(u.imageFadeDuration, h) }) } function h() { if (x >= 0) { w(I).show() } if (D >= 0) { w(d).show() } w(c).css("marginTop", -c.offsetHeight).css("width", L-20).animate({ marginTop: 0 }, u.captionAnimationDuration); G.style.visibility = "" } function q() { k.onload = null; k.src = t.src = J.src = n; w([a, g, c]).stop(true); w([I, d, g, G]).hide() } function C() { if (F >= 0) { q(); F = x = D = -1; w(a).hide(); w(H).stop().fadeOut(u.overlayFadeDuration, j) } return false } })(jQuery);

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)

function InitializeSlimbox() {
    if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
        jQuery("a[rel^='lightbox']").slimbox({}, null, function (el) {
            return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
        });
    }
}

/*
 * Galleria v 1.2 prerelease 1.1 2010-11-20
 * http://galleria.aino.se
 *
 * Copyright (c) 2010, Aino
 * Licensed under the MIT license.
 */

(function($) {

// some references
var undef,
    window = this,
    doc    = document,
    $doc   = jQuery( doc );

// internal constants
var DEBUG = false,
    NAV   = navigator.userAgent.toLowerCase(),
    HASH  = window.location.hash.replace(/#\//, ''),
    CLICK = function() {
        // use this to make touch devices snappier
        return Galleria.TOUCH ? 'touchstart' : 'click';
    },
    IE    = (function() {
        var v = 3,
            div = doc.createElement( 'div' );
        while (
            div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
            div.getElementsByTagName('i')[0]
        );
        return v > 4 ? v : undef;
    }() ),
    DOM   = function() {
        return {
            html:  doc.documentElement,
            body:  doc.body,
            head:  doc.getElementsByTagName('head')[0],
            title: doc.title
        };
    },

    // the internal timeouts object
    // provides helper methods for controlling timeouts
    _timeouts = {

        trunk: {},

        add: function( id, fn, delay, loop ) {
            loop = loop || false;
            this.clear( id );
            if ( loop ) {
                var old = fn;
                fn = function() {
                    old();
                    _timeouts.add( id, fn, delay );
                };
            }
            this.trunk[ id ] = window.setTimeout( fn, delay );
        },

        clear: function( id ) {

            var del = function( i ) {
                window.clearTimeout( this.trunk[ i ] );
                delete this.trunk[ i ];
            };

            if ( !!id && id in this.trunk ) {
                del.call( _timeouts, id );

            } else if ( typeof id == 'undefined' ) {
                for ( var i in this.trunk ) {
                    del.call( _timeouts, i );
                }
            }
        }
    },

    // the internal gallery holder
    _galleries = [],

    // the transitions holder
    _transitions = {

        fade: function(params, complete) {
            jQuery(params.next).css('opacity', 0).show().animate({
                opacity: 1
            }, params.speed, complete);

            if (params.prev) {
                jQuery(params.prev).css('opacity', 1).show().animate({
                    opacity: 0
                }, params.speed);
            }
        },

        flash: function(params, complete) {
            jQuery(params.next).css('opacity', 0);
            if (params.prev) {
                jQuery(params.prev).animate({
                    opacity: 0
                }, (params.speed / 2), function() {
                    jQuery(params.next).animate({
                        opacity: 1
                    }, params.speed, complete);
                });
            } else {
                jQuery(params.next).animate({
                    opacity: 1
                }, params.speed, complete);
            }
        },

        pulse: function(params, complete) {
            if (params.prev) {
                jQuery(params.prev).hide();
            }
            jQuery(params.next).css('opacity', 0).animate({
                opacity:1
            }, params.speed, complete);
        },

        slide: function(params, complete) {
            var image  = jQuery(params.next).parent(),
                images = this.jQuery('images'), // ??
                width  = this._stageWidth,
                easing = this.getOptions( 'easing' );

            image.css({
                left: width * ( params.rewind ? -1 : 1 )
            });
            images.animate({
                left: width * ( params.rewind ? 1 : -1 )
            }, {
                duration: params.speed,
                queue: false,
                easing: easing,
                complete: function() {
                    images.css('left', 0);
                    image.css('left', 0);
                    complete();
                }
            });
        },

        fadeslide: function(params, complete) {

            var x = 0,
                easing = this.getOptions('easing'),
                distance = this.getStageWidth();

            if (params.prev) {
                x = Utils.parseValue( jQuery(params.prev).css('left') );
                jQuery(params.prev).css({
                    opacity: 1,
                    left: x
                }).animate({
                    opacity: 0,
                    left: x + ( distance * ( params.rewind ? 1 : -1 ) )
                },{
                    duration: params.speed,
                    queue: false,
                    easing: easing
                });
            }

            x = Utils.parseValue( jQuery(params.next).css('left') );

            jQuery(params.next).css({
                left: x + ( distance * ( params.rewind ? -1 : 1 ) ),
                opacity: 0
            }).animate({
                opacity: 1,
                left: x
            }, {
                duration: params.speed,
                complete: complete,
                queue: false,
                easing: easing
            });
        }
    },

    // the Utils singleton
    Utils = (function() {

        return {

            array : function( obj ) {
                return Array.prototype.slice.call(obj);
            },

            create : function( className, nodeName ) {
                nodeName = nodeName || 'div';
                var elem = doc.createElement( nodeName );
                elem.className = className;
                return elem;
            },

            forceStyles : function( elem, styles ) {
                elem = jQuery(elem);
                if ( elem.attr( 'style' ) ) {
                    elem.data( 'styles', elem.attr( 'style' ) ).removeAttr( 'style' );
                }
                elem.css( styles );
            },

            revertStyles : function() {
                jQuery.each( Utils.array( arguments ), function( i, elem ) {

                    elem = jQuery( elem ).removeAttr( 'style' );

                    if ( elem.data( 'styles' ) ) {
                        elem.attr( 'style', elem.data('styles') ).data( 'styles', null );
                    }
                });
            },

            moveOut : function( elem ) {
                Utils.forceStyles( elem, {
                    position: 'absolute',
                    left: -10000
                });
            },

            moveIn : function() {
                Utils.revertStyles.apply( Utils, Utils.array( arguments ) );
            },

            hide : function( elem, speed, callback ) {
                elem = jQuery(elem);

                // save the value if not exist
                if (! elem.data('opacity') ) {
                    elem.data('opacity', elem.css('opacity') );
                }

                // always hide
                var style = { opacity: 0 };

                if (speed) {
                    elem.stop().animate( style, speed, callback );
                } else {
                    elem.css( style );
                };
            },

            show : function( elem, speed, callback ) {
                elem = jQuery(elem);

                // bring back saved opacity
                var saved = parseFloat( elem.data('opacity') ) || 1,
                    style = { opacity: saved };

                // reset save if opacity == 1
                if (saved == 1) {
                    elem.data('opacity', null);
                }

                // animate or toggle
                if (speed) {
                    elem.stop().animate( style, speed, callback );
                } else {
                    elem.css( style );
                };
            },

            addTimer : function() {
                _timeouts.add.apply( _timeouts, Utils.array( arguments ) );
                return this;
            },

            clearTimer : function() {
                _timeouts.clear.apply( _timeouts, Utils.array( arguments ) );
                return this;
            },

            wait : function(options) {
                options = jQuery.extend({
                    until : function() { return false; },
                    success : function() {},
                    error : function() { Galleria.raise('Could not complete wait function.'); },
                    timeout: 3000
                }, options);

                var start = Utils.timestamp(),
                    elapsed,
                    now;

                window.setTimeout(function() {
                    now = Utils.timestamp();
                    elapsed = now - start;
                    if ( options.until( elapsed ) ) {
                        options.success();
                        return false;
                    }

                    if (now >= start + options.timeout) {
                        options.error();
                        return false;
                    }
                    window.setTimeout(arguments.callee, 2);
                }, 2);
            },

            toggleQuality : function( img, force ) {

                if ( !( IE == 7 || IE == 8 ) || !!img === false ) {
                    return;
                }

                if ( typeof force === 'undefined' ) {
                    force = img.style.msInterpolationMode == 'nearest-neighbor';
                }

                img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor';
            },

            insertStyleTag : function( styles ) {
                var style = doc.createElement( 'style' );
                DOM().head.appendChild( style );

                if ( style.styleSheet ) { // IE
                    style.styleSheet.cssText = styles;
                } else {
                    var cssText = doc.createTextNode( styles );
                    style.appendChild( cssText );
                }
            },

            // a loadscript method that works for local scripts
            loadScript: function( url, callback ) {
                var done = false,
                    script = jQuery('<scr'+'ipt>').attr({
                        src: url,
                        async: true
                    }).get(0);

               // Attach handlers for all browsers
               script.onload = script.onreadystatechange = function() {
                   if ( !done && (!this.readyState ||
                       this.readyState == 'loaded' || this.readyState == 'complete') ) {
                       done = true;

                       if (typeof callback == 'function') {
                           callback.call( this, this );
                       }

                       // Handle memory leak in IE
                       script.onload = script.onreadystatechange = null;
                   }
               };

               var s = doc.getElementsByTagName( 'script' )[0];
               s.parentNode.insertBefore( script, s );
            },

            // parse anything into a number
            parseValue: function( val ) {
                if (typeof val == 'number') {
                    return val;
                } else if (typeof val == 'string') {
                    var arr = val.match(/\-?\d/g);
                    return arr && arr.constructor == Array ? arr.join('') * 1 : 0;
                } else {
                    return 0;
                }
            },

            // timestamp abstraction
            timestamp: function() {
                return new Date().getTime();
            },

            // this is pretty crap, but works for now
            // it will add a callback, but it can't guarantee that the styles can be fetched
            // using getComputedStyle further checking needed, possibly a dummy element
            loadCSS : function( href, id, callback ) {

                var link,
                    ready = false,
                    length;

                // look for manual css
                jQuery('link[rel=stylesheet]').each(function() {
                    if ( new RegExp( href ).test( this.href ) ) {
                        link = this;
                        return false;
                    }
                });

                if ( typeof id == 'function' ) {
                    callback = id;
                    id = undef;
                }

                callback = callback || function() {}; // dirty

                // if already present, return
                if ( link ) {
                    callback.call( link, link );
                    return link;
                }

                // save the length of stylesheets to check against
                length = doc.styleSheets.length;

                // add timestamp if DEBUG is true
                if ( DEBUG ) {
                    href += '?' + Utils.timestamp();
                }

                // check for existing id
                if( jQuery('#'+id).length ) {
                    jQuery('#'+id).attr('href', href);
                    length--;
                    ready = true;
                } else {
                    link = jQuery( '<link>' ).attr({
                        rel: 'stylesheet',
                        href: href,
                        id: id
                    }).get(0);

                    window.setTimeout(function() {
                        var styles = jQuery('link[rel="stylesheet"], style');
                        if ( styles.length ) {
                            styles.get(0).parentNode.insertBefore( link, styles[0] );
                        } else {
                            DOM().head.appendChild( link );
                        }

                        if ( IE ) {
                            link.attachEvent( 'onreadystatechange', function(e) {
                                if( link.readyState == 'complete' ) {
                                    ready = true;
                                }
                            });
                        } else {
                            // what to do here? returning for now.
                            ready = true;
                        }
                    }, 10);
                }

                if (typeof callback == 'function') {

                    Utils.wait({
                        until: function() {
                            return ready && doc.styleSheets.length > length;
                        },
                        success: function() {
                            Utils.addTimer( 'css', function() {
                                callback.call( link, link );
                            }, 100);
                        },
                        error: function() {
                            Galleria.raise( 'Theme CSS could not load' );
                        },
                        timeout: 1000
                    });
                }
                return link;
            }
        };
    })();

/**
    The main Galleria class

    @class

    @example var gallery = new Galleria();

    @author http://aino.se

    @requires jQuery

    @returns {Galleria}
*/

Galleria = function() {

    var self = this;

    // the theme used
    this._theme = undef;

    // internal options
    this._options = {};

    // flag for controlling play/pause
    this._playing = false;

    // internal interval for slideshow
    this._playtime = 5000;

    // internal variable for the currently active image
    this._active = null;

    // the internal queue, arrayified
    this._queue = { length: 0 };

    // the internal data array
    this._data = [];

    // the internal dom collection
    this._dom = {};

    // the internal thumbnails array
    this._thumbnails = [];

    // internal init flag
    this._initialized = false;

    // global stagewidth/height
    this._stageWidth = 0;
    this._stageHeight = 0;

    // target holder
    this._target = undef;

    // instance id
    this._id = Utils.timestamp();

    // add some elements
    var divs =  'container stage images image-nav image-nav-left image-nav-right ' +
                'info info-text info-title info-description info-author ' +
                'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' +
                'loader counter tooltip',
        spans = 'current total';

    jQuery.each( divs.split(' '), function( i, elemId ) {
        self._dom[ elemId ] = Utils.create( 'galleria-' + elemId );
    });

    jQuery.each( spans.split(' '), function( i, elemId ) {
        self._dom[ elemId ] = Utils.create( 'galleria-' + elemId, 'span' );
    });

    // the internal keyboard object
    // keeps reference of the keybinds and provides helper methods for binding keys
    var keyboard = this._keyboard = {

        keys : {
            'UP': 38,
            'DOWN': 40,
            'LEFT': 37,
            'RIGHT': 39,
            'RETURN': 13,
            'ESCAPE': 27,
            'BACKSPACE': 8,
            'SPACE': 32
        },

        map : {},

        bound: false,

        press: function(e) {
            var key = e.keyCode || e.which;
            if ( key in keyboard.map && typeof keyboard.map[key] == 'function' ) {
                keyboard.map[key].call(self, e);
            }
        },

        attach: function(map) {
            for( var key in map ) {
                var up = key.toUpperCase();
                if ( up in keyboard.keys ) {
                    keyboard.map[ keyboard.keys[up] ] = map[key];
                }
            }
            if ( !keyboard.bound ) {
                keyboard.bound = true;
                $doc.bind('keydown', keyboard.press);
            }
        },

        detach: function() {
            keyboard.bound = false;
            $doc.unbind('keydown', keyboard.press);
        }
    };

    // internal controls for keeping track of active / inactive images
    var controls = this._controls = {

        0: undef,

        1: undef,

        active : 0,

        swap : function() {
            controls.active = controls.active ? 0 : 1;
        },

        getActive : function() {
            return controls[ controls.active ];
        },

        getNext : function() {
            return controls[ 1 - controls.active ];
        }
    };

    // internal carousel object
    var carousel = this._carousel = {

        // shortcuts
        next: self.jQuery('thumb-nav-right'),
        prev: self.jQuery('thumb-nav-left'),

        // cache the width
        width: 0,

        // track the current position
        current: 0,

        // cache max value
        max: 0,

        // save all hooks for each width in an array
        hooks: [],

        // update the carousel
        // you can run this method anytime, f.ex on window.resize
        update: function() {
            var w = 0,
                h = 0,
                hooks = [0];

            jQuery.each( self._thumbnails, function( i, thumb ) {
                if ( thumb.ready ) {
                    w += thumb.outerWidth || jQuery( thumb.container ).outerWidth( true );
                    hooks[ i+1 ] = w;
                    h = Math.max( h, thumb.outerHeight || jQuery( thumb.container).outerHeight( true ) );
                }
            });

            self.jQuery( 'thumbnails' ).css({
                width: w,
                height: h
            });

            carousel.max = w;
            carousel.hooks = hooks;
            carousel.width = self.jQuery( 'thumbnails-list' ).width();
            carousel.setClasses();

            self.jQuery( 'thumbnails-container' ).toggleClass( 'galleria-carousel', w > carousel.width );

            // todo: fix so the carousel moves to the left
        },

        bindControls: function() {

            carousel.next.bind( CLICK(), function(e) {
                e.preventDefault();

                if ( self._options.carousel_steps == 'auto' ) {

                    for ( var i = carousel.current; i < carousel.hooks.length; i++ ) {
                        if ( carousel.hooks[i] - carousel.hooks[ carousel.current ] > carousel.width ) {
                            carousel.set(i - 2);
                            break;
                        }
                    }

                } else {
                    carousel.set( carousel.current + self._options.carousel_steps);
                }
            });

            carousel.prev.bind( CLICK(), function(e) {
                e.preventDefault();

                if ( self._options.carousel_steps == 'auto' ) {

                    for ( var i = carousel.current; i >= 0; i-- ) {
                        if ( carousel.hooks[ carousel.current ] - carousel.hooks[i] > carousel.width ) {
                            carousel.set( i + 2 );
                            break;
                        } else if ( i == 0 ) {
                            carousel.set( 0 );
                            break;
                        }
                    }
                } else {
                    carousel.set( carousel.current - self._options.carousel_steps );
                }
            });
        },

        // calculate and set positions
        set: function( i ) {
            i = Math.max( i, 0 );
            while ( carousel.hooks[i - 1] + carousel.width > carousel.max && i >= 0 ) {
                i--;
            }
            carousel.current = i;
            carousel.animate();
        },

        // get the last position
        getLast: function(i) {
            return ( i || carousel.current ) - 1;
        },

        // follow the active image
        follow: function(i) {

            //don't follow if position fits
            if ( i == 0 || i == carousel.hooks.length - 2 ) {
                carousel.set( i );
                return;
            }

            // calculate last position
            var last = carousel.current;
            while( carousel.hooks[last] - carousel.hooks[ carousel.current ] <
                   carousel.width && last <= carousel.hooks.length ) {
                last ++;
            }

            // set position
            if ( i - 1 < carousel.current ) {
                carousel.set( i - 1 );
            } else if ( i + 2 > last) {
                carousel.set( i - last + carousel.current + 2 );
            }
        },

        // helper for setting disabled classes
        setClasses: function() {
            carousel.prev.toggleClass( 'disabled', !carousel.current );
            carousel.next.toggleClass( 'disabled', carousel.hooks[ carousel.current ] + carousel.width > carousel.max );
        },

        // the animation method
        animate: function(to) {
            carousel.setClasses();
            var num = carousel.hooks[ carousel.current ] * -1;

            if ( isNaN( num ) ) {
                return;
            }

            self.jQuery( 'thumbnails' ).animate({
                left: num
            },{
                duration: self._options.carousel_speed,
                easing: self._options.easing,
                queue: false
            });
        }
    };

    // tooltip control
    // added in 1.2
    var tooltip = this._tooltip = {

        initialized : false,

        active: null,

        open: false,

        init: function() {

            tooltip.initialized = true;

            var css = '.galleria-tooltip{padding:3px 8px;max-width:50%;background:#ffe;color:#000;z-index:3;position:absolute;font-size:11px;line-height:1.3' +
                      'opacity:0;box-shadow:0 0 2px rgba(0,0,0,.4);-moz-box-shadow:0 0 2px rgba(0,0,0,.4);-webkit-box-shadow:0 0 2px rgba(0,0,0,.4);}';

            Utils.insertStyleTag(css);

            self.jQuery( 'tooltip' ).css('opacity', .8);
            Utils.hide( self.get('tooltip') );

        },

        // move handler
        move: function( e ) {
            var mouseX = self.getMousePosition(e).x,
                mouseY = self.getMousePosition(e).y,
                $elem = self.jQuery( 'tooltip' ),
                x = mouseX,
                y = mouseY,
                height = $elem.outerHeight( true ) + 1,
                width = $elem.outerWidth( true ),
                limitY = height + 15;

            var maxX = self.jQuery( 'container').width() - width,
                maxY = self.jQuery( 'container').height() - height;

            if ( !isNaN(x) && !isNaN(y) ) {

                x += 15;
                y -= 35;

                x = Math.max( 0, Math.min( maxX, x ) );
                y = Math.max( 0, Math.min( maxY, y ) );

                if( mouseY < limitY ) {
                    y = limitY;
                }

                $elem.css({ left: x, top: y });
            }
        },

        // bind elements to the tooltip
        // you can bind multiple elementIDs using { elemID : function } or { elemID : string }
        // you can also bind single DOM elements using bind(elem, string)
        bind: function( elem, value ) {

            if (! tooltip.initialized ) {
                tooltip.init();
            }

            var hover = function( elem, value) {

                tooltip.define( elem, value );

                jQuery( elem ).hover(function() {

                    tooltip.active = elem;
                    Utils.clearTimer('switch_tooltip');
                    self.jQuery('container').unbind( 'mousemove', tooltip.move ).bind( 'mousemove', tooltip.move ).trigger( 'mousemove' );
                    tooltip.show( elem );

                    Galleria.utils.addTimer( 'tooltip', function() {
                        self.jQuery( 'tooltip' ).stop();
                        Utils.show( self.get( 'tooltip' ), 400 );
                        tooltip.open = true;

                    }, tooltip.open ? 0 : 1000);

                }, function() {

                    tooltip.active = null;

                    self.jQuery( 'container' ).unbind( 'mousemove', tooltip.move );
                    Utils.clearTimer( 'tooltip' );
                    
                    self.jQuery( 'tooltip' ).stop();
                    
                    Utils.hide( self.get( 'tooltip' ), 200, function() {
                        Utils.addTimer('switch_tooltip', function() {
                            tooltip.open = false;
                        }, 1000);
                    });
                });
            };

            if (typeof value == 'string') {
                hover( ( elem in self._dom ? self.get(elem) : elem ), value );
            } else {
                // asume elemID here
                jQuery.each( elem, function( elemID, val ) {
                    hover( self.get(elemID), val );
                });
            }
        },

        show: function( elem ) {
            var text = jQuery(elem).data('tt');
            if ( ! text ) {
                return;
            }
            text = typeof text == 'function' ? text() : text;
            self.jQuery( 'tooltip' ).html( text.replace(/\s/, '&nbsp;') );
        },

        // redefine the tooltip here
        define: function( elem, value ) {

            // we store functions, not strings
            if (typeof value !== 'function') {
                var s = value;
                value = function() {
                    return s;
                };
            }

            if ( elem in self._dom ) {
                elem = self.get( elem );
            }

            jQuery(elem).data('tt', value);

            tooltip.show( elem );

        },

        refresh: function() {
            jQuery.each( arguments, function(i, elem) {
                if ( tooltip.active == elem ) {
                    tooltip.show( elem );
                }
            });
        }
    };

    // internal fullscreen control
    // added in 1.195
    // still kind of experimental
    var fullscreen = this._fullscreen = {
        scrolled: 0,
        enter: function(callback) {

            // hide the image until rescale is complete
            Utils.hide( self.getActiveImage() );

            self.jQuery( 'container' ).addClass( 'fullscreen' );

            fullscreen.scrolled = jQuery(window).scrollTop();

            // begin styleforce
            Utils.forceStyles(self.get('container'), {
                position: 'fixed',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                zIndex: 10000
            });

            var htmlbody = {
                height: '100%',
                overflow: 'hidden',
                margin:0,
                padding:0
            };

            Utils.forceStyles( DOM().html, htmlbody );
            Utils.forceStyles( DOM().body, htmlbody );

            // attach some keys
            self.attachKeyboard({
                escape: self.exitFullscreen,
                right: self.next,
                left: self.prev
            });

            // init the first rescale and attach callbacks
            self.rescale(function() {

                Utils.addTimer('fullscreen_enter', function() {
                    // show the image after 50 ms
                    Utils.show( self.getActiveImage() );

                    if (typeof callback == 'function') {
                        callback.call( self );
                    }

                }, 100);

                self.trigger( Galleria.FULLSCREEN_ENTER );
            });

            // bind the scaling to the resize event
            jQuery(window).resize( function() {
                fullscreen.scale();
            } );
        },

        scale : function() {
            self.rescale();
        },

        exit: function(callback) {

            Utils.hide( self.getActiveImage() );

            self.jQuery('container').removeClass( 'fullscreen' );

            // revert all styles
            Utils.revertStyles( self.get('container'), DOM().html, DOM().body );

            // scroll back
            window.scrollTo(0, fullscreen.scrolled);

            // detach all keyboard events (is this good?)
            self.detachKeyboard();

            self.rescale(function() {
                Utils.addTimer('fullscreen_exit', function() {

                    // show the image after 50 ms
                    Utils.show( self.getActiveImage() );

                    if ( typeof callback == 'function' ) {
                        callback.call( self );
                    }

                }, 50);

                self.trigger( Galleria.FULLSCREEN_EXIT );
            });

            jQuery(window).unbind('resize', fullscreen.scale);
        }
    };

    // the internal idle object for controlling idle states
    // TODO occational event conflicts
    var idle = this._idle = {

        trunk: [],

        bound: false,

        add: function(elem, to) {
            if (!elem) {
                return;
            }
            if (!idle.bound) {
                idle.addEvent();
            }
            elem = jQuery(elem);

            var from = {};

            for (var style in to) {
                from[style] = elem.css(style);
            }
            elem.data('idle', {
                from: from,
                to: to,
                complete: true,
                busy: false
            });
            idle.addTimer();
            idle.trunk.push(elem);
        },

        remove: function(elem) {

            elem = jQuery(elem);

            jQuery.each(idle.trunk, function(i, el) {
                if ( el.length && !el.not(elem).length ) {
                    self._idle.show(elem);
                    self._idle.trunk.splice(i, 1);
                }
            });

            if (!idle.trunk.length) {
                idle.removeEvent();
                Utils.clearTimer('idle');
            }
        },

        addEvent : function() {
            idle.bound = true;
            self.jQuery('container').bind('mousemove click', idle.showAll );
        },

        removeEvent : function() {
            idle.bound = false;
            self.jQuery('container').unbind('mousemove click', idle.showAll );
        },

        addTimer : function() {
            Utils.addTimer('idle', function() {
                self._idle.hide();
            }, self._options.idle_time );
        },

        hide : function() {

            self.trigger( Galleria.IDLE_ENTER );

            jQuery.each( idle.trunk, function(i, elem) {

                var data = elem.data('idle');

                if (! data) {
                    return;
                }

                elem.data('idle').complete = false;
                
                elem.stop().animate(data.to, {
                    duration: 600,
                    queue: false,
                    easing: 'swing'
                });
            });
        },

        showAll : function() {

            Utils.clearTimer('idle');

            jQuery.each(self._idle.trunk, function( i, elem ) {
                self._idle.show( elem );
            });
        },

        show: function(elem) {

            var data = elem.data('idle');

            if (!data.busy && !data.complete) {

                data.busy = true;

                self.trigger( Galleria.IDLE_EXIT );
                
                Utils.clearTimer( 'idle' );

                elem.stop().animate(data.from, {
                    duration: 300,
                    queue: false,
                    easing: 'swing',
                    complete: function() {
                        jQuery(this).data('idle').busy = false;
                        jQuery(this).data('idle').complete = true;
                    }
                });
            }
            idle.addTimer();
        }
    };

    // internal lightbox object
    // creates a predesigned lightbox for simple popups of images in galleria
    var lightbox = this._lightbox = {

        width : 0,

        height : 0,

        initialized : false,

        active : null,

        image : null,

        elems : {},

        init : function() {

            // trigger the event
            self.trigger( Galleria.LIGHTBOX_OPEN );

            if ( lightbox.initialized ) {
                return;
            }
            lightbox.initialized = true;

            // create some elements to work with
            var elems = 'overlay box content shadow title info close prevholder prev nextholder next counter image',
                el = {},
                op = self._options,
                css = '',
                cssMap = {
                    overlay:    'position:fixed;display:none;opacity:'+op.overlay_opacity+';top:0;left:0;width:100%;height:100%;background:'+op.overlay_background+';z-index:99990',
                    box:        'position:fixed;display:none;width:400px;height:400px;top:50%;left:50%;margin-top:-200px;margin-left:-200px;z-index:99991',
                    shadow:     'position:absolute;background:#000;width:100%;height:100%;',
                    content:    'position:absolute;background-color:#fff;top:10px;left:10px;right:10px;bottom:10px;overflow:hidden',
                    info:       'position:absolute;bottom:10px;left:10px;right:10px;color:#444;font:11px/13px arial,sans-serif;height:13px',
                    close:      'position:absolute;top:10px;right:10px;height:20px;width:20px;background:#fff;text-align:center;cursor:pointer;color:#444;font:16px/22px arial,sans-serif;z-index:99999',
                    image:      'position:absolute;top:10px;left:10px;right:10px;bottom:30px;overflow:hidden',
                    prevholder: 'position:absolute;width:50%;height:100%;cursor:pointer',
                    nextholder: 'position:absolute;width:50%;height:100%;right:0;cursor:pointer',
                    prev:       'position:absolute;top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;left:20px;display:none;line-height:40px;text-align:center;color:#000',
                    next:       'position:absolute;top:50%;margin-top:-20px;height:40px;width:30px;background:#fff;right:20px;left:auto;display:none;line-height:40px;text-align:center;color:#000',
                    title:      'float:left',
                    counter:    'float:right;margin-left:8px'
                },
                hover = function(elem) {
                    return elem.hover(
                        function() { jQuery(this).css( 'color', '#bbb' ); },
                        function() { jQuery(this).css( 'color', '#444' ); }
                    );
                };

            // create and insert CSS
            jQuery.each(cssMap, function( key, value ) {
                css += '.galleria-lightbox-'+key+'{'+value+'}';
            });

            Utils.insertStyleTag( css );

            // create the elements
            jQuery.each(elems.split(' '), function( i, elemId ) {
                self.addElement( 'lightbox-' + elemId );
                el[ elemId ] = lightbox.elems[ elemId ] = self.get( 'lightbox-' + elemId );
            });

            // initiate the image
            lightbox.image = new Galleria.Picture();

            // append the elements
            self.append({
                'lightbox-box': ['lightbox-shadow','lightbox-content', 'lightbox-close','lightbox-prevholder','lightbox-nextholder'],
                'lightbox-info': ['lightbox-title','lightbox-counter'],
                'lightbox-content': ['lightbox-info', 'lightbox-image'],
                'lightbox-prevholder': 'lightbox-prev',
                'lightbox-nextholder': 'lightbox-next'
            });

            jQuery( el.image ).append( lightbox.image.container );

            jQuery( DOM().body ).append( el.overlay, el.box );

            // add the prev/next nav and bind some controls

            hover( jQuery( el.close ).bind( CLICK(), lightbox.hide ).html('&#215;') );

            jQuery.each( ['Prev','Next'], function(i, dir) {

                var $d = jQuery( el[ dir.toLowerCase() ] ).html( /v/.test( dir ) ? '‹&nbsp;' : '&nbsp;›' );

                jQuery( el[ dir.toLowerCase()+'holder'] ).hover(function() {
                    $d.show();
                }, function() {
                    $d.fadeOut( 200 );
                }).bind( CLICK(), function() {
                    lightbox[ 'show' + dir ]();
                });

            });
            jQuery( el.overlay ).bind( CLICK(), lightbox.hide );

        },

        rescale: function(event) {

            // calculate
             var width = Math.min( jQuery(window).width()-40, lightbox.width ),
                height = Math.min( jQuery(window).height()-60, lightbox.height ),
                ratio = Math.min( width / lightbox.width, height / lightbox.height ),
                destWidth = ( lightbox.width * ratio ) + 40,
                destHeight = ( lightbox.height * ratio ) + 60,
                to = {
                    width: destWidth,
                    height: destHeight,
                    marginTop: Math.ceil( destHeight / 2 ) *- 1,
                    marginLeft: Math.ceil( destWidth / 2 ) *- 1
                };

            // if rescale event, don't animate
            if ( event ) {
                jQuery( lightbox.elems.box ).css( to );
            } else {
                jQuery( lightbox.elems.box ).animate(
                    to,
                    self._options.lightbox_transition_speed,
                    self._options.easing,
                    function() {
                        var image = lightbox.image,
                            speed = self._options.lightbox_fade_speed;

                        self.trigger({
                            type: Galleria.LIGHTBOX_IMAGE,
                            imageTarget: image.image
                        });

                        image.show();
                        Utils.show( image.image, speed );
                        Utils.show( lightbox.elems.info, speed );
                    }
                );
            }
        },

        hide: function() {

            // remove the image
            lightbox.image.image = null;

            jQuery(window).unbind('resize', lightbox.rescale);

            jQuery( lightbox.elems.box ).hide();

            Utils.hide( lightbox.elems.info );

            Utils.hide( lightbox.elems.overlay, 200, function() {
                jQuery( this ).hide().css( 'opacity', self._options.overlay_opacity );
                self.trigger( Galleria.LIGHTBOX_CLOSE );
            });
        },

        showNext: function() {
            lightbox.show( self.getNext( lightbox.active ) );
        },

        showPrev: function() {
            lightbox.show( self.getPrev( lightbox.active ) );
        },

        show: function(index) {

            lightbox.active = index = typeof index == 'number' ? index : self.getIndex();

            if ( !lightbox.initialized ) {
                lightbox.init();
            }

            jQuery(window).unbind('resize', lightbox.rescale );

            var data = self.getData(index),
                total = self.getDataLength();

            Utils.hide( lightbox.elems.info );

            lightbox.image.load( data.image, function( image ) {

                lightbox.width = image.original.width;
                lightbox.height = image.original.height;

                jQuery( image.image ).css({
                    width: '100.5%',
                    height: '100.5%',
                    top: 0,
                    zIndex: 99998,
                    opacity: 0
                });

                lightbox.elems.title.innerHTML = data.title;
                lightbox.elems.counter.innerHTML = (index + 1) + ' / ' + total;
                jQuery(window).resize( lightbox.rescale );
                lightbox.rescale();
            });

            jQuery( lightbox.elems.overlay ).show();
            jQuery( lightbox.elems.box ).show();
        }
    };

    return this;
};

// end Galleria constructor

Galleria.prototype = {

    /**
        Use this function to initialize the gallery and start loading.
        Should only be called once per instance.

        @param {HTML Element} target The target element
        @param {Object} options The gallery options

        @returns {Galleria}
    */

    init: function( target, options ) {

        var self = this;

        // save the instance
        _galleries.push( this );

        // save the original ingredients
        this._original = {
            target: target,
            options: options,
            data: null
        };

        // save the target here
        this._target = this._dom.target = target.nodeName ? target : jQuery( target ).get(0);

        // raise error if no target is detected
        if ( !this._target ) {
             Galleria.raise('Target not found.');
             return;
        }

        // apply options
        this._options = {
            autoplay: false,
            carousel: true,
            carousel_follow: true,
            carousel_speed: 400,
            carousel_steps: 'auto',
            clicknext: false,
            data_config : function( elem ) { return {}; },
            data_selector: 'img',
            data_source: this._target,
            debug: undef,
            easing: 'galleria',
            extend: function(options) {},
            height: 'auto',
            idle_time: 3000,
            image_crop: false,
            image_margin: 0,
            image_pan: false,
            image_pan_smoothness: 12,
            image_position: '50%',
            keep_source: false,
            lightbox_fade_speed: 200,
            lightbox_transition_speed: 500,
            link_source_images: true,
            max_scale_ratio: undef,
            min_scale_ratio: undef,
            on_image: function(img,thumb) {},
            overlay_opacity: .85,
            overlay_background: '#0b0b0b',
            pause_on_interaction: true, // 1.9.96
            popup_links: false,
            preload: 2,
            queue: true,
            show: 0,
            show_info: true,
            show_counter: true,
            show_imagenav: true,
            thumb_crop: true,
            thumb_event_type: CLICK(),
            thumb_fit: true,
            thumb_margin: 0,
            thumb_quality: 'auto',
            thumbnails: true,
            transition: 'fade',
            transition_initial: undef,
            transition_speed: 400,
            width: 'auto'
        };

        // apply debug
        if ( options && options.debug === true ) {
            DEBUG = true;
        }

        // hide all content
        jQuery( this._target ).children().hide();

        // now we just have to wait for the theme...
        if ( Galleria.theme ) {
            this._init();
        } else {
            Utils.addTimer('themeload', function() {
                Galleria.raise( 'No theme found.', true);
            }, 2000);

            $doc.one( Galleria.THEMELOAD, function() {
                Utils.clearTimer( 'themeload' );
                self._init.call( self );
            });
        }
    },

    // the internal _init is called when the THEMELOAD event is triggered
    // this method should only be called once per instance
    // for manipulation of data, use the .load method

    _init: function() {
        var self = this;

        if ( this._initialized ) {
            Galleria.raise( 'Init failed: Gallery instance already initialized.' );
            return this;
        }

        this._initialized = true;

        if ( !Galleria.theme ) {
            Galleria.raise( 'Init failed: No theme found.' );
            return this;
        }

        // merge the theme & caller options
        jQuery.extend( true, this._options, Galleria.theme.defaults, this._original.options );

        // bind the gallery to run when data is ready
        this.bind( Galleria.DATA, function() {

            // save the new data
            this._original.data = this._data;

            // lets show the counter here
            this.get('total').innerHTML = this.getDataLength();

            // cache the container
            var $container = this.jQuery( 'container' );

            // the gallery is ready, let's just wait for the css
            var num = { width: 0, height: 0 };
            var testElem =  Utils.create('galleria-image');

            // check container and thumbnail height
            Utils.wait({
                until: function() {

                    // keep trying to get the value
                    jQuery.each(['width', 'height'], function( i, m ) {
                        
                        // first check if options is set
                        
                        if (self._options[ m ] && typeof self._options[ m ] == 'number') {
                            num[ m ] = self._options[ m ];
                        } else {
                            
                            // else extract the meassures in the following order:
                            
                            num[m] = Utils.parseValue( $container.css( m ) ) ||         // 1. the container css
                                     Utils.parseValue( self.jQuery( 'target' ).css( m ) ) || // 2. the target css
                                     $container[ m ]() ||                               // 3. the container jQuery method
                                     self.jQuery( 'target' )[ m ]();                         // 4. the container jQuery method
                        }

                    });

                    var thumbHeight = function() {
                        return true;
                    };

                    // make sure thumbnails have a height as well
                    if ( self._options.thumbnails ) {
                        self.jQuery('thumbnails').append( testElem );
                        thumbHeight = function() {
                            return !!jQuery( testElem ).height();
                        };
                    }

                    return thumbHeight() && num.width && num.height > 50;

                },
                success: function() {

                    // remove the testElem
                    jQuery( testElem ).remove();

                    // apply the new meassures
                    $container.width( num.width );
                    $container.height( num.height );

                    // for some strange reason, webkit needs a single setTimeout to play ball
                    if ( Galleria.WEBKIT ) {
                        window.setTimeout( function() {
                            self._run();
                        }, 1);
                    } else {
                        self._run();
                    }
                },
                error: function() {
                    // Height was probably not set, raise a hard error
                    Galleria.raise('Width & Height not found.', true);
                },
                timeout: 2000
            });
        });

        // postrun some stuff after the gallery is ready
        // make sure it only runs once
        var one = false;

        this.bind( Galleria.READY, function() {

            // show counter
            Utils.show( this.get('counter') );

            // bind clicknext
            if ( this._options.clicknext ) {
                jQuery.each( this._data, function( i, data ) {
                    delete data.link;
                });
                this.jQuery( 'stage' ).css({ cursor : 'pointer' }).bind( CLICK(), function(e) {
                    self.next();
                });
            }

            // bind carousel nav
            if ( this._options.carousel ) {
                this._carousel.bindControls();
            }

            // start autoplay
            if ( this._options.autoplay ) {

                this.pause();

                if ( typeof this._options.autoplay == 'number' ) {
                    this._playtime = this._options.autoplay;
                }

                this.trigger( Galleria.PLAY );
                this._playing = true;
            }

            // if second load, just do the show and return
            if ( one ) {
                if ( typeof this._options.show == 'number' ) {
                    this.show( this._options.show );
                }
                return;
            }

            one = true;

            // initialize the History plugin
            if ( Galleria.History ) {

                // bind the show method
                Galleria.History.change(function(e) {

                    // grab history ID
                    var val = parseInt( e.value.replace( /\//, '' ) );

                    // if ID is NaN, the user pressed back from the first image
                    // return to previous address
                    if (isNaN(val)) {
                        window.history.go(-1);

                    // else show the image
                    } else {
                        self.show( val, undef, true );
                    }
                });
            }

            // call the theme init method
            Galleria.theme.init.call( this, this._options );

            // call the extend option
            this._options.extend.call( this, this._options );

            // show the initial image
            // first test for permalinks in history
            if ( /^[0-9]{1,4}$/.test( HASH ) && Galleria.History ) {
                this.show( HASH, undef, true );

            } else {
                this.show( this._options.show );
            }

        });

        // build the gallery frame
        this.append({
            'info-text' :
                ['info-title', 'info-description', 'info-author'],
            'info' :
                ['info-text'],
            'image-nav' :
                ['image-nav-right', 'image-nav-left'],
            'stage' :
                ['images', 'loader', 'counter', 'image-nav'],
            'thumbnails-list' :
                ['thumbnails'],
            'thumbnails-container' :
                ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'],
            'container' :
                ['stage', 'thumbnails-container', 'info', 'tooltip']
        });

        Utils.hide( this.jQuery( 'counter' ).append(
            this.get( 'current' ),
            ' / ',
            this.get( 'total' )
        ) );

        this.setCounter('&#8211;');

        // add images to the controls
        jQuery.each( new Array(2), function(i) {

            // create a new Picture instance
            var image = new Galleria.Picture();

            // apply some styles
            jQuery( image.container ).css({
                position: 'absolute',
                top: 0,
                left: 0
            });

            // append the image
            self.jQuery( 'images' ).append( image.container );

            // reload the controls
            self._controls[i] = image;

        });

        // some forced generic styling
        this.jQuery( 'images' ).css({
            position: 'relative',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%'
        });

        this.jQuery( 'thumbnails, thumbnails-list' ).css({
            overflow: 'hidden',
            position: 'relative'
        });

        // bind image navigation arrows
        this.jQuery( 'image-nav-right, image-nav-left' ).bind( CLICK(), function(e) {

            // tune the clicknext option
            if ( self._options.clicknext ) {
                e.stopPropagation();
            }

            // pause if options is set
            if ( self._options.pause_on_interaction ) {
                self.pause();
            }

            // navigate
            var fn = /right/.test( this.className ) ? 'next' : 'prev';
            self[ fn ]();

        });

        // hide controls if chosen to
        jQuery.each( ['info','counter','image-nav'], function( i, el ) {
            if ( self._options[ 'show_' + el.replace(/-/, '') ] === false ) {
                Utils.moveOut( self.get( el ) );
            }
        });

        // load up target content
        this.load();

        // now it's usually safe to remove the content
        // IE will never stop loading if we remove it, so let's keep it hidden for IE (it's usually fast enough anyway)
        if ( !this._options.keep_source && !IE ) {
            this._target.innerHTML = '';
        }

        // append the gallery frame
        this.jQuery( 'target' ).append( this.get( 'container' ) );

        // parse the carousel on each thumb load
        if ( this._options.carousel ) {
            this.bind( Galleria.THUMBNAIL, function() {
                this.updateCarousel();
            });
        }

        // bind on_image helper
        this.bind( Galleria.IMAGE, function( e ) {
            this._options.on_image.call( this, e.imageTarget, e.thumbTarget );
        });

        return this;
    },

    // the internal _run method should be called after loading data into galleria
    // creates thumbnails and makes sure the gallery has proper meassurements
    _run : function() {
        // shortcuts
        var self = this,
            o = this._options,

            // width/height for calculations
            width  = 0,
            height = 0,

            // cache the thumbnail option
            optval = typeof o.thumbnails == 'string' ? o.thumbnails.toLowerCase() : null;

        // loop through data and create thumbnails
        for( var i = 0; this._data[i]; i++ ) {

            var thumb,
                data = this._data[i],
                $container;

            if ( o.thumbnails === true ) {

                // add a new Picture instance
                thumb = new Galleria.Picture(i);

                // get source from thumb or image
                var src = data.thumb || data.image;

                // append the thumbnail
                this.jQuery( 'thumbnails' ).append( thumb.container );

                // cache the container
                $container = jQuery( thumb.container );

                // move some data into the instance
                // for some reason, jQuery cant handle css(property) when zooming in FF, breaking the gallery
                // so we resort to getComputedStyle for browsers who support it
                var getStyle = function( prop ) {
                    return doc.defaultView && doc.defaultView.getComputedStyle ?
                        doc.defaultView.getComputedStyle( thumb.container, null )[ prop ] :
                        $container.css( prop );
                };

                thumb.data = {
                    width  : Utils.parseValue( getStyle( 'width' ) ),
                    height : Utils.parseValue( getStyle( 'height' ) ),
                    order  : i
                };

                // grab & reset size for smoother thumbnail loads
                $container.css(( o.thumb_fit && o.thumb_crop !== true ) ?
                    { width: 0, height: 0 } :
                    { width: thumb.data.width, height: thumb.data.height });

                // load the thumbnail
                thumb.load( src, function( thumb ) {

                    // scale when ready
                    thumb.scale({
                        width:    thumb.data.width,
                        height:   thumb.data.height,
                        crop:     o.thumb_crop,
                        margin:   o.thumb_margin,
                        complete: function( thumb ) {

                            // shrink thumbnails to fit
                            var top = ['left', 'top'];
                            var arr = ['Width', 'Height'];

                            // calculate shrinked positions
                            jQuery.each(arr, function( i, meassure ) {
                                var m = meassure.toLowerCase();
                                if ( (o.thumb_crop !== true || o.thumb_crop == m ) && o.thumb_fit ) {
                                    var css = {};
                                    css[m] = thumb[m];
                                    jQuery( thumb.container ).css( css );
                                    css = {};
                                    css[top[i]] = 0;
                                    jQuery( thumb.image ).css( css);
                                }

                                // cache outer meassures
                                thumb['outer' + meassure] = jQuery( thumb.container )['outer' + meassure]( true );
                            });

                            // set high quality if downscale is moderate
                            Utils.toggleQuality( thumb.image,
                                o.thumb_quality === true ||
                                ( o.thumb_quality == 'auto' && thumb.original.width < thumb.width * 3 )
                            );

                            // trigger the THUMBNAIL event
                            self.trigger({
                                type: Galleria.THUMBNAIL,
                                thumbTarget: thumb.image,
                                index: thumb.data.order
                            });
                        }
                    });
                });

                // preload all images here
                if ( o.preload == 'all' ) {
                    thumb.add( data.image );
                }

            // create empty spans if thumbnails is set to 'empty'
            } else if ( optval == 'empty' || optval == 'numbers' ) {

                thumb = {
                    container:  Utils.create( 'galleria-image' ),
                    image: Utils.create( 'img', 'span' ),
                    ready: true
                };

                // create numbered thumbnails
                if ( optval == 'numbers' ) {
                    jQuery( thumb.image ).text( i + 1 );
                }
                
                this.jQuery( 'thumbnails' ).append( thumb.container );
                
                // we need to "fake" a loading delay before we append and trigger
                // 50+ should be enough
                
                window.setTimeout((function(image, index, container) {
                    return function() {
                        jQuery( container ).append( image );
                        self.trigger({
                            type: Galleria.THUMBNAIL,
                            thumbTarget: image,
                            index: index
                        });
                    }
                })( thumb.image, i, thumb.container ), 50 + (i*20) );
                

            // create null object to silent errors
            } else {
                thumb = {
                    container: null,
                    image: null
                };
            }

            // add events for thumbnails
            // you can control the event type using thumb_event_type
            // we'll add the same event to the source if it's kept

            jQuery( thumb.container ).add( o.keep_source && o.link_source_images ? data.original : null )
                .data('index', i).bind(o.thumb_event_type, function(e) {
                    // pause if option is set
                    if ( o.pause_on_interaction ) {
                        self.pause();
                    }

                    // extract the index from the data
                    var index = jQuery( e.currentTarget ).data( 'index' );
                    if ( self.getIndex() !== index ) {
                        self.show( index );
                    }

                    e.preventDefault();
            });

            this._thumbnails.push( thumb );
        }

        // make sure we have a stageHeight && stageWidth

        Utils.wait({

            until: function() {
                self._stageWidth  = self.jQuery( 'stage' ).width();
                self._stageHeight = self.jQuery( 'stage' ).height();
                return( self._stageWidth && 
                        self._stageHeight > 50 ); // what is an acceptable height?
            },

            success: function() {
                self.trigger( Galleria.READY );
            },

            error: function() {
                Galleria.raise('stage meassures not found');
            }

        });
    },

    /**
        Loads data into the gallery.
        You can call this method on an existing gallery to reload the gallery with new data.

        @param {Array or String} source Optional JSON array of data or selector of where to find data in the document.
        Defaults to the Galleria target or data_source option.

        @param {String} selector Optional element selector of what elements to parse.
        Defaults to 'img'.

        @param {Function} config Optional function to modify the data extraction proceedure from the selector.
        See the data_config option for more information.

        @returns {Galleria}
    */

    load : function( source, selector, config ) {

        var self = this;

        // empty the data array
        this._data = [];

        // empty the thumbnails
        this._thumbnails = [];
        this.jQuery('thumbnails').empty();

        // shorten the arguments
        if ( typeof selector == 'function' ) {
            config = selector;
            selector = null;
        }

        // use the source set by target
        source = source || this._options.data_source;

        // use selector set by option
        selector = selector || this._options.data_selector;

        // use the data_config set by option
        config = config || this._options.data_config;

        // check if the data is an array already
        if ( source.constructor == Array ) {
            if ( this.validate( source) ) {
                this._data = source;
                this.trigger( Galleria.DATA );
            } else {
                Galleria.raise( 'Load failed: JSON Array not valid.' );
            }
            return this;
        }
        // loop through images and set data
        jQuery( source ).find( selector ).each( function( i, img ) {
            var data = {},
                img = jQuery( img ),
                parent = img.parent(),
                href = parent.attr( 'href' );

            // check if it's a link to another image
            if ( /\.(png|gif|jpg|jpeg)$/i.test(href) ) {
                data.image = href;

            // else assign the href as a link if it exists
            } else if ( href ) {
                data.link = href;
            }

            // mix default extractions with the hrefs and config
            // and push it into the data array
            self._data.push( jQuery.extend({

                title:       img.attr('title'),
                thumb:       img.attr('src'),
                image:       img.attr('src'),
                description: img.attr('alt'),
                link:        img.attr('longdesc'),
                original:    img.get(0) // saved as a reference

            }, data, config( img ) ) );

        });
        // trigger the DATA event and return
        if ( this.getDataLength() ) {
            this.trigger( Galleria.DATA );
        } else {
            Galleria.raise('Load failed: no data found.');
        }
        return this;

    },

    _getActive: function() {
        return this._controls.getActive();
    },

    validate : function( data ) {
        // todo: validate a custom data array
        return true;
    },

    /**
        Bind any event to Galleria

        @param {String} type The Event type to listen for
        @param {Function} fn The function to execute when the event is triggered

        @example this.bind( Galleria.IMAGE, function() { Galleria.log('image shown') });

        @returns {Galleria}
    */

    bind : function(type, fn) {
        this.jQuery( 'container' ).bind( type, this.proxy(fn) );
        return this;
    },

    /**
        Unbind any event to Galleria

        @param {String} type The Event type to forget

        @returns {Galleria}
    */

    unbind : function(type) {
        this.jQuery( 'container' ).unbind( type );
        return this;
    },

    /**
        Manually trigger a Galleria event

        @param {String} type The Event to trigger

        @returns {Galleria}
    */

    trigger : function( type ) {
        type = typeof type == 'object' ?
            jQuery.extend( type, { scope: this } ) :
            { type: type, scope: this };
        this.jQuery( 'container' ).trigger( type );
        return this;
    },

    /**
        Assign an "idle state" to any element.
        The idle state will be applied after a certain amount of idle time
        Useful to hide f.ex navigation when the gallery is inactive

        @param {HTML Element or String} elem The Dom node or selector to apply the idle state to
        @param {Object} styles the CSS styles to apply

        @example addIdleState( this.get('image-nav'), { opacity: 0 });
        @example addIdleState( '.galleria-image-nav', { top: -200 });

        @returns {Galleria}
    */

    addIdleState: function( elem, styles ) {
        this._idle.add.apply( this._idle, Utils.array( arguments ) );
        return this;
    },

    /**
        Removes any idle state previously set using addIdleState()

        @param {HTML Element or String} elem The Dom node or selector to remove the idle state from.

        @returns {Galleria}
    */

    removeIdleState: function( elem ) {
        this._idle.remove.apply( this._idle, Utils.array( arguments ) );
        return this;
    },

    /**
        Force Galleria to enter idle mode.

        @returns {Galleria}
    */

    enterIdleMode: function() {
        this._idle.hide();
        return this;
    },

    /**
        Force Galleria to exit idle mode.

        @returns {Galleria}
    */

    exitIdleMode: function() {
        this.idle._show();
        return this;
    },

    /**
        Enter FullScreen mode

        @param {Function} callback the function to be executed when the fullscreen mode is fully applied.

        @returns {Galleria}
    */

    enterFullscreen: function( callback ) {
        this._fullscreen.enter.apply( this, Utils.array( arguments ) );
        return this;
    },

    /**
        Exits FullScreen mode

        @param {Function} callback the function to be executed when the fullscreen mode is fully applied.

        @returns {Galleria}
    */

    exitFullscreen: function( callback ) {
        this._fullscreen.exit.apply( this, Utils.array( arguments ) );
        return this;
    },

    /**
        Adds a tooltip to any element.
        You can also call this method with an object as argument with elemID:value pairs to apply tooltips to (see examples)

        @param {HTML Element} elem The DOM Node to attach the event to
        @param {String or Function} value The tooltip message. Can also be a function that returns a string.

        @example this.bindTooltip( this.get('thumbnails'), 'My thumbnails');
        @example this.bindTooltip( this.get('thumbnails'), function() { return 'My thumbs' });
        @example this.bindTooltip( { image_nav: 'Navigation' });

        @returns {Galleria}
    */

    bindTooltip: function( elem, value ) {
        this._tooltip.bind.apply( this._tooltip, Utils.array(arguments) );
        return this;
    },

    /**
        Redefine a tooltip
        Use this if you want to change the tooltip value at runtime

        @param {HTML Element} elem The DOM Node to attach the event to
        @param {String or Function} value The tooltip message. Can also be a function that returns a string.

        @returns {Galleria}
    */

    defineTooltip: function( elem, value ) {
        this._tooltip.define.apply( this._tooltip, Utils.array(arguments) );
        return this;
    },

    // leave this out of the API for now

    refreshTooltip: function() {
        this._tooltip.refresh.apply( this._tooltip, Utils.array(arguments) );
        return this;
    },

    /**
        Open a pre-designed lightbox with the currently active image.
        You can control some visuals using gallery options.

        @returns {Galleria}
    */

    openLightbox: function() {
        this._lightbox.show.apply( this._lightbox, Utils.array( arguments ) );
        return this;
    },

    /**
        Close the lightbox.

        @returns {Galleria}
    */

    closeLightbox: function() {
        this._lightbox.hide.apply( this._lightbox, Utils.array( arguments ) );
        return this;
    },

    /**
        Get the currently active image element.

        @returns {HTML Element} The image element
    */

    getActiveImage: function() {
        return this._getActive().image || undef;
    },

    /**
        Get the currently active thumbnail element.

        @returns {HTML Element} The thumbnail element
    */

    getActiveThumb: function() {
        return this._thumbnails[ this._active ].image || undef;
    },

    /**
        Get the mouse position relative to the gallery container

        @param e The mouse event

        @example

var gallery = this;
jQuery(document).mousemove(function(e) {
    console.log( gallery.getMousePosition(e).x );
});

        @returns {Object} Object with x & y of the relative mouse postion
    */

    getMousePosition : function(e) {
        return {
            x: e.pageX - this.jQuery( 'container' ).offset().left,
            y: e.pageY - this.jQuery( 'container' ).offset().top
        };
    },

    /**
        Adds a panning effect to the image

        @param img The optional image element. If not specified it takes the currently active image

        @returns {Galleria}
    */

    addPan : function( img ) {

        if ( this._options.image_crop === false ) {
            return;
        }

        img = jQuery( img || this.getActiveImage() );

        // define some variables and methods
        var self   = this,
            x      = img.width() / 2,
            y      = img.height() / 2,
            curX   = destX = parseInt( img.css( 'left' ) ) || 0,
            curY   = destY = parseInt( img.css( 'top' ) ) || 0,
            distX  = 0,
            distY  = 0,
            active = false,
            ts     = Utils.timestamp(),
            cache  = 0,
            move   = 0,

            // positions the image
            position = function( dist, cur, pos ) {
                if ( dist > 0 ) {
                    move = Math.round( Math.max( dist * -1, Math.min( 0, cur ) ) );
                    if ( cache != move ) {

                        cache = move;

                        if ( IE == 8 ) { // scroll is faster for IE
                            img.parent()[ 'scroll' + pos ]( move * -1 );
                        } else {
                            var css = {};
                            css[ pos.toLowerCase() ] = move;
                            img.css(css);
                        }
                    }
                }
            },

            // calculates mouse position after 50ms
            calculate = function(e) {
                if (Utils.timestamp() - ts < 50) {
                    return;
                }
                active = true;
                x = self.getMousePosition(e).x;
                y = self.getMousePosition(e).y;
            },

            // the main loop to check
            loop = function(e) {

                if (!active) {
                    return;
                }

                distX = img.width() - self._stageWidth;
                distY = img.height() - self._stageHeight;
                destX = x / self._stageWidth * distX * -1;
                destY = y / self._stageHeight * distY * -1;
                curX += ( destX - curX ) / self._options.image_pan_smoothness;
                curY += ( destY - curY ) / self._options.image_pan_smoothness;

                position( distY, curY, 'Top' );
                position( distX, curX, 'Left' );

            };

        // we need to use scroll in IE8 to speed things up
        if ( IE == 8 ) {

            img.parent().scrollTop( curY * -1 ).scrollLeft( curX * -1 );
            img.css({
                top: 0,
                left: 0
            });

        }

        // unbind and bind event
        this.jQuery( 'stage' ).unbind( 'mousemove', calculate ).bind( 'mousemove', calculate );

        // loop the loop
        Utils.addTimer('pan', loop, 50, true);

        return this;
    },

    /**
        Brings the scope into any callback

        @param fn The callback to bring the scope into
        @param scope Optional scope to bring

        @example jQuery('#fullscreen').click( this.proxy(function() { this.enterFullscreen(); }) )

        @returns {Function} Return the callback with the gallery scope
    */

    proxy : function( fn, scope ) {
        if ( typeof fn !== 'function' ) {
            return function() {};
        }
        scope = scope || this;
        return function() {
            return fn.apply( scope, Utils.array( arguments ) );
        };
    },

    /**
        Removes the panning effect set by addPan()

        @returns {Galleria}
    */

    removePan: function() {

        if ( IE == 8 ) {
            // todo: doublecheck this
        }
        this.jQuery( 'stage' ).unbind( 'mousemove' );

        Utils.clearTimer('pan');

        return this;
    },

    /**
        Adds an element to the Galleria DOM array.
        When you add an element here, you can access it using element ID in many API calls

        @param {String} id The element ID you wish to use. You can add many elements by adding more arguments.

        @example addElement('mybutton');
        @example addElement('mybutton','mylink');

        @returns {Galleria}
    */

    addElement : function( id ) {

        var dom = this._dom;

        jQuery.each( Utils.array(arguments), function( i, blueprint ) {
           dom[ blueprint ] = Utils.create( 'galleria-' + blueprint );
        });

        return this;
    },

    /**
        Attach keyboard events to Galleria

        @param {Object} map The map object of events.
        Possible keys are 'UP', 'DOWN', 'LEFT', 'RIGHT', 'RETURN', 'ESCAPE', 'BACKSPACE', and 'SPACE'.

        @example

this.attachKeyboard({
    right: this.next,
    left: this.prev,
    up: function() {
        console.log( 'up key pressed' )
    }
});

        @returns {Galleria}
    */

    attachKeyboard : function( map ) {
        this._keyboard.attach.apply( this._keyboard, Utils.array( arguments ) );
        return this;
    },

    /**
        Detach all keyboard events to Galleria

        @returns {Galleria}
    */

    detachKeyboard : function() {
        this._keyboard.detach.apply( this._keyboard, Utils.array( arguments ) );
        return this;
    },

    /**
        Fast helper for appending galleria elements that you added using addElement()

        @param {String} parentID The parent element ID where the element will be appended
        @param {String} childID the element ID that should be appended

        @example this.addElement('myElement');
        this.appendChild( 'info', 'myElement' );

        @returns {Galleria}
    */

    appendChild : function( parentID, childID ) {
        this.jQuery( parentID ).append( this.get( childID ) || childID );
        return this;
    },

    /**
        Fast helper for appending galleria elements that you added using addElement()

        @param {String} parentID The parent element ID where the element will be preppended
        @param {String} childID the element ID that should be preppended

        @example

this.addElement('myElement');
this.prependChild( 'info', 'myElement' );

        @returns {Galleria}
    */

    prependChild : function( parentID, childID ) {
        this.jQuery( parentID ).prepend( this.get( childID ) || childID );
        return this;
    },

    /**
        Remove an element by blueprint

        @param {String} elemID The element to be removed.
        You can remove multiple elements by adding arguments.

        @returns {Galleria}
    */

    remove : function( elemID ) {
        this.jQuery( Utils.array( arguments ).join(',') ).remove();
        return this;
    },

    // a fast helper for building dom structures
    // leave this out of the API for now

    append : function( data ) {
        for( var i in data) {
            if ( data[i].constructor == Array ) {
                for( var j = 0; data[i][j]; j++ ) {
                    this.appendChild( i, data[i][j] );
                }
            } else {
                this.appendChild( i, data[i] );
            }
        }
        return this;
    },

    // an internal helper for scaling according to options
    _scaleImage : function( image, options ) {
        
        options = jQuery.extend({
            width:    this._stageWidth,
            height:   this._stageHeight,
            crop:     this._options.image_crop,
            max:      this._options.max_scale_ratio,
            min:      this._options.min_scale_ratio,
            margin:   this._options.image_margin,
            position: this._options.image_position
        }, options );

       ( image || this._controls.getActive() ).scale( options );

        return this;
    },

    /**
        Updates the carousel,
        useful if you resize the gallery and want to re-check if the carousel nav is needed.

        @returns {Galleria}
    */

    updateCarousel : function() {
        this._carousel.update();
        return this;
    },

    /**
        Rescales the gallery

        @param {Number} width The target width
        @param {Number} height The target height
        @param {Function} complete The callback to be called when the scaling is complete

        @returns {Galleria}
    */

    rescale : function( width, height, complete ) {

        var self = this;

        // allow rescale(fn)
        if ( typeof width == 'function' ) {
            complete = width;
            width = undef;
        }

        var scale = function() {

            // shortcut
            var o = self._options;

            // set stagewidth
            self._stageWidth = width || self.jQuery( 'stage' ).width();
            self._stageHeight = height || self.jQuery( 'stage' ).height();

            // scale the active image
            self._scaleImage();

            if ( self._options.carousel ) {
                self.updateCarousel();
            }

            self.trigger( Galleria.RESCALE );

            if ( typeof complete == 'function' ) {
                complete.call( self );
            }
        };

        if ( Galleria.WEBKIT && !width && !height ) {
            Utils.addTimer( 'scale', scale, 5 );// webkit is too fast
        } else {
            scale.call( self );
        }

        return this;
    },

    /**
        Refreshes the gallery.
        Useful if you change image options at runtime and want to apply the changes to the active image.

        @returns {Galleria}
    */

    refreshImage : function() {
        this._scaleImage();
        if ( this._options.image_pan ) {
            this.addPan();
        }
        return this;
    },

    /**
        Shows an image by index

        @param {Number} index The index to show
        @param {Boolean} rewind A boolean that should be true if you want the transition to go back

        @returns {Galleria}
    */

    show : function( index, rewind, _history ) {

        // do nothing if index is false or queue is false and transition is in progress
        if ( index === false || !this._options.queue && this._queue.stalled ) {
            return;
        }
        
        index = Math.max( 0, Math.min( parseInt(index), this.getDataLength() - 1 ) );

        rewind = typeof rewind != 'undefined' ? !!rewind : index < this.getIndex();

        _history = _history || false;

        // do the history thing and return
        if ( !_history && Galleria.History ) {
            Galleria.History.value( index.toString() );
            return;
        }

        this._active = index;

        Array.prototype.push.call( this._queue, {
            index : index,
            rewind : rewind
        });
        if ( !this._queue.stalled ) {
            this._show();
        }

        return this;
    },

    // the internal _show method does the actual showing
    _show : function() {

        // shortcuts
        var self   = this,
            queue  = this._queue[ 0 ],
            data   = this.getData( queue.index );
        
        if ( !data ) {
            return;
        }
        
        var src    = data.image,
            active = this._controls.getActive(),
            next   = this._controls.getNext(),
            cached = next.isCached( src ),
            thumb  = this._thumbnails[ queue.index ];

            // to be fired when loading & transition is complete:
        var complete = function() {

            // remove stalled
            self._queue.stalled = false;

            // optimize quality
            Utils.toggleQuality( next.image, self._options.image_quality );

            // swap
            jQuery( active.container ).css({
                zIndex: 0,
                opacity: 0
            });
            jQuery( next.container ).css({
                zIndex: 1,
                opacity: 1
            });
            self._controls.swap();

            // add pan according to option
            if ( self._options.image_pan ) {
                self.addPan( next.image );
            }

            // make the image link
            if ( data.link ) {
                jQuery( next.image ).css({
                    cursor: 'pointer'
                }).bind( CLICK(), function() {

                    // popup link
                    if ( self._options.popup_links ) {
                        var win = window.open( data.link, '_blank' );
                    } else {
                        window.location.href = data.link;
                    }
                });
            }

            // remove the queued image
            Array.prototype.shift.call( self._queue );

            // if we still have images in the queue, show it
            if ( self._queue.length ) {
                self._show();
            }

            // check if we are playing
            self._playCheck();

            // trigger IMAGE event
            self.trigger({
                type:        Galleria.IMAGE,
                index:       queue.index,
                imageTarget: next.image,
                thumbTarget: thumb.image
            });
        };

        // let the carousel follow
        if ( this._options.carousel && this._options.carousel_follow ) {
            this._carousel.follow( queue.index );
        }

        // preload images
        if ( this._options.preload ) {

            var p,
                n = this.getNext();

            try {
                for ( var i = this._options.preload; i > 0; i-- ) {
                    p = new Galleria.Picture();
                    p.add( self.getData( n ).image );
                    n = self.getNext( n );
                }
            } catch(e) {}
        }

        // show the next image, just in case
        Utils.show( next.container );

        // add active classes
        jQuery( self._thumbnails[ queue.index ].container )
            .addClass( 'active' )
            .siblings( '.active' )
            .removeClass( 'active' );

        // trigger the LOADSTART event
        self.trigger( {
            type: Galleria.LOADSTART,
            cached: cached,
            index: queue.index,
            imageTarget: next.image,
            thumbTarget: thumb.image
        });
        // begin loading the next image
        next.load( src, function( next ) {
            self._scaleImage( next, {

                complete: function( next ) {

                    Utils.show( next.container );

                    // toggle low quality for IE
                    if ( 'image' in active ) {
                        Utils.toggleQuality( active.image, false );
                    }
                    Utils.toggleQuality( next.image, false );

                    // stall the queue
                    self._queue.stalled = true;

                    // remove the image panning, if applied
                    // TODO: rethink if this is necessary
                    self.removePan();

                    // set the captions and counter
                    self.setInfo( queue.index );
                    self.setCounter( queue.index );

                    // trigger the LOADFINISH event
                    self.trigger({
                        type: Galleria.LOADFINISH,
                        cached: cached,
                        index: queue.index,
                        imageTarget: next.image,
                        thumbTarget: self._thumbnails[ queue.index ].image
                    });

                    var transition = active.image === null && self._options.transition_initial ?
                        self._options.transition_initial : self._options.transition;

                    // validate the transition
                    if ( transition in _transitions === false ) {

                        complete();

                    } else {
                        var params = {
                            prev:   active.image,
                            next:   next.image,
                            rewind: queue.rewind,
                            speed:  self._options.transition_speed || 400
                        };

                        // call the transition function and send some stuff
                        _transitions[ transition ].call(self, params, complete );

                    }
                }
            });
        });
    },

    /**
        Gets the next index

        @param {Number} base Optional starting point

        @returns {Number} the next index, or the first if you are at the first (looping)
    */

    getNext : function( base ) {
        base = typeof base == 'number' ? base : this.getIndex();
        return base == this.getDataLength() - 1 ? 0 : base + 1;
    },

    /**
        Gets the previous index

        @param {Number} base Optional starting point

        @returns {Number} the previous index, or the last if you are at the first (looping)
    */

    getPrev : function( base ) {
        base = typeof base == 'number' ? base : this.getIndex();
        return base === 0 ? this.getDataLength() - 1 : base - 1;
    },

    /**
        Shows the next image in line

        @returns {Galleria}
    */

    next : function() {
        if ( this.getDataLength() > 1 ) {
            this.show( this.getNext(), false );
        }
        return this;
    },

    /**
        Shows the previous image in line

        @returns {Galleria}
    */

    prev : function() {
        if ( this.getDataLength() > 1 ) {
            this.show( this.getPrev(), true );
        }
        return this;
    },

    /**
        Retrieve a DOM element by element ID

        @param {String} elemId The delement ID to fetch

        @returns {HTML Element} The elements DOM node or null if not found.
    */

    get : function( elemId ) {
        return elemId in this._dom ? this._dom[ elemId ] : null;
    },

    /**
        Retrieve a data object

        @param {Number} index The data index to retrieve.
        If no index specified it will take the currently active image

        @returns {Object} The data object
    */

    getData : function( index ) {
        return index in this._data ?
            this._data[ index ] : this._data[ this._active ];
    },

    /**
        Retrieve the number of data items

        @returns {Number} The data length
    */
    getDataLength : function() {
        return this._data.length;
    },

    /**
        Retrieve the currently active index

        @returns {Number} The active index
    */

    getIndex : function() {
        return typeof this._active === 'number' ? this._active : false;
    },

    /**
        Retrieve the stage height

        @returns {Number} The stage height
    */

    getStageHeight : function() {
        return this._stageHeight;
    },

    /**
        Retrieve the stage width

        @returns {Number} The stage width
    */

    getStageWidth : function() {
        return this._stageWidth;
    },

    /**
        Retrieve the option

        @param {String} key The option key to retrieve. If no key specified it will return all options in an object.

        @returns option or options
    */

    getOptions : function( key ) {
        return typeof key == 'undefined' ? this._options : this._options[ key ];
    },

    /**
        Set options to the instance.
        You can set options using a key & value argument or a single object argument (see examples)

        @param {String} key The option key
        @param {String} value the the options value

        @example setOptions( 'autoplay', true )
        @example setOptions({ autoplay: true });

        @returns {Galleria}
    */

    setOptions : function( key, value ) {
        if ( typeof key == 'object' ) {
            jQuery.extend( this._options, key );
        } else {
            this._options[ key ] = value;
        }
        return this;
    },

    /**
        Starts playing the slideshow

        @param {Number} delay Sets the slideshow interval in milliseconds.
        If you set it once, you can just call play() and get the same interval the next time.

        @returns {Galleria}
    */

    play : function( delay ) {

        this.trigger( Galleria.PLAY );

        this._playing = true;
        this._playtime = delay || this._playtime;

        this._playCheck();

        return this;
    },

    /**
        Stops the slideshow if currently playing

        @returns {Galleria}
    */

    pause : function() {
        this.trigger( Galleria.PAUSE );
        this._playing = false;
        return this;
    },

    /**
        Toggle between play and pause events.

        @param {Number} delay Sets the slideshow interval in milliseconds.

        @returns {Galleria}
    */

    playToggle : function( delay ) {
        return ( this._playing ) ? this.pause() : this.play( delay );
    },

    _playCheck : function() {
        var self = this,
            played = 0,
            interval = 20,
            now = Utils.timestamp();

        if ( this._playing ) {

            Utils.clearTimer('play');
            var fn = function() {

                played = Utils.timestamp() - now;
                if ( played >= self._playtime && self._playing ) {
                    Utils.clearTimer('play');
                    self.next();
                    return;
                }
                if ( self._playing ) {

                    // trigger the PROGRESS event
                    self.trigger({
                        type:         Galleria.PROGRESS,
                        percent:      Math.ceil( played / self._playtime * 100 ),
                        seconds:      Math.floor( played / 1000 ),
                        milliseconds: played
                    });

                    Utils.addTimer( 'play', fn, interval );
                }
            };
            Utils.addTimer( 'play', fn, interval );
        }
    },

    setIndex: function( val ) {
        this._active = val;
        return this;
    },

    /**
        Manually modify the counter

        @param {Number} index Optional data index to fectch,
        if no index found it assumes the currently active index

        @returns {Galleria}
    */

    setCounter: function( index ) {

        if ( typeof index == 'number' ) {
            index++;
        } else if ( typeof index == 'undefined' ) {
            index = this.getIndex()+1;
        }

        this.get( 'current' ).innerHTML = index;

        if ( IE == 8 ) { // weird IE8 bug

            var opacity = this.jQuery( 'counter' ).css( 'opacity' );
            this.jQuery( 'counter' ).css( 'opacity', opacity );

        }

        return this;
    },

    /**
        Manually set captions

        @param {Number} index Optional data index to fectch and apply as caption,
        if no index found it assumes the currently active index

        @returns {Galleria}
    */

    setInfo : function( index ) {

        var self = this,
            data = this.getData( index );

        jQuery.each( ['title','description','author'], function( i, type ) {

            var elem = self.jQuery( 'info-' + type );

            if ( !!data[type] ) {
                elem[ data[ type ].length ? 'show' : 'hide' ]().html( data[ type ] );
            } else {
               elem.empty().hide();
            }
        });

        return this;
    },

    /**
        Checks if the data contains any captions

        @param {Number} index Optional data index to fectch,
        if no index found it assumes the currently active index.

        @returns {Boolean}
    */

    hasInfo : function( index ) {

        var d = this.getData( index );
        var check = 'title description'.split(' ');
        for ( var i = 0; check[i]; i++ ) {
            if ( !!this.getData( index )[ check[i] ] ) {
                return true;
            }
        }
        return false;

    },

    jQuery : function( str ) {

        var self = this,
            ret = [];

        jQuery.each( str.split(','), function( i, elemId ) {
            elemId = jQuery.trim( elemId );

            if ( self.get( elemId ) ) {
                ret.push( elemId );
            }
        });

        var jQ = jQuery( self.get( ret.shift() ) );

        jQuery.each( ret, function( i, elemId ) {
            jQ = jQ.add( self.get( elemId ) );
        });

        return jQ;

    },

    /**
        Converts element IDs into a jQuery collection
        You can call for multiple IDs separated with commas.

        @param {String} str One or more element IDs (comma-separated)

        @returns {jQuery}

        @example this.jQuery('info,container').hide();
    */

    $ : function() {
        return this.jQuery.apply( this, Utils.array( arguments ) );
    }

};

// End of Galleria prototype

jQuery.extend( Galleria, {

    // Event placeholders
    DATA:             'g_data',
    READY:            'g_ready',
    THUMBNAIL:        'g_thumbnail',
    LOADSTART:        'g_loadstart',
    LOADFINISH:       'g_loadfinish',
    IMAGE:            'g_image',
    THEMELOAD:        'g_themeload',
    PLAY:             'g_play',
    PAUSE:            'g_pause',
    PROGRESS:         'g_progress',
    FULLSCREEN_ENTER: 'g_fullscreen_enter',
    FULLSCREEN_EXIT:  'g_fullscreen_exit',
    IDLE_ENTER:       'g_idle_enter',
    IDLE_EXIT:        'g_idle_exit',
    RESCALE:          'g_rescale',
    LIGHTBOX_OPEN:    'g_lightbox_open',
    LIGHTBOX_CLOSE:   'g_lightbox_close',
    LIGHTBOX_IMAGE:   'g_lightbox_image',

    // Browser helpers
    IE9:     IE == 9,
    IE8:     IE == 8,
    IE7:     IE == 7,
    IE6:     IE == 6,
    IE:      !!IE,
    WEBKIT:  /webkit/.test( NAV ),
    SAFARI:  /safari/.test( NAV ),
    CHROME:  /chrome/.test( NAV ),
    QUIRK:   ( IE && doc.compatMode && doc.compatMode == "BackCompat" ),
    MAC:     /mac/.test( navigator.platform.toLowerCase() ),
    OPERA:   !!window.opera,
    IPHONE:  /iphone/.test( NAV ),
    IPAD:    /ipad/.test( NAV ),
    ANDROID: /android/.test( NAV ),

    // Todo detect touch devices in a better way, possibly using event detection
    TOUCH:   !!( /iphone/.test( NAV ) || /ipad/.test( NAV ) || /android/.test( NAV ) )

});

// Galleria static methods

/**
    Adds a theme that you can use for your Gallery

    @param {Object} theme Object that should contain all your theme settings.
    <ul>
        <li>name – name of the theme</li>
        <li>author - name of the author</li>
        <li>version - version number</li>
        <li>css - css file name (not path)</li>
        <li>defaults - default options to apply, including theme-specific options</li>
        <li>init - the init function</li>
    </ul>

    @returns {Object} theme
*/

Galleria.addTheme = function( theme ) {

    // make sure we have a name
    if ( !!theme['name'] === false ) {
        Galleria.raise('No theme name specified');
    }

    if ( typeof theme.defaults != 'object' ) {
        theme.defaults = {};
    }

    if ( typeof theme.css == 'string' ) {

        var css;

        // look for the absolute path
        jQuery('script').each(function( i, script ) {

            // look for the theme script
            var reg = new RegExp( 'galleria\\.' + theme.name.toLowerCase() + '\\.' );
            if( reg.test( script.src )) {

                // we have a match
                css = script.src.replace(/[^\/]*$/, '') + theme.css;

                Utils.addTimer( "css", function() {
                    Utils.loadCSS( css, 'galleria-theme', function() {
                        Galleria.theme = theme;
                        $doc.trigger( Galleria.THEMELOAD );
                    });
                }, 1);

            }
        });

        if ( !css ) {
            Galleria.raise('No theme CSS loaded');
        }
    } else {
        Galleria.theme = theme;
        $doc.trigger( Galleria.THEMELOAD );
    }
    return theme;
};

/**
    loadTheme loads a theme js file and attaches a load event to Galleria

    @param {String} src The relative path to the theme source file

    @param {Object} option Optional options you want to apply
*/

Galleria.loadTheme = function( src, options ) {

    var loaded = false,
        length = _galleries.length;

    // first clear the current theme, if exists
    Galleria.theme = undef;

    // load the theme
    Utils.loadScript( src, function() {
        loaded = true;
    } );

    // set a 1 sec timeout, then display a hard error if no theme is loaded
    Utils.wait({
        until: function() {
            return loaded;
        },
        error: function() {
            Galleria.raise( "Theme at " + src + " could not load, check theme path.", true );
        },
        success: function() {

            // check for existing galleries and reload them with the new theme
            if ( length ) {

                // temporary save the new galleries
                var refreshed = [];

                // refresh all instances
                // when adding a new theme to an existing gallery, all options will be resetted but the data will be kept
                // you can apply new options as a second argument
                jQuery.each( Galleria.get(), function(i, instance) {

                    // mix the old data and options into the new instance
                    var op = jQuery.extend( instance._original.options, {
                        data_source: instance._data
                    }, options);

                    // remove the old container
                    instance.jQuery('container').remove();

                    // create a new instance
                    var g = new Galleria();

                    // move the id
                    g._id = instance._id;

                    // initialize the new instance
                    g.init( instance._original.target, op );

                    // push the new instance
                    refreshed.push( g );
                });

                // now overwrite the old holder with the new instances
                _galleries = refreshed;
            }
        },
        timeout: 2000
    });
};

/**
    Retrieves a Galleria instance.

    @param {Number} index Optional index to retrieve.
    If no index is supplied, the method will return all instances in an array.

    @returns {Galleria or Array}
*/

Galleria.get = function( index ) {
    if ( !!_galleries[ index ] ) {
        return _galleries[ index ];
    } else if ( typeof index !== 'number' ) {
        return _galleries;
    } else {
        Galleria.raise('Gallery index ' + index + ' not found');
    }
};

/**
    Creates a transition to be used in your gallery

    @param {String} name The name of the transition that you will use as an option

    @param {Function} fn The function to be executed in the transition.
    The function contains two arguments, params and complete.
    Use the params Object to integrate the transition, and then call complete when you are done.

*/

Galleria.addTransition = function( name, fn ) {
    _transitions[name] = fn;
};

Galleria.utils = Utils;

/**
    A helper metod for cross-browser logging.
    It uses the console log if available otherwise it falls back to the opera
    debugger and finally <code>alert()</code>

    @example Galleria.log("hello", document.body, [1,2,3]);
*/

Galleria.log = function() {
    try {
        window.console.log.apply( window.console, Utils.array(arguments) );
    } catch( e ) {
        try {
            opera.postError.apply( opera, arguments );
        } catch( er ) {
              alert( Utils.array(arguments).split(', ') );
        }
    }
};

/**
    Method for raising errors

    @param {String} msg The message to throw

    @param {Boolean} fatal Set this to true to override debug settings and display a fatal error
*/

Galleria.raise = function( msg, fatal ) {
    if ( DEBUG || fatal ) {
        var type = fatal ? 'Fatal error' : 'Error';
        throw new Error( type + ': ' + msg );
    }
};

/**
    Adds preload, cache, scale and crop functionality

    @constructor

    @requires jQuery

    @param {Number} id Optional id to keep track of instances
*/

Galleria.Picture = function( id ) {

    // save the id
    this.id = id || null;

    // the image should be null until loaded
    this.image = null;

    // Create a new container
    this.container = Utils.create('galleria-image');

    // add container styles
    jQuery( this.container ).css({
        overflow: 'hidden',
        position: 'relative' // for IE Standards mode
    });

    // saves the original meassurements
    this.original = {
        width: 0,
        height: 0
    };

    // flag when the image is ready
    this.ready = false;

    // flag when the image is loaded
    this.loaded = false;

};

Galleria.Picture.prototype = {

    // the inherited cache object
    cache: {},

    // creates a new image and adds it to cache when loaded
    add: function( src ) {

        var self = this;

        // create the image
        var image = new Image();

        // force a block display
        jQuery( image ).css( 'display', 'block');

        if ( self.cache[ src ] ) {
            // no need to onload if the image is cached
            image.src = src;
            self.loaded = true;
            self.original = {
                height: image.height,
                width: image.width
            };
            return image;
        }

        // begin preload and insert in cache when done
        image.onload = function() {
            self.original = {
                height: this.height,
                width: this.width
            };
            self.cache[ src ] = src; // will override old cache
            self.loaded = true;
        };

        image.src = src;
        return image;

    },

    // show the image on stage
    show: function() {
        Utils.show( this.image );
    },

    // hide the image
    hide: function() {
        Utils.moveOut( this.image );
    },

    clear: function() {
        this.image = null;
    },

    /**
        Checks if an image is in cache

        @param {String} src The image source path, ex '/path/to/img.jpg'

        @returns {Boolean}
    */

    isCached: function( src ) {
        return !!this.cache[src];
    },

    /**
        Loads an image and call the callback when ready.
        Will also add the image to cache.

        @param {String} src The image source path, ex '/path/to/img.jpg'
        @param {Function} callback The function to be executed when the image is loaded & scaled

        @returns {jQuery} The image container object
    */

    load: function(src, callback) {

        // save the instance
        var self = this;

        jQuery( this.container ).empty(true);

        // add the image to cache and hide it
        this.image = this.add( src );
        Utils.hide( this.image );

        // append the image into the container
        jQuery( this.container ).append( this.image );

        // check for loaded image using a timeout
        Utils.wait({
            until: function() {
                // TODO this should be properly tested in Opera
                return self.loaded && self.image.complete && self.image.width;
            },
            success: function() {
                // call success
                window.setTimeout(function() { callback.call( self, self ); }, 50 );
            },
            error: function() {
                window.setTimeout(function() { callback.call( self, self ); }, 50 );
                Galleria.raise('image not loaded in 10 seconds: '+ src);
            },
            timeout: 10000
        });

        // return the container
        return this.container;
    },

    /**
        Scales and crops the image

        @param {Object} options The method takes an object with a number of options:

        <ul>
            <li>width - width of the container</li>
            <li>height - height of the container</li>
            <li>min - minimum scale ratio</li>
            <li>max - maximum scale ratio</li>
            <li>margin - distance in pixels from the image border to the container</li>
            <li>complete - a callback that fires when scaling is complete</li>
            <li>position - positions the image, works like the css background-image property.</li>
            <li>crop - defines how to crop. Can be true, false, 'width' or 'height'</li>
        </ul>

        @returns {jQuery} The image container object
    */

    scale: function( options ) {

        // extend some defaults
        options = jQuery.extend({
            width: 0,
            height: 0,
            min: undef,
            max: undef,
            margin: 0,
            complete: function() {},
            position: 'center',
            crop: false
        }, options);

        // return the element if no image found
        if (!this.image) {
            return this.container;
        }

        // store locale variables of width & height
        var width,
            height,
            self = this,
            $container = jQuery( self.container );

        // wait for the width/height
        Utils.wait({
            until: function() {

                width  = options.width
                    || $container.width()
                    || Utils.parseValue( $container.css('width') );

                height = options.height
                    || $container.height()
                    || Utils.parseValue( $container.css('height') );

                return width && height;
            },
            success: function() {
                // calculate some cropping
                var newWidth = ( width - options.margin * 2 ) / self.original.width,
                    newHeight = ( height - options.margin * 2 ) / self.original.height,
                    cropMap = {
                        'true'  : Math.max( newWidth, newHeight ),
                        'width' : newWidth,
                        'height': newHeight,
                        'false' : Math.min( newWidth, newHeight )
                    },
                    ratio = cropMap[ options.crop.toString() ];

                // allow max_scale_ratio
                if ( options.max ) {
                    ratio = Math.min( options.max, ratio );
                }

                // allow min_scale_ratio
                if ( options.min ) {
                    ratio = Math.max( options.min, ratio );
                }

                jQuery( self.container ).width( width ).height( height );

                // round up the width / height
                jQuery.each( ['width','height'], function( i, m ) {
                    jQuery( self.image )[ m ]( self[ m ] = Math.ceil( self.original[ m ] * ratio ) );
                });

                // calculate image_position
                var pos = {},
                    mix = {},
                    getPosition = function(value, meassure, margin) {
                        var result = 0;
                        if (/\%/.test(value)) {
                            var flt = parseInt(value) / 100;
                            result = Math.ceil( jQuery( self.image )[ meassure ]() * -1 * flt + margin * flt );
                        } else {
                            result = Utils.parseValue( value );
                        }
                        return result;
                    },
                    positionMap = {
                        'top': { top: 0 },
                        'left': { left: 0 },
                        'right': { left: '100%' },
                        'bottom': { top: '100%' }
                    };

                jQuery.each( options.position.toLowerCase().split(' '), function( i, value ) {
                    if ( value == 'center' ) {
                        value = '50%';
                    }
                    pos[i ? 'top' : 'left'] = value;
                });

                jQuery.each( pos, function( i, value ) {
                    if ( positionMap.hasOwnProperty( value ) ) {
                        jQuery.extend( mix, positionMap[ value ] );
                    }
                });

                pos = pos.top ? jQuery.extend( pos, mix ) : mix;

                pos = jQuery.extend({
                    top: '50%',
                    left: '50%'
                }, pos);

                // apply position
                jQuery( self.image ).css({
                    position : 'relative',
                    top :  getPosition(pos.top, 'height', height) - options.margin,
                    left : getPosition(pos.left, 'width', width) - options.margin
                });

                // show the image
                self.show();

                // flag ready and call the callback
                self.ready = true;
                options.complete.call( self, self );
            },
            error: function() {
                Galleria.raise('Could not scale image: '+self.image.src);
            },
            timeout: 1000
        });
        return this;
    }
};

// our own easings
jQuery.extend( jQuery.easing, {
    galleria: function (_, t, b, c, d) {
        if ((t/=d/2) < 1) {
            return c/2*t*t*t*t + b;
        }
        return -c/2 * ((t-=2)*t*t*t - 2) + b;
    },
    galleriaIn: function (_, t, b, c, d) {
    return c*(t/=d)*t*t*t + b;
  },
  galleriaOut: function (_, t, b, c, d) {
    return -c * ((t=t/d-1)*t*t*t - 1) + b;
  }
});

// the plugin initializer
jQuery.fn.galleria = function( options ) {

    return this.each(function() {

        var gallery = new Galleria();
        gallery.init( this, options );

    });
};

// expose Galleria
window.Galleria = Galleria;

// phew

})( jQuery );

/*
 * Galleria Classic Theme v. 1.5 2010-10-28
 * http://galleria.aino.se
 *
 * Copyright (c) 2010, Aino
 * Licensed under the MIT license.
 */

(function($) {

Galleria.addTheme({
    name: 'classic',
    author: 'Galleria',
    version: '1.5',
    css: '../../Content/galleria/galleria.classic.css',
    defaults: {
        transition: 'slide',
        thumb_crop: 'height',
        
		// set this to false if you want to show the caption all the time:
        _toggle_info: true
    },
    init: function(options) {
        
        // add some elements
        this.addElement('info-link','info-close');
        this.append({
            'info' : ['info-link','info-close']
        });
        
        // cache some stuff
        var toggle   = this.jQuery('image-nav-left,image-nav-right,counter'),
            info     = this.jQuery('info-link,info-close,info-text'),
            click    = Galleria.TOUCH ? 'touchstart' : 'click';
        
        // show loader & counter with opacity
        this.jQuery('loader,counter').show().css('opacity',.4)

        // some stuff for non-touch browsers
        if (! Galleria.TOUCH ) {
            
            // fade thumbnails
            this.jQuery('thumbnails').children().hover(function() {
                jQuery(this).not('.active').children().stop().fadeTo(100, 1);
            }, function() {
                jQuery(this).not('.active').children().stop().fadeTo(400, .6);
            });
            
            this.addIdleState( this.get('image-nav-left'), { left:-50 });
            this.addIdleState( this.get('image-nav-right'), { right:-50 });
            this.addIdleState( this.get('counter'), { opacity:0 });
        }
        
        // toggle info
        if ( options._toggle_info ) {
            info.bind( click, function() {
                info.toggle();
            });
        }
        
        // bind some stuff
        this.bind(Galleria.THUMBNAIL, function(e) {
            jQuery(e.thumbTarget).parent(':not(.active)').children().css('opacity',.6)
        });
        
        this.bind(Galleria.LOADSTART, function(e) {
            if (!e.cached) {
                this.jQuery('loader').show().fadeTo(200, .4);
            }
            
            this.jQuery('info').toggle( this.hasInfo() );
            
            jQuery(e.thumbTarget).css('opacity',1).parent().siblings().children().css('opacity',.6);
        });
        
        this.bind(Galleria.LOADFINISH, function(e) {
            this.jQuery('loader').fadeOut(200);
        });
    }
});

})(jQuery);


/*Yetii - Yet (E)Another Tab Interface Implementation,version 1.6,http://www.kminek.pl/lab/yetii/,Copyright (c) Grzegorz Wojcik,Code licensed under the BSD License: http://www.kminek.pl/bsdlicense.txt*/function Yetii(){this.defaults={id:null,active:1,interval:null,wait:null,persist:null,tabclass:'tab',activeclass:'active',callback:null,leavecallback:null};this.activebackup=null;for(var n in arguments[0]){this.defaults[n]=arguments[0][n]};this.getTabs=function(){var a=[];var b=document.getElementById(this.defaults.id).getElementsByTagName('*');var c=new RegExp("(^|\\s)"+this.defaults.tabclass.replace(/\-/g,"\\-")+"(\\s|$)");for(var i=0;i<b.length;i++){if(c.test(b[i].className))a.push(b[i])}return a};this.links=document.getElementById(this.defaults.id+'-nav').getElementsByTagName('a');this.listitems=document.getElementById(this.defaults.id+'-nav').getElementsByTagName('li');this.show=function(a){for(var i=0;i<this.tabs.length;i++){this.tabs[i].style.display=((i+1)==a)?'block':'none';if((i+1)==a){this.addClass(this.links[i],this.defaults.activeclass);this.addClass(this.listitems[i],this.defaults.activeclass+'li')}else{this.removeClass(this.links[i],this.defaults.activeclass);this.removeClass(this.listitems[i],this.defaults.activeclass+'li')}}if(this.defaults.leavecallback&&(a!=this.activebackup))this.defaults.leavecallback(this.defaults.active);this.activebackup=a;this.defaults.active=a;if(this.defaults.callback)this.defaults.callback(a)};this.rotate=function(a){this.show(this.defaults.active);this.defaults.active++;if(this.defaults.active>this.tabs.length)this.defaults.active=1;var b=this;if(this.defaults.wait)clearTimeout(this.timer2);this.timer1=setTimeout(function(){b.rotate(a)},a*1000)};this.next=function(){var a=(this.defaults.active+1>this.tabs.length)?1:this.defaults.active+1;this.show(a);this.defaults.active=a};this.previous=function(){var a=((this.defaults.active-1)==0)?this.tabs.length:this.defaults.active-1;this.show(a);this.defaults.active=a};this.previous=function(){this.defaults.active--;if(!this.defaults.active)this.defaults.active=this.tabs.length;this.show(this.defaults.active)};this.gup=function(a){a=a.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");var b="[\\?&]"+a+"=([^&#]*)";var c=new RegExp(b);var d=c.exec(window.location.href);if(d==null)return null;else return d[1]};this.parseurl=function(a){var b=this.gup(a);if(b==null)return null;if(parseInt(b))return parseInt(b);if(document.getElementById(b)){for(var i=0;i<this.tabs.length;i++){if(this.tabs[i].id==b)return(i+1)}}return null};this.createCookie=function(a,b,c){if(c){var d=new Date();d.setTime(d.getTime()+(c*24*60*60*1000));var e="; expires="+d.toGMTString()}else var e="";document.cookie=a+"="+b+e+"; path=/"};this.readCookie=function(a){var b=a+"=";var d=document.cookie.split(';');for(var i=0;i<d.length;i++){var c=d[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(b)==0)return c.substring(b.length,c.length)}return null};this.contains=function(a,b,c){return a.indexOf(b,c)!=-1};this.hasClass=function(a,b){return this.contains(a.className,b,' ')};this.addClass=function(a,b){if(!this.hasClass(a,b))a.className=(a.className+' '+b).replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/g,'')};this.removeClass=function(a,b){a.className=a.className.replace(new RegExp('(^|\\s)'+b+'(?:\\s|$)'),'$1');a.className.replace(/\s{2,}/g,' ').replace(/^\s+|\s+$/g,'')};this.tabs=this.getTabs();this.defaults.active=(this.parseurl(this.defaults.id))?this.parseurl(this.defaults.id):this.defaults.active;if(this.defaults.persist&&this.readCookie(this.defaults.id))this.defaults.active=this.readCookie(this.defaults.id);this.activebackup=this.defaults.active;this.show(this.defaults.active);var f=this;for(var i=0;i<this.links.length;i++){this.links[i].customindex=i+1;this.links[i].onclick=function(){if(f.timer1)clearTimeout(f.timer1);if(f.timer2)clearTimeout(f.timer2);f.show(this.customindex);if(f.defaults.persist)f.createCookie(f.defaults.id,this.customindex,0);if(f.defaults.wait)f.timer2=setTimeout(function(){f.rotate(f.defaults.interval)},f.defaults.wait*1000);return false}}if(this.defaults.interval)this.rotate(this.defaults.interval)};

/*

CUSTOM FORM ELEMENTS

Created by Ryan Fait
www.ryanfait.com

The only things you may need to change in this file are the following
variables: checkboxHeight, radioHeight and selectWidth (lines 24, 25, 26)

The numbers you set for checkboxHeight and radioHeight should be one quarter
of the total height of the image want to use for checkboxes and radio
buttons. Both images should contain the four stages of both inputs stacked
on top of each other in this order: unchecked, unchecked-clicked, checked,
checked-clicked.

You may need to adjust your images a bit if there is a slight vertical
movement during the different stages of the button activation.

The value of selectWidth should be the width of your select list image.

Visit http://ryanfait.com/ for more information.

*/

var checkboxHeight = "25";
var radioHeight = "26";
var selectWidth = "138";


/* No need to change anything after this */


document.write('<style type="text/css">input.styled { display: none; } select.styled { position: relative; width: ' + selectWidth + 'px; opacity: 0; filter: alpha(opacity=0); z-index: 5; } .disabled { opacity: 0.5; filter: alpha(opacity=50); }</style>');

var Custom = {
    init: function () {
        var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
        for (a = 0; a < inputs.length; a++) {
            if ((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
                span[a] = document.createElement("span");
                span[a].className = inputs[a].type;

                if (inputs[a].checked == true) {
                    if (inputs[a].type == "checkbox") {
                        position = "0 -" + (checkboxHeight * 2) + "px";
                        span[a].style.backgroundPosition = position;
                    } else {
                        position = "0 -" + (radioHeight * 2) + "px";
                        span[a].style.backgroundPosition = position;
                    }
                }
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);

                var oldOnChange = inputs[a].onchange;
                inputs[a].onchange = function () {
                    if (oldOnChange && typeof oldOnChange === "function") {
                        oldOnChange();
                    }
                    Custom.clear();
                };

                if (!inputs[a].getAttribute("disabled")) {
                    span[a].onmousedown = Custom.pushed;
                    span[a].onmouseup = Custom.check;
                } else {
                    span[a].className = span[a].className += " disabled";
                }
            }
        }
        inputs = document.getElementsByTagName("select");
        for (a = 0; a < inputs.length; a++) {
            if (inputs[a].className == "styled") {
                option = inputs[a].getElementsByTagName("option");
                active = option[0].childNodes[0].nodeValue;
                textnode = document.createTextNode(active);
                for (b = 0; b < option.length; b++) {
                    if (option[b].selected == true) {
                        textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
                    }
                }
                span[a] = document.createElement("span");
                span[a].className = "select";
                span[a].id = "select" + inputs[a].name;
                span[a].appendChild(textnode);
                inputs[a].parentNode.insertBefore(span[a], inputs[a]);
                if (!inputs[a].getAttribute("disabled")) {
                    var oldOnChange = inputs[a].onchange;
                    inputs[a].onchange = function () {
                        if (oldOnChange && typeof oldOnChange === "function") {
                            oldOnChange();
                        }
                        Custom.choose(this);
                    };
                } else {
                    inputs[a].previousSibling.className = inputs[a].previousSibling.className += " disabled";
                }
            }
        }
        document.onmouseup = Custom.clear;
    },
    pushed: function () {
        element = this.nextSibling;
        if (element.checked == true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + checkboxHeight * 3 + "px";
        } else if (element.checked == true && element.type == "radio") {
            this.style.backgroundPosition = "0 -" + radioHeight * 3 + "px";
        } else if (element.checked != true && element.type == "checkbox") {
            this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
        } else {
            this.style.backgroundPosition = "0 -" + radioHeight + "px";
        }
    },
    check: function (tag) {
        var spanElement = null;
        var element;
        if (tag && typeof tag != "undefined" && tag.type != "mouseup") {
            element = tag;

            while (element && (!element.tagName || element.tagName.toLowerCase() != "input")) {
                if (element.tagName && element.tagName.toLowerCase() == "span")
                    spanElement = element;
                element = element.nextSibling;
            }

            if (!element) {
                return;
            }
        }
        else {
            element = this.nextSibling;
            spanElement = this;
        }

        if (spanElement) {
            if (element.checked == true && element.type == "checkbox") {
                spanElement.style.backgroundPosition = "0 0";
                element.checked = false;
            } else {
                if (element.type == "checkbox") {
                    spanElement.style.backgroundPosition = "0 -" + checkboxHeight * 2 + "px";
                } else {
                    spanElement.style.backgroundPosition = "0 -" + radioHeight * 2 + "px";
                    var group = element.name;
                    var inputs = document.getElementsByTagName("input");
                    for (var a = 0; a < inputs.length; a++) {
                        if (inputs[a].name == group && inputs[a] != element) {
                            inputs[a].previousSibling.style.backgroundPosition = "0 0";
                        }
                    }
                }
                element.checked = true;
            }
        }
    },
    clear: function () {
        inputs = document.getElementsByTagName("input");
        for (var b = 0; b < inputs.length; b++) {
            if (inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight * 2 + "px";
            } else if (inputs[b].type == "checkbox" && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 0";
            } else if (inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight * 2 + "px";
            } else if (inputs[b].type == "radio" && inputs[b].className == "styled") {
                inputs[b].previousSibling.style.backgroundPosition = "0 0";
            }
        }
    },
    choose: function (tag) {
        option = tag.getElementsByTagName("option");
        for (d = 0; d < option.length; d++) {
            if (option[d].selected == true) {
                document.getElementById("select" + tag.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
            }
        }
    }
}
window.onload = Custom.init;

(function ($) {

    var DropList = function (el, settings, callback) {

        var self = this;

        //SETTINGS
        settings = settings || {};
        settings.direction = settings.direction || 'auto';

        // PRIVATE METHODS

        function setText(str) {
            self.option.html(str);
        }

        function customScroll() {
            var h1 = settings.height || 150,
				h2 = self.listWrapper.height();
            if (h2 > h1) {
                self.list.css('height', h1 + 'px').jScrollPane({ showArrows: false });
            }
        }

        function layout() {
            self.listWrapper.css('width', (self.obj.width - (self.listWrapper.outerWidth(true) - self.listWrapper.width())) + 'px');
            self.option.css('width', (self.obj.width - self.drop.width() - self.option.outerWidth(true)) + 'px');
        }

        var options2list = function (data) {
            var output = '<ul>';
            data.each(function () {
                var selected = jQuery(this).attr('selected') ? 'selected' : '';
                output += '<li class="' + selected + '"><a href="' + jQuery(this).val() + '">' + jQuery(this).text() + '</a></li>\t';
            });
            output += '</ul>';
            return output;
        };


        /* PUBLIC METHODS */

        self.open = function () {

            // just show
            self.listWrapper.show();
            self.wrapper.addClass('droplist-active');

            // auto direction
            if (settings.direction === 'auto') {
                var distanceFromBottom = (self.select.height() + self.wrapper.offset().top - jQuery(document).scrollTop() - jQuery(window).height()) * -1,
					objHeight = self.select.height() + self.listWrapper.height();
                if (distanceFromBottom < objHeight) {
                    self.wrapper.addClass('droplist-up');
                } else {
                    self.wrapper.removeClass('droplist-up');
                }
            } else if (settings.direction === 'up') {
                self.wrapper.addClass('droplist-up');
            }

            // events (clickout / ESC key / type-ahead)
            self.listItems = self.list.find('li');
            self.typedKeys = '';

            jQuery('html').bind('click', function (e) {

                // clickout
                if (jQuery(e.target).closest('.droplist').length === 0) {
                    self.close();
                }

            }).bind('keyup', function (e) {

                if (e === null) { // ie
                    keycode = event.keyCode;
                }
                else { // mozilla
                    keycode = e.which;
                }

                // esc
                if (keycode == 27) {
                    self.close();
                }

                // type-ahead support
                else if ((keycode >= 0x30 && keycode <= 0x7a)) {
                    self.typedKeys += '' + String.fromCharCode(keycode);
                    clearTimeout(self.typeDelay);
                    self.typeDelay = setTimeout(function () {
                        self.listItems.each(function () {
                            if (jQuery(this).find('>a').text().toUpperCase().indexOf(self.typedKeys) === 0) {
                                self.set(jQuery(this));
                                return false;
                            }
                        });
                        self.typedKeys = '';
                    }, 400);
                }

            });

            if (self.inputHidden) {
                self.inputHidden.trigger('droplistopen', self);
            }
            else {
                self.obj.trigger('droplistopen', self);
            }
        };

        self.close = function () {
            self.listWrapper.hide();
            self.wrapper.removeClass('droplist-active');
            jQuery('html').unbind('click').unbind('keyup');

            if (self.inputHidden) {
                self.inputHidden.trigger('droplistclose', self);
            }
            else {
                self.obj.trigger('droplistclose', self);
            }
        };

        self.set = function (el) {

            var str = jQuery(el).find('>a').text();
            setText(str);
            self.list.find('li').removeClass('selected').filter(el).addClass('selected');

            if (self.inputHidden.length > 0) {
                var val = el.find('a').attr('href');
                self.inputHidden.attr('value', val);
            }

            self.close();
            if (self.inputHidden) {
                self.inputHidden.trigger('droplistchange', self);
            }
            else {
                self.obj.trigger('droplistchange', self);
            }
        };

        self.get = function () {
            return self.list.find('.selected:first a').attr('href');
        };

        self.tabs = function () {
            var that = this;
            that.list.find('li').bind('click', function () {
                that.set(this);
                var id = jQuery(this).find('a').attr('href');
                jQuery(id).removeClass('hide').show().siblings().hide();
                return false;
            });
        };


        // CONTROLLER

        self.obj = jQuery(el);
        self.obj.css('border', 'none');

        self.obj.className = self.obj.attr('class');
        self.obj.name = self.obj.attr('name');
        self.obj.width = self.obj.width();
        self.obj.title = self.obj.attr('title');

        var isInsideForm = false;

        // insert wrapper
        var wrapperHtml = '<div class="' + self.obj.className + '"><div class="droplist-list"></div></div>';

        // get elements
        self.wrapper = self.obj.removeAttr('class').wrap(wrapperHtml).parent().parent();
        self.listWrapper = self.wrapper.find('.droplist-list:first');
        self.list = self.listWrapper.find('ul:first');

        // if it is a select tag
        if (self.list.length === 0) {
            isInsideForm = true;
            var html = '',
				optgroups = self.listWrapper.find('select:first optgroup'),
				options;
            if (optgroups.length > 0) {
                html += '<ul>';
                optgroups.each(function () {
                    options = jQuery(this).find('option');
                    html += '<li><strong>' + jQuery(this).attr('label') + '</strong>' + options2list(options) + '</li>';
                });
                html += '</ul>';
            } else {
                options = self.listWrapper.find('select:first option');
                html += options2list(options);
            }
            self.listWrapper.html(html);
            self.list = self.listWrapper.find('ul:first');
        }

        // insert HTML into the wrapper
        self.wrapper.prepend('<div class="droplist-value"><a href="#nogo"></a><div></div></div>');

        // input hidden
        if (isInsideForm) {
            self.wrapper.append('<input type="hidden" name="' + self.obj.name + '" id="' + self.obj.attr('id') + '" value="" />');
        }

        /* GET ELEMENTS */
        self.select = self.wrapper.find('.droplist-value:first');
        self.option = self.select.find('div:first');
        self.drop = self.select.find('a:first');
        self.inputHidden = self.wrapper.find('input[type=hidden]:first');

        // EVENTS

        // clicking on select
        self.select.bind('click', function () {
            if (self.listWrapper.is(':hidden')) {
                self.open();
            } else {
                self.close();
            }
        });

        // clicking on an option inside a form
        if (isInsideForm) {
            self.list.find('a').bind('click', function () {
                var parent = jQuery(this).parent();
                self.set(parent);
                return false;
            });
        }

        // ADJUST LAYOUT (WIDTHS)
        layout();

        // CUSTOM SCROLL
        if (settings.customScroll) { customScroll(); }

        // INITIAL STATE

        self.close();

        // set selected
        var selectedItem = self.list.find('.selected:first');
        if (selectedItem.length === 1) { self.set(selectedItem); }
        else { self.set(self.list.find('li:first')); }

        // title
        if (self.obj.title !== '') { setText(self.obj.title); }

        // CALLBACK
        if (typeof callback == 'function') { callback.apply(self); }

    };

    // extend jQuery
    jQuery.fn.droplist = function (settings, callback) {
        return this.each(function () {
            var obj = jQuery(this);
            if (obj.data('droplist')) return; // return early if this obj already has a plugin instance
            var instance = new DropList(this, settings, callback);
            obj.data('droplist', instance);
        });
    };

})(jQuery);

/**
* jQuery Simple Dialog Plugin
*   http://code.google.com/p/jquery-simpledialog/
*
* Copyright (c) 2009 Yusuke Horie
*
* Released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
* Since  : 0.01 - 07/06/2009
* Version: 0.11 - 08/08/2009
*/
(function (jQuery) {

    // Private Variables

    var 
    _doc = null,
    _win = null,
    _docHeight = 0,
    _winHeight = 0,
    _winWidth = 0,
    _t = null,
    _event = null,
    _target = null,
    _escapedContent = '',
    _title = '',
    _caption = '',
    _container = null,
    _content = null;

    // Public Methods

    jQuery.fn.simpleDialog = function (options) {
        var opts = jQuery.extend({}, jQuery.fn.simpleDialog.defaults, options);

        return this.each(function (i, e) {
            var $this = jQuery(e);
            var triggerEvent = ($this.is('form')) ? 'submit' : 'click';

            $this
        .bind(triggerEvent + '.simpledialog', function (event) {
            event.preventDefault();

            _t = this;
            _t.opts = opts;
            _event = event;

            _initialize();

            // show overlay
            _prepare();

            var $t = jQuery(this);

            if (_t.opts.title != '')
                _title = _t.opts.title;

            if ($t.is('a')) {
                if (_t.opts.useTitleAttr) {
                    var title = $t.attr('title');
                    if (typeof title != 'undefined' && title != '')
                        _title = title;
                }

                var href = $t.attr('href');
                var c = jQuery('#' + $t.attr('rel'));
                if (c.length > 0)
                {
                    _target = c;
                    _escapedContent = _target.clone().html();
                    _target.empty();
                    _show(_escapedContent);
                } else if ($t.find('img').length > 0) {
                    if (_t.opts.showCaption)
                        _caption = $t.find('img').attr('title');
                    _load(href);
                } else {
                    _request(href, {});
                }
            } else if ($t.is(':submit', ':button')) {
                var f = $t.parents('form');
                _request(f.attr('action'), f.serialize(), f.attr('method'));
            } else if ($t.is('form')) {
                _request($t.attr('action'), $t.serialize(), $t.attr('method'));
            } else {
                jQuery.simpleDialog.close(event);
            }
            return false;
        });
        });
    };

    jQuery.fn.simpleDialog.defaults = {
        title: '',
        useTitleAttr: true,
        containerId: 'sd_container',
        containerClass: 'sd_container',
        overlayId: 'sd_overlay',
        overlayClass: 'sd_overlay',
        loadingClass: 'sd_loading',
        closeLabelClass: 'sd_closelabel',
        showCloseLabel: true,
        closeLabel: 'close &times;',
        opacity: 0.6,
        duration: 400,
        easing: 'linear',
        zIndex: 1000,
        width: null,
        height: null,
        showCaption: true,
        open: null,
        close: null,
        closeSelector: '.close'
    };

    jQuery.simpleDialog = {
        close: function (event) {
            if (jQuery.isFunction(_t.opts.close))
                _t.opts.close.apply(this, [(typeof event == 'undefined') ? null : event, _t]);
            if (_container != null)
                _container.remove();
            if (_target != null)
                _target.html(_escapedContent);
            jQuery('#' + _t.opts.overlayId).remove();
            return false;
        }
    };

    // Private Methods

    var _initialize = function () {
        _doc = jQuery(document);
        _win = jQuery(window);
        _docHeight = _doc.height();
        _winHeight = _win.height();
        _winWidth = _win.width();
        _title = '';
        _caption = '';
    };

    var _show = function (content) {
        var body = '';

        if (_title != '')
            body += '<div class="sd_header">' + _title + '</div>';

        body += '<div class="sd_content">' + content + '</div>';

        if (_caption != '' && typeof _caption != 'undefined')
            body += ' <div class="sd_footer">' + _caption + '</div>';

        var tmp = jQuery('<div />')
      .addClass(_t.opts.containerClass)
      .hide()
      .css({
          position: 'absolute',
          height: 'auto'
      })
      .html(body)
      .appendTo(document.body);

        var w = (_t.opts.width) ? parseInt(_t.opts.width) : tmp.width();
        var h = (_t.opts.height) ? parseInt(_t.opts.height) : tmp.height();
        tmp.remove();
        var pos = _center(w, h);

        _container
      .removeClass(_t.opts.loadingClass)
      .animate({
          width: w + 'px',
          height: h + 'px',
          left: pos[0] + 'px',
          top: pos[1] + 'px'
      }, _t.opts.duration, _t.opts.easing, function () {
          _container
          .html(body)
          .find(_t.opts.closeSelector)
          .bind('click.simpledialog', jQuery.simpleDialog.close);

          if (_t.opts.showCloseLabel) {
              var sc = '<div id="sd_closelabel" class="' + _t.opts.closeLabelClass + '">' +
            '<a href="#">' + _t.opts.closeLabel + '</a></div>';

              _container.hover(
            function () {
                jQuery(this).append(sc);
                var scObj = jQuery('#sd_closelabel');
                scObj
                .css({
                    position: 'absolute',
                    top: 0,
                    left: (w - scObj.width()) + 'px',
                    opacity: 0.85
                })
                .find('a').click(jQuery.simpleDialog.close);
            },
            function () { jQuery('#sd_closelabel').remove() });
          }

          if (jQuery.isFunction(_t.opts.open))
              _t.opts.open.apply(_container, [_event, _t]);
      });
    };

    var _request = function (url, data, method) {
        jQuery.ajax({
            type: (typeof method == 'undefined') ? 'GET' : method,
            url: url,
            data: data,
            dataType: 'html',
            success: _show
        });
    };

    var _load = function (url) {
        jQuery(document.body)
      .append('<div id="sd_tmp_image" style="display:none;"><img src="' + url + '" alt="" /></div>');

        var tmp = jQuery('#sd_tmp_image');
        tmp.find('img')
      .load(function () {
          var h = tmp.html();
          tmp.remove();
          _show(h);
      })
      .error(function (e) {
          jQuery.simpleDialog.close(e);
          tmp.remove();
      });
    };

    var _prepare = function () {

        // overlay
        jQuery('<div />')
      .attr('id', _t.opts.overlayId)
      .addClass(_t.opts.overlayClass)
      .css({
          position: 'absolute',
          width: _winWidth,
          height: _docHeight,
          opacity: _t.opts.opacity,
          zIndex: _t.opts.zIndex
      })
      .bind('click.simpledialog', jQuery.simpleDialog.close)
      .appendTo(document.body);

        // container
        _container = jQuery('<div />')
      .attr('id', _t.opts.containerId)
      .addClass(_t.opts.loadingClass)
      .addClass(_t.opts.containerClass)
      .hide()
      .appendTo(document.body);

        var w = _container.width();
        var h = _container.height();
        var pos = _center(w, h);

        _container
      .css({
          position: 'absolute',
          left: pos[0] + 'px',
          top: pos[1] + 'px',
          width: w + 'px',
          height: h + 'px',
          zIndex: _t.opts.zIndex + 1000
      })
      .show();
    };

    var _center = function (w, h) {
        return [(_docHeight > _winHeight) ? _winWidth / 2 - w / 2 - 18 : _winWidth / 2 - w / 2,
      _doc.scrollTop() + _winHeight / 2 - h / 2];
    };

})(jQuery);


/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.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.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function(g){var q={vertical:!1,rtl:!1,start:1,offset:1,size:null,scroll:3,visible:null,animation:"normal",easing:"swing",auto:0,wrap:null,initCallback:null,setupCallback:null,reloadCallback:null,itemLoadCallback:null,itemFirstInCallback:null,itemFirstOutCallback:null,itemLastInCallback:null,itemLastOutCallback:null,itemVisibleInCallback:null,itemVisibleOutCallback:null,animationStepCallback:null,buttonNextHTML:"<div></div>",buttonPrevHTML:"<div></div>",buttonNextEvent:"click",buttonPrevEvent:"click", buttonNextCallback:null,buttonPrevCallback:null,itemFallbackDimension:null},m=!1;g(window).bind("load.jcarousel",function(){m=!0});g.jcarousel=function(a,c){this.options=g.extend({},q,c||{});this.autoStopped=this.locked=!1;this.buttonPrevState=this.buttonNextState=this.buttonPrev=this.buttonNext=this.list=this.clip=this.container=null;if(!c||c.rtl===void 0)this.options.rtl=(g(a).attr("dir")||g("html").attr("dir")||"").toLowerCase()=="rtl";this.wh=!this.options.vertical?"width":"height";this.lt=!this.options.vertical? this.options.rtl?"right":"left":"top";for(var b="",d=a.className.split(" "),f=0;f<d.length;f++)if(d[f].indexOf("jcarousel-skin")!=-1){g(a).removeClass(d[f]);b=d[f];break}a.nodeName.toUpperCase()=="UL"||a.nodeName.toUpperCase()=="OL"?(this.list=g(a),this.clip=this.list.parents(".jcarousel-clip"),this.container=this.list.parents(".jcarousel-container")):(this.container=g(a),this.list=this.container.find("ul,ol").eq(0),this.clip=this.container.find(".jcarousel-clip"));if(this.clip.size()===0)this.clip= this.list.wrap("<div></div>").parent();if(this.container.size()===0)this.container=this.clip.wrap("<div></div>").parent();b!==""&&this.container.parent()[0].className.indexOf("jcarousel-skin")==-1&&this.container.wrap('<div class=" '+b+'"></div>');this.buttonPrev=g(".jcarousel-prev",this.container);if(this.buttonPrev.size()===0&&this.options.buttonPrevHTML!==null)this.buttonPrev=g(this.options.buttonPrevHTML).appendTo(this.container);this.buttonPrev.addClass(this.className("jcarousel-prev"));this.buttonNext= g(".jcarousel-next",this.container);if(this.buttonNext.size()===0&&this.options.buttonNextHTML!==null)this.buttonNext=g(this.options.buttonNextHTML).appendTo(this.container);this.buttonNext.addClass(this.className("jcarousel-next"));this.clip.addClass(this.className("jcarousel-clip")).css({position:"relative"});this.list.addClass(this.className("jcarousel-list")).css({overflow:"hidden",position:"relative",top:0,margin:0,padding:0}).css(this.options.rtl?"right":"left",0);this.container.addClass(this.className("jcarousel-container")).css({position:"relative"}); !this.options.vertical&&this.options.rtl&&this.container.addClass("jcarousel-direction-rtl").attr("dir","rtl");var j=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible):null,b=this.list.children("li"),e=this;if(b.size()>0){var h=0,i=this.options.offset;b.each(function(){e.format(this,i++);h+=e.dimension(this,j)});this.list.css(this.wh,h+100+"px");if(!c||c.size===void 0)this.options.size=b.size()}this.container.css("display","block");this.buttonNext.css("display","block");this.buttonPrev.css("display", "block");this.funcNext=function(){e.next()};this.funcPrev=function(){e.prev()};this.funcResize=function(){e.resizeTimer&&clearTimeout(e.resizeTimer);e.resizeTimer=setTimeout(function(){e.reload()},100)};this.options.initCallback!==null&&this.options.initCallback(this,"init");!m&&g.browser.safari?(this.buttons(!1,!1),g(window).bind("load.jcarousel",function(){e.setup()})):this.setup()};var f=g.jcarousel;f.fn=f.prototype={jcarousel:"0.2.8"};f.fn.extend=f.extend=g.extend;f.fn.extend({setup:function(){this.prevLast= this.prevFirst=this.last=this.first=null;this.animating=!1;this.tail=this.resizeTimer=this.timer=null;this.inTail=!1;if(!this.locked){this.list.css(this.lt,this.pos(this.options.offset)+"px");var a=this.pos(this.options.start,!0);this.prevFirst=this.prevLast=null;this.animate(a,!1);g(window).unbind("resize.jcarousel",this.funcResize).bind("resize.jcarousel",this.funcResize);this.options.setupCallback!==null&&this.options.setupCallback(this)}},reset:function(){this.list.empty();this.list.css(this.lt, "0px");this.list.css(this.wh,"10px");this.options.initCallback!==null&&this.options.initCallback(this,"reset");this.setup()},reload:function(){this.tail!==null&&this.inTail&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+this.tail);this.tail=null;this.inTail=!1;this.options.reloadCallback!==null&&this.options.reloadCallback(this);if(this.options.visible!==null){var a=this,c=Math.ceil(this.clipping()/this.options.visible),b=0,d=0;this.list.children("li").each(function(f){b+=a.dimension(this, c);f+1<a.first&&(d=b)});this.list.css(this.wh,b+"px");this.list.css(this.lt,-d+"px")}this.scroll(this.first,!1)},lock:function(){this.locked=!0;this.buttons()},unlock:function(){this.locked=!1;this.buttons()},size:function(a){if(a!==void 0)this.options.size=a,this.locked||this.buttons();return this.options.size},has:function(a,c){if(c===void 0||!c)c=a;if(this.options.size!==null&&c>this.options.size)c=this.options.size;for(var b=a;b<=c;b++){var d=this.get(b);if(!d.length||d.hasClass("jcarousel-item-placeholder"))return!1}return!0}, get:function(a){return g(">.jcarousel-item-"+a,this.list)},add:function(a,c){var b=this.get(a),d=0,p=g(c);if(b.length===0)for(var j,e=f.intval(a),b=this.create(a);;){if(j=this.get(--e),e<=0||j.length){e<=0?this.list.prepend(b):j.after(b);break}}else d=this.dimension(b);p.get(0).nodeName.toUpperCase()=="LI"?(b.replaceWith(p),b=p):b.empty().append(c);this.format(b.removeClass(this.className("jcarousel-item-placeholder")),a);p=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible): null;d=this.dimension(b,p)-d;a>0&&a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))-d+"px");this.list.css(this.wh,f.intval(this.list.css(this.wh))+d+"px");return b},remove:function(a){var c=this.get(a);if(c.length&&!(a>=this.first&&a<=this.last)){var b=this.dimension(c);a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+b+"px");c.remove();this.list.css(this.wh,f.intval(this.list.css(this.wh))-b+"px")}},next:function(){this.tail!==null&&!this.inTail?this.scrollTail(!1): this.scroll((this.options.wrap=="both"||this.options.wrap=="last")&&this.options.size!==null&&this.last==this.options.size?1:this.first+this.options.scroll)},prev:function(){this.tail!==null&&this.inTail?this.scrollTail(!0):this.scroll((this.options.wrap=="both"||this.options.wrap=="first")&&this.options.size!==null&&this.first==1?this.options.size:this.first-this.options.scroll)},scrollTail:function(a){if(!this.locked&&!this.animating&&this.tail){this.pauseAuto();var c=f.intval(this.list.css(this.lt)), c=!a?c-this.tail:c+this.tail;this.inTail=!a;this.prevFirst=this.first;this.prevLast=this.last;this.animate(c)}},scroll:function(a,c){!this.locked&&!this.animating&&(this.pauseAuto(),this.animate(this.pos(a),c))},pos:function(a,c){var b=f.intval(this.list.css(this.lt));if(this.locked||this.animating)return b;this.options.wrap!="circular"&&(a=a<1?1:this.options.size&&a>this.options.size?this.options.size:a);for(var d=this.first>a,g=this.options.wrap!="circular"&&this.first<=1?1:this.first,j=d?this.get(g): this.get(this.last),e=d?g:g-1,h=null,i=0,k=!1,l=0;d?--e>=a:++e<a;){h=this.get(e);k=!h.length;if(h.length===0&&(h=this.create(e).addClass(this.className("jcarousel-item-placeholder")),j[d?"before":"after"](h),this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size)))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)));j=h;l=this.dimension(h);k&&(i+=l);if(this.first!==null&&(this.options.wrap=="circular"||e>=1&&(this.options.size===null||e<= this.options.size)))b=d?b+l:b-l}for(var g=this.clipping(),m=[],o=0,n=0,j=this.get(a-1),e=a;++o;){h=this.get(e);k=!h.length;if(h.length===0){h=this.create(e).addClass(this.className("jcarousel-item-placeholder"));if(j.length===0)this.list.prepend(h);else j[d?"before":"after"](h);if(this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)))}j=h;l=this.dimension(h);if(l===0)throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."); this.options.wrap!="circular"&&this.options.size!==null&&e>this.options.size?m.push(h):k&&(i+=l);n+=l;if(n>=g)break;e++}for(h=0;h<m.length;h++)m[h].remove();i>0&&(this.list.css(this.wh,this.dimension(this.list)+i+"px"),d&&(b-=i,this.list.css(this.lt,f.intval(this.list.css(this.lt))-i+"px")));i=a+o-1;if(this.options.wrap!="circular"&&this.options.size&&i>this.options.size)i=this.options.size;if(e>i){o=0;e=i;for(n=0;++o;){h=this.get(e--);if(!h.length)break;n+=this.dimension(h);if(n>=g)break}}e=i-o+ 1;this.options.wrap!="circular"&&e<1&&(e=1);if(this.inTail&&d)b+=this.tail,this.inTail=!1;this.tail=null;if(this.options.wrap!="circular"&&i==this.options.size&&i-o+1>=1&&(d=f.intval(this.get(i).css(!this.options.vertical?"marginRight":"marginBottom")),n-d>g))this.tail=n-g-d;if(c&&a===this.options.size&&this.tail)b-=this.tail,this.inTail=!0;for(;a-- >e;)b+=this.dimension(this.get(a));this.prevFirst=this.first;this.prevLast=this.last;this.first=e;this.last=i;return b},animate:function(a,c){if(!this.locked&& !this.animating){this.animating=!0;var b=this,d=function(){b.animating=!1;a===0&&b.list.css(b.lt,0);!b.autoStopped&&(b.options.wrap=="circular"||b.options.wrap=="both"||b.options.wrap=="last"||b.options.size===null||b.last<b.options.size||b.last==b.options.size&&b.tail!==null&&!b.inTail)&&b.startAuto();b.buttons();b.notify("onAfterAnimation");if(b.options.wrap=="circular"&&b.options.size!==null)for(var c=b.prevFirst;c<=b.prevLast;c++)c!==null&&!(c>=b.first&&c<=b.last)&&(c<1||c>b.options.size)&&b.remove(c)}; this.notify("onBeforeAnimation");if(!this.options.animation||c===!1)this.list.css(this.lt,a+"px"),d();else{var f=!this.options.vertical?this.options.rtl?{right:a}:{left:a}:{top:a},d={duration:this.options.animation,easing:this.options.easing,complete:d};if(g.isFunction(this.options.animationStepCallback))d.step=this.options.animationStepCallback;this.list.animate(f,d)}}},startAuto:function(a){if(a!==void 0)this.options.auto=a;if(this.options.auto===0)return this.stopAuto();if(this.timer===null){this.autoStopped= !1;var c=this;this.timer=window.setTimeout(function(){c.next()},this.options.auto*1E3)}},stopAuto:function(){this.pauseAuto();this.autoStopped=!0},pauseAuto:function(){if(this.timer!==null)window.clearTimeout(this.timer),this.timer=null},buttons:function(a,c){if(a==null&&(a=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="first"||this.options.size===null||this.last<this.options.size),!this.locked&&(!this.options.wrap||this.options.wrap=="first")&&this.options.size!==null&& this.last>=this.options.size))a=this.tail!==null&&!this.inTail;if(c==null&&(c=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="last"||this.first>1),!this.locked&&(!this.options.wrap||this.options.wrap=="last")&&this.options.size!==null&&this.first==1))c=this.tail!==null&&this.inTail;var b=this;this.buttonNext.size()>0?(this.buttonNext.unbind(this.options.buttonNextEvent+".jcarousel",this.funcNext),a&&this.buttonNext.bind(this.options.buttonNextEvent+".jcarousel",this.funcNext), this.buttonNext[a?"removeClass":"addClass"](this.className("jcarousel-next-disabled")).attr("disabled",a?!1:!0),this.options.buttonNextCallback!==null&&this.buttonNext.data("jcarouselstate")!=a&&this.buttonNext.each(function(){b.options.buttonNextCallback(b,this,a)}).data("jcarouselstate",a)):this.options.buttonNextCallback!==null&&this.buttonNextState!=a&&this.options.buttonNextCallback(b,null,a);this.buttonPrev.size()>0?(this.buttonPrev.unbind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev), c&&this.buttonPrev.bind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev),this.buttonPrev[c?"removeClass":"addClass"](this.className("jcarousel-prev-disabled")).attr("disabled",c?!1:!0),this.options.buttonPrevCallback!==null&&this.buttonPrev.data("jcarouselstate")!=c&&this.buttonPrev.each(function(){b.options.buttonPrevCallback(b,this,c)}).data("jcarouselstate",c)):this.options.buttonPrevCallback!==null&&this.buttonPrevState!=c&&this.options.buttonPrevCallback(b,null,c);this.buttonNextState= a;this.buttonPrevState=c},notify:function(a){var c=this.prevFirst===null?"init":this.prevFirst<this.first?"next":"prev";this.callback("itemLoadCallback",a,c);this.prevFirst!==this.first&&(this.callback("itemFirstInCallback",a,c,this.first),this.callback("itemFirstOutCallback",a,c,this.prevFirst));this.prevLast!==this.last&&(this.callback("itemLastInCallback",a,c,this.last),this.callback("itemLastOutCallback",a,c,this.prevLast));this.callback("itemVisibleInCallback",a,c,this.first,this.last,this.prevFirst, this.prevLast);this.callback("itemVisibleOutCallback",a,c,this.prevFirst,this.prevLast,this.first,this.last)},callback:function(a,c,b,d,f,j,e){if(!(this.options[a]==null||typeof this.options[a]!="object"&&c!="onAfterAnimation")){var h=typeof this.options[a]=="object"?this.options[a][c]:this.options[a];if(g.isFunction(h)){var i=this;if(d===void 0)h(i,b,c);else if(f===void 0)this.get(d).each(function(){h(i,this,d,b,c)});else for(var a=function(a){i.get(a).each(function(){h(i,this,a,b,c)})},k=d;k<=f;k++)k!== null&&!(k>=j&&k<=e)&&a(k)}}},create:function(a){return this.format("<li></li>",a)},format:function(a,c){for(var a=g(a),b=a.get(0).className.split(" "),d=0;d<b.length;d++)b[d].indexOf("jcarousel-")!=-1&&a.removeClass(b[d]);a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-"+c)).css({"float":this.options.rtl?"right":"left","list-style":"none"}).attr("jcarouselindex",c);return a},className:function(a){return a+" "+a+(!this.options.vertical?"-horizontal":"-vertical")}, dimension:function(a,c){var b=g(a);if(c==null)return!this.options.vertical?b.outerWidth(!0)||f.intval(this.options.itemFallbackDimension):b.outerHeight(!0)||f.intval(this.options.itemFallbackDimension);else{var d=!this.options.vertical?c-f.intval(b.css("marginLeft"))-f.intval(b.css("marginRight")):c-f.intval(b.css("marginTop"))-f.intval(b.css("marginBottom"));g(b).css(this.wh,d+"px");return this.dimension(b)}},clipping:function(){return!this.options.vertical?this.clip[0].offsetWidth-f.intval(this.clip.css("borderLeftWidth"))- f.intval(this.clip.css("borderRightWidth")):this.clip[0].offsetHeight-f.intval(this.clip.css("borderTopWidth"))-f.intval(this.clip.css("borderBottomWidth"))},index:function(a,c){if(c==null)c=this.options.size;return Math.round(((a-1)/c-Math.floor((a-1)/c))*c)+1}});f.extend({defaults:function(a){return g.extend(q,a||{})},intval:function(a){a=parseInt(a,10);return isNaN(a)?0:a},windowLoaded:function(){m=!0}});g.fn.jcarousel=function(a){if(typeof a=="string"){var c=g(this).data("jcarousel"),b=Array.prototype.slice.call(arguments, 1);return c[a].apply(c,b)}else return this.each(function(){var b=g(this).data("jcarousel");b?(a&&g.extend(b.options,a),b.reload()):g(this).data("jcarousel",new f(this,a))})}})(jQuery);


/*
 * jQuery Cycle Plugin (core engine)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version: 2.88 (08-JUN-2010)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.2.6 or later
 */
(function($){var ver="2.88";if($.support==undefined){$.support={opacity:!($.browser.msie)};}function debug(s){if($.fn.cycle.debug){log(s);}}function log(){if(window.console&&window.console.log){window.console.log("[cycle] "+Array.prototype.join.call(arguments," "));}}$.fn.cycle=function(options,arg2){var o={s:this.selector,c:this.context};if(this.length===0&&options!="stop"){if(!$.isReady&&o.s){log("DOM not ready, queuing slideshow");$(function(){$(o.s,o.c).cycle(options,arg2);});return this;}log("terminating; zero elements found by selector"+($.isReady?"":" (DOM not ready)"));return this;}return this.each(function(){var opts=handleArguments(this,options,arg2);if(opts===false){return;}opts.updateActivePagerLink=opts.updateActivePagerLink||$.fn.cycle.updateActivePagerLink;if(this.cycleTimeout){clearTimeout(this.cycleTimeout);}this.cycleTimeout=this.cyclePause=0;var $cont=$(this);var $slides=opts.slideExpr?$(opts.slideExpr,this):$cont.children();var els=$slides.get();if(els.length<2){log("terminating; too few slides: "+els.length);return;}var opts2=buildOptions($cont,$slides,els,opts,o);if(opts2===false){return;}var startTime=opts2.continuous?10:getTimeout(els[opts2.currSlide],els[opts2.nextSlide],opts2,!opts2.rev);if(startTime){startTime+=(opts2.delay||0);if(startTime<10){startTime=10;}debug("first timeout: "+startTime);this.cycleTimeout=setTimeout(function(){go(els,opts2,0,(!opts2.rev&&!opts.backwards));},startTime);}});};function handleArguments(cont,options,arg2){if(cont.cycleStop==undefined){cont.cycleStop=0;}if(options===undefined||options===null){options={};}if(options.constructor==String){switch(options){case"destroy":case"stop":var opts=$(cont).data("cycle.opts");if(!opts){return false;}cont.cycleStop++;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);}cont.cycleTimeout=0;$(cont).removeData("cycle.opts");if(options=="destroy"){destroy(opts);}return false;case"toggle":cont.cyclePause=(cont.cyclePause===1)?0:1;checkInstantResume(cont.cyclePause,arg2,cont);return false;case"pause":cont.cyclePause=1;return false;case"resume":cont.cyclePause=0;checkInstantResume(false,arg2,cont);return false;case"prev":case"next":var opts=$(cont).data("cycle.opts");if(!opts){log('options not found, "prev/next" ignored');return false;}$.fn.cycle[options](opts);return false;default:options={fx:options};}return options;}else{if(options.constructor==Number){var num=options;options=$(cont).data("cycle.opts");if(!options){log("options not found, can not advance slide");return false;}if(num<0||num>=options.elements.length){log("invalid slide index: "+num);return false;}options.nextSlide=num;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}if(typeof arg2=="string"){options.oneTimeFx=arg2;}go(options.elements,options,1,num>=options.currSlide);return false;}}return options;function checkInstantResume(isPaused,arg2,cont){if(!isPaused&&arg2===true){var options=$(cont).data("cycle.opts");if(!options){log("options not found, can not resume");return false;}if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}go(options.elements,options,1,(!opts.rev&&!opts.backwards));}}}function removeFilter(el,opts){if(!$.support.opacity&&opts.cleartype&&el.style.filter){try{el.style.removeAttribute("filter");}catch(smother){}}}function destroy(opts){if(opts.next){$(opts.next).unbind(opts.prevNextEvent);}if(opts.prev){$(opts.prev).unbind(opts.prevNextEvent);}if(opts.pager||opts.pagerAnchorBuilder){$.each(opts.pagerAnchors||[],function(){this.unbind().remove();});}opts.pagerAnchors=null;if(opts.destroy){opts.destroy(opts);}}function buildOptions($cont,$slides,els,options,o){var opts=$.extend({},$.fn.cycle.defaults,options||{},$.metadata?$cont.metadata():$.meta?$cont.data():{});if(opts.autostop){opts.countdown=opts.autostopCount||els.length;}var cont=$cont[0];$cont.data("cycle.opts",opts);opts.$cont=$cont;opts.stopCount=cont.cycleStop;opts.elements=els;opts.before=opts.before?[opts.before]:[];opts.after=opts.after?[opts.after]:[];opts.after.unshift(function(){opts.busy=0;});if(!$.support.opacity&&opts.cleartype){opts.after.push(function(){removeFilter(this,opts);});}if(opts.continuous){opts.after.push(function(){go(els,opts,0,(!opts.rev&&!opts.backwards));});}saveOriginalOpts(opts);if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($slides);}if($cont.css("position")=="static"){$cont.css("position","relative");}if(opts.width){$cont.width(opts.width);}if(opts.height&&opts.height!="auto"){$cont.height(opts.height);}if(opts.startingSlide){opts.startingSlide=parseInt(opts.startingSlide);}else{if(opts.backwards){opts.startingSlide=els.length-1;}}if(opts.random){opts.randomMap=[];for(var i=0;i<els.length;i++){opts.randomMap.push(i);}opts.randomMap.sort(function(a,b){return Math.random()-0.5;});opts.randomIndex=1;opts.startingSlide=opts.randomMap[1];}else{if(opts.startingSlide>=els.length){opts.startingSlide=0;}}opts.currSlide=opts.startingSlide||0;var first=opts.startingSlide;$slides.css({position:"absolute",top:0,left:0}).hide().each(function(i){var z;if(opts.backwards){z=first?i<=first?els.length+(i-first):first-i:els.length-i;}else{z=first?i>=first?els.length-(i-first):first-i:els.length-i;}$(this).css("z-index",z);});$(els[first]).css("opacity",1).show();removeFilter(els[first],opts);if(opts.fit&&opts.width){$slides.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}var reshape=opts.containerResize&&!$cont.innerHeight();if(reshape){var maxw=0,maxh=0;for(var j=0;j<els.length;j++){var $e=$(els[j]),e=$e[0],w=$e.outerWidth(),h=$e.outerHeight();if(!w){w=e.offsetWidth||e.width||$e.attr("width");}if(!h){h=e.offsetHeight||e.height||$e.attr("height");}maxw=w>maxw?w:maxw;maxh=h>maxh?h:maxh;}if(maxw>0&&maxh>0){$cont.css({width:maxw+"px",height:maxh+"px"});}}if(opts.pause){$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});}if(supportMultiTransitions(opts)===false){return false;}var requeue=false;options.requeueAttempts=options.requeueAttempts||0;$slides.each(function(){var $el=$(this);this.cycleH=(opts.fit&&opts.height)?opts.height:($el.height()||this.offsetHeight||this.height||$el.attr("height")||0);this.cycleW=(opts.fit&&opts.width)?opts.width:($el.width()||this.offsetWidth||this.width||$el.attr("width")||0);if($el.is("img")){var loadingIE=($.browser.msie&&this.cycleW==28&&this.cycleH==30&&!this.complete);var loadingFF=($.browser.mozilla&&this.cycleW==34&&this.cycleH==19&&!this.complete);var loadingOp=($.browser.opera&&((this.cycleW==42&&this.cycleH==19)||(this.cycleW==37&&this.cycleH==17))&&!this.complete);var loadingOther=(this.cycleH==0&&this.cycleW==0&&!this.complete);if(loadingIE||loadingFF||loadingOp||loadingOther){if(o.s&&opts.requeueOnImageNotLoaded&&++options.requeueAttempts<100){log(options.requeueAttempts," - img slide not loaded, requeuing slideshow: ",this.src,this.cycleW,this.cycleH);setTimeout(function(){$(o.s,o.c).cycle(options);},opts.requeueTimeout);requeue=true;return false;}else{log("could not determine size of image: "+this.src,this.cycleW,this.cycleH);}}}return true;});if(requeue){return false;}opts.cssBefore=opts.cssBefore||{};opts.animIn=opts.animIn||{};opts.animOut=opts.animOut||{};$slides.not(":eq("+first+")").css(opts.cssBefore);if(opts.cssFirst){$($slides[first]).css(opts.cssFirst);}if(opts.timeout){opts.timeout=parseInt(opts.timeout);if(opts.speed.constructor==String){opts.speed=$.fx.speeds[opts.speed]||parseInt(opts.speed);}if(!opts.sync){opts.speed=opts.speed/2;}var buffer=opts.fx=="shuffle"?500:250;while((opts.timeout-opts.speed)<buffer){opts.timeout+=opts.speed;}}if(opts.easing){opts.easeIn=opts.easeOut=opts.easing;}if(!opts.speedIn){opts.speedIn=opts.speed;}if(!opts.speedOut){opts.speedOut=opts.speed;}opts.slideCount=els.length;opts.currSlide=opts.lastSlide=first;if(opts.random){if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.backwards){opts.nextSlide=opts.startingSlide==0?(els.length-1):opts.startingSlide-1;}else{opts.nextSlide=opts.startingSlide>=(els.length-1)?0:opts.startingSlide+1;}}if(!opts.multiFx){var init=$.fn.cycle.transitions[opts.fx];if($.isFunction(init)){init($cont,$slides,opts);}else{if(opts.fx!="custom"&&!opts.multiFx){log("unknown transition: "+opts.fx,"; slideshow terminating");return false;}}}var e0=$slides[first];if(opts.before.length){opts.before[0].apply(e0,[e0,e0,opts,true]);}if(opts.after.length>1){opts.after[1].apply(e0,[e0,e0,opts,true]);}if(opts.next){$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?-1:1);});}if(opts.prev){$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?1:-1);});}if(opts.pager||opts.pagerAnchorBuilder){buildPager(els,opts);}exposeAddSlide(opts,els);return opts;}function saveOriginalOpts(opts){opts.original={before:[],after:[]};opts.original.cssBefore=$.extend({},opts.cssBefore);opts.original.cssAfter=$.extend({},opts.cssAfter);opts.original.animIn=$.extend({},opts.animIn);opts.original.animOut=$.extend({},opts.animOut);$.each(opts.before,function(){opts.original.before.push(this);});$.each(opts.after,function(){opts.original.after.push(this);});}function supportMultiTransitions(opts){var i,tx,txs=$.fn.cycle.transitions;if(opts.fx.indexOf(",")>0){opts.multiFx=true;opts.fxs=opts.fx.replace(/\s*/g,"").split(",");for(i=0;i<opts.fxs.length;i++){var fx=opts.fxs[i];tx=txs[fx];if(!tx||!txs.hasOwnProperty(fx)||!$.isFunction(tx)){log("discarding unknown transition: ",fx);opts.fxs.splice(i,1);i--;}}if(!opts.fxs.length){log("No valid transitions named; slideshow terminating.");return false;}}else{if(opts.fx=="all"){opts.multiFx=true;opts.fxs=[];for(p in txs){tx=txs[p];if(txs.hasOwnProperty(p)&&$.isFunction(tx)){opts.fxs.push(p);}}}}if(opts.multiFx&&opts.randomizeEffects){var r1=Math.floor(Math.random()*20)+30;for(i=0;i<r1;i++){var r2=Math.floor(Math.random()*opts.fxs.length);opts.fxs.push(opts.fxs.splice(r2,1)[0]);}debug("randomized fx sequence: ",opts.fxs);}return true;}function exposeAddSlide(opts,els){opts.addSlide=function(newSlide,prepend){var $s=$(newSlide),s=$s[0];if(!opts.autostopCount){opts.countdown++;}els[prepend?"unshift":"push"](s);if(opts.els){opts.els[prepend?"unshift":"push"](s);}opts.slideCount=els.length;$s.css("position","absolute");$s[prepend?"prependTo":"appendTo"](opts.$cont);if(prepend){opts.currSlide++;opts.nextSlide++;}if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($s);}if(opts.fit&&opts.width){$s.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}s.cycleH=(opts.fit&&opts.height)?opts.height:$s.height();s.cycleW=(opts.fit&&opts.width)?opts.width:$s.width();$s.css(opts.cssBefore);if(opts.pager||opts.pagerAnchorBuilder){$.fn.cycle.createPagerAnchor(els.length-1,s,$(opts.pager),els,opts);}if($.isFunction(opts.onAddSlide)){opts.onAddSlide($s);}else{$s.hide();}};}$.fn.cycle.resetState=function(opts,fx){fx=fx||opts.fx;opts.before=[];opts.after=[];opts.cssBefore=$.extend({},opts.original.cssBefore);opts.cssAfter=$.extend({},opts.original.cssAfter);opts.animIn=$.extend({},opts.original.animIn);opts.animOut=$.extend({},opts.original.animOut);opts.fxFn=null;$.each(opts.original.before,function(){opts.before.push(this);});$.each(opts.original.after,function(){opts.after.push(this);});var init=$.fn.cycle.transitions[fx];if($.isFunction(init)){init(opts.$cont,$(opts.elements),opts);}};function go(els,opts,manual,fwd){if(manual&&opts.busy&&opts.manualTrump){debug("manualTrump in go(), stopping active transition");$(els).stop(true,true);opts.busy=false;}if(opts.busy){debug("transition active, ignoring new tx request");return;}var p=opts.$cont[0],curr=els[opts.currSlide],next=els[opts.nextSlide];if(p.cycleStop!=opts.stopCount||p.cycleTimeout===0&&!manual){return;}if(!manual&&!p.cyclePause&&!opts.bounce&&((opts.autostop&&(--opts.countdown<=0))||(opts.nowrap&&!opts.random&&opts.nextSlide<opts.currSlide))){if(opts.end){opts.end(opts);}return;}var changed=false;if((manual||!p.cyclePause)&&(opts.nextSlide!=opts.currSlide)){changed=true;var fx=opts.fx;curr.cycleH=curr.cycleH||$(curr).height();curr.cycleW=curr.cycleW||$(curr).width();next.cycleH=next.cycleH||$(next).height();next.cycleW=next.cycleW||$(next).width();if(opts.multiFx){if(opts.lastFx==undefined||++opts.lastFx>=opts.fxs.length){opts.lastFx=0;}fx=opts.fxs[opts.lastFx];opts.currFx=fx;}if(opts.oneTimeFx){fx=opts.oneTimeFx;opts.oneTimeFx=null;}$.fn.cycle.resetState(opts,fx);if(opts.before.length){$.each(opts.before,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});}var after=function(){$.each(opts.after,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});};debug("tx firing; currSlide: "+opts.currSlide+"; nextSlide: "+opts.nextSlide);opts.busy=1;if(opts.fxFn){opts.fxFn(curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}else{if($.isFunction($.fn.cycle[opts.fx])){$.fn.cycle[opts.fx](curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}else{$.fn.cycle.custom(curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}}}if(changed||opts.nextSlide==opts.currSlide){opts.lastSlide=opts.currSlide;if(opts.random){opts.currSlide=opts.nextSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];if(opts.nextSlide==opts.currSlide){opts.nextSlide=(opts.currSlide==opts.slideCount-1)?0:opts.currSlide+1;}}else{if(opts.backwards){var roll=(opts.nextSlide-1)<0;if(roll&&opts.bounce){opts.backwards=!opts.backwards;opts.nextSlide=1;opts.currSlide=0;}else{opts.nextSlide=roll?(els.length-1):opts.nextSlide-1;opts.currSlide=roll?0:opts.nextSlide+1;}}else{var roll=(opts.nextSlide+1)==els.length;if(roll&&opts.bounce){opts.backwards=!opts.backwards;opts.nextSlide=els.length-2;opts.currSlide=els.length-1;}else{opts.nextSlide=roll?0:opts.nextSlide+1;opts.currSlide=roll?els.length-1:opts.nextSlide-1;}}}}if(changed&&opts.pager){opts.updateActivePagerLink(opts.pager,opts.currSlide,opts.activePagerClass);}var ms=0;if(opts.timeout&&!opts.continuous){ms=getTimeout(els[opts.currSlide],els[opts.nextSlide],opts,fwd);}else{if(opts.continuous&&p.cyclePause){ms=10;}}if(ms>0){p.cycleTimeout=setTimeout(function(){go(els,opts,0,(!opts.rev&&!opts.backwards));},ms);}}$.fn.cycle.updateActivePagerLink=function(pager,currSlide,clsName){$(pager).each(function(){$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);});};function getTimeout(curr,next,opts,fwd){if(opts.timeoutFn){var t=opts.timeoutFn.call(curr,curr,next,opts,fwd);while((t-opts.speed)<250){t+=opts.speed;}debug("calculated timeout: "+t+"; speed: "+opts.speed);if(t!==false){return t;}}return opts.timeout;}$.fn.cycle.next=function(opts){advance(opts,opts.rev?-1:1);};$.fn.cycle.prev=function(opts){advance(opts,opts.rev?1:-1);};function advance(opts,val){var els=opts.elements;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if(opts.random&&val<0){opts.randomIndex--;if(--opts.randomIndex==-2){opts.randomIndex=els.length-2;}else{if(opts.randomIndex==-1){opts.randomIndex=els.length-1;}}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.random){opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.currSlide+val;if(opts.nextSlide<0){if(opts.nowrap){return false;}opts.nextSlide=els.length-1;}else{if(opts.nextSlide>=els.length){if(opts.nowrap){return false;}opts.nextSlide=0;}}}}var cb=opts.onPrevNextEvent||opts.prevNextClick;if($.isFunction(cb)){cb(val>0,opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,val>=0);return false;}function buildPager(els,opts){var $p=$(opts.pager);$.each(els,function(i,o){$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);});opts.updateActivePagerLink(opts.pager,opts.startingSlide,opts.activePagerClass);}$.fn.cycle.createPagerAnchor=function(i,el,$p,els,opts){var a;if($.isFunction(opts.pagerAnchorBuilder)){a=opts.pagerAnchorBuilder(i,el);debug("pagerAnchorBuilder("+i+", el) returned: "+a);}else{a='<a href="#">'+(i+1)+"</a>";}if(!a){return;}var $a=$(a);if($a.parents("body").length===0){var arr=[];if($p.length>1){$p.each(function(){var $clone=$a.clone(true);$(this).append($clone);arr.push($clone[0]);});$a=$(arr);}else{$a.appendTo($p);}}opts.pagerAnchors=opts.pagerAnchors||[];opts.pagerAnchors.push($a);$a.bind(opts.pagerEvent,function(e){e.preventDefault();opts.nextSlide=i;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}var cb=opts.onPagerEvent||opts.pagerClick;if($.isFunction(cb)){cb(opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,opts.currSlide<i);});if(!/^click/.test(opts.pagerEvent)&&!opts.allowPagerClickBubble){$a.bind("click.cycle",function(){return false;});}if(opts.pauseOnPagerHover){$a.hover(function(){opts.$cont[0].cyclePause++;},function(){opts.$cont[0].cyclePause--;});}};$.fn.cycle.hopsFromLast=function(opts,fwd){var hops,l=opts.lastSlide,c=opts.currSlide;if(fwd){hops=c>l?c-l:opts.slideCount-l;}else{hops=c<l?l-c:l+opts.slideCount-c;}return hops;};function clearTypeFix($slides){debug("applying clearType background-color hack");function hex(s){s=parseInt(s).toString(16);return s.length<2?"0"+s:s;}function getBg(e){for(;e&&e.nodeName.toLowerCase()!="html";e=e.parentNode){var v=$.css(e,"background-color");if(v.indexOf("rgb")>=0){var rgb=v.match(/\d+/g);return"#"+hex(rgb[0])+hex(rgb[1])+hex(rgb[2]);}if(v&&v!="transparent"){return v;}}return"#ffffff";}$slides.each(function(){$(this).css("background-color",getBg(this));});}$.fn.cycle.commonReset=function(curr,next,opts,w,h,rev){$(opts.elements).not(curr).hide();opts.cssBefore.opacity=1;opts.cssBefore.display="block";if(w!==false&&next.cycleW>0){opts.cssBefore.width=next.cycleW;}if(h!==false&&next.cycleH>0){opts.cssBefore.height=next.cycleH;}opts.cssAfter=opts.cssAfter||{};opts.cssAfter.display="none";$(curr).css("zIndex",opts.slideCount+(rev===true?1:0));$(next).css("zIndex",opts.slideCount+(rev===true?0:1));};$.fn.cycle.custom=function(curr,next,opts,cb,fwd,speedOverride){var $l=$(curr),$n=$(next);var speedIn=opts.speedIn,speedOut=opts.speedOut,easeIn=opts.easeIn,easeOut=opts.easeOut;$n.css(opts.cssBefore);if(speedOverride){if(typeof speedOverride=="number"){speedIn=speedOut=speedOverride;}else{speedIn=speedOut=1;}easeIn=easeOut=null;}var fn=function(){$n.animate(opts.animIn,speedIn,easeIn,cb);};$l.animate(opts.animOut,speedOut,easeOut,function(){if(opts.cssAfter){$l.css(opts.cssAfter);}if(!opts.sync){fn();}});if(opts.sync){fn();}};$.fn.cycle.transitions={fade:function($cont,$slides,opts){$slides.not(":eq("+opts.currSlide+")").css("opacity",0);opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.opacity=0;});opts.animIn={opacity:1};opts.animOut={opacity:0};opts.cssBefore={top:0,left:0};}};$.fn.cycle.ver=function(){return ver;};$.fn.cycle.defaults={fx:"fade",timeout:4000,timeoutFn:null,continuous:0,speed:1000,speedIn:null,speedOut:null,next:null,prev:null,onPrevNextEvent:null,prevNextEvent:"click.cycle",pager:null,onPagerEvent:null,pagerEvent:"click.cycle",allowPagerClickBubble:false,pagerAnchorBuilder:null,before:null,after:null,end:null,easing:null,easeIn:null,easeOut:null,shuffle:null,animIn:null,animOut:null,cssBefore:null,cssAfter:null,fxFn:null,height:"auto",startingSlide:0,sync:1,random:0,fit:0,containerResize:1,pause:0,pauseOnPagerHover:0,autostop:0,autostopCount:0,delay:0,slideExpr:null,cleartype:!$.support.opacity,cleartypeNoBg:false,nowrap:0,fastOnEvent:0,randomizeEffects:1,rev:0,manualTrump:true,requeueOnImageNotLoaded:true,requeueTimeout:250,activePagerClass:"activeSlide",updateActivePagerLink:null,backwards:false};})(jQuery);

/*
 * jQuery Orbit Plugin 1.1 
 * www.ZURB.com/playground
 * Copyright 2010, ZURB
 * Free to use under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
*/


(function(e){e.fn.orbit=function(a){a=e.extend({animation:"fade",animationSpeed:800,advanceSpeed:4E3,startClockOnMouseOut:true,startClockOnMouseOutAfter:3E3,directionalNav:true,captions:true,captionAnimationSpeed:800,timer:false,bullets:false},a);return this.each(function(){function m(c){function g(){f.eq(h).css({"z-index":1});s=false}var h=b,k=c;if(h==k)return false;if(!s){s=true;if(c=="next"){b++;if(b==n)b=0}else if(c=="prev"){b--;if(b<0)b=n-1}else{b=c;if(h<b)k="next";else if(h>b)k="prev"}a.bullets&&
x();if(a.animation=="fade"){f.eq(h).css({"z-index":2});f.eq(b).css({opacity:0,"z-index":3}).animate({opacity:1},a.animationSpeed,g);a.captions&&o()}if(a.animation=="horizontal-slide"){f.eq(h).css({"z-index":2});k=="next"&&f.eq(b).css({left:t,"z-index":3}).animate({left:0},a.animationSpeed,g);k=="prev"&&f.eq(b).css({left:-t,"z-index":3}).animate({left:0},a.animationSpeed,g);a.captions&&o()}if(a.animation=="vertical-slide"){f.eq(h).css({"z-index":2});k=="prev"&&f.eq(b).css({top:u,"z-index":3}).animate({top:0},
a.animationSpeed,g);k=="next"&&f.eq(b).css({top:-u,"z-index":3}).animate({top:0},a.animationSpeed,g);a.captions&&o()}}}var b=0,n=0,t,u,s,d=e(this).addClass("orbit"),f=d.find("img, a img");f.each(function(){var c=e(this),g=c.width();c=c.height();d.width(g);t=d.width();d.height(c);u=d.height();n++});f.eq(b).css({"z-index":3});if(a.timer){d.append('<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>');var j=e("div.timer"),p;if(j.length!=0){var C=
a.advanceSpeed/180,v=e("div.timer span.rotator"),y=e("div.timer span.mask"),z=e("div.timer span.pause"),l=0,A,w=function(){p=true;z.removeClass("active");A=setInterval(function(){var c="rotate("+l+"deg)";l+=2;v.css({"-webkit-transform":c,"-moz-transform":c,"-o-transform":c});if(l>180){v.addClass("move");y.addClass("move")}if(l>360){v.removeClass("move");y.removeClass("move");l=0;m("next")}},C)},q=function(){p=false;clearInterval(A);z.addClass("active")};w();j.click(function(){p?q():w()});if(a.startClockOnMouseOut){var B;
d.mouseleave(function(){B=setTimeout(function(){p||w()},a.startClockOnMouseOutAfter)});d.mouseenter(function(){clearTimeout(B)})}}}if(a.captions){d.append('<div class="caption"><span class="orbit-caption"></span></div>');var r=d.children("div.caption").children("span").addClass("orbit-caption").show(),o=function(){var c=f.eq(b).attr("rel"),g=e("#"+c).html(),h=r.height()+20;r.attr("id","#"+c).html(g);g?r.parent().stop().animate({bottom:0},a.captionAnimationSpeed):r.parent().stop().animate({bottom:-h},
a.captionAnimationSpeed)};o()}if(a.directionalNav){d.append('<div class="slider-nav"><span class="right">Right</span><span class="left">Left</span></div>');j=d.children("div.slider-nav").children("span.left");var D=d.children("div.slider-nav").children("span.right");j.click(function(){a.timer&&q();m("prev")});D.click(function(){a.timer&&q();m("next")})}if(a.bullets){d.append('<ul class="orbit-bullets"></ul>');var E=e("ul.orbit-bullets");for(i=0;i<n;i++){j=e("<li>"+i+"</li>");e("ul.orbit-bullets").append(j);
j.data("index",i);j.click(function(){a.timer&&q();m(e(this).data("index"))})}var x=function(){E.children("li").removeClass("active").eq(b).addClass("active")};x()}})}})(jQuery);

(function ($) {
    var defaults = {
        vertical: false
    };

    $.expandablelist = function (e, o) {
        this.options = $.extend({}, defaults, o || {});

        this.list = $(e);
        this.list.find('.piranya-expandablelist-content').css('display', 'none');
        this.list.find('.piranya-expandablelist-header').bind('click', function () {
            if (jQuery(this).siblings('.piranya-expandablelist-content').first().css("display") == 'block')
                jQuery(this).siblings('.piranya-expandablelist-content').css('display', 'none');
            else
                jQuery(this).siblings('.piranya-expandablelist-content').css('display', 'block');
        });
    };

    // Create shortcut for internal use
    var $jc = $.expandablelist;

    $jc.fn = $jc.prototype = {
        expandablelist: '0.1.0'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({

});

$jc.extend({
    /**
    * Gets/Sets the global default configuration properties.
    *
    * @method defaults
    * @return {Object}
    * @param d {Object} A set of key/value pairs to set as configuration properties.
    */
    defaults: function (d) {
        return $.extend(defaults, d || {});
    },

    intval: function (v) {
        v = parseInt(v, 10);
        return isNaN(v) ? 0 : v;
    }
});

$.fn.expandablelist = function (o) {
    if (typeof o == 'string') {
        var instance = $(this).data('expandablelist'), args = Array.prototype.slice.call(arguments, 1);
        return instance[o].apply(instance, args);
    } else {
        return this.each(function () {
            var instance = $(this).data('expandablelist');
            if (instance) {
                if (o) {
                    $.extend(instance.options, o);
                }
                //instance.reload();
            } else {
                $(this).data('expandablelist', new $jc(this, o));
            }
        });
    }
};

})(jQuery);


jQuery(document).ready(function () {
    if (typeof window.EnableAjaxRecursive == 'function') {
        if (document.location.hash && document.location.pathname.length > 1) {
            var hash = document.location.hash.toString();
            if (document.location.origin) {
                document.location.href = document.location.origin.toString() + hash;
            }
            else {
                document.location.href = document.location.protocol + "//" + document.location.host + hash;
            }
            return;
        }

        GetPageByHash(document.location.hash);
    }

    OnPageLoad();
});

function OnPageLoad() {

    if (typeof window.EnableAjaxRecursive == 'function') {
        EnableAjaxRecursive(jQuery("body"));
    }

    if (typeof window.InitializeScrollBars == 'function') {
        InitializeScrollBars();
    }

    if (typeof window.InitializeSlimbox == 'function') {
        InitializeSlimbox();
    }
    if (typeof window.BlockBrowser == 'function') {
        BlockBrowser();
    }
}


