$(document).ready(function() {
    if ($('#background li').length)
        background._slideshow();
    background._position();
    nav.init();
    gallery.init();

    $(window).resize(function() {
        background._position();
    });

    $('#toggle').click(function(e) {
        e.preventDefault();
        if (typeof(vetrine) != 'undefined') clearTimeout(vetrine);
        var el = $('#vetrine');
        if (!el.hasClass('open'))
            el.animate({'height': 123}, 350, function() {
                $(this).addClass('open');
            })
        else
            el.animate({'height': 16}, 350, function() {
                $(this).removeClass('open');
            })

    });

    //sposta in basso il footer nelle pagine con contenuto flessibile
    /*if ($('#content').height() > 400) {
        $('#wrapper').height($('#content').height() + 200);
    } */

});

var background = {
    max_width: 1280,
    min_width: 990,
    img_ratio: 1.666666,
    current: 0,
    _position: function() {
        background.w_w = $(window).width();
        background.bg_w = '1280';
        if (background.w_w < background.max_width && background.w_w > background.min_width) {
            $('#background img').css({width: background.w_w, height: background.w_w / background.img_ratio});
            $('#background #innerwrapper').css({left:0});
            $('#background #innerwrapper ul').css({height:background.w_w / background.img_ratio});
        }
        else if (background.w_w > background.max_width) {
            $('#background img').css({width: 1280, height: 1280 / background.img_ratio});
            $('#background #innerwrapper').css({left: (background.w_w - background.bg_w) / 2 });
            $('#background #innerwrapper ul').css({height:1280 / background.img_ratio});
        }
    },
    _slideshow: function() {
        $('#background li img:first').show();
        if ($('#background li').length == 1) return;
        background.div = $('#background ul');
        background.images = $('#background li');
        currentInterval = setInterval('background.showNext(1)', 6000);

    },
    showNext: function(dir) {
        background.current = (dir) ? background.current + dir : background.current++;
        background.current = (background.current == background.images.length) ? 0 : (background.current < 0) ? background.images.length - 1 : background.current;
        $toshow = $('img', background.div).eq(background.current);
        $toshow.css('zIndex', 10);
        $toshow.fadeIn('slow', function() {
            $toshow.css('zIndex', 0);
            $('img', background.div).not($toshow).hide();
        });
    }
}


var nav = {
    init: function() {
        var $mainmenu = $("#nav>ul")
        var $headers = $("#nav ul").parent()
        $headers.each(function(i) {
            var $curobj = $(this);
            var $subul = $(this).find('ul:eq(0)');
            $curobj.hover(
                    function(e) {
                        $curobj.addClass('active');
                        var position = $(this).position();
                        if ($subul.hasClass('lev3')) $subul.css({top: -position.top, left: $curobj.width()});
                        if ($subul.hasClass('lev4')) $subul.css({top: 0, left: $curobj.width()});
                        $subul.show();
                    },
                    function(e) {
                        $subul.hide();
                        $curobj.removeClass('active');
                    });
        });
    }
}

var finiture = {
    init: function() {

        //extract options
        var select_html = '';
        $(els_finiture.els).each(function() {
            select_html += '<option>' + this.name + '</option>';
        });

        //populate select and apply plugin
        $('#sel-finiture')
                .html(select_html)
                .sSelect();

        //populate first option list
        finiture.populateOptions(0);

        $('.newList a').bind('click', function(e) {
            var $clickedLi = $(e.target);

            //update counter
            currentIndex = $('.newList a').index($clickedLi);
            finiture.populateOptions(currentIndex);
        });
    },
    populateOptions: function(index) {
        el = els_finiture.els[index];
        var options_html = '';
        $(el.options).each(function() {
            options_html += '<li><a href="#"><span>' + this.name + '</span></a></li>';
        });

        $('#essenze, #essenza-detail').remove();

        $('ul.options')
                .html(options_html)
                .find('a')
                .click(function() {
            if ($(this).hasClass('active')) return;
            $('ul.options li a').removeClass('active');
            _opt = $('ul.options li a').index($(this));
            $(this).addClass('active');
            finiture.findEssenze(els_finiture.els[index], _opt)
        });
    },
    findEssenze: function (obj, sel_opt) {
        el = obj.options[sel_opt];
        var label = obj.options[sel_opt].label;
        essenze_html = '<div class="cnt-block" id="essenze"><h3>' + label + '</h3><ul id="essenze">';
        $(el.images).each(function() {
            essenze_html += '<li><a href="#" title="' + this.name + '"><img src="' + this.path_thumb + '" alt="' + this.name + '" /></a></li>';
        });
        essenze_html += '</ul></div>';

        $('#essenze, #essenza-detail').remove();

        $('#content')
                .append(essenze_html)
                .find('a')
                .click(function() {
            if ($(this).hasClass('active')) return;
            $('#essenze ul li a').removeClass('active');
            _opt = $('#essenze ul li a').index($(this));
            $(this).addClass('active');
            finiture.openEssenza(obj.options[sel_opt], _opt)
        });
    },
    openEssenza: function (obj, sel_opt) {
        el = obj;
        var title = el.images[sel_opt].name;
        var src = el.images[sel_opt].path_big;
        essenzabig_html = '<div class="cnt-block" id="essenza-detail"><h3>' + title + '</h3><div id="pic-big"><img src="' + src + '" />';

        $('#content')
                .find('#essenza-detail')
                .remove()
                .end()
                .append(essenzabig_html);
    }
}


var gallery = {
    thDistance: 88,
    startImage: 0,
    visible: 7,
    animationRunning: false,
    init: function() {
        gallery.arrows = $('.th-browse');
        gallery.thumbWrap = $('#thumbsWrapper ul');
        gallery.thumbs = $('#thumbsWrapper ul a');
        gallery.caption_p = $('p#caption');
        $(gallery.thumbWrap).width($(gallery.thumbs).length * gallery.thDistance);

        //build images array
        gallery.array = [];
        $(gallery.thumbs).each(function(i) {
            gallery.array[i] = [$(this).attr('path'), this.title];
        });

        //load first
        var pic = new Image();

        $(pic).load(function() {
            $('#imgWrapper').append(pic);
            //$(gallery.thumbs).eq(0).addClass('active');

            //if (gallery.caption_p.length)
            //    $(gallery.caption_p).text($(gallery.thumbs).eq(0).attr('title'));

        });

        $(pic).attr({src: $(gallery.thumbs).eq(0).attr('href')});

        gallery.listen();
        $(gallery.thumbs).eq(0).addClass('active');
        $(gallery.caption_p).text($(gallery.thumbs).eq(0).attr('title'));

    },
    listen: function() {
        gallery.arrows.click(function() {
            if ($(this).attr('id') == 'th-prev')
                dir = 1;
            else dir = -1;
            gallery.moveThumbs(dir);
        });

        gallery.thumbs.click(function(e) {
            e.preventDefault();
            //if ($(this).hasClass('active')) return;
            var target = this.href;
            $(gallery.thumbs).removeClass('active');
            $(this).addClass('active');
            gallery.startImage = $(gallery.thumbs).index($(this));
            gallery.loadImage(target);
            gallery.caption = this.title;

        });

        $('#zoom').click(function() {
            $.slimbox(gallery.array, gallery.startImage);
        });
    },
    loadImage : function(src) {
        //var pic = new Image();

        $('#imgWrapper img').fadeOut('slow', function() {
            //$(this).remove();
            $(gallery.caption_p).text('');
            //$('#.loader').fadeIn('fast');

            /*
            $(pic).load(function() {
                $('#imgWrapper')
                        .append(pic);

                if (gallery.caption_p.length)
                     $(gallery.caption_p).text(gallery.caption);

            });

            */
            $(this).attr({src:src});

            $(this).load(function() {
                $(this).fadeIn('slow', function() {
                    if (gallery.caption_p.length)
                        $(gallery.caption_p).text(gallery.caption);
                });
            });




        });
    },
    moveThumbs: function(dir) {
        if (gallery.animationRunning) return;

        gallery.animationRunning = true;

        var marg = parseInt($(gallery.thumbWrap).css('marginLeft'));
        var targ = marg + (gallery.thDistance * dir);

        var thumbItems = gallery.thumbWrap.find("li").length;
        var thumbsHidden = (Math.floor(Math.abs(targ / gallery.thDistance)));

        if (targ > 0 || (thumbItems - thumbsHidden < gallery.visible)) {
            gallery.animationRunning = false;
        }
        else {
            $(gallery.thumbWrap).animate({marginLeft: targ + 'px'}, 'fast', function() {
                gallery.animationRunning = false;
            });
        }
    }
};


var news = {
    distance: 165,
    visible: 3,
    animationRunning: false,
    init: function() {
        news.arrows = $('.news-browse');
        news.itemsWrap = $('#itemsWrapper ul');
        news.items = $('#itemsWrapper ul a');
        $(news.itemsWrap).width($(news.items).length * news.distance);

        //position active item
        var active_index = $(news.items).index($('.active'));
        if (active_index == 0 || active_index == 1) {
            news.listen();
            return;
        }
        else {
            //last item
            if (active_index == (news.items.length - 1)) {
                $(news.itemsWrap).css({marginLeft: -(news.items.length - news.visible) * news.distance + 'px'});
            }
            else {
                $(news.itemsWrap).css({marginLeft: -((active_index - 1) * news.distance) + 'px'});
            }
        }

        news.listen();
    },
    listen: function() {
        news.arrows.click(function() {
            if ($(this).attr('id') == 'news-prev')
                dir = 1;
            else dir = -1;
            news.moveItems(dir);
        });
    },
    moveItems: function(dir) {
        if (news.animationRunning) return;

        news.animationRunning = true;

        var marg = parseInt($(news.itemsWrap).css('marginLeft'));
        var targ = marg + (news.distance * dir);

        var thumbItems = news.itemsWrap.find("li").length;
        var thumbsHidden = (Math.floor(Math.abs(targ / news.distance)));

        if (targ > 0 || (thumbItems - thumbsHidden < news.visible)) {
            news.animationRunning = false;
        }
        else {
            $(news.itemsWrap).animate({marginLeft: targ + 'px'}, 'fast', function() {
                news.animationRunning = false;
            });
        }
    }
};


var designer = {
    distance: 126,
    visible: 4,
    animationRunning: false,
    init: function() {
        designer.arrows = $('.designer-browse');
        designer.itemsWrap = $('#itemsWrapper ul');
        designer.items = $('#itemsWrapper ul a');
        $(designer.itemsWrap).width($(designer.items).length * designer.distance);
        if (designer.items.length <= designer.visible) $(designer.arrows).hide();

        designer.listen();
    },
    listen: function() {
        designer.arrows.click(function() {
            if ($(this).attr('id') == 'designer-prev')
                dir = 1;
            else dir = -1;
            designer.moveItems(dir);
        });

    },
    moveItems: function(dir) {
        if (designer.animationRunning) return;

        designer.animationRunning = true;

        var marg = parseInt($(designer.itemsWrap).css('marginLeft'));
        var targ = marg + (designer.distance * dir);

        var thumbItems = designer.itemsWrap.find("li").length;
        var thumbsHidden = (Math.floor(Math.abs(targ / designer.distance)));

        if (targ > 0 || (thumbItems - thumbsHidden < designer.visible)) {
            designer.animationRunning = false;
        }
        else {
            $(designer.itemsWrap).animate({marginLeft: targ + 'px'}, 'fast', function() {
                designer.animationRunning = false;
            });
        }
    }
};

var press = {
    distance: 455,
    visible: 2,
    events: [],
    animationRunning: false,
    init: function() {
        press.arrows = $('.press-browse');
        press.itemsWrap = $('#press-wrapper ul');
        press.items = $('#press-wrapper ul a');
        press.boxes = $("#press-wrapper ul li").length,
                $(press.itemsWrap).width($(press.items).length * press.distance);

        var activeIndex = $("#press-wrapper #active-index");
        if (activeIndex.is("p")) {
            var slides = new Number(activeIndex.text());

            if (slides == (press.boxes - 1)) {
                --slides;
            }

            if (slides > 0) {
                $(press.itemsWrap).css("marginLeft", (press.distance * -slides) + "px");
            }
        }
        press.bindPrevNext();
    },
    bindPrevNext: function() {
        press.arrows.click(function() {
            var id = $(this).attr('id');
            press.events.push(id == 'prev' ? 1 : -1);
            press.consumeEvent();
        });
    },
    delayAndConsumeNextEvent: function(millisec) {
        $("#press-wrapper").animate({opacity: 1.0}, millisec, function() {
            press.consumeEvent();
        });
    },
    consumeEvent: function() {
        if (press.events.length <= 0) return;

        if (!press.animationRunning) {
            press.animationRunning = true;
            var dir = press.events.shift();

            var marg = parseInt($(press.itemsWrap).css('marginLeft'));

            var index = Math.abs(Math.floor(marg / press.distance));
            var forward = (dir < 0);

            var animate = true;

            if ((forward ) && (index + 2) > (press.boxes - 1)) animate = false;
            if ((!forward) && (index < 1)) animate = false;

            if (animate) {
                var targ = marg + (press.distance * dir);
                $(press.itemsWrap).animate({marginLeft: targ + 'px'}, 'fast', function() {
                    press.animationRunning = false;
                });
            } else {
                press.animationRunning = false;
            }
        }
        press.delayAndConsumeNextEvent(100);
    }
};


function finevideo(){
    video.close();
}

var video = {
	width: 764,
	height: 430,
	open: function(file) {
		backgroundDiv = "<div class='overlay'></div>";
		$('body').append(backgroundDiv);
		$('body').append("<div id='videoWrapper'><a id='closeLayer' onclick='video.close()' href='#'><img alt='Close' src='/system/modules/it.killnine.febal.opencms.frontend/resources/img/shared/video-close.png'></a><div id='videoHolder' /></div>");
		$('div.overlay')
			.css('opacity',0)
			.fadeTo('fast',0.9, function() {
					$('div#videoWrapper').fadeIn('fast');
				});


		$('#videoHolder')
			.media({
				bgColor: 'transparent',
				width: video.width,
				height: video.height,
				autoplay: true,
				params:    {scale:'noscale', allowfullscreen:'true'},
				attrs :	{ id : 'player', scale:'noscale', allowfullscreen:'true' },
				flashvars:  {videoPath: file, skinPath: '/system/modules/it.killnine.febal.opencms.frontend/resources/video/ClearOverAll.swf', autostart: true, usefullscreen : true},
				src:       '/system/modules/it.killnine.febal.opencms.frontend/resources/video/video.swf',
				caption:   false
			});
	},
	close: function() {
		$('div#videoWrapper').fadeOut('fast', function() {
				$('div.overlay').fadeOut('fast', function() {
					$('div#videoWrapper').remove();
					$('div.overlay').remove();
				});
		});
	}
}

//easing plugin
eval(function(p, a, c, k, e, r) {
    e = function(c) {
        return(c < a ? '' : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36))
    };
    if (!''.replace(/^/, String)) {
        while (c--)r[e(c)] = k[c] || e(c);
        k = [function(e) {
            return r[e]
        }];
        e = function() {
            return'\\w+'
        };
        c = 1
    }
    ;
    while (c--)if (k[c])p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]);
    return p
}('h.i[\'E\']=h.i[\'y\'];h.F(h.i,{z:\'A\',y:9(x,t,b,c,d){6 h.i[h.i.z](x,t,b,c,d)},G:9(x,t,b,c,d){6 c*(t/=d)*t+b},A:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},H:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},I:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},K:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},L:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},N:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},O:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},P:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},R:9(x,t,b,c,d){6-c*8.B(t/d*(8.g/2))+c+b},S:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},T:9(x,t,b,c,d){6-c/2*(8.B(8.g*t/d)-1)+b},U:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},V:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},X:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},Y:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Z:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},11:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.r(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.u(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},12:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.r(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.u(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},13:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.r(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.u(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},14:9(x,t,b,c,d,s){e(s==v)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},15:9(x,t,b,c,d,s){e(s==v)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==v)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.C))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.C))+1)*t+s)+2)+b},D:9(x,t,b,c,d){6 c-h.i.w(x,d-t,0,c,d)+b},w:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.17/2.k))*t+.18)+b}m{6 c*(7.q*(t-=(2.19/2.k))*t+.1a)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.D(x,t*2,0,c,d)*.5+b;6 h.i.w(x,t*2-d,0,c,d)*.5+c*.5+b}});', 62, 74, '||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|abs|||asin|undefined|easeOutBounce||swing|def|easeOutQuad|cos|525|easeInBounce|jswing|extend|easeInQuad|easeInOutQuad|easeInCubic|easeOutCubic|easeInOutCubic|easeInQuart|easeOutQuart|easeInOutQuart|easeInQuint|easeOutQuint|easeInOutQuint|easeInSine|easeOutSine|easeInOutSine|easeInExpo|easeOutExpo|easeInOutExpo|easeInCirc|easeOutCirc|easeInOutCirc||easeInElastic|easeOutElastic|easeInOutElastic|easeInBack|easeOutBack|easeInOutBack|25|9375|625|984375|easeInOutBounce'.split('|'), 0, {}));


/*
 reflection.js for jQuery v1.03
 (c) 2006-2009 Christophe Beyls <http://www.digitalia.be>
 MIT-style license.
 */
(function(a) {
    a.fn.extend({reflect:function(b) {
        b = a.extend({height:1 / 3,opacity:0.5}, b);
        return this.unreflect().each(function() {
            var c = this;
            if (/^img$/i.test(c.tagName)) {
                function d() {
                    var g = c.width,f = c.height,l,i,m,h,k;
                    i = Math.floor((b.height > 1) ? Math.min(f, b.height) : f * b.height);
                    if (a.browser.msie) {
                        l = a("<img />").attr("src", c.src).css({width:g,height:f,marginBottom:i - f,filter:"flipv progid:DXImageTransform.Microsoft.Alpha(opacity=" + (b.opacity * 100) + ", style=1, finishOpacity=0, startx=0, starty=0, finishx=0, finishy=" + (i / f * 100) + ")"})[0]
                    } else {
                        l = a("<canvas />")[0];
                        if (!l.getContext) {
                            return
                        }
                        h = l.getContext("2d");
                        try {
                            a(l).attr({width:g,height:i});
                            h.save();
                            h.translate(0, f - 1);
                            h.scale(1, -1);
                            h.drawImage(c, 0, 0, g, f);
                            h.restore();
                            h.globalCompositeOperation = "destination-out";
                            k = h.createLinearGradient(0, 0, 0, i);
                            k.addColorStop(0, "rgba(255, 255, 255, " + (1 - b.opacity) + ")");
                            k.addColorStop(1, "rgba(255, 255, 255, 1.0)");
                            h.fillStyle = k;
                            h.rect(0, 0, g, i);
                            h.fill()
                        } catch(j) {
                            return
                        }
                    }
                    a(l).css({display:"block",border:0});
                    m = a(/^a$/i.test(c.parentNode.tagName) ? "<span />" : "<div />").insertAfter(c).append([c,l])[0];
                    m.className = c.className;
                    a.data(c, "reflected", m.style.cssText = c.style.cssText);
                    a(m).css({width:g,height:f + i,overflow:"hidden"});
                    c.style.cssText = "display: block; border: 0px";
                    c.className = "reflected"
                }

                if (c.complete) {
                    d()
                } else {
                    a(c).load(d)
                }
            }
        })
    },unreflect:function() {
        return this.unbind("load").each(function() {
            var c = this,b = a.data(this, "reflected"),d;
            if (b !== undefined) {
                d = c.parentNode;
                c.className = d.className;
                c.style.cssText = b;
                a.removeData(c, "reflected");
                d.parentNode.replaceChild(c, d)
            }
        })
    }})
})(jQuery);

/*
 Stylish Select 0.4.1 - $ plugin to replace a select drop down box with a stylable unordered list
 http://github.com/sko77sun/Stylish-Select

 Requires: jQuery 1.3 or newer

 Contributions from Justin Beasley: http://www.harvest.org/ & Anatoly Ressin: http://www.artazor.lv/

 Dual licensed under the MIT and GPL licenses.

 */
(function($) {
    //add class to html tag
    $('html').addClass('stylish-select');

    //create cross-browser indexOf
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
    }

    //utility methods
    $.fn.extend({
        getSetSSValue: function(value) {
            if (value) {
                //set value and trigger change event
                $(this).val(value).change();
                return this;
            } else {
                return $(this).find(':selected').val();
            }
        },
        //added by Justin Beasley
        resetSS: function() {
            var oldOpts = $(this).data('ssOpts');
            $this = $(this);
            $this.next().remove();
            //unbind all events and redraw
            $this.unbind('.sSelect').sSelect(oldOpts);
        }
    });

    $.fn.sSelect = function(options) {

        return this.each(function() {

            var defaults = {
                defaultText: 'Please select',
                animationSpeed: 0, //set speed of dropdown
                ddMaxHeight: '', //set css max-height value of dropdown
                containerClass: '' //additional classes for container div
            };

            //initial variables
            var opts = $.extend(defaults, options),
                    $input = $(this),
                    $containerDivText = $('<div class="selectedTxt"></div>'),
                    $containerDiv = $('<div class="newListSelected ' + opts.containerClass + '"></div>'),
                    $newUl = $('<ul class="newList" style="visibility:hidden;"></ul>'),
                    itemIndex = -1,
                    currentIndex = -1,
                    keys = [],
                    prevKey = false,
                    prevented = false,
                    $newLi;

            //added by Justin Beasley
            $(this).data('ssOpts', options);

            //build new list
            $containerDiv.insertAfter($input);
            $containerDiv.attr("tabindex", $input.attr("tabindex") || "0");
            $containerDivText.prependTo($containerDiv);
            $newUl.appendTo($containerDiv);
            $input.hide();

            //added by Justin Beasley (used for lists initialized while hidden)
            $containerDivText.data('ssReRender', !$containerDivText.is(':visible'));

            //test for optgroup
            if ($input.children('optgroup').length == 0) {
                $input.children().each(function(i) {
                    var option = $(this).html();
                    var key = $(this).val();

                    //add first letter of each word to array
                    keys.push(option.charAt(0).toLowerCase());
                    if ($(this).attr('selected') == true) {
                        opts.defaultText = option;
                        currentIndex = i;
                    }
                    $newUl.append($('<li><a href="JavaScript:void(0);">' + option + '</a></li>').data('key', key));

                });
                //cache list items object
                $newLi = $newUl.children().children();

            } else { //optgroup
                $input.children('optgroup').each(function() {

                    var optionTitle = $(this).attr('label'),
                            $optGroup = $('<li class="newListOptionTitle">' + optionTitle + '</li>');

                    $optGroup.appendTo($newUl);

                    var $optGroupList = $('<ul></ul>');

                    $optGroupList.appendTo($optGroup);

                    $(this).children().each(function() {
                        ++itemIndex;
                        var option = $(this).html();
                        var key = $(this).val();
                        //add first letter of each word to array
                        keys.push(option.charAt(0).toLowerCase());
                        if ($(this).attr('selected') == true) {
                            opts.defaultText = option;
                            currentIndex = itemIndex;
                        }
                        $optGroupList.append($('<li><a href="JavaScript:void(0);">' + option + '</a></li>').data('key', key));
                    })
                });
                //cache list items object
                $newLi = $newUl.find('ul li a');
            }

            //get heights of new elements for use later
            var newUlHeight = $newUl.height(),
                    containerHeight = $containerDiv.height(),
                    newLiLength = $newLi.length;

            //check if a value is selected
            if (currentIndex != -1) {
                navigateList(currentIndex, true);
            } else {
                //set placeholder text
                $containerDivText.text(opts.defaultText);
            }

            //decide if to place the new list above or below the drop-down
            function newUlPos() {
                var containerPosY = $containerDiv.offset().top,
                        docHeight = jQuery(window).height(),
                        scrollTop = jQuery(window).scrollTop();

                //if height of list is greater then max height, set list height to max height value
                if (newUlHeight > parseInt(opts.ddMaxHeight)) {
                    newUlHeight = parseInt(opts.ddMaxHeight);
                }

                containerPosY = containerPosY - scrollTop;
                if (containerPosY + newUlHeight >= docHeight) {
                    $newUl.css({
                        top: '-' + newUlHeight + 'px',
                        height: newUlHeight
                    });
                    $input.onTop = true;
                } else {
                    $newUl.css({
                        top: containerHeight + 'px',
                        height: newUlHeight
                    });
                    $input.onTop = false;
                }
            }

            //run function on page load
            newUlPos();

            //run function on browser window resize
            $(window).bind('resize.sSelect scroll.sSelect', newUlPos);

            //positioning
            function positionFix() {
                $containerDiv.css('position', 'relative');
            }

            function positionHideFix() {
                $containerDiv.css('position', 'static');
            }

            $containerDivText.bind('click.sSelect', function(event) {
                event.stopPropagation();

                //added by Justin Beasley
                if ($(this).data('ssReRender')) {
                    newUlHeight = $newUl.height('').height();
                    containerHeight = $containerDiv.height();
                    $(this).data('ssReRender', false);
                    newUlPos();
                }

                //hide all menus apart from this one
                $('.newList').not($(this).next()).hide()
                        .parent()
                        .css('position', 'static')
                        .removeClass('newListSelFocus');

                //show/hide this menu
                $newUl.toggle();
                positionFix();
                //scroll list to selected item
                $newLi.eq(currentIndex).focus();

            });

            $newLi.bind('click.sSelect', function(e) {
                var $clickedLi = $(e.target);

                //update counter
                currentIndex = $newLi.index($clickedLi);

                //remove all hilites, then add hilite to selected item
                prevented = true;
                navigateList(currentIndex);
                $newUl.hide().parent().removeClass('newListSelFocus');
                $containerDiv.css('position', 'static');//ie
            });

            $newLi.bind('mouseenter.sSelect',
                    function(e) {
                        var $hoveredLi = $(e.target);
                        $hoveredLi.addClass('newListHover');
                    }
                    ).bind('mouseleave.sSelect',
                    function(e) {
                        var $hoveredLi = $(e.target);
                        $hoveredLi.removeClass('newListHover');
                    }
                    );

            function navigateList(currentIndex, init) {
                $newLi.removeClass('hiLite')
                        .eq(currentIndex)
                        .addClass('hiLite');

                if ($newUl.is(':visible')) {
                    $newLi.eq(currentIndex).focus();
                }

                var text = $newLi.eq(currentIndex).html();
                var val = $newLi.eq(currentIndex).parent().data('key');

                //page load
                if (init == true) {
                    $input.val(val);
                    $containerDivText.text(text);
                    return false;
                }

                try {
                    $input.val(val)
                } catch(ex) {
                    // handle ie6 exception
                    $input[0].selectedIndex = currentIndex;
                }

                $input.change();
                $containerDivText.text(text);
            }

            $input.bind('change.sSelect', function(event) {
                $targetInput = $(event.target);
                //stop change function from firing
                if (prevented == true) {
                    prevented = false;
                    return false;
                }
                $currentOpt = $targetInput.find(':selected');

                //currentIndex = $targetInput.find('option').index($currentOpt);
                currentIndex = $targetInput.find('option').index($currentOpt);

                navigateList(currentIndex, true);
            });

            //handle up and down keys
            function keyPress(element) {
                //when keys are pressed
                $(element).unbind('keydown.sSelect').bind('keydown.sSelect', function(e) {
                    var keycode = e.which;

                    //prevent change function from firing
                    prevented = true;

                    switch (keycode) {
                        case 40: //down
                        case 39: //right
                            incrementList();
                            return false;
                            break;
                        case 38: //up
                        case 37: //left
                            decrementList();
                            return false;
                            break;
                        case 33: //page up
                        case 36: //home
                            gotoFirst();
                            return false;
                            break;
                        case 34: //page down
                        case 35: //end
                            gotoLast();
                            return false;
                            break;
                        case 13:
                        case 27:
                            $newUl.hide();
                            positionHideFix();
                            return false;
                            break;
                    }

                    //check for keyboard shortcuts
                    keyPressed = String.fromCharCode(keycode).toLowerCase();

                    var currentKeyIndex = keys.indexOf(keyPressed);

                    if (typeof currentKeyIndex != 'undefined') { //if key code found in array
                        ++currentIndex;
                        currentIndex = keys.indexOf(keyPressed, currentIndex); //search array from current index
                        if (currentIndex == -1 || currentIndex == null || prevKey != keyPressed) currentIndex = keys.indexOf(keyPressed); //if no entry was found or new key pressed search from start of array


                        navigateList(currentIndex);
                        //store last key pressed
                        prevKey = keyPressed;
                        return false;
                    }
                });
            }

            function incrementList() {
                if (currentIndex < (newLiLength - 1)) {
                    ++currentIndex;
                    navigateList(currentIndex);
                }
            }

            function decrementList() {
                if (currentIndex > 0) {
                    --currentIndex;
                    navigateList(currentIndex);
                }
            }

            function gotoFirst() {
                currentIndex = 0;
                navigateList(currentIndex);
            }

            function gotoLast() {
                currentIndex = newLiLength - 1;
                navigateList(currentIndex);
            }

            $containerDiv.bind('click.sSelect', function(e) {
                e.stopPropagation();
                keyPress(this);
            });

            $containerDiv.bind('focus.sSelect', function() {
                $(this).addClass('newListSelFocus');
                keyPress(this);
            });

            $containerDiv.bind('blur.sSelect', function() {
                $(this).removeClass('newListSelFocus');
            });

            //hide list on blur
            $(document).bind('click.sSelect', function() {
                $containerDiv.removeClass('newListSelFocus');
                $newUl.hide();
                positionHideFix();
            });

            //add classes on hover
            $containerDivText.bind('mouseenter.sSelect',
                    function(e) {
                        var $hoveredTxt = $(e.target);
                        $hoveredTxt.parent().addClass('newListSelHover');
                    }
                    ).bind('mouseleave.sSelect',
                    function(e) {
                        var $hoveredTxt = $(e.target);
                        $hoveredTxt.parent().removeClass('newListSelHover');
                    }
                    );

            //reset left property and hide
            $newUl.css({
                left: '0',
                display: 'none',
                visibility: 'visible'
            });

        });

    };

})(jQuery);


/*
 * jQuery Media Plugin for converting elements into rich media content.
 *
 * Examples and documentation at: http://malsup.com/jquery/media/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @author: M. Alsup
 * @version: 0.92 (24-SEP-2009)
 * @requires jQuery v1.1.2 or later
 * $Id: jquery.media.js 2460 2007-07-23 02:53:15Z malsup $
 *
 * Supported Media Players:
 *	- Flash
 *	- Quicktime
 *	- Real Player
 *	- Silverlight
 *	- Windows Media Player
 *	- iframe
 *
 * Supported Media Formats:
 *	 Any types supported by the above players, such as:
 *	 Video: asf, avi, flv, mov, mpg, mpeg, mp4, qt, smil, swf, wmv, 3g2, 3gp
 *	 Audio: aif, aac, au, gsm, mid, midi, mov, mp3, m4a, snd, rm, wav, wma
 *	 Other: bmp, html, pdf, psd, qif, qtif, qti, tif, tiff, xaml
 *
 * Thanks to Mark Hicken and Brent Pedersen for helping me debug this on the Mac!
 * Thanks to Dan Rossi for numerous bug reports and code bits!
 * Thanks to Skye Giordano for several great suggestions!
 * Thanks to Richard Connamacher for excellent improvements to the non-IE behavior!
 */
;(function($) {

/**
 * Chainable method for converting elements into rich media.
 *
 * @param options
 * @param callback fn invoked for each matched element before conversion
 * @param callback fn invoked for each matched element after conversion
 */
$.fn.media = function(options, f1, f2) {
	if (options == 'undo') {
		return this.each(function() {
			var $this = $(this);
			var html = $this.data('media.origHTML');
			if (html)
				$this.replaceWith(html);
		});
	}

	return this.each(function() {
		if (typeof options == 'function') {
			f2 = f1;
			f1 = options;
			options = {};
		}
		var o = getSettings(this, options);
		// pre-conversion callback, passes original element and fully populated options
		if (typeof f1 == 'function') f1(this, o);

		var r = getTypesRegExp();
		var m = r.exec(o.src.toLowerCase()) || [''];

		o.type ? m[0] = o.type : m.shift();
		for (var i=0; i < m.length; i++) {
			fn = m[i].toLowerCase();
			if (isDigit(fn[0])) fn = 'fn' + fn; // fns can't begin with numbers
			if (!$.fn.media[fn])
				continue;  // unrecognized media type
			// normalize autoplay settings
			var player = $.fn.media[fn+'_player'];
			if (!o.params) o.params = {};
			if (player) {
				var num = player.autoplayAttr == 'autostart';
				o.params[player.autoplayAttr || 'autoplay'] = num ? (o.autoplay ? 1 : 0) : o.autoplay ? true : false;
			}
			var $div = $.fn.media[fn](this, o);

			$div.css('backgroundColor', o.bgColor).width(o.width);

			if (o.canUndo) {
				var $temp = $('<div></div>').append(this);
				$div.data('media.origHTML', $temp.html()); // store original markup
			}

			// post-conversion callback, passes original element, new div element and fully populated options
			if (typeof f2 == 'function') f2(this, $div[0], o, player.name);
			break;
		}
	});
};

/**
 * Non-chainable method for adding or changing file format / player mapping
 * @name mapFormat
 * @param String format File format extension (ie: mov, wav, mp3)
 * @param String player Player name to use for the format (one of: flash, quicktime, realplayer, winmedia, silverlight or iframe
 */
$.fn.media.mapFormat = function(format, player) {
	if (!format || !player || !$.fn.media.defaults.players[player]) return; // invalid
	format = format.toLowerCase();
	if (isDigit(format[0])) format = 'fn' + format;
	$.fn.media[format] = $.fn.media[player];
	$.fn.media[format+'_player'] = $.fn.media.defaults.players[player];
};

// global defautls; override as needed
$.fn.media.defaults = {
	standards:  false,      // use object tags only (no embeds for non-IE browsers)
	canUndo:    true,       // tells plugin to store the original markup so it can be reverted via: $(sel).mediaUndo()
	width:		400,
	height:		400,
	autoplay:	0,		   	// normalized cross-player setting
	bgColor:	'#ffffff', 	// background color
	params:		{ wmode: 'transparent'},	// added to object element as param elements; added to embed element as attrs
	attrs:		{},			// added to object and embed elements as attrs
	flvKeyName: 'file', 	// key used for object src param (thanks to Andrea Ercolino)
	flashvars:	{},			// added to flash content as flashvars param/attr
	flashVersion:	'7',	// required flash version
	expressInstaller: null,	// src for express installer

	// default flash video and mp3 player (@see: http://jeroenwijering.com/?item=Flash_Media_Player)
	flvPlayer:	 'mediaplayer.swf',
	mp3Player:	 'mediaplayer.swf',

	// @see http://msdn2.microsoft.com/en-us/library/bb412401.aspx
	silverlight: {
		inplaceInstallPrompt: 'true', // display in-place install prompt?
		isWindowless:		  'true', // windowless mode (false for wrapping markup)
		framerate:			  '24',	  // maximum framerate
		version:			  '0.9',  // Silverlight version
		onError:			  null,	  // onError callback
		onLoad:			      null,   // onLoad callback
		initParams:			  null,	  // object init params
		userContext:		  null	  // callback arg passed to the load callback
	}
};

// Media Players; think twice before overriding
$.fn.media.defaults.players = {
	flash: {
		name:		 'flash',
		title:		 'Flash',
		types:		 'flv,mp3,swf',
		mimetype:	 'application/x-shockwave-flash',
		pluginspage: 'http://www.adobe.com/go/getflashplayer',
		ieAttrs: {
			classid:  'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
			type:	  'application/x-oleobject',
			codebase: 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + $.fn.media.defaults.flashVersion
		}
	},
	quicktime: {
		name:		 'quicktime',
		title:		 'QuickTime',
		mimetype:	 'video/quicktime',
		pluginspage: 'http://www.apple.com/quicktime/download/',
		types:		 'aif,aiff,aac,au,bmp,gsm,mov,mid,midi,mpg,mpeg,mp4,m4a,psd,qt,qtif,qif,qti,snd,tif,tiff,wav,3g2,3gp',
		ieAttrs: {
			classid:  'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
			codebase: 'http://www.apple.com/qtactivex/qtplugin.cab'
		}
	},
	realplayer: {
		name:		  'real',
		title:		  'RealPlayer',
		types:		  'ra,ram,rm,rpm,rv,smi,smil',
		mimetype:	  'audio/x-pn-realaudio-plugin',
		pluginspage:  'http://www.real.com/player/',
		autoplayAttr: 'autostart',
		ieAttrs: {
			classid: 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'
		}
	},
	winmedia: {
		name:		  'winmedia',
		title:		  'Windows Media',
		types:		  'asx,asf,avi,wma,wmv',
		mimetype:	  $.browser.mozilla && isFirefoxWMPPluginInstalled() ? 'application/x-ms-wmp' : 'application/x-mplayer2',
		pluginspage:  'http://www.microsoft.com/Windows/MediaPlayer/',
		autoplayAttr: 'autostart',
		oUrl:		  'url',
		ieAttrs: {
			classid:  'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6',
			type:	  'application/x-oleobject'
		}
	},
	// special cases
	iframe: {
		name:  'iframe',
		types: 'html,pdf'
	},
	silverlight: {
		name:  'silverlight',
		types: 'xaml'
	}
};

//
//	everything below here is private
//


// detection script for FF WMP plugin (http://www.therossman.org/experiments/wmp_play.html)
// (hat tip to Mark Ross for this script)
function isFirefoxWMPPluginInstalled() {
	var plugs = navigator.plugins;
	for (var i = 0; i < plugs.length; i++) {
		var plugin = plugs[i];
		if (plugin['filename'] == 'np-mswmp.dll')
			return true;
	}
	return false;
}

var counter = 1;

for (var player in $.fn.media.defaults.players) {
	var types = $.fn.media.defaults.players[player].types;
	$.each(types.split(','), function(i,o) {
		if (isDigit(o[0])) o = 'fn' + o;
		$.fn.media[o] = $.fn.media[player] = getGenerator(player);
		$.fn.media[o+'_player'] = $.fn.media.defaults.players[player];
	});
};

function getTypesRegExp() {
	var types = '';
	for (var player in $.fn.media.defaults.players) {
		if (types.length) types += ',';
		types += $.fn.media.defaults.players[player].types;
	};
	return new RegExp('\\.(' + types.replace(/,/ig,'|') + ')\\b');
};

function getGenerator(player) {
	return function(el, options) {
		return generate(el, options, player);
	};
};

function isDigit(c) {
	return '0123456789'.indexOf(c) > -1;
};

// flatten all possible options: global defaults, meta, option obj
function getSettings(el, options) {
	options = options || {};
	var $el = $(el);
	var cls = el.className || '';
	// support metadata plugin (v1.0 and v2.0)
	var meta = $.metadata ? $el.metadata() : $.meta ? $el.data() : {};
	meta = meta || {};
	var w = meta.width	 || parseInt(((cls.match(/w:(\d+)/)||[])[1]||0));
	var h = meta.height || parseInt(((cls.match(/h:(\d+)/)||[])[1]||0));

	if (w) meta.width	= w;
	if (h) meta.height = h;
	if (cls) meta.cls = cls;

	var a = $.fn.media.defaults;
	var b = options;
	var c = meta;

	var p = { params: { bgColor: options.bgColor || $.fn.media.defaults.bgColor } };
	var opts = $.extend({}, a, b, c);
	$.each(['attrs','params','flashvars','silverlight'], function(i,o) {
		opts[o] = $.extend({}, p[o] || {}, a[o] || {}, b[o] || {}, c[o] || {});
	});

	if (typeof opts.caption == 'undefined') opts.caption = $el.text();

	// make sure we have a source!
	opts.src = opts.src || $el.attr('href') || $el.attr('src') || 'unknown';
	return opts;
};

//
//	Flash Player
//

// generate flash using SWFObject library if possible
$.fn.media.swf = function(el, opts) {
	if (!window.SWFObject && !window.swfobject) {
		// roll our own
		if (opts.flashvars) {
			var a = [];
			for (var f in opts.flashvars)
				a.push(f + '=' + opts.flashvars[f]);
			if (!opts.params) opts.params = {};
			opts.params.flashvars = a.join('&');
		}
		return generate(el, opts, 'flash');
	}

	var id = el.id ? (' id="'+el.id+'"') : '';
	var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
	var $div = $('<div' + id + cls + '>');

	// swfobject v2+
	if (window.swfobject) {
		$(el).after($div).appendTo($div);
		if (!el.id) el.id = 'movie_player_' + counter++;

		// replace el with swfobject content
		swfobject.embedSWF(opts.src, el.id, opts.width, opts.height, opts.flashVersion,
			opts.expressInstaller, opts.flashvars, opts.params, opts.attrs);
	}
	// swfobject < v2
	else {
		$(el).after($div).remove();
		var so = new SWFObject(opts.src, 'movie_player_' + counter++, opts.width, opts.height, opts.flashVersion, opts.bgColor);
		if (opts.expressInstaller) so.useExpressInstall(opts.expressInstaller);

		for (var p in opts.params)
			if (p != 'bgColor') so.addParam(p, opts.params[p]);
		for (var f in opts.flashvars)
			so.addVariable(f, opts.flashvars[f]);
		so.write($div[0]);
	}

	if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
	return $div;
};

// map flv and mp3 files to the swf player by default
$.fn.media.flv = $.fn.media.mp3 = function(el, opts) {
	var src = opts.src;
	var player = /\.mp3\b/i.test(src) ? $.fn.media.defaults.mp3Player : $.fn.media.defaults.flvPlayer;
	var key = opts.flvKeyName;
	src = encodeURIComponent(src);
	opts.src = player;
	opts.src = opts.src + '?'+key+'=' + (src);
	var srcObj = {};
	srcObj[key] = src;
	opts.flashvars = $.extend({}, srcObj, opts.flashvars );
	return $.fn.media.swf(el, opts);
};

//
//	Silverlight
//
$.fn.media.xaml = function(el, opts) {
	if (!window.Sys || !window.Sys.Silverlight) {
		if ($.fn.media.xaml.warning) return;
		$.fn.media.xaml.warning = 1;
		alert('You must include the Silverlight.js script.');
		return;
	}

	var props = {
		width: opts.width,
		height: opts.height,
		background: opts.bgColor,
		inplaceInstallPrompt: opts.silverlight.inplaceInstallPrompt,
		isWindowless: opts.silverlight.isWindowless,
		framerate: opts.silverlight.framerate,
		version: opts.silverlight.version
	};
	var events = {
		onError: opts.silverlight.onError,
		onLoad: opts.silverlight.onLoad
	};

	var id1 = el.id ? (' id="'+el.id+'"') : '';
	var id2 = opts.id || 'AG' + counter++;
	// convert element to div
	var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
	var $div = $('<div' + id1 + cls + '>');
	$(el).after($div).remove();

	Sys.Silverlight.createObjectEx({
		source: opts.src,
		initParams: opts.silverlight.initParams,
		userContext: opts.silverlight.userContext,
		id: id2,
		parentElement: $div[0],
		properties: props,
		events: events
	});

	if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
	return $div;
};

//
// generate object/embed markup
//
function generate(el, opts, player) {
	var $el = $(el);
	var o = $.fn.media.defaults.players[player];

	if (player == 'iframe') {
		var o = $('<iframe' + ' width="' + opts.width + '" height="' + opts.height + '" >');
		o.attr('src', opts.src);
		o.css('backgroundColor', o.bgColor);
	}
	else if ($.browser.msie) {
		var a = ['<object width="' + opts.width + '" height="' + opts.height + '" '];
		for (var key in opts.attrs)
			a.push(key + '="'+opts.attrs[key]+'" ');
		for (var key in o.ieAttrs || {}) {
			var v = o.ieAttrs[key];
			if (key == 'codebase' && window.location.protocol == 'https:')
				v = v.replace('http','https');
			a.push(key + '="'+v+'" ');
		}
		a.push('></ob'+'ject'+'>');
		var p = ['<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">'];
		for (var key in opts.params)
			p.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
		var o = document.createElement(a.join(''));
		for (var i=0; i < p.length; i++)
			o.appendChild(document.createElement(p[i]));
	}
	else if (o.standards) {
		// Rewritten to be standards compliant by Richard Connamacher
		var a = ['<object type="' + o.mimetype +'" width="' + opts.width + '" height="' + opts.height +'"'];
		if (opts.src) a.push(' data="' + opts.src + '" ');
		a.push('>');
		a.push('<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">');
		for (var key in opts.params) {
			if (key == 'wmode' && player != 'flash') // FF3/Quicktime borks on wmode
				continue;
			a.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
		}
		// Alternate HTML
		a.push('<div><p><strong>'+o.title+' Required</strong></p><p>'+o.title+' is required to view this media. <a href="'+o.pluginspage+'">Download Here</a>.</p></div>');
		a.push('</ob'+'ject'+'>');
	}
	 else {
	        var a = ['<embed width="' + opts.width + '" height="' + opts.height + '" style="display:block"'];
	        if (opts.src) a.push(' src="' + opts.src + '" ');
	        for (var key in opts.attrs)
	            a.push(key + '="'+opts.attrs[key]+'" ');
	        for (var key in o.eAttrs || {})
	            a.push(key + '="'+o.eAttrs[key]+'" ');
	        for (var key in opts.params) {
	            if (key == 'wmode' && player != 'flash') // FF3/Quicktime borks on wmode
	            	continue;
	            a.push(key + '="'+opts.params[key]+'" ');
	        }
	        a.push('></em'+'bed'+'>');
	    }
	// convert element to div
	var id = el.id ? (' id="'+el.id+'"') : '';
	var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
	var $div = $('<div' + id + cls + '>');
	$el.after($div).remove();
	($.browser.msie || player == 'iframe') ? $div.append(o) : $div.html(a.join(''));
	if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
	return $div;
};


})(jQuery);
