
// create the lcpbox object first
var lcpbox = {};

lcpbox.lib = function(){

    // local style camelizing for speed
    var styleCache = {};
    var camelRe = /(-[a-z])/gi;
    var camelFn = function(m, a){
        return a.charAt(1).toUpperCase();
    };
    var toCamel = function(style){
        var camel;
        if(!(camel = styleCache[style])){
            camel = styleCache[style] = style.replace(camelRe, camelFn);
        }
        return camel;
    };

    var view = document.defaultView;
    var alphaRe = /alpha\([^\)]*\)/gi;

    var setOpacity = function(el, opacity){
        var s = el.style;
        if(window.ActiveXObject){ // IE
            s.zoom = 1; // give "layout"
            s.filter = (s.filter || '').replace(alphaRe, '') +
                (opacity == 1 ? '' : ' alpha(opacity=' + (opacity * 100) + ')');
        }else{
            s.opacity = opacity;
        }
    };

    return {

        adapter: 'standalone',

        getStyle: function(){
            return view && view.getComputedStyle
                ? function(el, style){
                    var v, cs, camel;
                    if(style == 'float') style = 'cssFloat';
                    if(v = el.style[style]) return v;
                    if(cs = view.getComputedStyle(el, '')){
                        return cs[toCamel(style)];
                    }
                    return null;
                }
                : function(el, style){
                    var v, cs, camel;
                    if(style == 'opacity'){
                        if(typeof el.style.filter == 'string'){
                            var m = el.style.filter.match(/alpha\(opacity=(.+)\)/i);
                            if(m){
                                var fv = parseFloat(m[1]);
                                if(!isNaN(fv)) return (fv ? fv / 100 : 0);
                            }
                        }
                        return 1;
                    }else if(style == 'float'){
                        style = 'styleFloat';
                    }
                    var camel = toCamel(style);
                    if(v = el.style[camel]) return v;
                    if(cs = el.currentStyle) return cs[camel];
                    return null;
                };
        }(),
        setStyle: function(el, style, value){
            if(typeof style == 'string'){
                var camel = toCamel(style);
                if(camel == 'opacity'){
                    setOpacity(el, value);
                }else{
                    el.style[camel] = value;
                }
            }else{
                for(var s in style){
                    this.setStyle(el, s, style[s]);
                }
            }
        },
        get: function(el){
            return typeof el == 'string' ? document.getElementById(el) : el;
        },


        remove: function(el){
            el.parentNode.removeChild(el);
        },

        getTarget: function(e){
            var t = e.target ? e.target : e.srcElement;
            return t.nodeType == 3 ? t.parentNode : t;
        },

        getPageXY: function(e){
            var x = e.pageX || (e.clientX +
                (document.documentElement.scrollLeft || document.body.scrollLeft));
            var y = e.pageY || (e.clientY +
                (document.documentElement.scrollTop || document.body.scrollTop));
            return [x, y];
        },

        preventDefault: function(e){
            if(e.preventDefault){
                e.preventDefault();
            }else{
                e.returnValue = false;
            }
        },

        keyCode: function(e){
            return e.which ? e.which : e.keyCode;
        },

        addEvent: function(el, name, handler){
            if(el.addEventListener){
                el.addEventListener(name, handler, false);
            }else if(el.attachEvent){
                el.attachEvent('on' + name, handler);
            }
        },

        removeEvent: function(el, name, handler){
            if(el.removeEventListener){
                el.removeEventListener(name, handler, false);
            }else if(el.detachEvent){
                el.detachEvent('on' + name, handler);
            }
        },

        append: function(el, html){
            if(el.insertAdjacentHTML){
                el.insertAdjacentHTML('BeforeEnd', html);
            }else if(el.lastChild){
                var range = el.ownerDocument.createRange();
                range.setStartAfter(el.lastChild);
                var frag = range.createContextualFragment(html);
                el.appendChild(frag);
            }else{
                el.innerHTML = html;
            }
        }

    };

}();





if(typeof lcpbox == 'undefined'){
    throw 'Unable to load lcpbox, no base library adapter found';
}

(function(){

    var options = {
		autoplayMovies:     true,
        animate:            true,
        animateFade:        true,
        animSequence:       'wh',
        modal:              false,
        overlayColor:       '#000',
        overlayOpacity:     0.8,
        flashBgColor:       '#000000',
        showMovieControls:  true,
        slideshowDelay:     3,
        resizeDuration:     0.55,
        fadeDuration:       0.35,
        displayNav:         true,
        continuous:         true,
        displayCounter:     true,
        counterType:        'default',
        counterLimit:       10,
        viewportPadding:    20,
        handleOversize:     'resize',
        handleException:    null,
        handleUnsupported:  'link',
        initialHeight:      160,
        initialWidth:       320,
        enableKeys:         true,
        onOpen:             null,
        onFinish:           null,
        onChange:           null,
        onClose:            null,
        skipSetup:          false,

        ext:     {
            img:        ['png', 'jpg', 'jpeg', 'gif', 'bmp']
        }

    };

    // shorthand
    var SB = lcpbox;
    var SL = SB.lib;
    var default_options;
    var RE = {
        domain:         /:\/\/(.*?)[:\/]/, // domain prefix
        inline:         /#(.+)$/, // inline element id
        rel:            /^(light|shadow)box/i, // rel attribute format
        gallery:        /^(light|shadow)box\[(.*?)\]/i, // rel attribute format for gallery link
        unsupported:    /^unsupported-(\w+)/, // unsupported media type
        param:          /\s*([a-z_]*?)\s*=\s*(.+)\s*/, // rel string parameter
        empty:          /^(?:br|frame|hr|img|input|link|meta|range|spacer|wbr|area|param|col)$/i // elements that don't have children
    };

    var cache = [];
    var gallery;
    var current;
    var content;
    var content_id = 'lcpbox_content';
    var dims;
    var initialized = false;
    var activated = false;
    var slide_timer = 'paused';
    var slide_start;
    var slide_delay = 0;
    var ua = navigator.userAgent.toLowerCase();
    var client = {
        isStrict:   document.compatMode == 'CSS1Compat',
        isOpera:    ua.indexOf('opera') > -1,
        isIE:       ua.indexOf('msie') > -1,
        isIE7:      ua.indexOf('msie 7') > -1,
        isSafari:   /webkit|khtml/.test(ua),
        isWindows:  ua.indexOf('windows') != -1 || ua.indexOf('win32') != -1,
        isMac:      ua.indexOf('macintosh') != -1 || ua.indexOf('mac os x') != -1,
        isLinux:    ua.indexOf('linux') != -1
    };
    client.isBorderBox = client.isIE && !client.isStrict;
    client.isSafari3 = client.isSafari && !!(document.evaluate);
    client.isGecko = ua.indexOf('gecko') != -1 && !client.isSafari;

    var ltIE7 = client.isIE && !client.isIE7;

    var plugins;

    var apply = function(o, e){
        for(var p in e) o[p] = e[p];
        return o;
    };

    var isLink = function(el){
        return el && typeof el.tagName == 'string' && (el.tagName.toUpperCase() == 'A' || el.tagName.toUpperCase() == 'AREA');
    };

    SL.getViewportHeight = function(){
        var h = window.innerHeight; // Safari
        var mode = document.compatMode;

        if((mode || client.isIE) && !client.isOpera){
            h = client.isStrict ? document.documentElement.clientHeight : document.body.clientHeight;
        }

        return h;
    };

    SL.getViewportWidth = function(){
        var w = window.innerWidth; // Safari
        var mode = document.compatMode;
        if(mode || client.isIE){
            w = client.isStrict ? document.documentElement.clientWidth : document.body.clientWidth;
        }
        return w;
    };

    SL.createHTML = function(obj){
        var html = '<' + obj.tag;
        for(var attr in obj){
            if(attr == 'tag' || attr == 'html' || attr == 'children') continue;
            if(attr == 'cls'){
                html += ' class="' + obj['cls'] + '"';
            }else{
                html += ' ' + attr + '="' + obj[attr] + '"';
            }
        }
        if(RE.empty.test(obj.tag)){
            html += '/>';
        }else{
            html += '>';
            var cn = obj.children;
            if(cn){
                for(var i = 0, len = cn.length; i < len; ++i){
                    html += this.createHTML(cn[i]);
                }
            }
            if(obj.html) html += obj.html;
            html += '</' + obj.tag + '>';
        }
        return html;
    };

	lcpbox.loadSkin = function(skin, dir){

        if(!(/\/$/.test(dir))) dir += '/';
        skin = dir + skin + '/';

        // Safari 2.0 fails using DOM, use document.write instead
        document.write('<link rel="stylesheet" type="text/css" href="' + skin + 'skin.css">');
		 document.write('<scr' + 'ipt type="text/javascript" src="' + skin + 'skin.js"><\/script>');

    };

	
    var ease = function(x){
        return 1 + Math.pow(x - 1, 3);
    };

    var animate = function(el, p, to, d, cb){

        var from = parseFloat(SL.getStyle(el, p));
        if(isNaN(from)) from = 0;

        if(from == to){
            if(typeof cb == 'function') cb();
            return; // nothing to animate
        }

        var delta = to - from;
        var op = p == 'opacity';
        var unit = op ? '' : 'px'; // default unit is px
        var fn = function(ease){
            SL.setStyle(el, p, from + ease * delta + unit);
        };

        // cancel the animation here if set in the options
        if(!options.animate && !op || op && !options.animateFade){
            fn(1);
            if(typeof cb == 'function') cb();
            return;
        }

        d *= 1000; // convert to milliseconds
        var begin = new Date().getTime();
        var end = begin + d;

        var timer = setInterval(function(){
            var time = new Date().getTime();
            if(time >= end){ // end of animation
                clearInterval(timer);
                fn(1);
                if(typeof cb == 'function') cb();
            }else{
                fn(ease((time - begin) / d));
            }
        }, 10); // 10 ms interval is minimum on WebKit
    };
    var clearOpacity = function(el){
        var s = el.style;
        if(client.isIE){
            if(typeof s.filter == 'string' && (/alpha/i).test(s.filter)){
                // careful not to overwrite other filters!
                s.filter = s.filter.replace(/[\w\.]*alpha\(.*?\);?/i, '');
            }
        }else{
            s.opacity = '';
            s['-moz-opacity'] = '';
            s['-khtml-opacity'] = '';
        }
    };

    var getComputedHeight = function(el){
        var h = Math.max(el.offsetHeight, el.clientHeight);
        if(!h){
            h = parseInt(SL.getStyle(el, 'height'), 10) || 0;
            if(!client.isBorderBox){
                h += parseInt(SL.getStyle(el, 'padding-top'), 10)
                    + parseInt(SL.getStyle(el, 'padding-bottom'), 10)
                    + parseInt(SL.getStyle(el, 'border-top-width'), 10)
                    + parseInt(SL.getStyle(el, 'border-bottom-width'), 10);
            }
        }

        return h;
    };

    var getPlayer = function(url){
        var m = url.match(RE.domain);
        var d = m && document.domain == m[1]; // same domain
        if(url.indexOf('#') > -1 && d) return 'inline';
        var q = url.indexOf('?');
        if(q > -1) url = url.substring(0, q); // strip query string for player detection purposes
        if(RE.img.test(url)) return 'img';
      
    };

    var handleClick = function(ev){
        // get anchor/area element
        var link;
        if(isLink(this)){
            link = this; // jQuery, Prototype, YUI
        }else{
            link = SL.getTarget(ev); // Ext, standalone
            while(!isLink(link) && link.parentNode){
                link = link.parentNode;
            }
        }

        //SL.preventDefault(ev); // good for debugging

        if(link){
            SB.open(link);
            if(gallery.length) SL.preventDefault(ev); // stop event
        }
    };

    var toggleNav = function(id, on){
        var el = SL.get('lcpbox_nav_' + id);
        if(el) el.style.display = on ? '' : 'none';
    };

    var buildBars = function(cb){
        var obj = gallery[current];
        var title_i = SL.get('lcpbox_title_inner');

        // build the title
        title_i.innerHTML = obj.title || '';
		
		//create save button
		var save = SL.get('lcpbox_nav_save');
		save.href = 	obj.realpic;
		save.target= '_blank';

        // build the nav
        var nav = SL.get('lcpbox_nav');
        if(nav){
            var c, n, pl, pa, p;

            // need to build the nav?
            if(options.displayNav){
                c = true;
                // next & previous links
                var len = gallery.length;
                if(len > 1){
                    if(options.continuous){
                        n = p = true; // show both
                    }else{
                        n = (len - 1) > current; // not last in gallery, show next
                        p = current > 0; // not first in gallery, show previous
                    }
                }
                // in a slideshow?
                if(options.slideshowDelay > 0 && hasNext()){
                    pa = slide_timer != 'paused';
                    pl = !pa;
                }
            }else{
                c = n = pl = pa = p = false;
            }

            toggleNav('close', c);
            toggleNav('next', n);
            toggleNav('play', pl);
            toggleNav('pause', pa);
            toggleNav('previous', p);
        }

        // build the counter
        var counter = SL.get('lcpbox_counter');
        if(counter){
            var co = '';

            // need to build the counter?
            if(options.displayCounter && gallery.length > 1){
                if(options.counterType == 'skip'){
                    // limit the counter?
                    var i = 0, len = gallery.length, end = len;
                    var limit = parseInt(options.counterLimit);
                    if(limit < len){ // support large galleries
                        var h = Math.round(limit / 2);
                        i = current - h;
                        if(i < 0) i += len;
                        end = current + (limit - h);
                        if(end > len) end -= len;
                    }
                    while(i != end){
                        if(i == len) i = 0;
                        co += '<a onclick="lcpbox.change(' + i + ');"';
                        if(i == current) co += ' class="lcpbox_counter_current"';
                        co += '>' + (++i) + '</a>';
                    }
                }else{ // default
                    co = (current + 1) + ' van ' + len;
                }
            }

            counter.innerHTML = co;
        }

        cb();
    };

    var hideBars = function(anim, cb){

        var obj = gallery[current];
        var title = SL.get('lcpbox_title');
        var info = SL.get('lcpbox_info');
        var title_i = SL.get('lcpbox_title_inner');
        var info_i = SL.get('lcpbox_info_inner');

        // build bars after they are hidden
        var fn = function(){
            buildBars(cb);
        };

        var title_h = getComputedHeight(title);
        var info_h = getComputedHeight(info) * -1;

		if(title_h='NaN'){title_h=20;}

        if(anim){	
	
            // animate the transition
            animate(title_i, 'margin-top', title_h, 0.35,null);
            animate(info_i, 'margin-top', info_h, 0.35, fn);
        }else{
            SL.setStyle(title_i, 'margin-top', title_h + 'px');
            SL.setStyle(info_i, 'margin-top', info_h + 'px');
            fn();
        }
		
    };

    var showBars = function(cb){
	
        var title_i = SL.get('lcpbox_title_inner');
        var info_i = SL.get('lcpbox_info_inner');
        var t = title_i.innerHTML != ''; // is there a title to display?
	
        if(t) animate(title_i, 'margin-top', 0, 0.35,null);
        animate(info_i, 'margin-top', 0, 0.35, cb);
		
    };

    var loadContent = function(){
        var obj = gallery[current];
        if(!obj) return; // invalid

        var changing = false;
        if(content){
            content.remove(); // remove old content first
            changing = true; // changing from some previous content
        }

        // determine player, inline is really just HTML
        var p = obj.player == 'inline' ? 'html' : obj.player;

        // make sure player is loaded
        if(typeof SB[p] != 'function'){
            SB.raise('Unknown player ' + obj.player);
        }
        content = new SB[p](content_id, obj); // instantiate new content object

        listenKeys(false); // disable the keyboard temporarily
        toggleLoading(true);

        hideBars(changing, function(){ // if changing, animate the bars transition
            if(!content) return;

            // if opening, clear #lcpbox display
            if(!changing){
                 SL.get('lcpbox').style.display = '';
            }

            var fn = function(){
                resizeContent(function(){
                    if(!content) return;


                    showBars(function(){
                        if(!content) return;

                        // append content just before hiding the loading layer
                        SL.get('lcpbox_body_inner').innerHTML = SL.createHTML(content.markup(dims));

                        toggleLoading(false, function(){
                            if(!content) return;

                            if(typeof content.onLoad == 'function'){
                                content.onLoad(); // call onLoad callback if present
                            }
                            if(options.onFinish && typeof options.onFinish == 'function'){
                                options.onFinish(gallery[current]); // fire onFinish handler
                            }
                            if(slide_timer != 'paused'){
                                SB.play(); // kick off next slide
                            }
                            listenKeys(true); // re-enable the keyboard
                        });
                    });
                });
            };

            if(typeof content.ready != 'undefined'){ // does the object have a ready property?
                var id = setInterval(function(){ // if so, wait for the object to be ready
                    if(content){
                        if(content.ready){
                            clearInterval(id); // clean up
                            id = null;
                            fn();
                        }
                    }else{ // content has been removed
                        clearInterval(id);
                        id = null;
                    }
                }, 100);
            }else{
                fn();
            }
        });

        // preload neighboring gallery images
        if(gallery.length > 1){
            var next = gallery[current + 1] || gallery[0];
            if(next.player == 'img'){
                var a = new Image();
                a.src = next.content;
				a.alt = next.alt;
            }
            var prev = gallery[current - 1] || gallery[gallery.length - 1];
            if(prev.player == 'img'){
                var b = new Image();
                b.src = prev.content;
				b.alt = prev.alt;
            }
        }
    };

    var setDimensions = function(height, width, resizable){

        resizable = resizable || false;

        var sb = SL.get('lcpbox_body');
        var h = height = parseInt(height);
        var w = width = parseInt(width);
        var view_h = SL.getViewportHeight();
        var view_w = SL.getViewportWidth();

        // calculate the max width
        var border_w = parseInt(SL.getStyle(sb, 'border-left-width'), 10)
            + parseInt(SL.getStyle(sb, 'border-right-width'), 10);
        var extra_w = border_w + 2 * options.viewportPadding;
        if(w + extra_w >= view_w){
            w = view_w - extra_w;
        }

        // calculate the max height
        var border_h = parseInt(SL.getStyle(sb, 'border-top-width'), 10)
            + parseInt(SL.getStyle(sb, 'border-bottom-width'), 10);
        var bar_h = getComputedHeight(SL.get('lcpbox_title'))
            + getComputedHeight(SL.get('lcpbox_info'));
        var extra_h = border_h + 2 * options.viewportPadding + bar_h;
        if(h + extra_h >= view_h){
            h = view_h - extra_h;
        }

        // handle oversized content
        var drag = false;
        var resize_h = height;
        var resize_w = width;
        var handle = options.handleOversize;
        if(resizable && (handle == 'resize' || handle == 'drag')){
            var change_h = (height - h) / height;
            var change_w = (width - w) / width;
            if(handle == 'resize'){
                if(change_h > change_w){
                    w = Math.round((width / height) * h);
                }else if(change_w > change_h){
                    h = Math.round((height / width) * w);
                }
                // adjust resized height or width accordingly
                resize_w = w;
                resize_h = h;
            }else{
                // drag on oversized images only
                var link = gallery[current];
                if(link) drag = link.player == 'img' && (change_h > 0 || change_w > 0);
            }
        }
		var th = 0
	
		th = (view_h - (h + extra_h)) / 2 + options.viewportPadding;

        // update dims
        dims = {
            height:     h + border_h + bar_h,
            width:      w + border_w,
            inner_h:    h,
            inner_w:    w,
            top:        th,
            resize_h:   resize_h,
            resize_w:   resize_w,
            drag:       drag
        };

    };

    var resizeContent = function(cb){

        if(!content) return; // no content

        // set new dimensions
        setDimensions(content.height, content.width, content.resizable);

        if(cb){
            switch(options.animSequence){
                case 'hw':
                    adjustHeight(dims.inner_h, dims.top, true, function(){
                        adjustWidth(dims.width, true, cb);
                    });
                    break;
                case 'wh':
                    adjustWidth(dims.width, true, function(){
                        adjustHeight(dims.inner_h, dims.top, true, cb);
                    });
                    break;
                case 'sync':
                default:
                    adjustWidth(dims.width, true);
                    adjustHeight(dims.inner_h, dims.top, true, cb);
            }
        }else{ // window resize
            adjustWidth(dims.width, false);
            adjustHeight(dims.inner_h, dims.top, false);
            var c = SL.get(content_id);
            if(c){
                // resize resizable content when in resize mode
                if(content.resizable && options.handleOversize == 'resize'){
                    c.height = dims.resize_h;
                    c.width = dims.resize_w;
                }
                // fix draggable positioning if enlarging viewport
                if(gallery[current].player == 'img' && options.handleOversize == 'drag'){
                    var top = parseInt(SL.getStyle(c, 'top'));
                    if(top + content.height < dims.inner_h){
                        SL.setStyle(c, 'top', dims.inner_h - content.height + 'px');
                    }
                    var left = parseInt(SL.getStyle(c, 'left'));
                    if(left + content.width < dims.inner_w){
                        SL.setStyle(c, 'left', dims.inner_w - content.width + 'px');
                    }
                }
            }
        }
    };


    var adjustHeight = function(height, top, anim, cb){

        height = parseInt(height);

        // adjust the height
        var sb = SL.get('lcpbox_body');
			
        if(anim){
            animate(sb, 'height', height, options.resizeDuration,null);
        }else{
            SL.setStyle(sb, 'height', height + 'px');
        }

        // adjust the top
        var s = SL.get('lcpbox');
	
        if(anim){
	
            animate(s, 'top', top, options.resizeDuration, cb);
        }else{
            SL.setStyle(s, 'top', top + 'px');
            if(typeof cb == 'function') cb();
        }
    };

    var adjustWidth = function(width, anim, cb){

        width = parseInt(width);

        // adjust the width
        var s = SL.get('lcpbox');
	
        if(anim){
		
            animate(s, 'width', width, options.resizeDuration, cb);
	
        }else{
            SL.setStyle(s, 'width', width + 'px');
            if(typeof cb == 'function') cb();
        }
		
    };

    var listenKeys = function(on){
        if(!options.enableKeys) return;
        SL[(on ? 'add' : 'remove') + 'Event'](document, 'keydown', handleKey);
    };

    var handleKey = function(e){
        var code = SL.keyCode(e);

        // attempt to prevent default key action
        SL.preventDefault(e);

        if(code == 81 || code == 88 || code == 27){ // q, x, or esc
            SB.close();
        }else if(code == 37){ // left arrow
            SB.previous();
        }else if(code == 39){ // right arrow
            SB.next();
        }else if(code == 32){ // space bar
            SB[(typeof slide_timer == 'number' ? 'pause' : 'play')]();
        }
    };

    var toggleLoading = function(on, cb){

        var loading = SL.get('lcpbox_loading');
        if(on){
            loading.style.display = '';
            if(typeof cb == 'function') cb();
        }else{
            var p = gallery[current].player;
            var anim = (p == 'img' || p == 'html'); // fade on images & html
            var fn = function(){
                loading.style.display = 'none';
                clearOpacity(loading);
                if(typeof cb == 'function') cb();
            };
		
            if(anim){
                animate(loading, 'opacity', 0, options.fadeDuration, fn);
            }else{
                fn();
            }
        }
    };


    var fixTop = function(){
        SL.get('lcpbox_container').style.top = document.documentElement.scrollTop + 'px';
    };

    var fixHeight = function(){
        SL.get('lcpbox_overlay').style.height = SL.getViewportHeight() + 'px';
    };

    var hasNext = function(){
        return gallery.length > 1 && (current != gallery.length - 1 || options.continuous);
    };

    var toggleVisible = function(cb){
        var els, v = (cb) ? 'hidden' : 'visible';
        var hide = ['select', 'object', 'embed']; // tags to hide
        for(var i = 0; i < hide.length; ++i){
            els = document.getElementsByTagName(hide[i]);
            for(var j = 0, len = els.length; j < len; ++j){
                els[j].style.visibility = v;
            }
        }

        // resize & show container
        var so = SL.get('lcpbox_overlay');
        var sc = SL.get('lcpbox_container');
        var sb = SL.get('lcpbox');
        if(cb){
            // set overlay color/opacity
            SL.setStyle(so, {
                backgroundColor: options.overlayColor,
                opacity: 0
            });
            if(!options.modal) SL.addEvent(so, 'click', SB.close);
            if(ltIE7){
                // fix container top & overlay height before showing
                fixTop();
                fixHeight();
                SL.addEvent(window, 'scroll', fixTop);
            }

            // fade in animation
            sb.style.display = 'none'; // will be cleared in loadContent()
            sc.style.visibility = 'visible';
	
            animate(so, 'opacity', parseFloat(options.overlayOpacity), options.fadeDuration, cb);
	
        }else{
            SL.removeEvent(so, 'click', SB.close);
            if(ltIE7) SL.removeEvent(window, 'scroll', fixTop);

            // fade out effect
            sb.style.display = 'none';
            animate(so, 'opacity', 0, options.fadeDuration, function(){
                sc.style.visibility = 'hidden';
                sb.style.display = '';
                clearOpacity(so);
            });	
        }
    };

	function getScrollY() {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}
	
    lcpbox.init = function(opts){
        // don't initialize twice
        if(initialized) return;

        // make sure skin is loaded
      /*  if(typeof SB.SKIN == 'undefined'){
            SB.raise('No lcpbox skin loaded');
            return;
        } */

        // apply custom options
        apply(options, opts || {});

        // add markup
        var markup = SB.SKIN.markup.replace(/\{(\w+)\}/g, function(m, p){
            return null;
        });
        var bd = document.body || document.documentElement;
        SL.append(bd, markup);

        // several fixes for IE6

		if( client.isIE7){
		  SL.setStyle(SL.get('lcpbox_container'), 'position', 'absolute');
		  SL.setStyle(SL.get('lcpbox_container'), 'top', getScrollY() +' px');
			  
		  window.onscroll = function(){
		  SL.setStyle(SL.get('lcpbox_container'), 'position', 'absolute');
		  SL.setStyle(SL.get('lcpbox_container'), 'top', getScrollY() +' px');
		  
		  }
		}
        if(ltIE7){

            // give the container absolute positioning
            SL.setStyle(SL.get('lcpbox_container'), 'position', 'absolute');
            // give lcpbox_body "layout"...whatever that is
            SL.get('lcpbox_body').style.zoom = 1;
            // use AlphaImageLoader for transparent PNG support
            var png = SB.SKIN.png_fix;
            if(png && png.constructor == Array){
                for(var i = 0; i < png.length; ++i){
                    var el = SL.get(png[i]);
                    if(el){
                        var match = SL.getStyle(el, 'background-image').match(/url\("(.*\.png)"\)/);
                        if(match){
                            SL.setStyle(el, {
                                backgroundImage: 'none',
                                filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src=' + match[1] + ',sizingMethod=scale);'
                            });
                        }
                    }
                }
            }
        }

        // compile file type regular expressions here for speed
        for(var e in options.ext){
            RE[e] = new RegExp('\.(' + options.ext[e].join('|') + ')\s*$', 'i');
        }

        // set up window resize event handler
        var id;
        SL.addEvent(window, 'resize', function(){
            // use 50 ms event buffering to prevent jerky window resizing
            if(id){
                clearTimeout(id);
                id = null;
            }
            id = setTimeout(function(){
                if(ltIE7) fixHeight();
                resizeContent();
            }, 50);
        });

        if(!options.skipSetup) SB.setup();
        initialized = true;
    };

    lcpbox.setup = function(links, opts){
        // get links if none specified
        if(!links){
            var links = [];
            var a = document.getElementsByTagName('a'), rel;
            for(var i = 0, len = a.length; i < len; ++i){
                rel = a[i].getAttribute('rel');
                if(rel && RE.rel.test(rel)) links[links.length] = a[i];
						
            }
        }else if(!links.length){
            links = [links]; // one link
        }

        var link;
        for(var i = 0, len = links.length; i < len; ++i){
            link = links[i];
            if(typeof link.lcpboxCacheKey == 'undefined'){
                // assign cache key expando
                // use integer primitive to avoid memory leak in IE
                link.lcpboxCacheKey = cache.length;
                SL.addEvent(link, 'click', handleClick); // add listener
            }
            cache[link.lcpboxCacheKey] = this.buildCacheObj(link, opts);
        }
    };

    lcpbox.buildCacheObj = function(link, opts){
        var href = link.href; // don't use getAttribute() here
		var rel = link.rel.split(';')[1];
		var imgalt= link.getElementsByTagName('img')[0].alt;
        var o = {
            el:         link,
            title:      link.getAttribute('title'),
            player:     getPlayer(href),
            options:    apply({}, opts || {}), // break the reference
            content:    href,
			realpic:	rel,
			alt:		imgalt
        };

        // remove link-level options from top-level options
        var opt, l_opts = ['player', 'title', 'height', 'width', 'gallery'];
        for(var i = 0, len = l_opts.length; i < len; ++i){
            opt = l_opts[i];
            if(typeof o.options[opt] != 'undefined'){
                o[opt] = o.options[opt];
                delete o.options[opt];
            }
        }

        // HTML options always trump JavaScript options, so do these last
        var rel = link.getAttribute('rel');
        if(rel){
            // extract gallery name from lcpbox[name] format
            var match = rel.match(RE.gallery);
            if(match) o.gallery = escape(match[2]);

        }

        return o;
    };

    lcpbox.applyOptions = function(opts){
        if(opts){
            // use apply here to break references
            default_options = apply({}, options); // store default options
            options = apply(options, opts); // apply options
        }
    };

    lcpbox.revertOptions = function(){
        if(default_options){
            options = default_options; // revert to default options
            default_options = null; // erase for next time
        }
    };

    lcpbox.open = function(obj, opts){
        // revert options
        this.revertOptions();

        // is it a link?
        if(isLink(obj)){
            if(typeof obj.lcpboxCacheKey == 'undefined' || typeof cache[obj.lcpboxCacheKey] == 'undefined'){
                // link element that hasn't been set up before
                // create on-the-fly object
                obj = this.buildCacheObj(obj, opts);
            }else{
                // link element that has been set up before, get from cache
                obj = cache[obj.lcpboxCacheKey];
            }
        }

        // is it already a gallery?
        if(obj.constructor == Array){
            gallery = obj;
            current = 0;
        }else{
            // create a copy so it doesn't get modified later
            var copy = apply({}, obj);

            // is it part of a gallery?
            if(!obj.gallery){ // single item, no gallery
                gallery = [copy];
                current = 0;
            }else{
                current = null; // reset current
                gallery = []; // clear the current gallery
                var ci;
                for(var i = 0, len = cache.length; i < len; ++i){
                    ci = cache[i];
                    if(ci.gallery){
                        if(ci.content == obj.content
                            && ci.gallery == obj.gallery
                            && ci.title == obj.title){ // compare content, gallery, & title
                                current = gallery.length; // key element found
                        }
                        if(ci.gallery == obj.gallery){
                            gallery.push(apply({}, ci));
                        }
                    }
                }
                // if not found in cache, prepend to front of gallery
                if(current == null){
                    gallery.unshift(copy);
                    current = 0;
                }
            }
        }

        obj = gallery[current];

        // apply custom options
        if(obj.options || opts){
            // use apply here to break references
            this.applyOptions(apply(apply({}, obj.options || {}), opts || {}));
        }

        // filter gallery for unsupported elements
        var match, r;
        for(var i = 0, len = gallery.length; i < len; ++i){
            r = false; // remove the element?
            if(gallery[i].player == 'unsupported'){ // don't support this at all
                r = true;
            }else if(match = RE.unsupported.exec(gallery[i].player)){ // handle unsupported elements
                if(options.handleUnsupported == 'link'){
                    gallery[i].player = 'html';
                    // generate a link to the appropriate plugin download page(s)
                    var s, a, oe = options.errors;
                    switch(match[1]){
                        default:
                            s = 'single';
                            if(match[1] == 'swf' || match[1] == 'flv') match[1] = 'fla';
                            a = [oe[match[1]].url, oe[match[1]].name];
                    }
                    var msg = ''
					//SB.LANG.errors[s].replace(/\{(\d+)\}/g, function(m, i){
                    //    return a[i];
                    //});
                    gallery[i].content = '<div class="lcpbox_message">' + msg + '</div>';
                }else{
                    r = true;
                }
            }else if(gallery[i].player == 'inline'){ // handle inline elements
                // retrieve the innerHTML of the inline element
                var match = RE.inline.exec(gallery[i].content);
                if(match){
                    var el;
                    if(el = SL.get(match[1])){
                        gallery[i].content = el.innerHTML;
                    }else{
                        SB.raise('Cannot find element with id ' + match[1]);
                    }
                }else{
                    SB.raise('Cannot find element id for inline content');
                }
            }
            if(r){
                gallery.splice(i, 1); // remove the element from the gallery
                if(i < current){
                    --current;
                }else if(i == current){
                    // if current is unsupported, look for supported neighbor
                    current = i > 0 ? current - 1 : i;
                }
                --i; // decrement to account for splice
                len = gallery.length; // gallery.length has changed!
            }
        }

        // anything left?
        if(gallery.length){
            // fire onOpen hook
            if(options.onOpen && typeof options.onOpen == 'function'){
                options.onOpen(obj);
            }

            if(!activated){
                // set initial dimensions & load
                setDimensions(options.initialHeight, options.initialWidth);
                adjustHeight(dims.inner_h, dims.top, false);
                adjustWidth(dims.width, false);
                toggleVisible(loadContent);
            } else {
                loadContent();
            }

            activated = true;
        }
    };
    lcpbox.change = function(num){
        if(!gallery) return; // no current gallery
        if(!gallery[num]){ // index does not exist
            if(!options.continuous){
                return;
            }else{
                num = num < 0 ? (gallery.length - 1) : 0; // loop
            }
        }

        if(typeof slide_timer == 'number'){
            clearTimeout(slide_timer);
            slide_timer = null;
            slide_delay = slide_start = 0; // reset slideshow variables
        }
        current = num; // update current

        if(options.onChange && typeof options.onChange == 'function'){
            options.onChange(gallery[current]); // fire onChange handler
        }

        loadContent();
    };
    lcpbox.next = function(){
        this.change(current + 1);
    };

    lcpbox.previous = function(){
        this.change(current - 1);
    };

    lcpbox.play = function(){
        if(!hasNext()) return;
        if(!slide_delay) slide_delay = options.slideshowDelay * 1000;
        if(slide_delay){
            slide_start = new Date().getTime();
            slide_timer = setTimeout(function(){
                slide_delay = slide_start = 0; // reset slideshow
                SB.next();
            }, slide_delay);

            // change play nav to pause
            toggleNav('play', false);
            toggleNav('pause', true);
        }
    };

    lcpbox.pause = function(){
        if(typeof slide_timer == 'number'){
            var time = new Date().getTime();
            slide_delay = Math.max(0, slide_delay - (time - slide_start));

            // any delay left on current slide? if so, stop the timer
            if(slide_delay){
                clearTimeout(slide_timer);
                slide_timer = 'paused';
            }

            // change pause nav to play
            toggleNav('pause', false);
            toggleNav('play', true);
        }
    };

    lcpbox.close = function(){
        if(!activated) return; // already closed

        // stop listening for keys
        listenKeys(false);
        // hide
        toggleVisible(false);
        // remove the content
        if(content){
            content.remove();
            content = null;
        }

        // clear slideshow variables
        if(typeof slide_timer == 'number') clearTimeout(slide_timer);
        slide_timer = null;
        slide_delay = 0;

        // fire onClose handler
        if(options.onClose && typeof options.onClose == 'function'){
            options.onClose(gallery[current]);
        }

        activated = false;
    };

    lcpbox.clearCache = function(){
        for(var i = 0, len = cache.length; i < len; ++i){
            if(cache[i].el){
                SL.removeEvent(cache[i].el, 'click', handleClick);
                delete cache[i].el.lcpboxCacheKey; // remove expando
            }
        }
        cache = [];
    };

    lcpbox.getPlugins = function(){
        return plugins;
    };

    lcpbox.getOptions = function(){
        return options;
    };
    lcpbox.getCurrent = function(){
        return gallery[current];
    };


    lcpbox.getClient = function(){
        return client;
    };
	lcpbox.getContent = function(){
        return content;
    };

    lcpbox.getDimensions = function(){
        return dims;
    };
    lcpbox.raise = function(e){
        if(typeof options.handleException == 'function'){
            options.handleException(e);
        }else{
            throw e;
        }
    };

})();


(function(){
    // shorthand
    var SB = lcpbox;
    var SL = SB.lib;
    var C = SB.getClient();


    var drag;
    var draggable;
    var drag_id = 'lcpbox_drag_layer';
    var preloader;
    var resetDrag = function(){
        drag = {
            x:          0,
            y:          0,
            start_x:    null,
            start_y:    null
        };
    };
    var toggleDrag = function(on, h, w){
        if(on){
            resetDrag();
            // add transparent drag layer to prevent browser dragging of actual image
            var styles = [
                'position:absolute',
                'height:' + h + 'px',
                'width:' + w + 'px',
                'cursor:' + (C.isGecko ? '-moz-grab' : 'move'),
                'background-color:' + (C.isIE ? '#fff;filter:alpha(opacity=0)' : 'transparent')
            ];
            SL.append(SL.get('lcpbox_body_inner'), '<div id="' + drag_id + '" style="' + styles.join(';') + '"></div>');
            SL.addEvent(SL.get(drag_id), 'mousedown', listenDrag);
        }else{
            var d = SL.get(drag_id);
            if(d){
                SL.removeEvent(d, 'mousedown', listenDrag);
                SL.remove(d);
            }
        }
    };
    var listenDrag = function(e){
        // prevent browser dragging
        SL.preventDefault(e);

        var coords = SL.getPageXY(e);
        drag.start_x = coords[0];
        drag.start_y = coords[1];

        draggable = SL.get('lcpbox_content');
        SL.addEvent(document, 'mousemove', positionDrag);
        SL.addEvent(document, 'mouseup', unlistenDrag);
        if(C.isGecko) SL.setStyle(SL.get(drag_id), 'cursor', '-moz-grabbing');
    };
    var unlistenDrag = function(){
        SL.removeEvent(document, 'mousemove', positionDrag);
        SL.removeEvent(document, 'mouseup', unlistenDrag); // clean up
        if(C.isGecko) SL.setStyle(SL.get(drag_id), 'cursor', '-moz-grab');
    };
    var positionDrag = function(e){
        var content = SB.getContent();
        var dims = SB.getDimensions();
        var coords = SL.getPageXY(e);

        var move_x = coords[0] - drag.start_x;
        drag.start_x += move_x;
        drag.x = Math.max(Math.min(0, drag.x + move_x), dims.inner_w - content.width); // x boundaries
        SL.setStyle(draggable, 'left', drag.x + 'px');

        var move_y = coords[1] - drag.start_y;
        drag.start_y += move_y;
        drag.y = Math.max(Math.min(0, drag.y + move_y), dims.inner_h - content.height); // y boundaries
        SL.setStyle(draggable, 'top', drag.y + 'px');
    };
    lcpbox.img = function(id, obj){
        this.id = id;
        this.obj = obj;
        // images are resizable
        this.resizable = true;

        // preload the image
        this.ready = false;
        var self = this; // needed inside preloader callback
        preloader = new Image();
        preloader.onload = function(){
            // height defaults to image height
            self.height = self.obj.height ? parseInt(self.obj.height, 10) : preloader.height;

            // width defaults to image width
            self.width = self.obj.width ? parseInt(self.obj.width, 10) : preloader.width;

            // ready to go
            self.ready = true;

            // clean up to prevent memory leak in IE
            preloader.onload = '';
            preloader = null;
        };
		preloader.alt = this.obj.alt;
        preloader.src = this.obj.content;
		

    };

    lcpbox.img.prototype = {
        markup: function(dims){
            return {
                tag:    'img',
                id:     this.id,
                height: dims.resize_h, // use resized dimensions
                width:  dims.resize_w,
                src:    this.obj.content,
                style:  'position:absolute',
				alt:	this.obj.alt
            };
        },

        onLoad: function(){
            var dims = SB.getDimensions();
            if(dims.drag && SB.getOptions().handleOversize == 'drag'){
                // listen for drag
                // in the case of oversized images, the "resized" height and
                // width will actually be the original image height and width
                toggleDrag(true, dims.resize_h, dims.resize_w);
            }
        },


        remove: function(){
            var el = SL.get(this.id);
            if(el) SL.remove(el);

            // disable drag layer
            toggleDrag(false);

            // prevent old image requests from loading
            if(preloader){
                preloader.onload = '';
                preloader = null;
            }
        }

    };

})();

