/**
CEICOM - SOLUÇÕES EM INTERNET
 */
var Shadowbox = function(){

    var ua = navigator.userAgent.toLowerCase(),
    S = {

        version: "3.0b",
        adapter: null,

        current: -1,
        gallery: [],
        cache: [],
        content: null,

        dimensions: null,

        plugins: null,

        path: '',
        options: {
            adapter: null,              
            animate: true,              
            animateFade: true,         
            autoplayMovies: true,       
            autoDimensions: false,      
                                        
                                       
            continuous: false,          
                                     
                                       
            counterLimit: 10,          
                                     
            counterType: 'default',    
                                        
                                        
            displayCounter: true,       
            displayNav: true,         

            ease: function(x){
                return 1 + Math.pow(x - 1, 3);
            },

            enableKeys: true,        

    
            errors: {
                fla: {
                    name:   'Flash',
                    url:    'http://www.adobe.com/products/flashplayer/'
                },
                qt: {
                    name:   'QuickTime',
                    url:    'http://www.apple.com/quicktime/download/'
                },
                wmp: {
                    name:   'Windows Media Player',
                    url:    'http://www.microsoft.com/windows/windowsmedia/'
                },
                f4m: {
                    name:   'Flip4Mac',
                    url:    'http://www.flip4mac.com/wmv_download.htm'
                }
            },

            
            ext: {
                img:        ['png', 'jpg', 'jpeg', 'gif', 'bmp'],
                swf:        ['swf'],
                flv:        ['flv'],
                qt:         ['dv', 'mov', 'moov', 'movie', 'mp4'],
                wmp:        ['asf', 'wm', 'wmv'],
                qtwmp:      ['avi', 'mpg', 'mpeg'],
                iframe:     ['asp', 'aspx', 'cgi', 'cfm', 'htm', 'html', 'jsp',
                    'pl', 'php', 'php3', 'php4', 'php5', 'phtml', 'rb', 'rhtml',
                    'shtml', 'txt', 'vbs']
            },

            fadeDuration: 0.35,       
            flashParams: {
                bgcolor:            '#000',
                allowFullScreen:    true
            },

            flashVars: {},              
            flashVersion: '9.0.115',   
            handleOversize: 'resize',

            handleUnsupported: 'link',

            initialHeight: 160,         
            initialWidth: 320,          
            language: 'en',             
            modal: false,               
                                        
            onChange: null,             
                                        
                                       
            onClose: null,              
                                        
            onFinish: null,            
                                       
                                       
            onOpen: null,               
                                        
            overlayColor: '#000',     
            overlayOpacity: 0.7,        
            players: ['img'],           
            resizeDuration: 0.35,       
            showOverlay: true,          
            showMovieControls: true,   
            skipSetup: false,           
                                        
            slideshowDelay: 0,        
                                      
                                       
            useSizzle: true,            
            viewportPadding: 20        
                                       
        },

       
        client: {
            isIE:       ua.indexOf('msie') > -1,
            isIE6:      ua.indexOf('msie 6') > -1,
            isIE7:      ua.indexOf('msie 7') > -1,
            isGecko:    ua.indexOf('gecko') > -1 && ua.indexOf('safari') == -1,
            isWebkit:   ua.indexOf('applewebkit/') > -1,
            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
        },

        regex: {
            domain:         /:\/\/(.*?)[:\/]/,             
            inline:         /#(.+)$/,                       
            rel:            /^(light|shadow)box/i,        
            gallery:        /^(light|shadow)box\[(.*?)\]/i, 
            unsupported:    /^unsupported-(\w+)/,           
            param:          /\s*([a-z_]*?)\s*=\s*(.+)\s*/   
        },

      
        libraries: {
            Prototype:  'prototype',
            jQuery:     'jquery',
            MooTools:   'mootools',
            YAHOO:      'yui',
            dojo:       'dojo',
            Ext:        'ext'
        },

        applyOptions: function(opts){
            if(opts){
                default_options = apply({}, S.options);
                apply(S.options, opts);
            }
        },

        buildCacheObj: function(link, opts){
            var href = link.href, // don't use getAttribute() here
            obj = {
                el:         link,
                title:      link.getAttribute('title'),
                options:    apply({}, opts || {}),
                content:    href
            };

            // remove link-level options from top-level options
            each(['player', 'title', 'height', 'width', 'gallery'], function(o){
                if(typeof obj.options[o] != 'undefined'){
                    obj[o] = obj.options[o];
                    delete obj.options[o];
                }
            });

            if(!obj.player)
                obj.player = getPlayer(href);

            // HTML options always trump JavaScript options, so do these last
            var rel = link.getAttribute('rel');
            if(rel){
                // extract gallery name from shadowbox[name] format
                var m = rel.match(S.regex.gallery);
                if(m)
                    obj.gallery = escape(m[2]);

                // other parameters
                each(rel.split(';'), function(p){
                    m = p.match(S.regex.param);
                    if(m){
                        if(m[1] == 'options')
                            eval('apply(obj.options,' + m[2] + ')');
                        else
                            obj[m[1]] = m[2];
                    }
                });
            }

            return obj;
        },

        change: function(n){
            if(!S.gallery) return; // no current gallery
            if(!S.gallery[n]){ // index does not exist
                if(!S.options.continuous){
                    return;
                }else{
                    n = n < 0 ? S.gallery.length - 1 : 0; // loop
                }
            }

            // update current
            S.current = n;

            if(typeof slide_timer == 'number'){
                clearTimeout(slide_timer);
                slide_timer = null;
                slide_delay = slide_start = 0; // reset slideshow variables
            }

            if(S.options.onChange)
                S.options.onChange();

            loadContent();
        },

        clearCache: function(){
            each(S.cache, function(obj){
                if(obj.el)
                    S.lib.removeEvent(obj.el, 'click', handleClick);
            });
            S.cache = [];
        },

        close: function(){
            if(!active) return; // already closed
            active = false;

            listenKeys(false);

            // remove the content
            if(S.content){
                S.content.remove();
                S.content = null;
            }

            // clear slideshow variables
            if(typeof slide_timer == 'number')
                clearTimeout(slide_timer);
            slide_timer = null;
            slide_delay = 0;

            if(S.options.onClose)
                S.options.onClose();

            S.skin.onClose();

            S.revertOptions();

            // reset troublesome elements to stored visibility settings
            each(v_cache, function(c){
                c[0].style.visibility = c[1];
            });
        },


        contentId: function(){
            return content_id;
        },

        getCounter: function(){
            var len = S.gallery.length;

            if(S.options.counterType == 'skip'){
                // limit the counter?
                var c = [],
                    i = 0,
                    end = len,
                    limit = parseInt(S.options.counterLimit) || 0;

                if(limit < len && limit > 2){ // support large galleries
                    var h = Math.floor(limit / 2);
                    i = S.current - h;
                    if(i < 0) i += len;
                    end = S.current + (limit - h);
                    if(end > len) end -= len;
                }
                while(i != end){
                    if(i == len) i = 0;
                    c.push(i++);
                }
            }else
                var c = (S.current + 1) + ' ' + S.lang.of + ' ' + len;

            return c;
        },


        getCurrent: function(){
            return S.current > -1 ? S.gallery[S.current] : null;
        },


        hasNext: function(){
            return S.gallery.length > 1 &&
                (S.current != S.gallery.length - 1 || S.options.continuous);
        },

       
        init: function(opts){
            if(initialized) return; // don't initialize twice
            initialized = true;

            opts = opts || {};
            init_options = opts;

            // apply options
            if(opts)
                apply(S.options, opts);

            // compile file type regular expressions here for speed
            for(var e in S.options.ext)
                S.regex[e] = new RegExp('\.(' + S.options.ext[e].join('|') + ')\s*$', 'i');

            if(!S.path){
                // determine script path automatically
                var path_re = /(.+)shadowbox\.js/i, path;
                each(document.getElementsByTagName('script'), function(s){
                    if((path = path_re.exec(s.src)) != null){
                        S.path = path[1];
                        return false;
                    }
                });
            }

            // determine adapter
            if(S.options.adapter)
                S.adapter = S.options.adapter;
            else{
                for(var lib in S.libraries){
                    if(typeof window[lib] != 'undefined'){
                        S.adapter = S.libraries[lib];
                        break;
                    }
                }
                if(!S.adapter)
                    S.adapter = 'base';
            }

            // load dependencies
            if(S.options.useSizzle && !window['Sizzle'])
                U.include(S.path + 'libraries/sizzle/sizzle.js');
            if(!S.lang)
                U.include(S.path + 'languages/shadowbox-' + S.options.language + '.js');
            each(S.options.players, function(p){
                if((p == 'swf' || p == 'flv') && !window['swfobject'])
                    U.include(S.path + 'libraries/swfobject/swfobject.js');
                if(!S[p])
                    U.include(S.path + 'players/shadowbox-' + p + '.js');
            });
            if(!S.lib)
                U.include(S.path + 'adapters/shadowbox-' + S.adapter + '.js');
        },

        isActive: function(){
            return active;
        },

    
        isPaused: function(){
            return slide_timer == 'paused';
        },


        load: function(){
            // apply skin options, re-apply user init options in case they overwrite
            if(S.skin.options){
                apply(S.options, S.skin.options);
                apply(S.options, init_options);
            }

            // append markup and initialize skin
            var markup = S.skin.markup.replace(/\{(\w+)\}/g, function(m, p){
                return S.lang[p];
            });
            S.lib.append(document.body, markup);

            if(S.skin.init)
                S.skin.init();

            // set up window resize event handler
            var id;
            S.lib.addEvent(window, 'resize', function(){
                // use 50 ms event buffering to prevent jerky window resizing
                if(id){
                    clearTimeout(id);
                    id = null;
                }
                // check if activated because IE7 fires window resize event
                // when container display is set to block
                if(active){
                    id = setTimeout(function(){
                        if(S.skin.onWindowResize)
                            S.skin.onWindowResize();
                        var c = S.content;
                        if(c && c.onWindowResize)
                            c.onWindowResize();
                    }, 50);
                }
            });

            if(!S.options.skipSetup)
                S.setup();
        },

        next: function(){
            S.change(S.current + 1);
        },

        open: function(obj){
            // if it's a link element, build an object on the fly
            if(U.isLink(obj))
                obj = S.buildCacheObj(obj);

            // set up the gallery
            if(obj.constructor == Array){
                S.gallery = obj;
                S.current = 0;
            }else{
                if(!obj.gallery){
                    // single item, no gallery
                    S.gallery = [obj];
                    S.current = 0;
                }else{
                    // gallery item, build gallery from cached gallery elements
                    S.current = null;
                    S.gallery = [];
                    each(S.cache, function(c){
                        if(c.gallery && c.gallery == obj.gallery){
                            if(S.current == null && c.content == obj.content && c.title == obj.title)
                                S.current = S.gallery.length;
                            S.gallery.push(c);
                        }
                    });

                    // if not found in cache, prepend to front of gallery
                    if(S.current == null){
                        S.gallery.unshift(obj);
                        S.current = 0;
                    }
                }
            }

            obj = S.getCurrent();
            if(obj.options){
                S.revertOptions();
                S.applyOptions(obj.options);
            }

            // filter gallery for unsupported elements
            var g, r, m, s, a, oe = S.options.errors, msg, el;
            for(var i = 0; i < S.gallery.length; ++i){

                g = S.gallery[i] = apply({}, S.gallery[i]);
                r = false; // remove the element?
                if(g.player == 'unsupported'){
                    // don't support this at all
                    r = true;
                }else if(m = S.regex.unsupported.exec(g.player)){
                    // handle unsupported elements
                    if(S.options.handleUnsupported == 'link'){
                        g.player = 'html';
                        // generate a link to the appropriate plugin download page(s)
                        switch(m[1]){
                            case 'qtwmp':
                                s = 'either';
                                a = [oe.qt.url, oe.qt.name, oe.wmp.url, oe.wmp.name];
                            break;
                            case 'qtf4m':
                                s = 'shared';
                                a = [oe.qt.url, oe.qt.name, oe.f4m.url, oe.f4m.name];
                            break;
                            default:
                                s = 'single';
                                if(m[1] == 'swf' || m[1] == 'flv') m[1] = 'fla';
                                a = [oe[m[1]].url, oe[m[1]].name];
                        }
                        msg = S.lang.errors[s].replace(/\{(\d+)\}/g, function(m, n){
                            return a[n];
                        });
                        g.content = '<div class="sb-message">' + msg + '</div>';
                    }else
                        r = true;
                }else if(g.player == 'inline'){
                    // inline element, retrieve innerHTML
                    m = S.regex.inline.exec(g.content);
                    if(m){
                        var el = U.get(m[1]);
                        if(el)
                            g.content = el.innerHTML;
                        else
                            throw 'Cannot find element with id ' + m[1];
                    }else
                        throw 'Cannot find element id for inline content';
                }else if(g.player == 'swf' || g.player == 'flv'){
                    var version = (g.options && g.options.flashVersion) || S.options.flashVersion;
                    if(!swfobject.hasFlashPlayerVersion(version)){
 
                        g.width = 310;
                        // minimum height is 127, but +20 pixels on top and bottom
                        // looks better
                        g.height = 177;
                    }
                }
                if(r){
                    S.gallery.splice(i, 1); // remove from gallery
                    if(i < S.current)
                        --S.current; // maintain integrity of S.current
                    else if(i == S.current)
                        S.current = i > 0 ? i - 1 : i; // look for supported neighbor
                    --i; // decrement index for next loop
                }
            }

            // anything left to display?
            if(S.gallery.length){
                if(!active){
                    // fire onOpen hook
                    if(typeof S.options.onOpen == 'function' && S.options.onOpen(obj) === false) return;

                    // hide elements troublesome for modal overlays
                    v_cache = [];
                    each(['select', 'object', 'embed', 'canvas'], function(tag){
                        each(document.getElementsByTagName(tag), function(el){
                            v_cache.push([el, el.style.visibility || 'visible']);
                            el.style.visibility = 'hidden';
                        });
                    });

                    // set initial dimensions & load
                    var h = S.options.autoDimensions && 'height' in obj
                        ? obj.height
                        : S.options.initialHeight;
                    var w = S.options.autoDimensions && 'width' in obj
                        ? obj.width
                        : S.options.initialWidth;

                    S.skin.onOpen(h, w, loadContent);
                }else
                    loadContent();

                active = true;
            }
        },

        /**
         * Pauses the current slideshow.
         *
         * @return  void
         * @public
         */
        pause: function(){
            if(typeof slide_timer != 'number') return;

            var time = new Date().getTime();
            slide_delay = Math.max(0, slide_delay - (time - slide_start));

            // if there's any time left on current slide, pause the timer
            if(slide_delay){
                clearTimeout(slide_timer);
                slide_timer = 'paused';

                if(S.skin.onPause)
                    S.skin.onPause();
            }
        },

        play: function(){
            if(!S.hasNext()) return;
            if(!slide_delay) slide_delay = S.options.slideshowDelay * 1000;
            if(slide_delay){
                slide_start = new Date().getTime();
                slide_timer = setTimeout(function(){
                    slide_delay = slide_start = 0; // reset slideshow
                    S.next();
                }, slide_delay);

                if(S.skin.onPlay)
                    S.skin.onPlay();
            }
        },

        previous: function(){
            S.change(S.current - 1);
        },

        revertOptions: function(){
            apply(S.options, default_options);
        },

        setDimensions: function(height, width, max_h, max_w, tb, lr, resizable){
            var h = height = parseInt(height),
                w = width = parseInt(width),
                pad = parseInt(S.options.viewportPadding) || 0;

            // calculate the max height/width
            var extra_h = 2 * pad + tb;
            if(h + extra_h >= max_h) h = max_h - extra_h;
            var extra_w = 2 * pad + lr;
            if(w + extra_w >= max_w) w = max_w - extra_w;

            // handle oversized content
            var resize_h = height,
                resize_w = width,
                change_h = (height - h) / height,
                change_w = (width - w) / width,
                oversized = (change_h > 0 || change_w > 0);
            if(resizable && oversized && S.options.handleOversize == 'resize'){
                // adjust resized height/width, preserve original aspect ratio
                if(change_h > change_w)
                    w = Math.round((width / height) * h);
                else if(change_w > change_h)
                    h = Math.round((height / width) * w);
                resize_w = w;
                resize_h = h;
            }

            // update Shadowbox.dimensions
            S.dimensions = {
                height:     h + tb,
                width:      w + lr,
                inner_h:    h,
                inner_w:    w,
                top:        (max_h - (h + extra_h)) / 2 + pad,
                left:       (max_w - (w + extra_w)) / 2 + pad,
                oversized:  oversized,
                resize_h:   resize_h,
                resize_w:   resize_w
            };

            return S.dimensions;
        },

        setup: function(links, opts){
            // get links if none specified
            if(!links){
                var links = [], rel;
                each(document.getElementsByTagName('a'), function(a){
                    rel = a.getAttribute('rel');
                    if(rel && S.regex.rel.test(rel)) links.push(a);
                });
            }else{
                var len = links.length;
                if(len){
                    if(window['Sizzle']){
                        if(typeof links == 'string')
                            links = Sizzle(links); // lone selector
                        else if(len == 2 && links.push && typeof links[0] == 'string' && links[1].nodeType)
                            links = Sizzle(links[0], links[1]); // selector + context
                    }
                }else
                    links = [links]; // single link
            }

            each(links, function(link){
                if(typeof link.shadowboxCacheKey == 'undefined'){
                    // assign cache key expando, use integer primitive to avoid
                    // memory leak in IE
                    link.shadowboxCacheKey = S.cache.length;
                    // add onclick listener
                    S.lib.addEvent(link, 'click', handleClick);
                }
                S.cache[link.shadowboxCacheKey] = S.buildCacheObj(link, opts);
            });
        }

    },

    U = S.util = {

        animate: function(el, p, to, d, cb){
            var from = parseFloat(S.lib.getStyle(el, p));
            if(isNaN(from)) from = 0;

            var delta = to - from;
            if(delta == 0){
                if(cb) cb();
                return; // nothing to animate
            }

            var op = p == 'opacity';

            function fn(ease){
                var to = from + ease * delta;
                if(op)
                    U.setOpacity(el, to);
                else
                    el.style[p] = to + 'px'; // default unit is px
            }

  
            if(!d || (!op && !S.options.animate) || (op && !S.options.animateFade)){
                fn(1);
                if(cb) cb();
                return;
            }

            d *= 1000; // convert to milliseconds
            var begin = new Date().getTime(),
                end = begin + d,
                time,
                timer = setInterval(function(){
                    time = new Date().getTime();
                    if(time >= end){ // end of animation
                        clearInterval(timer);
                        fn(1);
                        if(cb) cb();
                    }else
                        fn(S.options.ease((time - begin) / d));
                }, 10); // 10 ms interval is minimum on webkit
        },

        apply: function(o, e){
            for(var p in e)
                o[p] = e[p];
            return o;
        },


        clearOpacity: function(el){
            var s = el.style;
            if(window.ActiveXObject){
                // be careful not to overwrite other filters!
                if(typeof s.filter == 'string' && (/alpha/i).test(s.filter))
                    s.filter = s.filter.replace(/[\w\.]*alpha\(.*?\);?/i, '');
            }else
                s.opacity = '';
        },


        each: function(obj, fn, scope){
            for(var i = 0, len = obj.length; i < len; ++i)
                if(fn.call(scope || obj[i], obj[i], i, obj) === false) return;
        },


        get: function(id){
            return document.getElementById(id);
        },

        include: function(){
            var includes = {};
            return function(file){
                if(includes[file]) return; // don't include same file twice
                includes[file] = true;
                document.write('<scr' + 'ipt type="text/javascript" src="' + file + '"><\/script>');
            }
        }(),

        isLink: function(obj){
            if(!obj || !obj.tagName) return false;
            var up = obj.tagName.toUpperCase();
            return up == 'A' || up == 'AREA';
        },

        removeChildren: function(el){
            while(el.firstChild)
                el.removeChild(el.firstChild);
        },

      
        setOpacity: function(el, o){
            var s = el.style;
            if(window.ActiveXObject){
                s.zoom = 1; // trigger hasLayout
                s.filter = (s.filter || '').replace(/\s*alpha\([^\)]*\)/gi, '') +
                    (o == 1 ? '' : ' alpha(opacity=' + (o * 100) + ')');
            }else
                s.opacity = o;
        }

    },

    // shorthand
    apply = U.apply,
    each = U.each,


    init_options,

    initialized = false,

    default_options = {},

    content_id = 'sb-content',

    active = false,

    slide_timer,

    slide_start,

    slide_delay = 0,

    v_cache = [];

    if(navigator.plugins && navigator.plugins.length){
        var names = [];
        each(navigator.plugins, function(p){
            names.push(p.name);
        });
        names = names.join();
        var detectPlugin = function(n){
            return names.indexOf(n) > -1;
        }
        var f4m = detectPlugin('Flip4Mac');
        S.plugins = {
            fla:    detectPlugin('Shockwave Flash'),
            qt:     detectPlugin('QuickTime'),
            wmp:    !f4m && detectPlugin('Windows Media'), // if it's Flip4Mac, it's not really WMP
            f4m:    f4m
        }
    }else{
        function detectPlugin(n){
            try{
                var axo = new ActiveXObject(n);
            }catch(e){}
            return !!axo;
        }
        S.plugins = {
            fla:    detectPlugin('ShockwaveFlash.ShockwaveFlash'),
            qt:     detectPlugin('QuickTime.QuickTime'),
            wmp:    detectPlugin('wmplayer.ocx'),
            f4m:    false
        }
    }

    function getPlayer(url){
        var re = S.regex,
            p = S.plugins,
            m = url.match(re.domain),
            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';
        if(re.swf.test(url)) return p.fla ? 'swf' : 'unsupported-swf';
        if(re.flv.test(url)) return p.fla ? 'flv' : 'unsupported-flv';
        if(re.qt.test(url)) return p.qt ? 'qt' : 'unsupported-qt';
        if(re.wmp.test(url)){
            if(p.wmp) return 'wmp';
            if(p.f4m) return 'qt';
            if(S.client.isMac) return p.qt ? 'unsupported-f4m' : 'unsupported-qtf4m';
            return 'unsupported-wmp';
        }
        if(re.qtwmp.test(url)){
            if(p.qt) return 'qt';
            if(p.wmp) return 'wmp';
            return S.client.isMac ? 'unsupported-qt' : 'unsupported-qtwmp';
        }
        if(!d || re.iframe.test(url))
            return 'iframe';
        return 'unsupported'; // same domain, not supported
    }

    function handleClick(e){
        // get anchor/area element
        var link;
        if(U.isLink(this)){
            link = this; // jQuery, Prototype, YUI
        }else{
            link = S.lib.getTarget(e); // Ext, standalone
            while(!U.isLink(link) && link.parentNode)
                link = link.parentNode;
        }


        if(link){
            // if this link has already been set up, use the cached version
            var key = link.shadowboxCacheKey;
            if(typeof key != 'undefined' && typeof S.cache[key] != 'undefined')
                link = S.cache[key];

            S.open(link);
            if(S.gallery.length) S.lib.preventDefault(e); // stop event
        }
    }

    function listenKeys(on){
        if(!S.options.enableKeys) return;
        S.lib[(on ? 'add' : 'remove') + 'Event'](document, 'keydown', handleKey);
    }

    function handleKey(e){
        var code = S.lib.keyCode(e);

        // attempt to prevent default key action
        S.lib.preventDefault(e);

        switch(code){
            case 81: // q
            case 88: // x
            case 27: // esc
                S.close();
                break;
            case 37: // left
                S.previous();
                break;
            case 39: // right
                S.next();
                break;
            case 32: // space
                S[(typeof slide_timer == 'number' ? 'pause' : 'play')]();
        }
    }

    function loadContent(){
        var obj = S.getCurrent();
        if(!obj) return;

        // determine player, inline is really just HTML
        var p = obj.player == 'inline' ? 'html' : obj.player;
        if(typeof S[p] != 'function')
            throw 'Unknown player: ' + p;

        var change = false;
        if(S.content){
            // changing from some previous content
            S.content.remove(); // remove old content
            change = true;

            S.revertOptions();
            if(obj.options)
                S.applyOptions(obj.options);
        }

        // make sure the body element doesn't have any children, just in case
        U.removeChildren(S.skin.bodyEl());

        // load the content
        S.content = new S[p](obj);
        listenKeys(false); // disable the keyboard while content is loading

        S.skin.onLoad(S.content, change, function(){
            if(!S.content) return;

            if(typeof S.content.ready != 'undefined'){
                // if content object has a ready property, wait for it to be
                // ready before loading
                var id = setInterval(function(){
                    if(S.content){
                        if(S.content.ready){
                            clearInterval(id);
                            id = null;
                            S.skin.onReady(contentReady);
                        }
                    }else{ // content has been removed
                        clearInterval(id);
                        id = null;
                    }
                }, 100);
            }else
                S.skin.onReady(contentReady);
        });

        // preload neighboring gallery images
        if(S.gallery.length > 1){
            var next = S.gallery[S.current + 1] || S.gallery[0];
            if(next.player == 'img'){
                var a = new Image();
                a.src = next.content;
            }
            var prev = S.gallery[S.current - 1] || S.gallery[S.gallery.length - 1];
            if(prev.player == 'img'){
                var b = new Image();
                b.src = prev.content;
            }
        }
    }


    function contentReady(){
        if(!S.content) return;
        S.content.append(S.skin.bodyEl(), content_id, S.dimensions);
        S.skin.onFinish(finishContent);
    }

    function finishContent(){
        if(!S.content) return;

        if(S.content.onLoad)
            S.content.onLoad();
        if(S.options.onFinish)
            S.options.onFinish();
        if(!S.isPaused())
            S.play(); // kick off next slide

        listenKeys(true); // re-enable keyboard when finished
    }

    return S;

}();

Shadowbox.skin = function(){

    var S = Shadowbox,
        U = S.util,
    overlay_on = false,
    png = [
        'sb-nav-close',
        'sb-nav-next',
        'sb-nav-play',
        'sb-nav-pause',
        'sb-nav-previous'
    ];

    function fixTop(){
        U.get('sb-container').style.top = document.documentElement.scrollTop + 'px';
    }

    function toggleVisible(cb){
        var so = U.get('sb-overlay'),
            sc = U.get('sb-container'),
            sb = U.get('sb-wrapper');

        if(cb){
            if(S.client.isIE6){
                // fix container top before showing
                fixTop();
                S.lib.addEvent(window, 'scroll', fixTop);
            }
            if(S.options.showOverlay){
                overlay_on = true;

                // set overlay color/opacity
                so.style.backgroundColor = S.options.overlayColor;
                U.setOpacity(so, 0);
                if(!S.options.modal) S.lib.addEvent(so, 'click', S.close);

                sb.style.display = 'none'; // cleared in onLoad
            }
            sc.style.visibility = 'visible';
            if(overlay_on){
                // fade in effect
                var op = parseFloat(S.options.overlayOpacity);
                U.animate(so, 'opacity', op, S.options.fadeDuration, cb);
            }else
                cb();
        }else{
            if(S.client.isIE6)
                S.lib.removeEvent(window, 'scroll', fixTop);
            S.lib.removeEvent(so, 'click', S.close);
            if(overlay_on){
                // fade out effect
                sb.style.display = 'none';
                U.animate(so, 'opacity', 0, S.options.fadeDuration, function(){
                    sc.style.display = '';
                    sb.style.display = '';
                    U.clearOpacity(so);
                });
            }else
                sc.style.visibility = 'hidden';
        }
    }


    function toggleNav(id, on){
        var el = U.get('sb-nav-' + id);
        if(el) el.style.display = on ? '' : 'none';
    }

    function toggleLoading(on, cb){
        var ld = U.get('sb-loading'),
            p = S.getCurrent().player,
            anim = (p == 'img' || p == 'html'); // fade on images & html

        if(on){
            function fn(){
                U.clearOpacity(ld);
                if(cb) cb();
            }

            U.setOpacity(ld, 0);
            ld.style.display = '';

            if(anim)
                U.animate(ld, 'opacity', 1, S.options.fadeDuration, fn);
            else
                fn();
        }else{
            function fn(){
                ld.style.display = 'none';
                U.clearOpacity(ld);
                if(cb) cb();
            }

            if(anim)
                U.animate(ld, 'opacity', 0, S.options.fadeDuration, fn);
            else
                fn();
        }
    }

    function buildBars(cb){
        var obj = S.getCurrent();

        // build the title, if present
        U.get('sb-title-inner').innerHTML = obj.title || '';

        // build the nav
        var c, n, pl, pa, p;
        if(S.options.displayNav){
            c = true;
            // next & previous links
            var len = S.gallery.length;
            if(len > 1){
                if(S.options.continuous)
                    n = p = true; // show both
                else{
                    n = (len - 1) > S.current; // not last in gallery, show next
                    p = S.current > 0; // not first in gallery, show previous
                }
            }
            // in a slideshow?
            if(S.options.slideshowDelay > 0 && S.hasNext()){
                pa = !S.isPaused();
                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 c = '';
        if(S.options.displayCounter && S.gallery.length > 1){
            var count = S.getCounter();
            if(typeof count == 'string') // default
                c = count;
            else{
                U.each(count, function(i){
                    c += '<a onclick="Shadowbox.change(' + i + ');"'
                    if(i == S.current) c += ' class="sb-counter-current"';
                    c += '>' + (i + 1) + '</a>';
                });
            }
        }
        U.get('sb-counter').innerHTML = c;

        cb();
    }

    function hideBars(anim, cb){
        var sw = U.get('sb-wrapper'),
            st = U.get('sb-title'),
            si = U.get('sb-info'),
            ti = U.get('sb-title-inner'),
            ii = U.get('sb-info-inner'),
            t = parseInt(S.lib.getStyle(ti, 'height')) || 0,
            b = parseInt(S.lib.getStyle(ii, 'height')) || 0;

        function fn(){
            // hide bars here in case of overflow, build after hidden
            ti.style.visibility = ii.style.visibility = 'hidden';
            buildBars(cb);
        }

        if(anim){
            U.animate(st, 'height', 0, 0.35);
            U.animate(si, 'height', 0, 0.35);
            U.animate(sw, 'paddingTop', t, 0.35);
            U.animate(sw, 'paddingBottom', b, 0.35, fn);
        }else{
            st.style.height = si.style.height = '0px';
            sw.style.paddingTop = t + 'px';
            sw.style.paddingBottom = b + 'px';
            fn();
        }
    }

    function showBars(cb){
        var sw = U.get('sb-wrapper'),
            st = U.get('sb-title'),
            si = U.get('sb-info'),
            ti = U.get('sb-title-inner'),
            ii = U.get('sb-info-inner'),
            t = parseInt(S.lib.getStyle(ti, 'height')) || 0,
            b = parseInt(S.lib.getStyle(ii, 'height')) || 0;

        // clear visibility before animating into view
        ti.style.visibility = ii.style.visibility = '';

        // show title?
        if(ti.innerHTML != ''){
            U.animate(st, 'height', t, 0.35);
            U.animate(sw, 'paddingTop', 0, 0.35);
        }
        U.animate(si, 'height', b, 0.35);
        U.animate(sw, 'paddingBottom', 0, 0.35, cb);
    }

    function adjustHeight(height, top, anim, cb){
        var sb = U.get('sb-body'),
            s = U.get('sb-wrapper'),
            h = parseInt(height),
            t = parseInt(top);

        if(anim){
            U.animate(sb, 'height', h, S.options.resizeDuration);
            U.animate(s, 'top', t, S.options.resizeDuration, cb);
        }else{
            sb.style.height = h + 'px';
            s.style.top = t + 'px';
            if(cb) cb();
        }
    }

    function adjustWidth(width, left, anim, cb){
        var s = U.get('sb-wrapper'),
            w = parseInt(width),
            l = parseInt(left);

        if(anim){
            U.animate(s, 'width', w, S.options.resizeDuration);
            U.animate(s, 'left', l, S.options.resizeDuration, cb);
        }else{
            s.style.width = w + 'px';
            s.style.left = l + 'px';
            if(cb) cb();
        }
    }

    function resizeContent(cb){
        var c = S.content;
        if(!c) return;

        // set new dimensions
        var d = setDimensions(c.height, c.width, c.resizable);

        switch(S.options.animSequence){
            case 'hw':
                adjustHeight(d.inner_h, d.top, true, function(){
                    adjustWidth(d.width, d.left, true, cb);
                });
            break;
            case 'wh':
                adjustWidth(d.width, d.left, true, function(){
                    adjustHeight(d.inner_h, d.top, true, cb);
                });
            break;
            default: // sync
                adjustWidth(d.width, d.left, true);
                adjustHeight(d.inner_h, d.top, true, cb);
        }
    }

    function setDimensions(height, width, resizable){
        var sbi = U.get('sb-body-inner')
            sw = U.get('sb-wrapper'),
            so = U.get('sb-overlay'),
            tb = sw.offsetHeight - sbi.offsetHeight,
            lr = sw.offsetWidth - sbi.offsetWidth,
            max_h = so.offsetHeight, // measure overlay to get viewport size for IE6
            max_w = so.offsetWidth;

        return S.setDimensions(height, width, max_h, max_w, tb, lr, resizable);
    }

    return {

        markup: '<div id="sb-container">' +
                    '<div id="sb-overlay"></div>' +
                    '<div id="sb-wrapper">' +
                        '<div id="sb-title">' +
                            '<div id="sb-title-inner"></div>' +
                        '</div>' +
                        '<div id="sb-body">' +
                            '<div id="sb-body-inner"></div>' +
                            '<div id="sb-loading">' +
                                '<a onclick="Shadowbox.close()">{cancel}</a>' +
                            '</div>' +
                        '</div>' +
                        '<div id="sb-info">' +
                            '<div id="sb-info-inner">' +
                                '<div id="sb-counter"></div>' +
                                '<div id="sb-nav">' +
                                    '<a id="sb-nav-close" title="{close}" onclick="Shadowbox.close()"></a>' +
                                    '<a id="sb-nav-next" title="{next}" onclick="Shadowbox.next()"></a>' +
                                    '<a id="sb-nav-play" title="{play}" onclick="Shadowbox.play()"></a>' +
                                    '<a id="sb-nav-pause" title="{pause}" onclick="Shadowbox.pause()"></a>' +
                                    '<a id="sb-nav-previous" title="{previous}" onclick="Shadowbox.previous()"></a>' +
                                '</div>' +
                                '<div style="clear:both"></div>' +
                            '</div>' +
                        '</div>' +
                    '</div>' +
                '</div>',

        options: {

            /**
             * Determines the sequence of the resizing animations. A value of
             * "hw" will resize first the height, then the width. Likewise, "wh"
             * will resize the width first, then the height. The default is
             * "sync" and will resize both simultaneously.
             *
             * @var     String
             * @public
             */
            animSequence: 'sync'

        },

        /**
         * Initialization function. Called immediately after this skin's markup
         * has been appended to the document with all of the necessary language
         * replacements done.
         *
         * @return  void
         * @public
         */
        init: function(){
            // several fixes for IE6
            if(S.client.isIE6){
                // trigger hasLayout on sb-body
                U.get('sb-body').style.zoom = 1;

                // support transparent PNG's via AlphaImageLoader
                var el, m, re = /url\("(.*\.png)"\)/;
                U.each(png, function(id){
                    el = U.get(id);
                    if(el){
                        m = S.lib.getStyle(el, 'backgroundImage').match(re);
                        if(m){
                            el.style.backgroundImage = 'none';
                            el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,src=' +
                                m[1] + ',sizingMethod=scale);';
                        }
                    }
                });
            }
        },

        bodyEl: function(){
            return U.get('sb-body-inner');
        },

        onOpen: function(h, w, cb){
            U.get('sb-container').style.display = 'block';

            var d = setDimensions(h, w);
            adjustHeight(d.inner_h, d.top, false);
            adjustWidth(d.width, d.left, false);
            toggleVisible(cb);
        },

        onLoad: function(content, change, cb){
            toggleLoading(true);

            hideBars(change, function(){ // if changing, animate the bars transition
                if(!content) return;

                // if opening, clear #sb-wrapper display
                if(!change) U.get('sb-wrapper').style.display = '';

                cb();
            });
        },

        onReady: function(cb){
            resizeContent(function(){
                showBars(cb);
            });
        },


        onFinish: function(cb){
            toggleLoading(false, cb);
        },

        onClose: function(){
            toggleVisible(false);
        },


        onPlay: function(){
            toggleNav('play', false);
            toggleNav('pause', true);
        },


        onPause: function(){
            toggleNav('pause', false);
            toggleNav('play', true);
        },


        onWindowResize: function(){
            var c = S.content;
            if(!c) return;

            // set new dimensions
            var d = setDimensions(c.height, c.width, c.resizable);

            adjustWidth(d.width, d.left, false);
            adjustHeight(d.inner_h, d.top, false);

            var el = U.get(S.contentId());
            if(el){
               
                if(c.resizable && S.options.handleOversize == 'resize'){
                    el.height = d.resize_h;
                    el.width = d.resize_w;
                }
            }
        }

    };

}();

