// Begin ~/Scripts/base/UI.Tooltip.js

/*
 * jQuery UI Tooltip @VERSION
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Tooltip
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */
(function($) {

var increments = 0;

$.widget("ui.tooltip", {
	options: {
		items: "[title]",
		extraClass :'',
		content: function() {
			return $(this).attr("title");
		},
		position: {
			my: "left center",
			at: "right center",
			offset: "15 0"
		}
	},
	_create: function() {
		var self = this;
		this.tooltip = $("<div></div>")
			.attr("id", "ui-tooltip-" + increments++)
			.attr("role", "tooltip")
			.attr("aria-hidden", "true")
			.addClass("ui-tooltip ui-widget ui-corner-all ui-widget-content")
			.appendTo(document.body)
			.hide();
		this.tooltipContent = $("<div></div>")
			.addClass("ui-tooltip-content "+self.options.extraClass)
			.appendTo(this.tooltip);
		this.opacity = this.tooltip.css("opacity");
		this.element
			.bind("focus.tooltip mouseover.tooltip", function(event) {
				self.open( event );
			})
			.bind("blur.tooltip mouseout.tooltip", function(event) {
				self.close( event );
			});
	},
	
	enable: function() {
		this.options.disabled = false;
	},
	
	disable: function() {
		this.options.disabled = true;
	},
	
	destroy: function() {
		this.tooltip.remove();
		$.Widget.prototype.destroy.apply(this, arguments);
	},
	
	widget: function() {
		return this.element.pushStack(this.tooltip.get());
	},
	
	open: function(event) {
		var target = $(event && event.target || this.element).closest(this.options.items);
		// already visible? possible when both focus and mouseover events occur
		if (this.current && this.current[0] == target[0])
			return;
		var self = this;
		this.current = target;
		this.currentTitle = target.attr("title");
		var content = this.options.content.call(target[0], function(response) {
			// IE may instantly serve a cached response, need to give it a chance to finish with _show before that
			setTimeout(function() {
				// ignore async responses that come in after the tooltip is already hidden
				if (self.current == target)
					self._show(event, target, response);
			}, 13);
		});
		if (content) {
			self._show(event, target, content);
		}
	},
	
	_show: function(event, target, content) {
		if (!content)
			return;
		
		target.attr("title", "");
		
		if (this.options.disabled)
			return;
			
		this.tooltipContent.html(content);
		this.tooltip.css({
			top: 0,
			left: 0
		}).show().position( $.extend({
			of: target
		}, this.options.position )).hide();
		
		this.tooltip.attr("aria-hidden", "false");
		target.attr("aria-describedby", this.tooltip.attr("id"));

		this.tooltip.stop(false, true).fadeIn();

		this._trigger( "open", event );
	},
	
	close: function(event) {
		if (!this.current)
			return;
		this.current.removeAttr("aria-describedby");
		var current = this.current.attr("title", this.currentTitle);
		
		this.current = null;
		
		if (this.options.disabled)
			return;
		
		this.tooltip.attr("aria-hidden", "true");
		
		this.tooltip.stop(false, true).fadeOut();
		
		this._trigger( "close", event );
	}
	
});

})(jQuery);
// End ~/Scripts/base/UI.Tooltip.js

// Begin ~/Scripts/plugins/jquery.hoverIntent.js

/**
 * hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
 * <http://cherne.net/brian/resources/jquery.hoverIntent.html>
 *
 * @param  f  onMouseOver function || An object with configuration options
 * @param  g  onMouseOut function  || Nothing (use configuration options object)
 * @author    Brian Cherne <brian@cherne.net>
 */
(function($){
    $.fn.hoverIntent = function(f, g){
        var cfg = {
            sensitivity: 7,
            interval: 100,
            timeout: 0
        };
        cfg = $.extend(cfg, g ? {
            over: f,
            out: g
        } : f);
        var cX, cY, pX, pY;
        var track = function(ev){
            cX = ev.pageX;
            cY = ev.pageY;
        };
        var compare = function(ev, ob){
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) {
                $(ob).unbind("mousemove", track);
                ob.hoverIntent_s = 1;
                return cfg.over.apply(ob, [ev]);
            }
            else {
                pX = cX;
                pY = cY;
                ob.hoverIntent_t = setTimeout(function(){
                    compare(ev, ob);
                }, cfg.interval);
            }
        };
        var delay = function(ev, ob){
            ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            ob.hoverIntent_s = 0;
            return cfg.out.apply(ob, [ev]);
        };
        var handleHover = function(e){
            var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
            while (p && p != this) {
                try {
                    p = p.parentNode;
                } 
                catch (e) {
                    p = this;
                }
            }
            if (p == this) {
                return false;
            }
            var ev = jQuery.extend({}, e);
            var ob = this;
            if (ob.hoverIntent_t) {
                ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
            }
            if (e.type == "mouseover") {
                pX = ev.pageX;
                pY = ev.pageY;
                $(ob).bind("mousemove", track);
                if (ob.hoverIntent_s != 1) {
                    ob.hoverIntent_t = setTimeout(function(){
                        compare(ev, ob);
                    }, cfg.interval);
                }
            }
            else {
                $(ob).unbind("mousemove", track);
                if (ob.hoverIntent_s == 1) {
                    ob.hoverIntent_t = setTimeout(function(){
                        delay(ev, ob);
                    }, cfg.timeout);
                }
            }
        };
        return this.mouseover(handleHover).mouseout(handleHover);
    };
})(jQuery);

// End ~/Scripts/plugins/jquery.hoverIntent.js

// Begin ~/Scripts/plugins/jquery.printarea.js

(function($){
    var printAreaCount = 0;
    $.fn.printArea = function(){
        var ele = $(this);
        var idPrefix = "printArea_";
        removePrintArea(idPrefix + printAreaCount);
        printAreaCount++;
        var iframeId = idPrefix + printAreaCount;
        var iframeStyle = 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;';
        iframe = document.createElement('IFRAME');
        $(iframe).attr({
            style: iframeStyle,
            id: iframeId
        });
        document.body.appendChild(iframe);
        var doc = iframe.contentWindow.document;
        $(document).find("link").filter(function(){
            return $(this).attr("rel").toLowerCase() == "stylesheet";
        }).each(function(){
            doc.write('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" >');
        });
        doc.write('<div class="' + $(ele).attr("class") + '">' + $(ele).html() + '</div>');
        doc.close();
        var frameWindow = iframe.contentWindow;
        frameWindow.close();
        frameWindow.focus();
        frameWindow.print();
    }
    var removePrintArea = function(id){
        $("iframe#" + id).remove();
    };
})(jQuery);

// End ~/Scripts/plugins/jquery.printarea.js

// Begin ~/Scripts/plugins/jquery.swfobject.min.js

/* jquery.swfobject.license.txt */
(function(A){A.flashPlayerVersion=function(){var D,B=null,I=false,H="ShockwaveFlash.ShockwaveFlash";if(!(D=navigator.plugins["Shockwave Flash"])){try{B=new ActiveXObject(H+".7")}catch(G){try{B=new ActiveXObject(H+".6");D=[6,0,21];B.AllowScriptAccess="always"}catch(F){if(D&&D[0]===6){I=true}}if(!I){try{B=new ActiveXObject(H)}catch(E){D="X 0,0,0"}}}if(!I&&B){try{D=B.GetVariable("$version")}catch(C){}}}else{D=D.description}D=D.match(/^[A-Za-z\s]*?(\d+)(\.|,)(\d+)(\s+r|,)(\d+)/);return[D[1]*1,D[3]*1,D[5]*1]}();A.flashExpressInstaller="expressInstall.swf";A.hasFlashPlayer=(A.flashPlayerVersion[0]!==0);A.hasFlashPlayerVersion=function(C){var B=A.flashPlayerVersion;C=(/string|integer/.test(typeof C))?C.toString().split("."):C;return(C)?(B[0]>=(C.major||C[0]||B[0])&&B[1]>=(C.minor||C[1]||B[1])&&B[2]>=(C.release||C[2]||B[2])):(B[0]!==0)};A.flash=function(M){if(!A.hasFlashPlayer){return false}var C=M.swf||"",K=M.params||{},E=document.createElement("body"),B,L,H,D,J,I,G,F;M.height=M.height||180;M.width=M.width||320;if(M.hasVersion&&!A.hasFlashPlayerVersion(M.hasVersion)){A.extend(M,{id:"SWFObjectExprInst",height:Math.max(M.height,137),width:Math.max(M.width,214)});C=M.expressInstaller||A.flashExpressInstaller;K={flashvars:{MMredirectURL:window.location.href,MMplayerType:(A.browser.msie&&A.browser.win)?"ActiveX":"PlugIn",MMdoctitle:document.title.slice(0,47)+" - Flash Player Installation"}}}if(M.flashvars&&typeof K==="object"){A.extend(K,{flashvars:M.flashvars})}for(J in (I=["swf","expressInstall","hasVersion","params","flashvars"])){delete M[I[J]]}B=[];for(J in M){if(typeof M[J]==="object"){L=[];for(I in M[J]){L.push(I.replace(/([A-Z])/,"-$1").toLowerCase()+":"+M[J][I]+";")}M[J]=L.join("")}B.push(J+'="'+M[J]+'"')}M=B.join(" ");if(typeof K==="object"){B=[];for(J in K){if(typeof K[J]==="object"){L=[];for(I in K[J]){if(typeof K[J][I]==="object"){H=[];for(G in K[J][I]){if(typeof K[J][I][G]==="object"){D=[];for(F in K[J][I][G]){D.push(F.replace(/([A-Z])/,"-$1").toLowerCase()+":"+K[J][I][G][F]+";")}K[J][I][G]=D.join("")}H.push(G+"{"+K[J][I][G]+"}")}K[J][I]=H.join("")}L.push(window.escape(I)+"="+window.escape(K[J][I]))}K[J]=L.join("&amp;")}B.push('<PARAM NAME="'+J+'" VALUE="'+K[J]+'">')}K=B.join("")}if(!(/style=/.test(M))){M+=' style="vertical-align:text-top;"'}if(!(/style=(.*?)vertical-align/.test(M))){M=M.replace(/style="/,'style="vertical-align:text-top;')}if(A.browser.msie){M+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';K='<PARAM NAME="movie" VALUE="'+C+'">'+K}else{M+=' type="application/x-shockwave-flash" data="'+C+'"'}E.innerHTML="<OBJECT "+M+">"+K+"</OBJECT>";return A(E.firstChild)};A.fn.flash=function(C){if(!A.hasFlashPlayer){return this}var B=0,D;while((D=this.eq(B++))[0]){D.html(A.flash(A.extend({},C)));if(D[0].firstChild.getAttribute("id")==="SWFObjectExprInst"){B=this.length}}return this}}(jQuery));
// End ~/Scripts/plugins/jquery.swfobject.min.js

// Begin ~/Scripts/plugins/jquery.boxy.js

/**
* Boxy 0.1.4 - Facebook-style dialog, with frills
*
* (c) 2008 Jason Frame
* Licensed under the MIT License (LICENSE)
*/

/*
* jQuery plugin
*
* Options:
*   message: confirmation message for form submit hook (default: "Please confirm:")
* 
* Any other options - e.g. 'clone' - will be passed onto the boxy constructor (or
* Boxy.load for AJAX operations)
*/
jQuery.fn.boxy = function(options) {
    options = options || {};
    return this.each(function() {
        var node = this.nodeName.toLowerCase(), self = this;
        if (node == 'a') {
            jQuery(this).click(function() {
                var active = Boxy.linkedTo(this),
                    href = this.getAttribute('href'),
                    localOptions = jQuery.extend({ actuator: this, title: this.title }, options);

                if (active) {
                    active.show();
                } else if (href.indexOf('#') >= 0) {
                    var content = jQuery(href.substr(href.indexOf('#'))),
                        newContent = content.clone(true);
                    content.remove();
                    localOptions.unloadOnHide = false;
                    new Boxy(newContent, localOptions);
                } else { // fall back to AJAX; could do with a same-origin check
                    if (!localOptions.cache) localOptions.unloadOnHide = true;
                    Boxy.load(this.href, localOptions);
                }

                return false;
            });
        } else if (node == 'form') {
            jQuery(this).bind('submit.boxy', function() {
                Boxy.confirm(options.message || 'Please confirm:', function() {
                    jQuery(self).unbind('submit.boxy').submit();
                });
                return false;
            });
        }
    });
};

//
// Boxy Class

function Boxy(element, options) {

    this.boxy = jQuery(Boxy.WRAPPER);
    jQuery.data(this.boxy[0], 'boxy', this);

    this.visible = false;
    this.options = jQuery.extend({}, Boxy.DEFAULTS, options || {});

    if (this.options.modal) {
        this.options = jQuery.extend(this.options, { center: true, draggable: false });
    }

    // options.actuator == DOM element that opened this boxy
    // association will be automatically deleted when this boxy is remove()d
    if (this.options.actuator) {
        jQuery.data(this.options.actuator, 'active.boxy', this);
    }

    this.setContent(element || "<div></div>");
    this._setupTitleBar();

    this.boxy.css('display', 'none').appendTo(document.body);
    this.toTop();

    if (this.options.fixed) {
        if (jQuery.browser.msie && jQuery.browser.version < 7) {
            this.options.fixed = false; // IE6 doesn't support fixed positioning
        } else {
            this.boxy.addClass('fixed');
        }
    }

    if (this.options.center && Boxy._u(this.options.x, this.options.y)) {
        this.center();
    } else {
        this.moveTo(
            Boxy._u(this.options.x) ? this.options.x : Boxy.DEFAULT_X,
            Boxy._u(this.options.y) ? this.options.y : Boxy.DEFAULT_Y
        );
    }

    if (this.options.show) this.show();

};

Boxy.EF = function() { };

jQuery.extend(Boxy, {

    WRAPPER: "<table cellspacing='0' cellpadding='0' border='0' class='boxy-wrapper'>" +
                "<tr><td class='top-left'></td><td class='top'></td><td class='top-right'></td></tr>" +
                "<tr><td class='left'></td><td class='boxy-inner'></td><td class='right'></td></tr>" +
                "<tr><td class='bottom-left'></td><td class='bottom'></td><td class='bottom-right'></td></tr>" +
                "</table>",

    DEFAULTS: {
        title: null,           // titlebar text. titlebar will not be visible if not set.
        closeable: true,           // display close link in titlebar?
        draggable: true,           // can this dialog be dragged?
        clone: false,          // clone content prior to insertion into dialog?
        actuator: null,           // element which opened this dialog
        center: true,           // center dialog in viewport?
        show: true,           // show dialog immediately?
        modal: false,          // make dialog modal?
        fixed: true,           // use fixed positioning, if supported? absolute positioning used otherwise
        closeText: '[x]',      // text to use for default close link
        unloadOnHide: false,          // should this dialog be removed from the DOM after being hidden?
        clickToFront: false,          // bring dialog to foreground on any click (not just titlebar)?
        behaviours: Boxy.EF,        // function used to apply behaviours to all content embedded in dialog.
        afterDrop: Boxy.EF,        // callback fired after dialog is dropped. executes in context of Boxy instance.
        afterShow: Boxy.EF,        // callback fired after dialog becomes visible. executes in context of Boxy instance.
        afterHide: Boxy.EF,        // callback fired after dialog is hidden. executed in context of Boxy instance.
        beforeUnload: Boxy.EF         // callback fired after dialog is unloaded. executed in context of Boxy instance.
    },

    DEFAULT_X: 50,
    DEFAULT_Y: 50,
    zIndex: 10000, // original value was 1337 ... value was raised to ensure it appeared on top of everything else
    dragConfigured: false, // only set up one drag handler for all boxys
    resizeConfigured: false,
    dragging: null,

    // load a URL and display in boxy
    // url - url to load
    // options keys (any not listed below are passed to boxy constructor)
    //   type: HTTP method, default: GET
    //   cache: cache retrieved content? default: false
    //   filter: jQuery selector used to filter remote content
    load: function(url, options) {

        options = options || {};

        var ajax = {
            url: url, type: 'GET', dataType: 'html', cache: false, success: function(html) {
                html = jQuery(html);
                if (options.filter) html = jQuery(options.filter, html);
                new Boxy(html, options);
            }
        };

        jQuery.each(['type', 'cache'], function() {
            if (this in options) {
                ajax[this] = options[this];
                delete options[this];
            }
        });

        jQuery.ajax(ajax);

    },

    // allows you to get a handle to the containing boxy instance of any element
    // e.g. <a href='#' onclick='alert(Boxy.get(this));'>inspect!</a>.
    // this returns the actual instance of the boxy 'class', not just a DOM element.
    // Boxy.get(this).hide() would be valid, for instance.
    get: function(ele) {
        var p = jQuery(ele).parents('.boxy-wrapper');
        return p.length ? jQuery.data(p[0], 'boxy') : null;
    },

    // returns the boxy instance which has been linked to a given element via the
    // 'actuator' constructor option.
    linkedTo: function(ele) {
        return jQuery.data(ele, 'active.boxy');
    },

    // displays an alert box with a given message, calling optional callback
    // after dismissal.
    alert: function(message, callback, options) {
        return Boxy.ask(message, ['OK'], callback, options);
    },

    // displays an alert box with a given message, calling after callback iff
    // user selects OK.
    confirm: function(message, after, options) {
        return Boxy.ask(message, ['OK', 'Cancel'], function(response) {
            if (response == 'OK') after();
        }, options);
    },

    // asks a question with multiple responses presented as buttons
    // selected item is returned to a callback method.
    // answers may be either an array or a hash. if it's an array, the
    // the callback will received the selected value. if it's a hash,
    // you'll get the corresponding key.
    ask: function(question, answers, callback, options) {

        options = jQuery.extend({ modal: true, closeable: false },
                                options || {},
                                { show: true, unloadOnHide: true });

        var body = jQuery('<div></div>').append(jQuery('<div class="question"></div>').html(question));

        // ick
        var map = {}, answerStrings = [];
        if (answers instanceof Array) {
            for (var i = 0; i < answers.length; i++) {
                map[answers[i]] = answers[i];
                answerStrings.push(answers[i]);
            }
        } else {
            for (var k in answers) {
                map[answers[k]] = k;
                answerStrings.push(answers[k]);
            }
        }

        var buttons = jQuery('<form class="answers"></form>');
        buttons.html(jQuery.map(answerStrings, function(v) {
            return "<input type='button' value='" + v + "' />";
        }).join(' '));

        jQuery('input[type=button]', buttons).click(function() {
            var clicked = this;
            Boxy.get(this).hide(function() {
                if (callback) callback(map[clicked.value]);
            });
        });

        body.append(buttons);

        new Boxy(body, options);

    },

    // returns true if a modal boxy is visible, false otherwise
    isModalVisible: function() {
        return jQuery('.boxy-modal-blackout').length > 0;
    },

    _u: function() {
        for (var i = 0; i < arguments.length; i++)
            if (typeof arguments[i] != 'undefined') return false;
        return true;
    },

    _handleResize: function(evt) {
        var d = jQuery(document);
        jQuery('.boxy-modal-blackout').css('display', 'none').css({
            width: d.width(), height: d.height()
        }).css('display', 'block');
    },

    _handleDrag: function(evt) {
        var d;
        if (d = Boxy.dragging) {
            d[0].boxy.css({ left: evt.pageX - d[1], top: evt.pageY - d[2] });
        }
    },

    _nextZ: function() {
        return Boxy.zIndex++;
    },

    _viewport: function() {
        var d = document.documentElement, b = document.body, w = window;
        return jQuery.extend(
            jQuery.browser.msie ?
                { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop} :
                { left: w.pageXOffset, top: w.pageYOffset },
            !Boxy._u(w.innerWidth) ?
                { width: w.innerWidth, height: w.innerHeight} :
                (!Boxy._u(d) && !Boxy._u(d.clientWidth) && d.clientWidth != 0 ?
                    { width: d.clientWidth, height: d.clientHeight} :
                    { width: b.clientWidth, height: b.clientHeight }));
    }

});

Boxy.prototype = {

    // Returns the size of this boxy instance without displaying it.
    // Do not use this method if boxy is already visible, use getSize() instead.
    estimateSize: function() {
        this.boxy.css({ visibility: 'hidden', display: 'block' });
        var dims = this.getSize();
        this.boxy.css('display', 'none').css('visibility', 'visible');
        return dims;
    },

    // Returns the dimensions of the entire boxy dialog as [width,height]
    getSize: function() {
        return [this.boxy.width(), this.boxy.height()];
    },

    // Returns the dimensions of the content region as [width,height]
    getContentSize: function() {
        var c = this.getContent();
        return [c.width(), c.height()];
    },

    // Returns the position of this dialog as [x,y]
    getPosition: function() {
        var b = this.boxy[0];
        return [b.offsetLeft, b.offsetTop];
    },

    // Returns the center point of this dialog as [x,y]
    getCenter: function() {
        var p = this.getPosition();
        var s = this.getSize();
        return [Math.floor(p[0] + s[0] / 2), Math.floor(p[1] + s[1] / 2)];
    },

    // Returns a jQuery object wrapping the inner boxy region.
    // Not much reason to use this, you're probably more interested in getContent()
    getInner: function() {
        return jQuery('.boxy-inner', this.boxy);
    },

    // Returns a jQuery object wrapping the boxy content region.
    // This is the user-editable content area (i.e. excludes titlebar)
    getContent: function() {
        return jQuery('.boxy-content', this.boxy);
    },

    // Replace dialog content
    setContent: function(newContent) {
        newContent = jQuery(newContent).css({ display: 'block' }).addClass('boxy-content');
        if (this.options.clone) newContent = newContent.clone(true);
        this.getContent().remove();
        this.getInner().append(newContent);
        this._setupDefaultBehaviours(newContent);
        this.options.behaviours.call(this, newContent);
        return this;
    },

    // Move this dialog to some position, funnily enough
    moveTo: function(x, y) {
        this.moveToX(x).moveToY(y);
        return this;
    },

    // Move this dialog (x-coord only)
    moveToX: function(x) {
        if (typeof x == 'number') this.boxy.css({ left: x });
        else this.centerX();
        return this;
    },

    // Move this dialog (y-coord only)
    moveToY: function(y) {
        if (typeof y == 'number') this.boxy.css({ top: y });
        else this.centerY();
        return this;
    },

    // Move this dialog so that it is centered at (x,y)
    centerAt: function(x, y) {
        var s = this[this.visible ? 'getSize' : 'estimateSize']();
        if (typeof x == 'number') this.moveToX(x - s[0] / 2);
        if (typeof y == 'number') this.moveToY(y - s[1] / 2);
        return this;
    },

    centerAtX: function(x) {
        return this.centerAt(x, null);
    },

    centerAtY: function(y) {
        return this.centerAt(null, y);
    },

    // Center this dialog in the viewport
    // axis is optional, can be 'x', 'y'.
    center: function(axis) {
        var v = Boxy._viewport();
        var o = this.options.fixed ? [0, 0] : [v.left, v.top];
        if (!axis || axis == 'x') this.centerAt(o[0] + v.width / 2, null);
        if (!axis || axis == 'y') this.centerAt(null, o[1] + v.height / 2);
        return this;
    },

    // Center this dialog in the viewport (x-coord only)
    centerX: function() {
        return this.center('x');
    },

    // Center this dialog in the viewport (y-coord only)
    centerY: function() {
        return this.center('y');
    },

    // Resize the content region to a specific size
    resize: function(width, height, after) {
        if (!this.visible) return;
        var bounds = this._getBoundsForResize(width, height);
        this.boxy.css({ left: bounds[0], top: bounds[1] });
        this.getContent().css({ width: bounds[2], height: bounds[3] });
        if (after) after(this);
        return this;
    },

    // Tween the content region to a specific size
    tween: function(width, height, after) {
        if (!this.visible) return;
        var bounds = this._getBoundsForResize(width, height);
        var self = this;
        this.boxy.stop().animate({ left: bounds[0], top: bounds[1] });
        this.getContent().stop().animate({ width: bounds[2], height: bounds[3] }, function() {
            if (after) after(self);
        });
        return this;
    },

    // Returns true if this dialog is visible, false otherwise
    isVisible: function() {
        return this.visible;
    },

    // Make this boxy instance visible
    show: function() {
        if (this.visible) return;
        if (this.options.modal) {
            var self = this;
            if (!Boxy.resizeConfigured) {
                Boxy.resizeConfigured = true;
                jQuery(window).resize(function() { Boxy._handleResize(); });
            }
            this.modalBlackout = jQuery('<div class="boxy-modal-blackout"></div>')
                .css({ zIndex: Boxy._nextZ(),
                    opacity: 0.7,
                    width: jQuery(document).width(),
                    height: jQuery(document).height()
                })
                .appendTo(document.body);
            this.toTop();
            if (this.options.closeable) {
                jQuery(document.body).bind('keypress.boxy', function(evt) {
                    var key = evt.which || evt.keyCode;
                    if (key == 27) {
                        self.hide();
                        jQuery(document.body).unbind('keypress.boxy');
                    }
                });
            }
        }
        this.boxy.stop().css({ opacity: 1 }).show();
        this.visible = true;
        //hide the select elements for IE6
        if (document.all && !window.XMLHttpRequest) {
            $("select").css({ visibility: "hidden" });
            //we need to make the select elements inside the boxy pop-up
            visible
            $(".boxy-content select").css({ visibility: "visible" });
        }
        this._fire('afterShow');
        return this;
    },

    // Hide this boxy instance
    hide: function(after) {
        if (!this.visible) return;
        var self = this;
        if (this.options.modal) {
            jQuery(document.body).unbind('keypress.boxy');
            this.modalBlackout.animate({ opacity: 0 }, function() {
                jQuery(this).remove();
            });
        }
        this.boxy.stop().animate({ opacity: 0 }, 300, function() {
            self.boxy.css({ display: 'none' });
            self.visible = false;
            self._fire('afterHide');
            if (after) after(self);
            if (self.options.unloadOnHide) self.unload();
        });
        //show the select elements for IE6
        if (document.all && !window.XMLHttpRequest) {
            $("select").css({ visibility: "visible" });
        }
        return this;
    },

    toggle: function() {
        this[this.visible ? 'hide' : 'show']();
        return this;
    },

    hideAndUnload: function(after) {
        this.options.unloadOnHide = true;
        this.hide(after);
        return this;
    },

    unload: function() {
        this._fire('beforeUnload');
        this.boxy.remove();
        if (this.options.actuator) {
            jQuery.data(this.options.actuator, 'active.boxy', false);
        }
    },

    // Move this dialog box above all other boxy instances
    toTop: function() {
        this.boxy.css({ zIndex: Boxy._nextZ() });
        return this;
    },

    // Returns the title of this dialog
    getTitle: function() {
        return jQuery('> .title-bar h2', this.getInner()).html();
    },

    // Sets the title of this dialog
    setTitle: function(t) {
        jQuery('> .title-bar h2', this.getInner()).html(t);
        return this;
    },

    //
    // Don't touch these privates

    _getBoundsForResize: function(width, height) {
        var csize = this.getContentSize();
        var delta = [width - csize[0], height - csize[1]];
        var p = this.getPosition();
        return [Math.max(p[0] - delta[0] / 2, 0),
                Math.max(p[1] - delta[1] / 2, 0), width, height];
    },

    _setupTitleBar: function() {
        if (this.options.title) {
            var self = this;
            var tb = jQuery("<div class='title-bar'></div>").html("<h2>" + this.options.title + "</h2>");
            if (this.options.closeable) {
                tb.append(jQuery("<a href='#' class='close'></a>").html(this.options.closeText));
            }
            if (this.options.draggable) {
                tb[0].onselectstart = function() { return false; }
                tb[0].unselectable = 'on';
                tb[0].style.MozUserSelect = 'none';
                if (!Boxy.dragConfigured) {
                    jQuery(document).mousemove(Boxy._handleDrag);
                    Boxy.dragConfigured = true;
                }
                tb.mousedown(function(evt) {
                    self.toTop();
                    Boxy.dragging = [self, evt.pageX - self.boxy[0].offsetLeft, evt.pageY - self.boxy[0].offsetTop];
                    jQuery(this).addClass('dragging');
                }).mouseup(function() {
                    jQuery(this).removeClass('dragging');
                    Boxy.dragging = null;
                    self._fire('afterDrop');
                });
            }
            this.getInner().prepend(tb);
            this._setupDefaultBehaviours(tb);
        }
    },

    _setupDefaultBehaviours: function(root) {
        var self = this;
        if (this.options.clickToFront) {
            root.click(function() { self.toTop(); });
        }
        jQuery('.close', root).click(function() {
            self.hide();
            return false;
        }).mousedown(function(evt) { evt.stopPropagation(); });
    },

    _fire: function(event) {
        this.options[event].call(this);
    }

};

// End ~/Scripts/plugins/jquery.boxy.js

// Begin ~/Scripts/plugins/iCalendar/jquery.icalendar.min.js

/* http://keith-wood.name/icalendar.html
   iCalendar processing for jQuery v1.1.1.
   Written by Keith Wood (kbwood{at}iinet.com.au) October 2008.
   Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and 
   MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. 
   Please attribute the author if you use it. */
(function($){var p='icalendar';var q='icalendar-flash-copy';function iCalendar(){this._defaults={sites:[],icons:'icalendar.png',iconSize:16,target:'_blank',compact:false,popup:false,popupText:'Send to my calendar...',tipPrefix:'',echoUrl:'',echoField:'',start:null,end:null,title:'',summary:'',description:'',location:'',url:'',contact:'',recurrence:null,copyConfirm:'The event will be copied to your clipboard. Continue?',copySucceeded:'The event has been copied to your clipboard',copyFailed:'Failed to copy the event to the clipboard\n',copyFlash:'clipboard.swf',copyUnavailable:'The clipboard is unavailable, please copy the event details from below:\n'};this._sites={'google':{display:'Google',icon:0,override:null,url:'http://www.google.com/calendar/event?action=TEMPLATE'+'&amp;text={t}&amp;dates={s}/{e}&amp;details={d}&amp;location={l}&amp;sprop=website:{u}'},'icalendar':{display:'iCalendar',icon:1,override:null,url:'echo'},'outlook':{display:'Outlook',icon:2,override:null,url:'echo'},'yahoo':{display:'Yahoo',icon:3,override:yahooOverride,url:'http://calendar.yahoo.com/?v=60&amp;view=d&amp;type=20'+'&amp;title={t}&amp;st={s}&amp;dur={p}&amp;desc={d}&amp;in_loc={l}&amp;url={u}&amp;rpat={r}'}}}var r=[{method:'Seconds',factor:1},{method:'Minutes',factor:60},{method:'Hours',factor:3600},{method:'Date',factor:86400},{method:'Month',factor:1},{method:'FullYear',factor:12},{method:'Date',factor:604800}];var s=0;var t=1;var u=2;var w=3;var x=4;var y=5;var z=6;$.extend(iCalendar.prototype,{markerClassName:'hasICalendar',setDefaults:function(a){extendRemove(this._defaults,a||{});return this},addSite:function(a,b,c,d,e){this._sites[a]={display:b,icon:c,override:e,url:d};return this},getSites:function(){return this._sites},_attachICalendar:function(a,b){a=$(a);if(a.hasClass(this.markerClassName)){return}a.addClass(this.markerClassName);this._updateICalendar(a,b)},_changeICalendar:function(a,b){a=$(a);if(!a.hasClass(this.markerClassName)){return}this._updateICalendar(a,b)},_updateICalendar:function(i,j){j=extendRemove($.extend({},this._defaults,$.data(i[0],p)||{}),j);$.data(i[0],p,j);var k=j.sites||this._defaults.sites;if(k.length==0){$.each(this._sites,function(a){k[k.length]=a})}var l=function(b,c){var d={t:encodeURIComponent(j.title),d:encodeURIComponent(j.description),s:$.icalendar.formatDateTime(j.start),e:$.icalendar.formatDateTime(j.end),p:$.icalendar.calculateDuration(j.start,j.end),l:encodeURIComponent(j.location),u:encodeURIComponent(j.url),c:encodeURIComponent(j.contact),r:makeRecurrence(j.recurrence)};if(b.override){b.override.apply(i,[d,j])}var e=b.url;$.each(d,function(n,v){var a=new RegExp('\\{'+n+'\\}','g');e=e.replace(a,v)});var e=(b.url=='echo'?'#':e);var f=$('<li></li>');var g=$('<a href="'+e+'" title="'+j.tipPrefix+b.display+'"'+(b.url=='echo'?'':' target="'+j._target+'"')+'></a>');if(b.url=='echo'){g.click(function(){return $.icalendar._echo(i[0],c)})}var h='';if(b.icon!=null){if(typeof b.icon=='number'){h+='<span style="background: '+'transparent url('+j.icons+') no-repeat -'+(b.icon*j.iconSize)+'px 0px;'+($.browser.mozilla&&$.browser.version<'1.9'?' padding-left: '+j.iconSize+'px; padding-bottom: '+Math.max(0,(j.iconSize/2)-5)+'px;':'')+'"></span>'}else{h+='<img src="'+b.icon+'"'+(($.browser.mozilla&&$.browser.version<'1.9')||($.browser.msie&&$.browser.version<'7.0')?' style="vertical-align: bottom;"':($.browser.msie?' style="vertical-align: middle;"':($.browser.opera||$.browser.safari?' style="vertical-align: baseline;"':'')))+'/>'}h+=(j.compact?'':'&#xa0;')}g.html(h+(j.compact?'':b.display));f.append(g);return f};var m=$('<ul class="icalendar_list'+(j.compact?' icalendar_compact':'')+'"></ul>');var o=this._sites;$.each(k,function(a,b){m.append(l(o[b],b))});i.empty().append(m);if(j.popup){m.before('<span class="icalendar_popup_text">'+j.popupText+'</span>').wrap('<div class="icalendar_popup"></div>');i.click(function(){var a=$(this);var b=a.offset();$('.icalendar_popup',a).css('left',b.left).css('top',b.top+a.outerHeight()).toggle()})}},_destroyICalendar:function(a){a=$(a);if(!a.hasClass(this.markerClassName)){return}a.removeClass(this.markerClassName).empty();$.removeData(a[0],p)},_echo:function(a,b){var c=$.data(a,p);var d=makeICalendar(c);if(c.echoUrl){window.location.href=c.echoUrl+'?content='+escape(d)}else if(c.echoField){$(c.echoField).val(d)}else if(!c.copyFlash){alert(c.copyUnavailable+d)}else if(confirm(c.copyConfirm)){var e='';if(e=copyViaFlash(d,c.copyFlash)){alert(c.copyFailed+e)}else{alert(c.copySucceeded)}}return false},_ensureTwo:function(a){return(a<10?'0':'')+a},formatDate:function(a,b){return(!a?'':''+a.getFullYear()+this._ensureTwo(a.getMonth()+1)+this._ensureTwo(a.getDate()))},formatDateTime:function(a,b){return(!a?'':(b?''+a.getFullYear()+this._ensureTwo(a.getMonth()+1)+this._ensureTwo(a.getDate())+'T'+this._ensureTwo(a.getHours())+this._ensureTwo(a.getMinutes())+this._ensureTwo(a.getSeconds()):''+a.getUTCFullYear()+this._ensureTwo(a.getUTCMonth()+1)+this._ensureTwo(a.getUTCDate())+'T'+this._ensureTwo(a.getUTCHours())+this._ensureTwo(a.getUTCMinutes())+this._ensureTwo(a.getUTCSeconds())+'Z'))},calculateDuration:function(a,b){if(!a||!b){return''}var c=Math.abs(b.getTime()-a.getTime())/1000;var d=Math.floor(c/86400);c-=d*86400;var e=Math.floor(c/3600);c-=e*3600;var f=Math.floor(c/60);c-=f*60;return(a.getTime()>b.getTime()?'-':'')+'P'+(d>0?d+'D':'')+(e||f||c?'T'+e+'H':'')+(f||c?f+'M':'')+(c?c+'S':'')},addDuration:function(d,e){if(!e){return d}var f=new Date(d.getTime());var g=I.exec(e);if(!g){throw'Invalid duration';}if(g[2]&&(g[3]||g[5]||g[6]||g[7])){throw'Invalid duration - week must be on its own';}if(!g[4]&&(g[5]||g[6]||g[7])){throw'Invalid duration - missing time marker';}var h=(g[1]=='-'?-1:+1);var i=function(a,b,c){a=parseInt(a);if(!isNaN(a)){f['setUTC'+c](f['getUTC'+c]()+h*a*b)}};if(g[2]){i(g[2],7,'Date')}else{i(g[3],1,'Date');i(g[5],1,'Hours');i(g[6],1,'Minutes');i(g[7],1,'Seconds')}return f},parse:function(a){var b={};var c={};var d=unfoldLines(a);parseGroup(d,0,b,c);if(!b.vcalendar){throw'Invalid iCalendar data';}return b.vcalendar},getWeekOfYear:function(a,b){return getWeekOfYear(a,b)},_parseParams:function(a,b){return parseParams(a,b)}});function extendRemove(a,b){$.extend(a,b);for(var c in b){if(b[c]==null){a[c]=null}}return a}$.fn.icalendar=function(a){var b=Array.prototype.slice.call(arguments,1);return this.each(function(){if(typeof a=='string'){$.icalendar['_'+a+'ICalendar'].apply($.icalendar,[this].concat(b))}else{$.icalendar._attachICalendar(this,a||{})}})};$.icalendar=new iCalendar();function yahooOverride(b,c){var d=function(a){return(a<10?'0':'')+a};var e=(c.end?(c.end.getTime()-c.start.getTime())/60000:0);b.p=(e?d(Math.floor(e/60))+''+d(e%60):'');if(b.r){var f=(c.recurrence.by&&c.recurrence.by[0].type=='day'?c.recurrence.by[0].values.join('').toLowerCase():'');var g={daily:'dy',weekly:'wk',monthly:'mh',yearly:'yr'}[c.recurrence.freq];b.r=(f||g?d(c.recurrence.interval||1)+(f||g):'')}}function makeICalendar(c){var d=function(a){var b='';while(a.length>75){b+=a.substr(0,75)+'\n';a=' '+a.substr(75)}b+=a;return b};return'BEGIN:VCALENDAR\n'+'VERSION:2.0\n'+'PRODID:jquery.icalendar\n'+'METHOD:PUBLISH\n'+'BEGIN:VEVENT\n'+'UID:'+new Date().getTime()+'@'+(window.location.href.replace(/^[^\/]*\/\/([^\/]*)\/.*$/,'$1')||'localhost')+'\n'+'DTSTAMP:'+$.icalendar.formatDateTime(new Date())+'\n'+(c.url?d('URL:'+c.url)+'\n':'')+(c.contact?d('MAILTO:'+c.contact)+'\n':'')+d('TITLE:'+c.title)+'\n'+'DTSTART:'+$.icalendar.formatDateTime(c.start)+'\n'+'DTEND:'+$.icalendar.formatDateTime(c.end)+'\n'+(c.summary?d('SUMMARY:'+c.summary)+'\n':'')+(c.description?d('DESCRIPTION:'+c.description)+'\n':'')+(c.location?d('LOCATION:'+c.location)+'\n':'')+(c.recurrence?makeRecurrence(c.recurrence)+'\n':'')+'END:VEVENT\n'+'END:VCALENDAR'}function makeRecurrence(a){if(!a){return''}var b='';if(a.dates){b='RDATE;VALUE=DATE:';if(!isArray(a.dates)){a.dates=[a.dates]}for(var i=0;i<a.dates.length;i++){b+=(i>0?',':'')+$.icalendar.formatDate(a.dates[i])}}else if(a.times){b='RDATE;VALUE=DATE-TIME:';if(!isArray(a.times)){a.times=[a.times]}for(var i=0;i<a.times.length;i++){b+=(i>0?',':'')+$.icalendar.formatDateTime(a.times[i])}}else if(a.periods){b='RDATE;VALUE=PERIOD:';if(!isArray(a.periods[0])){a.periods=[a.periods]}for(var i=0;i<a.periods.length;i++){b+=(i>0?',':'')+$.icalendar.formatDateTime(a.periods[i][0])+'/'+(a.periods[i][1].constructor!=Date?a.periods[i][1]:$.icalendar.formatDateTime(a.periods[i][1]))}}else{b='RRULE:FREQ='+(a.freq||'daily').toUpperCase()+(a.interval?';INTERVAL='+a.interval:'')+(a.until?';UNTIL='+$.icalendar.formatDateTime(a.until):(a.count?';COUNT='+a.count:''))+(a.weekStart!=null?';WKST='+['SU','MO','TU','WE','TH','FR','SA'][a.weekStart]:'');if(a.by){if(!isArray(a.by)){a.by=[a.by]}for(var i=0;i<a.by.length;i++){if(!isArray(a.by[i].values)){a.by[i].values=[a.by[i].values]}b+=';BY'+a.by[i].type.toUpperCase()+'='+a.by[i].values.join(',')}}}return b}function copyViaFlash(a,b){$('#'+q).remove();try{$('body').append('<div id="'+q+'"><embed src="'+b+'" FlashVars="clipboard='+encodeURIComponent(a)+'" width="0" height="0" type="application/x-shockwave-flash"></embed></div>');return''}catch(e){return e}}var A=/^\s(.*)$/;var B=/^([A-Za-z0-9-]+)((?:;[A-Za-z0-9-]+=(?:"[^"]+"|[^";:,]+)(?:,(?:"[^"]+"|[^";:,]+))*)*):(.*)$/;var C=/;([A-Za-z0-9-]+)=((?:"[^"]+"|[^";:,]+)(?:,(?:"[^"]+"|[^";:,]+))*)/g;var D=/,?("[^"]+"|[^";:,]+)/g;var E=/^(\d{4})(\d\d)(\d\d)$/;var F=/^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)$/;var G=/^(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)\/(\d{4})(\d\d)(\d\d)T(\d\d)(\d\d)(\d\d)(Z?)$/;var H=/^([+-])(\d\d)(\d\d)$/;var I=/^([+-])?P(\d+W)?(\d+D)?(T)?(\d+H)?(\d+M)?(\d+S)?$/;var J=['class'];function unfoldLines(b){var c=b.replace(/\r\n/g,'\n').split('\n');for(var i=c.length-1;i>0;i--){var d=A.exec(c[i]);if(d){c[i-1]+=d[1];c[i]=''}}return $.map(c,function(a,i){return(a?a:null)})}function parseGroup(a,b,c,d){if(b>=a.length||a[b].indexOf('BEGIN:')!=0){throw'Missing group start';}var e={};var f=a[b].substr(6);addEntry(c,f.toLowerCase(),e);b++;while(b<a.length&&a[b].indexOf('END:')!=0){if(a[b].indexOf('BEGIN:')==0){b=parseGroup(a,b,e,d)}else{var g=parseEntry(a[b]);addEntry(e,g._name,(g._simple?g._value:g))}b++}if(f=='VTIMEZONE'){var h=H.exec(e.standard.tzoffsetto);if(h){d[e.tzid]=(h[1]=='-'?-1:+1)*(parseInt(h[2],10)*60+parseInt(h[3],10))}}else{for(var i in e){resolveTimezones(e[i],d)}}if(a[b]!='END:'+f){throw'Missing group end '+f;}return b}function resolveTimezones(c,d){if(!c){return}if(c.tzid&&c._value){var e=d[c.tzid];var f=function(a,b){a.setMinutes(a.getMinutes()-e);a._type=b};if(isArray(c._value)){for(var i=0;i<c._value.length;i++){f(c._value[i],c.tzid)}}else if(c._value.start&&c._value.end){f(c._value.start,c.tzid);f(c._value.end,c.tzid)}else{f(c._value,c.tzid)}}else if(isArray(c)){for(var i=0;i<c.length;i++){resolveTimezones(c[i],d)}}}function addEntry(a,b,c){if(typeof c=='string'){c=c.replace(/\\n/g,'\n')}if($.inArray(b,J)>-1){b+='_'}if(a[b]){if(!isArray(a[b])||a['_'+b+'IsArray']){a[b]=[a[b]]}a[b][a[b].length]=c;if(a['_'+b+'IsArray']){a['_'+b+'IsArray']=undefined}}else{a[b]=c;if(isArray(c)){a['_'+b+'IsArray']=true}}}function parseEntry(a){var b={};var c=B.exec(a);if(!c){throw'Missing entry name: '+a;}b._name=c[1].toLowerCase();b._value=checkDate(c[3]);b._simple=true;parseParams(b,c[2]);return b}function parseParams(a,b){var c=C.exec(b);while(c){var d=[];var e=D.exec(c[2]);while(e){d.push(checkDate(e[1].replace(/^"(.*)"$/,'$1')));e=D.exec(c[2])}a[c[1].toLowerCase()]=(d.length>1?d:d[0]);a._simple=false;c=C.exec(b)}}function checkDate(a){var b=F.exec(a);if(b){return makeDate(b)}b=G.exec(a);if(b){return{start:makeDate(b),end:makeDate(b.slice(7))}}b=E.exec(a);if(b){return makeDate(b.concat([0,0,0,'']))}return a}function makeDate(a){var b=new Date(a[1],a[2]-1,a[3],a[4],a[5],a[6]);b._type=(a[7]?'UTC':'float');return utcDate(b)}function utcDate(a){a.setMinutes(a.getMinutes()-a.getTimezoneOffset());return a}function getWeekOfYear(a,b){b=(b||b==0?b:1);var c=new Date(a.getFullYear(),a.getMonth(),a.getDate(),(a.getTimezoneOffset()/-60));var d=new Date(c.getFullYear(),1-1,4);var e=d.getDay();d.setDate(4+b-e-(b>e?7:0));if(c<d){c.setDate(c.getDate()-3);return getWeekOfYear(c,b)}else if(c>new Date(c.getFullYear(),12-1,28)){var f=new Date(c.getFullYear()+1,1-1,4);e=f.getDay();f.setDate(4+b-e-(b>e?7:0));if(c>=f){return 1}}return Math.floor(((c-d)/(r[w].factor*1000))/7)+1}function isArray(a){return(a&&a.constructor==Array)}})(jQuery);
// End ~/Scripts/plugins/iCalendar/jquery.icalendar.min.js

// Begin ~/Scripts/plugins/jPlayer/jquery.jplayer.min.js

/*
 * jPlayer Plugin for jQuery JavaScript Library
 * http://www.happyworm.com/jquery/jplayer
 *
 * Copyright (c) 2009 - 2010 Happyworm Ltd
 * Dual licensed under the MIT and GPL licenses.
 *  - http://www.opensource.org/licenses/mit-license.php
 *  - http://www.gnu.org/copyleft/gpl.html
 *
 * Author: Mark J Panaghiston
 * Version: 1.2.0
 * Date: 11th July 2010
 */

(function(c){function k(a,b){var d=function(e){e=c[a][e]||[];return typeof e=="string"?e.split(/,?\s+/):e}("getter");return c.inArray(b,d)!=-1}c.fn.jPlayer=function(a){var b=typeof a=="string",d=Array.prototype.slice.call(arguments,1);if(b&&a.substring(0,1)=="_")return this;if(b&&k("jPlayer",a,d)){var e=c.data(this[0],"jPlayer");return e?e[a].apply(e,d):undefined}return this.each(function(){var h=c.data(this,"jPlayer");!h&&!b&&c.data(this,"jPlayer",new c.jPlayer(this,a))._init();h&&b&&c.isFunction(h[a])&&
h[a].apply(h,d)})};c.jPlayer=function(a,b){this.options=c.extend({},b);this.element=c(a)};c.jPlayer.getter="jPlayerOnProgressChange jPlayerOnSoundComplete jPlayerVolume jPlayerReady getData jPlayerController";c.jPlayer.defaults={cssPrefix:"jqjp",swfPath:"js",volume:80,oggSupport:false,nativeSupport:true,preload:"none",customCssIds:false,graphicsFix:true,errorAlerts:false,warningAlerts:false,position:"absolute",width:"0",height:"0",top:"0",left:"0",quality:"high",bgcolor:"#ffffff"};c.jPlayer._config=
{version:"1.2.0",swfVersionRequired:"1.2.0",swfVersion:"unknown",jPlayerControllerId:undefined,delayedCommandId:undefined,isWaitingForPlay:false,isFileSet:false};c.jPlayer._diag={isPlaying:false,src:"",loadPercent:0,playedPercentRelative:0,playedPercentAbsolute:0,playedTime:0,totalTime:0};c.jPlayer._cssId={play:"jplayer_play",pause:"jplayer_pause",stop:"jplayer_stop",loadBar:"jplayer_load_bar",playBar:"jplayer_play_bar",volumeMin:"jplayer_volume_min",volumeMax:"jplayer_volume_max",volumeBar:"jplayer_volume_bar",
volumeBarValue:"jplayer_volume_bar_value"};c.jPlayer.count=0;c.jPlayer.timeFormat={showHour:false,showMin:true,showSec:true,padHour:false,padMin:true,padSec:true,sepHour:":",sepMin:":",sepSec:""};c.jPlayer.convertTime=function(a){var b=new Date(a),d=b.getUTCHours();a=b.getUTCMinutes();b=b.getUTCSeconds();d=c.jPlayer.timeFormat.padHour&&d<10?"0"+d:d;a=c.jPlayer.timeFormat.padMin&&a<10?"0"+a:a;b=c.jPlayer.timeFormat.padSec&&b<10?"0"+b:b;return(c.jPlayer.timeFormat.showHour?d+c.jPlayer.timeFormat.sepHour:
"")+(c.jPlayer.timeFormat.showMin?a+c.jPlayer.timeFormat.sepMin:"")+(c.jPlayer.timeFormat.showSec?b+c.jPlayer.timeFormat.sepSec:"")};c.jPlayer.prototype={_init:function(){var a=this,b=this.element;this.config=c.extend({},c.jPlayer.defaults,this.options,c.jPlayer._config);this.config.diag=c.extend({},c.jPlayer._diag);this.config.cssId={};this.config.cssSelector={};this.config.cssDisplay={};this.config.clickHandler={};this.element.data("jPlayer.config",this.config);c.extend(this.config,{id:this.element.attr("id"),
swf:this.config.swfPath+(this.config.swfPath!=""&&this.config.swfPath.slice(-1)!="/"?"/":"")+"Jplayer.swf",fid:this.config.cssPrefix+"_flash_"+c.jPlayer.count,aid:this.config.cssPrefix+"_audio_"+c.jPlayer.count,hid:this.config.cssPrefix+"_force_"+c.jPlayer.count,i:c.jPlayer.count,volume:this._limitValue(this.config.volume,0,100),autobuffer:this.config.preload!="none"});c.jPlayer.count++;if(this.config.ready!=undefined)if(c.isFunction(this.config.ready))this.jPlayerReadyCustom=this.config.ready;else this._warning("Constructor's ready option is not a function.");
this.config.audio=document.createElement("audio");this.config.audio.id=this.config.aid;c.extend(this.config,{canPlayMP3:!!(this.config.audio.canPlayType?""!=this.config.audio.canPlayType("audio/mpeg")&&"no"!=this.config.audio.canPlayType("audio/mpeg"):false),canPlayOGG:!!(this.config.audio.canPlayType?""!=this.config.audio.canPlayType("audio/ogg")&&"no"!=this.config.audio.canPlayType("audio/ogg"):false),aSel:c("#"+this.config.aid)});c.extend(this.config,{html5:!!(this.config.oggSupport?this.config.canPlayOGG?
true:this.config.canPlayMP3:this.config.canPlayMP3)});c.extend(this.config,{usingFlash:!(this.config.html5&&this.config.nativeSupport),usingMP3:!(this.config.oggSupport&&this.config.canPlayOGG&&this.config.nativeSupport)});var d={setButtons:function(g,f){a.config.diag.isPlaying=f;if(a.config.cssId.play!=undefined&&a.config.cssId.pause!=undefined)if(f){a.config.cssSelector.play.css("display","none");a.config.cssSelector.pause.css("display",a.config.cssDisplay.pause)}else{a.config.cssSelector.play.css("display",
a.config.cssDisplay.play);a.config.cssSelector.pause.css("display","none")}if(f)a.config.isWaitingForPlay=false}},e={setFile:function(g,f){try{a._getMovie().fl_setFile_mp3(f);a.config.autobuffer&&b.trigger("jPlayer.load");a.config.diag.src=f;a.config.isFileSet=true;b.trigger("jPlayer.setButtons",false)}catch(j){a._flashError(j)}},clearFile:function(){try{b.trigger("jPlayer.setButtons",false);a._getMovie().fl_clearFile_mp3();a.config.diag.src="";a.config.isFileSet=false}catch(g){a._flashError(g)}},
load:function(){try{a._getMovie().fl_load_mp3()}catch(g){a._flashError(g)}},play:function(){try{a._getMovie().fl_play_mp3()&&b.trigger("jPlayer.setButtons",true)}catch(g){a._flashError(g)}},pause:function(){try{a._getMovie().fl_pause_mp3()&&b.trigger("jPlayer.setButtons",false)}catch(g){a._flashError(g)}},stop:function(){try{a._getMovie().fl_stop_mp3()&&b.trigger("jPlayer.setButtons",false)}catch(g){a._flashError(g)}},playHead:function(g,f){try{a._getMovie().fl_play_head_mp3(f)&&b.trigger("jPlayer.setButtons",
true)}catch(j){a._flashError(j)}},playHeadTime:function(g,f){try{a._getMovie().fl_play_head_time_mp3(f)&&b.trigger("jPlayer.setButtons",true)}catch(j){a._flashError(j)}},volume:function(g,f){a.config.volume=f;try{a._getMovie().fl_volume_mp3(f)}catch(j){a._flashError(j)}}},h={setFile:function(g,f,j){a.config.diag.src=a.config.usingMP3?f:j;a.config.isFileSet&&!a.config.isWaitingForPlay&&b.trigger("jPlayer.pause");a.config.audio.autobuffer=a.config.autobuffer;a.config.audio.preload=a.config.preload;
if(a.config.autobuffer){a.config.audio.src=a.config.diag.src;a.config.audio.load()}else a.config.isWaitingForPlay=true;a.config.isFileSet=true;a.jPlayerOnProgressChange(0,0,0,0,0);clearInterval(a.config.jPlayerControllerId);if(a.config.autobuffer)a.config.jPlayerControllerId=window.setInterval(function(){a.jPlayerController(false)},100);clearInterval(a.config.delayedCommandId)},clearFile:function(){a.setFile("","");a.config.isWaitingForPlay=false;a.config.isFileSet=false},load:function(){if(a.config.isFileSet)if(a.config.isWaitingForPlay){a.config.audio.autobuffer=
true;a.config.audio.preload="auto";a.config.audio.src=a.config.diag.src;a.config.audio.load();a.config.isWaitingForPlay=false;clearInterval(a.config.jPlayerControllerId);a.config.jPlayerControllerId=window.setInterval(function(){a.jPlayerController(false)},100)}},play:function(){if(a.config.isFileSet){if(a.config.isWaitingForPlay){a.config.audio.src=a.config.diag.src;a.config.audio.load()}a.config.audio.play();b.trigger("jPlayer.setButtons",true);clearInterval(a.config.jPlayerControllerId);a.config.jPlayerControllerId=
window.setInterval(function(){a.jPlayerController(false)},100);clearInterval(a.config.delayedCommandId)}},pause:function(){if(a.config.isFileSet){a.config.audio.pause();b.trigger("jPlayer.setButtons",false);clearInterval(a.config.delayedCommandId)}},stop:function(){if(a.config.isFileSet)try{b.trigger("jPlayer.pause");a.config.audio.currentTime=0;clearInterval(a.config.jPlayerControllerId);a.config.jPlayerControllerId=window.setInterval(function(){a.jPlayerController(true)},100)}catch(g){clearInterval(a.config.delayedCommandId);
a.config.delayedCommandId=window.setTimeout(function(){a.stop()},100)}},playHead:function(g,f){if(a.config.isFileSet)try{b.trigger("jPlayer.load");if(typeof a.config.audio.buffered=="object"&&a.config.audio.buffered.length>0)a.config.audio.currentTime=f*a.config.audio.buffered.end(a.config.audio.buffered.length-1)/100;else if(a.config.audio.duration>0&&!isNaN(a.config.audio.duration))a.config.audio.currentTime=f*a.config.audio.duration/100;else throw"e";b.trigger("jPlayer.play")}catch(j){b.trigger("jPlayer.play");
b.trigger("jPlayer.pause");a.config.delayedCommandId=window.setTimeout(function(){a.playHead(f)},100)}},playHeadTime:function(g,f){if(a.config.isFileSet)try{b.trigger("jPlayer.load");a.config.audio.currentTime=f/1E3;b.trigger("jPlayer.play")}catch(j){b.trigger("jPlayer.play");b.trigger("jPlayer.pause");a.config.delayedCommandId=window.setTimeout(function(){a.playHeadTime(f)},100)}},volume:function(g,f){a.config.volume=f;a.config.audio.volume=f/100;a.jPlayerVolume(f)}};this.config.usingFlash?c.extend(d,
e):c.extend(d,h);for(var i in d){e="jPlayer."+i;this.element.unbind(e);this.element.bind(e,d[i])}if(this.config.usingFlash)if(this._checkForFlash(8))if(c.browser.msie){i='<object id="'+this.config.fid+'"';i+=' classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';i+=' codebase="'+document.URL.substring(0,document.URL.indexOf(":"))+'://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"';i+=' type="application/x-shockwave-flash"';i+=' width="'+this.config.width+'" height="'+this.config.height+
'">';i+="</object>";d=[];d[0]='<param name="movie" value="'+this.config.swf+'" />';d[1]='<param name="quality" value="high" />';d[2]='<param name="FlashVars" value="id='+escape(this.config.id)+"&fid="+escape(this.config.fid)+"&vol="+this.config.volume+'" />';d[3]='<param name="allowScriptAccess" value="always" />';d[4]='<param name="bgcolor" value="'+this.config.bgcolor+'" />';i=document.createElement(i);for(e=0;e<d.length;e++)i.appendChild(document.createElement(d[e]));this.element.html(i)}else{d=
'<embed name="'+this.config.fid+'" id="'+this.config.fid+'" src="'+this.config.swf+'"';d+=' width="'+this.config.width+'" height="'+this.config.height+'" bgcolor="'+this.config.bgcolor+'"';d+=' quality="high" FlashVars="id='+escape(this.config.id)+"&fid="+escape(this.config.fid)+"&vol="+this.config.volume+'"';d+=' allowScriptAccess="always"';d+=' type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';this.element.html(d)}else this.element.html("<p>Flash 8 or above is not installed. <a href='http://get.adobe.com/flashplayer'>Get Flash!</a></p>");
else{this.config.audio.autobuffer=this.config.autobuffer;this.config.audio.preload=this.config.preload;this.config.audio.addEventListener("canplay",function(){var g=0.1*Math.random();a.config.audio.volume=(a.config.volume+(a.config.volume<50?g:-g))/100},false);this.config.audio.addEventListener("ended",function(){clearInterval(a.config.jPlayerControllerId);a.jPlayerOnSoundComplete()},false);this.element.append(this.config.audio)}this.element.css({position:this.config.position,top:this.config.top,
left:this.config.left});if(this.config.graphicsFix){this.element.append('<div id="'+this.config.hid+'"></div>');c.extend(this.config,{hSel:c("#"+this.config.hid)});this.config.hSel.css({"text-indent":"-9999px"})}this.config.customCssIds||c.each(c.jPlayer._cssId,function(g,f){a.cssId(g,f)});if(!this.config.usingFlash){this.element.css({left:"-9999px"});window.setTimeout(function(){a.volume(a.config.volume);a.jPlayerReady()},100)}},jPlayerReady:function(a){if(this.config.usingFlash){this.config.swfVersion=
a;this.config.swfVersionRequired!=this.config.swfVersion&&this._error("jPlayer's JavaScript / SWF version mismatch!\n\nJavaScript requires SWF : "+this.config.swfVersionRequired+"\nThe Jplayer.swf used is : "+this.config.swfVersion)}else this.config.swfVersion="n/a";this.jPlayerReadyCustom()},jPlayerReadyCustom:function(){},setFile:function(a,b){this.element.trigger("jPlayer.setFile",[a,b])},clearFile:function(){this.element.trigger("jPlayer.clearFile")},load:function(){this.element.trigger("jPlayer.load")},
play:function(){this.element.trigger("jPlayer.play")},pause:function(){this.element.trigger("jPlayer.pause")},stop:function(){this.element.trigger("jPlayer.stop")},playHead:function(a){this.element.trigger("jPlayer.playHead",[a])},playHeadTime:function(a){this.element.trigger("jPlayer.playHeadTime",[a])},volume:function(a){a=this._limitValue(a,0,100);this.element.trigger("jPlayer.volume",[a])},cssId:function(a,b){var d=this;if(typeof b=="string")if(c.jPlayer._cssId[a]){this.config.cssId[a]!=undefined&&
this.config.cssSelector[a].unbind("click",this.config.clickHandler[a]);this.config.cssId[a]=b;this.config.cssSelector[a]=c("#"+b);this.config.clickHandler[a]=function(h){d[a](h);c(this).blur();return false};this.config.cssSelector[a].click(this.config.clickHandler[a]);var e=this.config.cssSelector[a].css("display");if(a=="play")this.config.cssDisplay.pause=e;if(!(a=="pause"&&e=="none")){this.config.cssDisplay[a]=e;a=="pause"&&this.config.cssSelector[a].css("display","none")}}else this._warning("Unknown/Illegal function in cssId\n\njPlayer('cssId', '"+
a+"', '"+b+"')");else this._warning("cssId CSS Id must be a string\n\njPlayer('cssId', '"+a+"', "+b+")")},loadBar:function(a){if(this.config.cssId.loadBar!=undefined){var b=this.config.cssSelector.loadBar.offset();a=a.pageX-b.left;b=this.config.cssSelector.loadBar.width();this.playHead(100*a/b)}},playBar:function(a){this.loadBar(a)},onProgressChange:function(a){if(c.isFunction(a))this.onProgressChangeCustom=a;else this._warning("onProgressChange parameter is not a function.")},onProgressChangeCustom:function(){},
jPlayerOnProgressChange:function(a,b,d,e,h){this.config.diag.loadPercent=a;this.config.diag.playedPercentRelative=b;this.config.diag.playedPercentAbsolute=d;this.config.diag.playedTime=e;this.config.diag.totalTime=h;this.config.cssId.loadBar!=undefined&&this.config.cssSelector.loadBar.width(a+"%");this.config.cssId.playBar!=undefined&&this.config.cssSelector.playBar.width(b+"%");this.onProgressChangeCustom(a,b,d,e,h);this._forceUpdate()},jPlayerController:function(a){var b=0,d=0,e=0,h=0,i=0;if(this.config.audio.readyState>=
1){b=this.config.audio.currentTime*1E3;d=this.config.audio.duration*1E3;d=isNaN(d)?0:d;e=d>0?100*b/d:0;if(typeof this.config.audio.buffered=="object"&&this.config.audio.buffered.length>0){h=100*this.config.audio.buffered.end(this.config.audio.buffered.length-1)/this.config.audio.duration;i=100*this.config.audio.currentTime/this.config.audio.buffered.end(this.config.audio.buffered.length-1)}else{h=100;i=e}}!this.config.diag.isPlaying&&h>=100&&clearInterval(this.config.jPlayerControllerId);a?this.jPlayerOnProgressChange(h,
0,0,0,d):this.jPlayerOnProgressChange(h,i,e,b,d)},volumeMin:function(){this.volume(0)},volumeMax:function(){this.volume(100)},volumeBar:function(a){if(this.config.cssId.volumeBar!=undefined){var b=this.config.cssSelector.volumeBar.offset();a=a.pageX-b.left;b=this.config.cssSelector.volumeBar.width();this.volume(100*a/b)}},volumeBarValue:function(a){this.volumeBar(a)},jPlayerVolume:function(a){if(this.config.cssId.volumeBarValue!=null){this.config.cssSelector.volumeBarValue.width(a+"%");this._forceUpdate()}},
onSoundComplete:function(a){if(c.isFunction(a))this.onSoundCompleteCustom=a;else this._warning("onSoundComplete parameter is not a function.")},onSoundCompleteCustom:function(){},jPlayerOnSoundComplete:function(){this.element.trigger("jPlayer.setButtons",false);this.onSoundCompleteCustom()},getData:function(a){for(var b=a.split("."),d=this.config,e=0;e<b.length;e++)if(d[b[e]]!=undefined)d=d[b[e]];else{this._warning("Undefined data requested.\n\njPlayer('getData', '"+a+"')");return}return d},_getMovie:function(){return document[this.config.fid]},
_checkForFlash:function(a){var b=false,d;if(window.ActiveXObject)try{new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+a);b=true}catch(e){}else if(navigator.plugins&&navigator.mimeTypes.length>0)if(d=navigator.plugins["Shockwave Flash"])if(navigator.plugins["Shockwave Flash"].description.replace(/.*\s(\d+\.\d+).*/,"$1")>=a)b=true;return b},_forceUpdate:function(){this.config.graphicsFix&&this.config.hSel.text(""+Math.random())},_limitValue:function(a,b,d){return a<b?b:a>d?d:a},_flashError:function(a){this._error("Problem with Flash component.\n\nCheck the swfPath points at the Jplayer.swf path.\n\nswfPath = "+
this.config.swfPath+"\nurl: "+this.config.swf+"\n\nError: "+a.message)},_error:function(a){this.config.errorAlerts&&this._alert("Error!\n\n"+a)},_warning:function(a){this.config.warningAlerts&&this._alert("Warning!\n\n"+a)},_alert:function(a){alert("jPlayer "+this.config.version+" : id='"+this.config.id+"' : "+a)}}})(jQuery);
// End ~/Scripts/plugins/jPlayer/jquery.jplayer.min.js

// Begin ~/Scripts/custom/SDO.ux.Forms.js

/*
 * forms widget - wire up html form for jQuery AJAX submission and response handling
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function($){

    $.widget("SDO.Forms", {
        options: {
            validationDisplay: 'top' /*[top|bottom|modal]*/
        },
        _init: function(){
            var self = this;
            var el = $(this.element);
            self.action = el.attr('submitaction') || '';
            self.submit = self.options.submitForm || self.submitForm;
            self.redirect = el.attr('successredirect') || '';
            el.keypress(function(event){
                if (event.keyCode == '13') {
                    event.preventDefault();
                    self.submit(self);
                }
            });
            $('.btn-submit', el).click(function(){
                var btn = $(this);
                el.addClass('masked');
                Ext.get(el.attr('id')).mask('Please Wait...', 'x-mask-loading');
                self.submit(self);
            });
        },
        submitForm: function(frm){
            frm.clearErrors();
            $.post(frm.action, $(frm.element).serialize(), function(result){
                if (result.success == true) {
                    frm.onSuccess(result);
                }
                else {
                    frm.onFailure(result);
                }
            }, "json");
        },
        clearErrors: function(){
            var self = this;
            var el = $(this.element);
            if (self.options.validationDisplay != 'modal') {
                $('.idc-frm-errs', el).remove();
            }
        },
        showErrors: function(errs){
            var self = this;
            var el = $(this.element);
			if(errs == undefined){
				errs = ["An unknown error occurred."];
			}
            if (errs && errs.length > 0) {
                var errContent = '<div class="idc-frm-errs site-error rc-5 xlt-shdw"><ul class="errors">'
                for (i = 0; i < errs.length; i++) {
                    errContent += "<li>" + errs[i] + "</li>";
                }
                errContent += "</ul></div>";
                if (self.options.validateDisplay == 'bottom') {
                    el.append(errContent);
                }
                else {
                    el.prepend(errContent);
                }
                var errctr = $(".idc-frm-errs");
                if (errctr.get(0) && el.height() > 300) {
                    $("html, body").animate({
                        scrollTop: errctr.offset().top - 10
                    }, "slow");
                }
            }
        },
        onSuccess: function(result){
            var self = this;
            var el = $(this.element);
            if (self.options.success) {
                self.options.success(result);
            }
            if (self.redirect.length > 0) {
                Internships.navigateWithReferrer(self.redirect);
            }
            else {
                el.removeClass('masked');
                Ext.get(el.attr('id')).unmask();
            }
        },
        onFailure: function(result){
            var self = this;
            var el = $(this.element);
            self.showErrors(result.errs);
            if (self.options.failure) {
                self.options.failure(result);
            }
            el.removeClass('masked');
            Ext.get(el.attr('id')).unmask();
        },
        destroy: function(){
            $.Widget.prototype.destroy.call(this);
        },
        widget: function(){
            return this.menu.element;
        }
    });
}(jQuery));

// End ~/Scripts/custom/SDO.ux.Forms.js

// Begin ~/Scripts/custom/SDO.ux.Placeholder.js

/*
* placeholder widget - simulate HTML5 placeholder functionality
*
* Depends:
*	jquery.ui.core.js
*	jquery.ui.widget.js
*/
(function ($) {

    $.widget("SDO.Placeholder", {
        options: {
            color: '#fff',
            cls: 'placeholder',
            lr_padding: 4
        },
        _init: function () {
            var self = this;
            var el = this.element;
            if (self.placholder) {
                var $ph = self.placholder;
                $ph.css(self.positionCSS($(el)));
                return true;
            }
            var ph = $('<label>' + $(el).attr('placeholder') + '</label>').insertBefore(el).addClass(self.options.cls).css({
                'position': 'absolute',
                'display': 'inline',
                'float': 'none',
                'overflow': 'hidden',
                'whiteSpace': 'nowrap',
                'textAlign': 'left',
                'color': self.options.color,
                'cursor': 'text',
                'fontSize': $(el).css('font-size'),
                'lineHeight': $(el).css('height')
            }).css(self.positionCSS(el));
            self.placholder = ph;
            ph.click(function () {
                el.focus();
            });
            el.focus(function () {
                ph.hide();
            }).blur(function () {
                ph[el.val().length ? 'hide' : 'show']();
            }).triggerHandler('blur');
            $(window).resize(function () {
                var $target = self.element;
                ph.css(self.positionCSS($target));
            })
        },
        destroy: function () {
            $.Widget.prototype.destroy.call(this);
        },
        browser_supported: function () {
            return this._supported !== undefined ? this._supported : (this._supported = !!('placeholder' in $('<input type="text">')[0]));
        },
        positionCSS: function (target) {

            var op = $(target).offsetParent().offset();
            var ot = $(target).offset();
            if ($(target).offsetParent()[0].tagName.toLowerCase() == 'body') {
                return {
                    top: ot.top + ($(target).outerHeight() - $(target).height()) / 2,
                    left: ot.left + this.options.lr_padding,
                    width: $(target).width() - this.options.lr_padding
                }
            }
            else {
                return {
                    top: ot.top - op.top + ($(target).outerHeight() - $(target).height()) / 2,
                    left: ot.left - op.left + this.options.lr_padding,
                    width: $(target).width() - this.options.lr_padding
                }
            }
        },
        widget: function () {
            return this.menu.element;
        }
    });
} (jQuery));

// End ~/Scripts/custom/SDO.ux.Placeholder.js

// Begin ~/Scripts/custom/SDO.ux.Rotator.js

/*
 * rotator widget - fade thru list item content w/ optional number nav
 *   TODO: add options for fade effects
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function($){

    $.widget("SDO.Rotator", {
        options: {
			showNumbers : false,
			timeout: 7000,
			speed: 'slow'
		},
        _init: function(){
            var self = this;
            var el = this.element;
            var $el = $(this.element);
			if($el.attr('data-timeout') && !isNaN(parseInt($el.attr('data-timeout')))){
				self.options.timeout = parseInt($el.attr('data-timeout'));
			}
			if($el.attr('data-speed') && !isNaN(parseInt($el.attr('data-speed')))){
				self.options.speed = parseInt($el.attr('data-speed'));
			}
            self.items = $('li', $el);
            self.currentIndex = 0;
            self.tmr = [];
			self.autoPlay = true;
			var pgr = $('<ul class="rotator-list-2-pager"/>');
            self.items.each(function(ind, el){
                var $item = $(el);
                $el.css('position', 'relative');
                self.itemWidth = $item.width() > self.itemWidth ? $item.width() : self.itemWidth;
                self.itemHeight = $item.height() > self.itemHeight ? $item.height() : self.itemHeight;
                $item.css('position', 'absolute').css('left', '0px').css('top', '0px').hide();
                $(this).hover(function(){
                    self.autoPlay = false;
                    self.clearTimeouts();
                    //self.showItem(ind);
                }, function(){
                    self.autoPlay = true;
                    self.clearTimeouts();
                    self.currentIndex = ind + 1;
                    self.tmr.push(setTimeout(function(){
                        self.showItem();
                    }, 2000));
                });
				var pgrbtn = $('<a>'+(ind+1)+'</a>').click(function(){
					self.autoPlay = false;
                    self.clearTimeouts();
                    self.showItem(ind);
				});
				var pgritm = $('<li class="pgr-btn-'+ind+'"/>');
				pgritm.append(pgrbtn);
				pgr.append(pgritm);
            });
			if (self.options.showNumbers) {
				$el.after(pgr);
			}
            $el.height(self.itemHeight);
            $el.width(self.itemWidth);
			self.showItem();
        },
        destroy: function(){
            $.Widget.prototype.destroy.call(this);
        },
        showItem: function(itm){
			//console.log('show', itm);
            var self = this;
            self.clearTimeouts();
            if (typeof(itm) != 'undefined') {
                self.currentIndex = itm;
            }
            if (self.currentIndex >= self.items.length) {
                self.currentIndex = 0;
            }
            $('li', $(self.element)).fadeOut();
			$('.rotator-list-2-pager li.selected', $(self.element).parent()).removeClass('selected');
			$('.rotator-list-2-pager li.pgr-btn-'+self.currentIndex, $(self.element).parent()).addClass('selected');
            self.items.each(function(ind, el){
                var $item = $(el);
                if (ind == self.currentIndex) {
                    $item.fadeIn(self.options.speed, function(){
                        if (self.autoPlay == true) {
                            self.currentIndex++;
                            if (self.currentIndex >= self.items.length) {
                                self.currentIndex = 0;
                            }
                            self.tmr.push(setTimeout(function(){
                                self.showItem();
                            }, self.options.timeout));
                            //console.log(tmr);
                        }
                    });
                }
            });
        },
        clearTimeouts: function(){
            var self = this;
            while (self.tmr.length > 0) {
                clearTimeout(self.tmr.shift());
            }
        },
        widget: function(){
            return this.element;
        }
    });
}(jQuery));

// End ~/Scripts/custom/SDO.ux.Rotator.js

// Begin ~/Scripts/custom/SDO.js



var SDO = {
    showModal: function(url, w, h, title, cb){
        $.get(url, function(data){
            SDO.showModalContent(data, w, h, title, cb);
        })
    },
    showModalContent: function(content, w, h, title, cb){
        if (!window.modalWin) {
            $('body').append('<div id="mw" style="display:none;"/>');
            window.modalWin = $('#mw');
        }
        var mw = $(window.modalWin);
        mw.dialog("destroy");
        mw.html(content);
        //console.log(mw.width(), mw.height());
        mw.dialog({
            height: h || (mw.height() + 50),
            width: w || (mw.width() + 30),
            modal: true,
            zIndex: 99000,
            title: title,
            open: cb ||
            function(){//not implemented
            }
        })
    },
    toggleText: function(mode){
        if (mode == 1) {
            $("body").addClass("text-large");
            SDO.Cookies.set("text-size", "large", "/");
        }
        else {
            $("body").removeClass("text-large");
            SDO.Cookies.set("text-size", null, "/");
        }
        
    },
    GenerateTimer: function(){
        $.getJSON("/json/GetTicketExpiration/" + dateFormat(new Date(), "yymmdd_hhMMss"), function(json){
            if (json.d != "TESSITURA_SEAT_LOCKING_EXCEPTION") {
                var expiration = parseInt(json);
                var sCartTimer = "";
                var secondsRemaining = expiration;
                //alert(expiration + ' seconds remaining');
                var timeRemaining = Math.floor(secondsRemaining / 60);
                if (timeRemaining < 30) {
                    if (timeRemaining > 1) {
                        $("div.timer").html("You have " + timeRemaining + " minutes remaining to complete your order").show();
                        setTimeout("SDO.UpdateTimer(" + timeRemaining + ")", 60000);
                        
                    }
                    else {
                        window.location = '/Account/SessionExpired/';
                    }
                }
            }
        });
    },
    UpdateTimer: function(currentTime){
        currentTime -= 1;
        if (currentTime > 0) {
            $("div.timer").html("You have " + currentTime + " minutes remaining to complete your order");
            setTimeout("SDO.UpdateTimer(" + currentTime + ")", 60000);
        }
        else {
            window.location = '/Account/SessionExpired';
        }
    },
    FormEffects: function(){
        //radio hotspots
        $("input[type=radio]", $(".radio-hotspot")).click(SDO.radioClickHandler);
        
        $(".radio-hotspot").removeClass("selected").attr("sel", "false");
        $(".radio-hotspot").each(function(ind, el){
            if ($("input[type=radio]:checked", $(el)).length > 0) {
                $(el).addClass("selected").attr("sel", "true");
            }
            $(el).attr("customtype", "radio-hotspot");
        });
        //checkbox hotspots
        $("input[type=checkbox]", $(".checkbox-hotspot")).click(SDO.checkboxClickHandler);
        
    },
    radioClickHandler: function(event){
        //event.stopPropagation();
        $(".radio-hotspot").removeClass("selected").attr("sel", "false");
        $(".radio-hotspot").each(function(ind2, el2){
            if ($("input[type=radio]:checked", $(el2)).length > 0) {
                $(el2).addClass("selected");
                $(el2).attr("sel", "true");
            }
        });
    },
    checkboxClickHandler: function(event){
        //event.stopPropagation();
        $(event.target).parent(".checkbox-hotspot").toggleClass("selected");
    },
    
    
    stopAllAudio: function(){
        $(".audioplayer").each(function(ind){
            try {
                $(this).jPlayer("pause");
            } 
            catch (err) {
            }
        });
        $(".audio_title").animate({
            width: "0px"
        }, {
            duration: 2000,
            easing: 'linear'
        });
    },
    
    Search: function(q){
        $.getJSON("/json/Search/?q=" + escape(q), function(data){
            var content = "<div class=\"search-results\">";
            if (data.length > 0) {
                for (i = 0; i < data.length; i++) {
                    content += "<div class=\"search-result\">";
                    content += "<h3><a href=\"" + data[i].Url + "\" target=\"_blank\">" + data[i].Title + "</a></h3>";
                    content += "<p>" + data[i].Summary + "</p></div>";
                }
                
            }
            else {
                content += "<div>Your search '" + q + "' did not return any valid results.</div>";
            }
            content += "</div>";
            
            var searchboxy = new Boxy(content, {
                "title": "San Diego Opera Search Results for '" + q + "'",
                modal: true,
                unloadOnHide: true
            });
        });
    },
    OperapaediaKeywords: function(){
        var self = this;
        var pathname = window.location.pathname;
        if (self.keywords == undefined) {
            $.getJSON("/json/OperapaediaKeywords/", function(data){
                self.keywords = data;
                if (data.length > 0 && pathname.toLowerCase().indexOf("gala") <= 0 && pathname.toLowerCase().indexOf("board") <= 0 && pathname.toLowerCase().indexOf("offer") <= 0) {
                    for (k = 0; k < self.keywords.length; k++) {
                        self.linkKeywords($("p", $("#col1")), self.keywords[k]);
                        self.linkKeywords($("li", $("#col1")), self.keywords[k]);
                        self.linkKeywords($("dl", $("#col1")), self.keywords[k]);
                        self.linkKeywords($("p", $("#mainoperapane")), self.keywords[k]);
                        self.linkKeywords($("li", $("#mainoperapane")), self.keywords[k]);
                    }
                }
            });
        }
        else {
            if (self.keywords.length > 0 && pathname.toLowerCase().indexOf("gala") <= 0 && pathname.toLowerCase().indexOf("board") <= 0 && pathname.toLowerCase().indexOf("offer") <= 0) {
                for (k = 0; k < self.keywords.length; k++) {
                    self.linkKeywords($("p", $("#col1")), self.keywords[k]);
                    self.linkKeywords($("li", $("#col1")), self.keywords[k]);
                    self.linkKeywords($("dl", $("#col1")), self.keywords[k]);
                    self.linkKeywords($("p", $("#mainoperapane")), self.keywords[k]);
                    self.linkKeywords($("li", $("#mainoperapane")), self.keywords[k]);
                }
            }
        }
    },
    linkKeywords: function(el, pat){
        function innerLink(node, pat){
            var skip = 0;
            if (node.nodeType == 3) {
                var pos = node.data.toUpperCase().indexOf(pat);
                
                if (pos >= 0) {
                
                
                    var spannode = document.createElement('a');
                    spannode.className = 'keyword';
                    spannode.target = "_blank";
                    spannode.href = "/Operapaedia/" + pat.toLowerCase();
                    var middlebit = node.splitText(pos);
                    var endbit = middlebit.splitText(pat.length);
                    var middleclone = middlebit.cloneNode(true);
                    spannode.appendChild(middleclone);
                    middlebit.parentNode.replaceChild(spannode, middlebit);
                    skip = 1;
                }
            }
            else 
                if (node.nodeType == 1 && node.childNodes && !/(script|style|a|h1|q|select)/i.test(node.tagName)) {
                    for (var i = 0; i < node.childNodes.length; ++i) {
                        i += innerLink(node.childNodes[i], pat);
                        
                    }
                }
            return skip;
        }
        return el.each(function(){
            innerLink(this, pat.toUpperCase());
        });
    }
};

function padRight(str, len){
    var s = str;
    var numspaces = len - str.length;
    if (numspaces > 0) {
        for (i = 0; i < numspaces; i++) {
            s += '&nbsp;';
        }
    }
    return s;
}

function padLeft(str, len){
    var s = str;
    var numspaces = len - str.length;
    if (numspaces > 0) {
        for (i = 0; i < numspaces; i++) {
            s = '&nbsp;' + s;
        }
    }
    return s;
}

//add array manipulation helpers
Array.prototype.move_element = function(index, delta){

    // This method moves an element within the array
    // index = the array item you want to move
    // delta = the direction and number of spaces to move the item.
    //
    // For example:
    // move_element(myarray, 5, -1); // move up one space
    // move_element(myarray, 2, 1); // move down one space
    //
    // Returns true for success, false for error.
    
    var index2, temp_item;
    
    // Make sure the index is within the array bounds
    if (index < 0 || index >= this.length) {
        return false;
    }
    
    // Make sure the target index is within the array bounds
    index2 = index + delta;
    if (index2 < 0 || index2 >= this.length || index2 == index) {
        return false;
    }
    
    // Move the elements in the array
    temp_item = this[index2];
    this[index2] = this[index];
    this[index] = temp_item;
    
    return true;
}

//dateFormat
/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */
var dateFormat = function(){
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(val, len){
        val = String(val);
        len = len || 2;
        while (val.length < len) 
            val = "0" + val;
        return val;
    };
    
    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc){
        var dF = dateFormat;
        
        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }
        
        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date();
        if (isNaN(date)) 
            throw new SyntaxError("invalid date");
        
        mask = String(dF.masks[mask] || mask || dF.masks["default"]);
        
        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }
        
        var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_ + "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = {
            d: d,
            dd: pad(d),
            ddd: dF.i18n.dayNames[D],
            dddd: dF.i18n.dayNames[D + 7],
            m: m + 1,
            mm: pad(m + 1),
            mmm: dF.i18n.monthNames[m],
            mmmm: dF.i18n.monthNames[m + 12],
            yy: String(y).slice(2),
            yyyy: y,
            h: H % 12 || 12,
            hh: pad(H % 12 || 12),
            H: H,
            HH: pad(H),
            M: M,
            MM: pad(M),
            s: s,
            ss: pad(s),
            l: pad(L, 3),
            L: pad(L > 99 ? Math.round(L / 10) : L),
            t: H < 12 ? "a" : "p",
            tt: H < 12 ? "am" : "pm",
            T: H < 12 ? "A" : "P",
            TT: H < 12 ? "AM" : "PM",
            Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
            o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
            S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
        };
        
        return mask.replace(token, function($0){
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
    monthNames: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
};

// For convenience...
Date.prototype.format = function(mask, utc){
    return dateFormat(this, mask, utc);
};

// End ~/Scripts/custom/SDO.js

// Begin ~/Scripts/custom/SDO.Utilities.js

var SDO = window.SDO || {};

/**
 * @class SDO.Utilities.Cookies
 * Utility class for managing and interacting with cookies.
 * @singleton
 */
SDO.Cookies = {
    
/**
     * Create a cookie with the specified name and value. Additional settings
     * for the cookie may be optionally specified (for example: expiration,
     * access restriction, SSL).
     * @param {String} name The name of the cookie to set. 
     * @param {Mixed} value The value to set for the cookie.
     * @param {Object} expires (Optional) Specify an expiration date the
     * cookie is to persist until.  Note that the specified Date object will
     * be converted to Greenwich Mean Time (GMT). 
     * @param {String} path (Optional) Setting a path on the cookie restricts
     * access to pages that match that path. Defaults to all pages ('/'). 
     * @param {String} domain (Optional) Setting a domain restricts access to
     * pages on a given domain (typically used to allow cookie access across
     * subdomains). For example, "sdopera.com" will create a cookie that can be
     * accessed from any subdomain of sdopera.com, including www.sdopera.com,
     * qa.sdopera.com, etc.
     * @param {Boolean} secure (Optional) Specify true to indicate that the cookie
     * should only be accessible via SSL on a page using the HTTPS protocol.
     * Defaults to false. Note that this will only work if the page
     * calling this code uses the HTTPS protocol, otherwise the cookie will be
     * created with default options.
     */
    set : function(name, value){
        var argv = arguments;
        var argc = arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : '/';
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        document.cookie = name + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires)) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
    },

    
/**
     * Retrieves cookies that are accessible by the current page. If a cookie
     * does not exist, get() returns null.  The following
     * example retrieves the cookie called "valid" and stores the String value
     * in the variable validStatus.
     * 

     * var validStatus = SDO.Utilities.Cookies.get("valid");
     * 

     * @param {String} name The name of the cookie to get
     * @return {Mixed} Returns the cookie value for the specified name;
     * null if the cookie name does not exist.
     */
    get : function(name){
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        var j = 0;
        while(i < clen){
            j = i + alen;
            if(document.cookie.substring(i, j) == arg){
                return SDO.Cookies.getCookieVal(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;
            if(i === 0){
                break;
            }
        }
        return null;
    },

    
/**
     * Removes a cookie with the provided name from the browser
     * if found by setting its expiration date to sometime in the past. 
     * @param {String} name The name of the cookie to remove
     */
    clear : function(name){
        if(SDO.Cookies.get(name)){
            document.cookie = name + "=" + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },
    /**
     * @private
     */
    getCookieVal : function(offset){
        var endstr = document.cookie.indexOf(";", offset);
        if(endstr == -1){
            endstr = document.cookie.length;
        }
        return unescape(document.cookie.substring(offset, endstr));
    }
};
// End ~/Scripts/custom/SDO.Utilities.js

// Begin ~/Scripts/custom/SDO.Page.js


var SDO = window.SDO || {};

SDO.Page = {
    init: function () {
        $(document).ready(function () {
            //jquery-ui tabs
            $(".ui-tabs").tabs({
                load: function (event, ui) {
                    SDO.OperapaediaKeywords();
                }
            });
            //check for text-size cookie and adjust if present.
            if (SDO.Cookies.get("text-size") == "large") {
                $("body").addClass("text-large");
            }

            //simple expand-collapse 
            $(".expandable-link").click(function () {
                $(".expandable-content", $(this).parent()).toggle();
            });

            //TODO: update for new menu
            $("ul.sf-menu>li").hover(function () {
                $(this).addClass('sfHover');
            }, function () {
                $(this).removeClass('sfHover');
            });
            $('.boxy').each(function () {
                var el = $(this);
                var href = el.attr('href');
                console.log(href);
                var title = el.attr('title');
                var w = 600;
                //change width of boxy for membership page
                if (href.indexOf("membership.htm") >= 0) {
                    w = 700;
                }

                if (el.attr('w') && !isNan(parseInt(el.attr('w')))) {
                    w = parseInt(el.attr('w'));
                }
                var h = 450;
                if (el.attr('h') && !isNan(parseInt(el.attr('h')))) {
                    h = parseInt(el.attr('h'));
                }
                el.click(function () {
                    if (href.charAt(0) == '#') {
                        SDO.showModalContent($(href).html(), w, h, $(href).attr('title'), function () {
                        });
                    }
                    else {
                        SDO.showModal(href, w, h, title, function () {
                        });
                    }
                });
                el.attr('href', 'javascript:;');
            });
            $('.modal-boxy').each(function () {
                var el = $(this);
                var href = el.attr('href');
                console.log(href);
                var title = el.attr('title');
                var w = 0;
                if (el.attr('w') && !isNan(parseInt(el.attr('w')))) {
                    w = parseInt(el.attr('w'));
                }
                var h = 0;
                if (el.attr('h') && !isNan(parseInt(el.attr('h')))) {
                    h = parseInt(el.attr('h'));
                }
                el.click(function () {
                    if (href.charAt(0) == '#') {
                        SDO.showModalContent($(href).html(), w, h, $(href).attr('title'), function () {
                        });
                    }
                    else {
                        SDO.showModal(href, w, h, title, function () {
                        });
                    }
                });
                el.attr('href', 'javascript:;');
            });

            $('.modal-boxy-flash').each(function () {
                var el = $(this);
                var href = el.attr('href');
                console.log(href);
                var title = el.attr('title');
                var w = 0;
                if (el.attr('w') && !isNan(parseInt(el.attr('w')))) {
                    w = parseInt(el.attr('w'));
                }
                var h = 0;
                if (el.attr('h') && !isNan(parseInt(el.attr('h')))) {
                    h = parseInt(el.attr('h'));
                }
                el.click(function () {
                    if (href.charAt(0) == '#') {
                        SDO.showModalContent($(href).html(), w, h, $(href).attr('title'), function () {
                            startFlash();
                        });
                    }
                    else {
                        SDO.showModal(href, w, h, title, function () {
                            startFlash();
                        });
                    }
                });
                el.attr('href', 'javascript:;');
            });

            // maxlength textarea with countdown
            $("textarea[maxlength]").each(function () {
                $(this).before("<div class=\"charsleft\"><span>" + $(this).attr("maxlength") + "</span> characters remaining.</div>");
                $field = $(this);
                $(this).keyup(function () {
                    var l = $field.val().length;
                    var maxl = parseInt($field.attr("maxlength"));
                    if (!isNaN(maxl)) {
                        $field.prev(".charsleft").html("<span>" + (maxl - l) + "</span> characters remaining.");
                    }
                });
            });

            //wire up tooltips
            $('.tip').tooltip();
            //$('[title]').tooltip();

            $(".videoLink, .videoLinkText, .videoLinkNoFloat").click(function () {
                SDO.stopAllAudio();
                var videosrc = $("a", $(this)).attr("href");
                console.log(videosrc)
                if (videosrc == "#view") {
                    videosrc = $("a", $(this)).attr("vsource");
                }
                $("a", $(this)).attr("href", "#view");
                $("a", $(this)).attr("vsource", videosrc);
                var vw = parseInt($("a", $(this)).attr("videowidth"));
                var vh = parseInt($("a", $(this)).attr("videoheight")) + 40;
                var vt = $(".videoTitle", $(this)).html();
                var vd = $(".videoDescription", $(this)).html();
                var videoboxy = new Boxy("<div style=\"width:" + vw + "px;height:" + vh + "px; background-color:#000000; padding:0px;\"><div id=\"video1\" style=\"z-index: 0;\"></div></div>", {
                    "title": vt,
                    modal: true,
                    unloadOnHide: true,
                    afterShow: function () {
                        $("#video1").flash({
                            swf: '/Content/flash/video_single.swf',
                            height: vh,
                            width: vw,
                            params: {
                                wmode: "transparent",
                                flashvars: {
                                    myPath: videosrc
                                }
                            }
                        });
                    }
                });
            });
            $(".videoLinkEducation").click(function () {
                SDO.stopAllAudio();
                var videosrc = $("a", $(this)).attr("href");
                console.log(videosrc)
                if (videosrc == "#view") {
                    videosrc = $("a", $(this)).attr("vsource");
                }
                $("a", $(this)).attr("href", "#view");
                $("a", $(this)).attr("vsource", videosrc);
                var vw = parseInt($("a", $(this)).attr("videowidth"));
                var vh = parseInt($("a", $(this)).attr("videoheight"));
                var vt = $(".videoTitle", $(this)).html();
                var vd = $(".videoDescription", $(this)).html();
                var videoboxy = new Boxy("<div style=\"width:" + vw + "px;height:" + vh + "px; background-color:#000000; padding:0px;\"><div id=\"video1\" style=\"z-index: 0;\"></div></div>", {
                    "title": vt,
                    modal: true,
                    unloadOnHide: true,
                    afterShow: function () {
                        $("#video1").flash({
                            swf: '/Content/flash/video_single.swf',
                            height: vh,
                            width: vw,
                            params: {
                                wmode: "transparent",
                                flashvars: {
                                    myPath: videosrc
                                }
                            }
                        });
                    }
                });
            });
            $(".youTubeLink, .youTubeLinkNoFloat").click(function () {
                SDO.stopAllAudio();
                var videosrc = $("a", $(this)).attr("href");
                if (videosrc == "#view") {
                    videosrc = $("a", $(this)).attr("vsource");
                }
                var vidID = videosrc.substring(31);
                $("a", $(this)).attr("href", "#view");
                $("a", $(this)).attr("vsource", videosrc);
                var vw = parseInt($("a", $(this)).attr("videowidth"));
                var vh = parseInt($("a", $(this)).attr("videoheight"));
                var vt = $(".videoTitle", $(this)).html();
                var vd = $(".videoDescription", $(this)).html();
                var videoContent = "<object width=\"" + vw + "\" height=\"" + vh + "\"><param name=\"movie\" value=\"http://www.youtube.com/v/" + vidID + "&hl=en&fs=1&\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><param name=\"wmode\" value=\"transparent\"></param><embed src=\"http://www.youtube.com/v/" + vidID + "&hl=en&fs=1&\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" allowfullscreen=\"true\" width=\"" + vw + "\" height=\"" + vh + "\" wmode=\"transparent\"></embed></object>";
                if (!window.modalWin) {
                    $('body').append('<div id="mw" style="display:none;"/>');
                    window.modalWin = $('#mw');
                }
                var mw = $(window.modalWin);
                mw.dialog("destroy");
                mw.html("<div style=\"width:" + vw + "px; height:" + vh + "px; padding:0px; margin:0px;\" id=\"video1\">" + videoContent + "</div>");
                mw.dialog({
                    height: (mw.height() + 50),
                    width: (mw.width() + 30),
                    modal: true,
                    zIndex: 99000,
                    title: vt,
                    open: function () {
                    }
                });
            });
            $(".audio.podcast").each(function (i) {
                var ind = "podcast" + i;
                var audiourl = $(this).attr("href");
                var autoplay = false;
                if ($(this).attr("autoplay") != undefined && $(this).attr("autoplay") == "true") {
                    autoplay = true;
                }
                var plyrhtml = '';
                plyrhtml += '<div id="jquery_jplayer_' + ind + '" class="audioplayer"></div><div id="player_container_' + ind + '" class="audiodisplay ' + $(this).attr("class") + '"><ul class="player_controls">';
                plyrhtml += '<li id="player_play_' + ind + '" class="player_play"><span>play</span></li>';
                plyrhtml += '<li id="player_pause_' + ind + '" class="player_pause"><span>pause</span></li></ul>';
                plyrhtml += '<div id="player_progress_' + ind + '" class="player_progress"><div id="player_progress_load_bar_' + ind + '" class="player_progress_load_bar">';
                plyrhtml += '<div id="player_progress_play_bar_' + ind + '" class="player_progress_play_bar"></div></div></div></div>';
                $(this).after(plyrhtml);
                $("#jquery_jplayer_" + ind).jPlayer({
                    ready: function () {
                        if (autoplay) {
                            $("#jquery_jplayer_" + ind).jPlayer('setFile', audiourl).jPlayer("play");
                            $("#audio_title_" + ind).animate({
                                width: ($("#audio_title_" + ind + " span").width() + 65) + "px"
                            }, {
                                duration: 3000,
                                easing: 'linear'
                            });
                        }
                        else {
                            $("#jquery_jplayer_" + ind).jPlayer('setFile', audiourl);
                        }
                    },
                    swfPath: "/Scripts/plugins/jPlayer",
                    customCssIds: true
                }).jPlayer("cssId", "play", "player_play_" + ind).jPlayer("cssId", "pause", "player_pause_" + ind).jPlayer("cssId", "loadBar", "player_progress_load_bar_" + ind).jPlayer("cssId", "playBar", "player_progress_play_bar_" + ind).jPlayer("onSoundComplete", function () {
                    this.play();
                });
                $("#player_play_" + ind).click(function () {
                    SDO.stopAllAudio();
                    $("#jquery_jplayer_" + ind).jPlayer("play");
                    $(this).hide();
                    $("#player_pause_" + ind).fadeIn();
                });
                $("#player_pause_" + ind).click(function () {
                    $("#jquery_jplayer_" + ind).jPlayer("pause");
                    $(this).hide();
                    $("#player_play_" + ind).fadeIn();
                });
                $(this).hide();
            });
            $(".audio.opera").each(function (i) {
                var ind = "opera" + i;
                var audiourl = $(this).attr("href");
                var title = $(this).html();
                var autoplay = false;
                if ($(this).attr("autoplay") != undefined && $(this).attr("autoplay") == "true") {
                    autoplay = true;
                };
                var plyrhtml = '';
                plyrhtml += '<div id="jquery_jplayer_' + ind + '" class="audioplayer"></div><div id="player_container_' + ind + '" class="audiodisplay ' + $(this).attr("class") + '"><ul class="player_controls">';
                plyrhtml += '<li id="player_play_' + ind + '" class="player_play"><span>play</span></li>';
                plyrhtml += '<li id="player_pause_' + ind + '" class="player_pause"><span>pause</span></li></ul>';
                plyrhtml += '<div id="audio_title_' + ind + '" class="audio_title"><span>' + title + '</span></div>';
                plyrhtml += '<div id="player_progress_' + ind + '" class="player_progress"><div id="player_progress_load_bar_' + ind + '" class="player_progress_load_bar">';
                plyrhtml += '<div id="player_progress_play_bar_' + ind + '" class="player_progress_play_bar"></div></div></div></div>';
                $(this).after(plyrhtml);
                $("#jquery_jplayer_" + ind).jPlayer({
                    ready: function () {
                        //                        if (autoplay) {
                        //                            //$("#jquery_jplayer_" + ind).jPlayer('setFile', audiourl).play();
                        //                            //$("#player_play_" + ind).fadeIn();
                        //                            //$("#audio_title_" + ind).animate({
                        //                            //    width: ($("#audio_title_" + ind + " span").width() + 65) + "px"
                        //                            //}, {
                        //                            //    duration: 3000,
                        //                            //    easing: 'linear'
                        //                            //});
                        //                            
                        //                        }
                        if (autoplay) {
                            $("#jquery_jplayer_" + ind).jPlayer('setFile', audiourl);
                            this.play();
                            $(this).hide();
                            $("#player_pause_" + ind).fadeIn();
                            $("#audio_title_" + ind).animate({
                                width: ($("#audio_title_" + ind + " span").width() + 65) + "px"
                            }, {
                                duration: 3000,
                                easing: 'linear'
                            });
                        }
                        else {
                            $("#jquery_jplayer_" + ind).jPlayer('setFile', audiourl);
                        }
                    },
                    swfPath: "/Scripts/plugins/jPlayer",
                    customCssIds: true
                }).jPlayer("cssId", "play", "player_play_" + ind).jPlayer("cssId", "pause", "player_pause_" + ind).jPlayer("cssId", "loadBar", "player_progress_load_bar_" + ind).jPlayer("cssId", "playBar", "player_progress_play_bar_" + ind).jPlayer("onSoundComplete", function () {
                    this.play();
                });
                $("#player_play_" + ind).click(function () {
                    SDO.stopAllAudio();
                    $(this).hide();
                    $("#player_pause_" + ind).fadeIn();
                    //$('#jquery_jplayer_' + ind).play();
                    $("#audio_title_" + ind).animate({
                        width: ($("#audio_title_" + ind + " span").width() + 65) + "px"
                    }, {
                        duration: 3000,
                        easing: 'linear'
                    });
                });
                $("#player_pause_" + ind).click(function () {
                    //$('#jquery_jplayer_' + ind).pause();
                    $(this).hide();
                    $("#player_play_" + ind).fadeIn();
                    $("#audio_title_" + ind).animate({
                        width: "0px"
                    }, {
                        duration: 2000,
                        easing: 'linear'
                    });
                });
                $(this).hide();
            });
            // add focus class for all browsers
            $("input").focus(function () {
                if (!$(this).hasClass("no-focus")) {
                    $(this).addClass("focus");
                }
            });
            $("input").blur(function () {
                $(this).removeClass("focus");
            });
            $("textarea").focus(function () {
                $(this).addClass("focus");
            });
            $("textarea").blur(function () {
                $(this).removeClass("focus");
            });
            $('input[placeholder]').Placeholder();
            $('textarea[placeholder]').Placeholder();

            $('.rotator-list').Rotator();

            SDO.FormEffects();
            //$(".resize").vjustify();
            //$("div.buttonSubmit").hoverClass("buttonSubmitHover");
            if ($.browser.safari) {
                $("body").addClass("safari");
            }
        });

        $(window).load(function () {
            if (window.location.href.indexOf('SessionExpired') < 0) {
                SDO.GenerateTimer();
            }
            $(".first-field").focus();
            if ($.browser.msie) {
                $("object", $(".audio")).each(function () {
                    var shtml = $(this).parent().html();
                    alert(shtml);
                    $(this).parent().html(shtml);
                });
            }
            SDO.OperapaediaKeywords();
        });
    }
};

// End ~/Scripts/custom/SDO.Page.js

// Begin ~/Scripts/jquery.bigPicture-min.js

(function($) {
    $.jquery = $.jquery || {};
    $.jquery.ux = $.jquery.ux || {};
    $.jquery.ux.ui = $.jquery.ux.ui || {};
    $.jquery.ux.ui.BPHelper = function() {
        return {
            AUTO_ID: 1001,
            galleries: {},
            isBoxRendered: function() {
                return $('#bp').size() > 0 ? true : false
            },
            isBoxVisible: function() {
                return $('#bp > .bp-wrap').is(':visible')
            },
            renderBox: function() {
                if ($.jquery.ux.ui.BPHelper.isBoxRendered()) {
                    return
                }
                var sbox = document.createElement('div');
                var mask = document.createElement('div');
                var wrap = document.createElement('div');
                var main = document.createElement('div');
                var view = document.createElement('div');
                var bbar = document.createElement('div');
                $(bbar).addClass('bp-bbar').append('<div class="bp-hide-link"><a href="#"><span>Close</span></a></div>').append('<div class="bp-info-link"><a href="#"><span>Image info</span></a></div>').append('<div class="bp-clear"></div>');
                $(view).addClass('bp-view').css({
                    'margin': 0
                }).append('<div class="bp-nav bp-prev-link"><a href="#"><span>Prev</span></a></div>').append('<div class="bp-nav bp-next-link"><a href="#"><span>Next</span></a></div>').append('<div class="bp-info-wrap"><div class="bp-info"></div></div>');
                $(main).addClass('bp-main').css({
                    'margin-left': 'auto',
                    'margin-right': 'auto'
                }).append(view).append(bbar);
                $(wrap).addClass('bp-wrap').append(main);
                $(mask).addClass('bp-mask');
                $(sbox).attr('id', 'bp').append(mask).append(wrap).appendTo('body');
                $(window).resize(function(e) {
                    if ($.jquery.ux.ui.BPHelper.isBoxVisible()) {
                        $.jquery.ux.ui.BPHelper.onWindowResize()
                    }
                });
                $(mask).click(function(e) {
                    $.jquery.ux.ui.BPHelper.hideBox()
                });
                $(wrap).click(function(e) {
                    $.jquery.ux.ui.BPHelper.hideBox()
                });
                $(main).click(function(e) {
                    e.preventDefault();
                    return false
                });
                $('.bp-hide-link', bbar).click(function(e) {
                    e.preventDefault();
                    $.jquery.ux.ui.BPHelper.hideBox()
                })
            },
            showBox: function() {
                $.jquery.ux.ui.BPHelper.onWindowResize();
                $('#bp .bp-mask').show();
                $('#bp .bp-wrap').show()
            },
            hideBox: function() {
                $.jquery.ux.ui.BPHelper.resetBox();
                $('#bp .bp-wrap').fadeOut('fast',
                function() {
                    $('#bp .bp-mask').hide()
                })
            },
            resetBox: function() {
                $('#bp .bp-bbar').stop().hide();
                $('#bp .bp-info-wrap').stop().hide().css({
                    'marginTop': 0
                });
                $('#bp .bp-info-link > a').removeClass('active');
                $('#bp .bp-view > img').remove()
            },
            onWindowResize: function() {
                var ds = $.jquery.ux.ui.BPHelper.getDimensions();
                var ps = $.jquery.ux.ui.BPHelper.getPageScroll();
                $('#bp .bp-mask').width(ds.pageWidth).height(ds.pageHeight);
                $('#bp .bp-wrap').css({
                    'left': 0,
                    'top': ps.y + (ds.windowHeight * 0.08)
                })
            },
            getDimensions: function() {
                var dims = {};
                var dbw, dbh;
                if (window.innerHeight && window.scrollMaxY) {
                    dbw = window.innerWidth + window.scrollMaxX;
                    dbh = window.innerHeight + window.scrollMaxY
                } else if (document.body.scrollHeight > document.body.offsetHeight) {
                    dbw = document.body.scrollWidth;
                    dbh = document.body.scrollHeight
                } else {
                    dbw = document.body.offsetWidth;
                    dbh = document.body.offsetHeight
                }
                if (self.innerHeight) {
                    if (document.documentElement.clientWidth) {
                        dims.windowWidth = document.documentElement.clientWidth
                    } else {
                        dims.windowWidth = self.innerWidth
                    }
                    dims.windowHeight = self.innerHeight
                } else if (document.documentElement && document.documentElement.clientHeight) {
                    dims.windowWidth = document.documentElement.clientWidth;
                    dims.windowHeight = document.documentElement.clientHeight
                } else if (document.body) {
                    dims.windowWidth = document.body.clientWidth;
                    dims.windowHeight = document.body.clientHeight
                }
                dims.pageHeight = Math.max(dbh, dims.windowHeight);
                dims.pageWidth = Math.max(dbw, dims.windowWidth);
                return dims
            },
            getPageScroll: function() {
                var scroll = {};
                if (self.pageYOffset) {
                    scroll.y = self.pageYOffset;
                    scroll.x = self.pageXOffset
                } else if (document.documentElement && document.documentElement.scrollTop) {
                    scroll.y = document.documentElement.scrollTop;
                    scroll.x = document.documentElement.scrollLeft
                } else if (document.body) {
                    scroll.y = document.body.scrollTop;
                    scroll.x = document.body.scrollLeft
                }
                return scroll
            }
        }
    } ();
    $.jquery.ux.ui.BigPicture = function(el, conf) {
        this.images = [];
        this.index = 0;
        this.gallery = '';
        this.offset = false;
        conf = $.extend({
            'cls': '',
            'prevLabel': 'Prev',
            'nextLabel': 'Next',
            'infoLabel': 'Image info',
            'hideLabel': 'Close',
            'boxEaseFn': '',
            'boxEaseSpeed': 750,
            'enableInfo': false,
            'infoPosition': 'bottom',
            'infoEaseFn': '',
            'infoEaseSpeed': 500
        },
        conf);
        if (!$(el).attr('id')) {
            $(el).attr('id', 'bigPicture-' + $.jquery.ux.ui.BPHelper.AUTO_ID++)
        }
        this.gallery = $(el).attr('rel');
        if (this.gallery && !$.jquery.ux.ui.BPHelper.galleries[this.gallery]) {
            $.jquery.ux.ui.BPHelper.galleries[this.gallery] = $("a[rel='" + this.gallery + "']").get()
        }
        this.launchBox = function() {
            if (this.images.length == 0) {
                if (this.gallery) {
                    this.images = $.jquery.ux.ui.BPHelper.galleries[this.gallery]
                } else {
                    this.images.push(el)
                }
            }
            this.index = 0;
            for (var i = 0; i < this.images.length; i++) {
                if (this.images[i].id == el.id) {
                    this.index = i;
                    break
                }
            }
            this.show()
        };
        this.show = function() {
            $.jquery.ux.ui.BPHelper.renderBox();
            $('#bp').removeClass().addClass(conf.cls);
            $('#bp .bp-prev-link > a > span').html(conf.prevLabel);
            $('#bp .bp-next-link > a > span').html(conf.nextLabel);
            $('#bp .bp-info-link > a > span').html(conf.infoLabel);
            $('#bp .bp-hide-link > a > span').html(conf.hideLabel);
            var sbox = this;
            $('#bp .bp-view').unbind('mouseenter.bp').unbind('mouseleave.bp').bind('mouseenter.bp',
            function() {
                sbox.toggleNavigation(true)
            }).bind('mouseleave.bp',
            function() {
                sbox.toggleNavigation(false)
            });
            $('#bp .bp-prev-link > a').unbind('click.bp').bind('click.bp',
            function(e) {
                e.preventDefault();
                sbox.back()
            });
            $('#bp .bp-next-link > a').unbind('click.bp').bind('click.bp',
            function(e) {
                e.preventDefault();
                sbox.next()
            });
            if (conf.enableInfo) {
                $('#bp .bp-info-link').show();
                $('#bp .bp-info-link > a').unbind('click.bp').bind('click.bp',
                function(e) {
                    e.preventDefault();
                    sbox.toggleInfo(this)
                })
            } else {
                $('#bp .bp-info-link').hide()
            }
            $('#bp .bp-main').width(64).height(64);
            if (!$.jquery.ux.ui.BPHelper.isBoxVisible()) {
                $.jquery.ux.ui.BPHelper.showBox()
            }
            this.load()
        };
        this.hide = function() {
            $.jquery.ux.ui.BPHelper.hideBox()
        };
        this.reset = function() {
            $.jquery.ux.ui.BPHelper.resetBox()
        };
        this.load = function() {
            this.reset();
            $('#bp .bp-main').addClass('loading');
            this.calculateOffset();
            var box = this;
            var img = new Image();
            $(img).load(function() {
                $('#bp .bp-main').animate({
                    'width': img.width + box.offset.x,
                    'height': img.height + box.offset.y
                },
                conf.boxEaseSpeed, conf.boxEaseFn,
                function() {
                    box.onLoad(img)
                })
            }).error(function() {
                box.hide();
                alert('There was an error loading the image')
            }).attr('src', $(this.images[this.index]).attr('href'))
        };
        this.onLoad = function(img) {
            if (conf.enableInfo) {
                var title = $(this.images[this.index]).attr('title');
                var divId = $(this.images[this.index]).attr('name');
                var count = this.images.length;
                var $wrap = $('#bp .bp-info-wrap');
                var txt = '';
                if (count > 1) {
                    txt += '<div class="bp-count">Image ' + (this.index + 1) + ' of ' + count + '</div>'
                }
                txt += title ? '<h2>' + title + '</h2>' : '';
                $('#bp .bp-info').html(txt);
				if(divId){
					$('#bp .bp-info').append($('#' + divId).contents().clone(true))
				}
                $('#bp .bp-info a').click(function(e) {
                    var href = $(this).attr('href');
                    if (href && href.charAt(0) != '#') {
                        document.location = href
                    }
                });
                var y = conf.infoPosition == 'top' ? (-1 * $wrap.outerHeight()) : img.height;
                $wrap.css({
                    'top': y
                });
            }
            $('#bp .bp-main').removeClass('loading');
            $('#bp .bp-info-wrap').before(img);
            $('#bp .bp-view').width(img.width).height(img.height).fadeIn('normal');
            $('#bp .bp-nav > a').width(Math.floor(img.width / 2)).height(img.height);
            var bh = img.height + this.offset.y + $('#bp .bp-bbar').outerHeight();
            $('#bp .bp-bbar').show();
            $('#bp .bp-nav').show().fadeTo("fast", 0.25);
            $('#bp .bp-main').animate({
                'height': bh
            },
            350);
            $(img).click().focus();
			$('#bp .bp-info-link > a').click();
        };
        this.toggleInfo = function(link) {
            if (!conf.enableInfo) {
                return
            }
            var h = $('#bp .bp-info-wrap').outerHeight();
            var b = conf.infoPosition == 'top' ? 0 : $('#bp .bp-view > img').height();
            var hide = false;
            if ($(link).hasClass('active')) {
                $(link).removeClass('active');
                h = conf.infoPosition == 'top' ? h : 0;
                hide = true
            } else {
                $(link).addClass('active');
                h = conf.infoPosition == 'top' ? 0 : h
            }
            $('#bp .bp-info-wrap').show().animate({
                'top': b - h
            },
            conf.infoEaseSpeed, conf.infoEaseFn,
            function() {
                if (hide) {
                    $('#bp .bp-info-wrap').hide()
                }
            })
        };
        this.toggleNavigation = function(show) {
            if (show == true && this.images.length > 1) {
                $('#bp .bp-nav').fadeTo("fast", 1.0)
            } else {
                $('#bp .bp-nav').fadeTo("fast", 0.25)
            }
            return false
        };
        this.back = function() {
            this.index--;
            if (this.index < 0) {
                this.index = this.images.length - 1
            }
            this.load()
        };
        this.next = function() {
            this.index++;
            if (this.index == this.images.length) {
                this.index = 0
            }
            this.load()
        };
        this.calculateOffset = function() {
            if (this.offset) {
                return
            }
            var $view = $('#bp .bp-view');
            this.offset = {
                x: 0,
                y: 0
            };
            this.offset.x = $view.outerWidth() - $view.width();
            this.offset.y = $view.outerHeight() - $view.height()
        }
    };
    $.fn.bigPicture = function(p) {
        return this.each(function() {
            if (this.bigPicture instanceof $.jquery.ux.ui.BigPicture) {
                return this
            }
            var box = new $.jquery.ux.ui.BigPicture(this, p);
            $(this).click(function(e) {
                e.preventDefault();
                box.launchBox()
            });
            this.bigPicture = box;
            return this
        })
    }
})(jQuery);
// End ~/Scripts/jquery.bigPicture-min.js

// Begin ~/Scripts/jquery.form.js

/*!
 * jQuery Form Plugin
 * version: 2.43 (12-MAR-2010)
 * @requires jQuery v1.3.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
	Usage Note:
	-----------
	Do not use both ajaxSubmit and ajaxForm on the same form.  These
	functions are intended to be exclusive.  Use ajaxSubmit if you want
	to bind your own submit handler to the form.  For example,

	$(document).ready(function() {
		$('#myForm').bind('submit', function() {
			$(this).ajaxSubmit({
				target: '#output'
			});
			return false; // <-- important!
		});
	});

	Use ajaxForm when you want the plugin to manage all the event binding
	for you.  For example,

	$(document).ready(function() {
		$('#myForm').ajaxForm({
			target: '#output'
		});
	});

	When using ajaxForm, the ajaxSubmit function will be invoked for you
	at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
	// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
	if (!this.length) {
		log('ajaxSubmit: skipping submit process - no element selected');
		return this;
	}

	if (typeof options == 'function')
		options = { success: options };

	var url = $.trim(this.attr('action'));
	if (url) {
		// clean url (don't include hash vaue)
		url = (url.match(/^([^#]+)/)||[])[1];
   	}
   	url = url || window.location.href || '';

	options = $.extend({
		url:  url,
		type: this.attr('method') || 'GET',
		iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank'
	}, options || {});

	// hook for manipulating the form data before it is extracted;
	// convenient for use with rich editors like tinyMCE or FCKEditor
	var veto = {};
	this.trigger('form-pre-serialize', [this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
		return this;
	}

	// provide opportunity to alter form data before it is serialized
	if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSerialize callback');
		return this;
	}

	var a = this.formToArray(options.semantic);
	if (options.data) {
		options.extraData = options.data;
		for (var n in options.data) {
		  if(options.data[n] instanceof Array) {
			for (var k in options.data[n])
			  a.push( { name: n, value: options.data[n][k] } );
		  }
		  else
			 a.push( { name: n, value: options.data[n] } );
		}
	}

	// give pre-submit callback an opportunity to abort the submit
	if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
		log('ajaxSubmit: submit aborted via beforeSubmit callback');
		return this;
	}

	// fire vetoable 'validate' event
	this.trigger('form-submit-validate', [a, this, options, veto]);
	if (veto.veto) {
		log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
		return this;
	}

	var q = $.param(a);

	if (options.type.toUpperCase() == 'GET') {
		options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
		options.data = null;  // data is null for 'get'
	}
	else
		options.data = q; // data is the query string for 'post'

	var $form = this, callbacks = [];
	if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
	if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

	// perform a load on the target only if dataType is not provided
	if (!options.dataType && options.target) {
		var oldSuccess = options.success || function(){};
		callbacks.push(function(data) {
			var fn = options.replaceTarget ? 'replaceWith' : 'html';
			$(options.target)[fn](data).each(oldSuccess, arguments);
		});
	}
	else if (options.success)
		callbacks.push(options.success);

	options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg
		for (var i=0, max=callbacks.length; i < max; i++)
			callbacks[i].apply(options, [data, status, xhr || $form, $form]);
	};

	// are there files to upload?
	var files = $('input:file', this).fieldValue();
	var found = false;
	for (var j=0; j < files.length; j++)
		if (files[j])
			found = true;

	var multipart = false;
//	var mp = 'multipart/form-data';
//	multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp);

	// options.iframe allows user to force iframe mode
	// 06-NOV-09: now defaulting to iframe mode if file input is detected
   if ((files.length && options.iframe !== false) || options.iframe || found || multipart) {
	   // hack to fix Safari hang (thanks to Tim Molendijk for this)
	   // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
	   if (options.closeKeepAlive)
		   $.get(options.closeKeepAlive, fileUpload);
	   else
		   fileUpload();
	   }
   else
	   $.ajax(options);

	// fire 'notify' event
	this.trigger('form-submit-notify', [this, options]);
	return this;


	// private function for handling file uploads (hat tip to YAHOO!)
	function fileUpload() {
		var form = $form[0];

		if ($(':input[name=submit]', form).length) {
			alert('Error: Form elements must not be named "submit".');
			return;
		}

		var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

		var id = 'jqFormIO' + (new Date().getTime());
		var $io = $('<iframe id="' + id + '" name="' + id + '" src="'+ opts.iframeSrc +'" onload="(jQuery(this).data(\'form-plugin-onload\'))()" />');
		var io = $io[0];

		$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

		var xhr = { // mock object
			aborted: 0,
			responseText: null,
			responseXML: null,
			status: 0,
			statusText: 'n/a',
			getAllResponseHeaders: function() {},
			getResponseHeader: function() {},
			setRequestHeader: function() {},
			abort: function() {
				this.aborted = 1;
				$io.attr('src', opts.iframeSrc); // abort op in progress
			}
		};

		var g = opts.global;
		// trigger ajax global events so that activity/block indicators work like normal
		if (g && ! $.active++) $.event.trigger("ajaxStart");
		if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
		}
		if (xhr.aborted)
			return;

		var cbInvoked = false;
		var timedOut = 0;

		// add submitting element to data if we know it
		var sub = form.clk;
		if (sub) {
			var n = sub.name;
			if (n && !sub.disabled) {
				opts.extraData = opts.extraData || {};
				opts.extraData[n] = sub.value;
				if (sub.type == "image") {
					opts.extraData[n+'.x'] = form.clk_x;
					opts.extraData[n+'.y'] = form.clk_y;
				}
			}
		}

		// take a breath so that pending repaints get some cpu time before the upload starts
		function doSubmit() {
			// make sure form attrs are set
			var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

			// ie borks in some cases when setting encoding
			if (! opts.skipEncodingOverride) {
				$form.attr({
					encoding: 'multipart/form-data',
					enctype:  'multipart/form-data'
				});
			}

			// support timout
			if (opts.timeout)
				setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

			// add "extra" data to form if provided in options
			var extraInputs = [];
			try {
				if (opts.extraData)
					for (var n in opts.extraData)
						extraInputs.push(
							$('<input type="hidden" name="'+n+'" value="'+opts.extraData[n]+'" />')
								.appendTo(form)[0]);

				// add iframe to doc and submit the form
				$io.appendTo('body');
				$io.data('form-plugin-onload', cb);
				form.submit();
			}
			finally {
				// reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
				t ? form.setAttribute('target', t) : $form.removeAttr('target');
				$(extraInputs).remove();
			}
		};

		if (opts.forceSync)
			doSubmit();
		else
			setTimeout(doSubmit, 10); // this lets dom updates render
	
		var domCheckCount = 100;

		function cb() {
			if (cbInvoked) 
				return;

			var ok = true;
			try {
				if (timedOut) throw 'timeout';
				// extract the server response from the iframe
				var data, doc;

				doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
				
				var isXml = opts.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc);
				log('isXml='+isXml);
				if (!isXml && (doc.body == null || doc.body.innerHTML == '')) {
				 	if (--domCheckCount) {
						// in some browsers (Opera) the iframe DOM is not always traversable when
						// the onload callback fires, so we loop a bit to accommodate
				 		log('requeing onLoad callback, DOM not available');
						setTimeout(cb, 250);
						return;
					}
					log('Could not access iframe DOM after 100 tries.');
					return;
				}

				log('response detected');
				cbInvoked = true;
				xhr.responseText = doc.body ? doc.body.innerHTML : null;
				xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
				xhr.getResponseHeader = function(header){
					var headers = {'content-type': opts.dataType};
					return headers[header];
				};

				if (opts.dataType == 'json' || opts.dataType == 'script') {
					// see if user embedded response in textarea
					var ta = doc.getElementsByTagName('textarea')[0];
					if (ta)
						xhr.responseText = ta.value;
					else {
						// account for browsers injecting pre around json response
						var pre = doc.getElementsByTagName('pre')[0];
						if (pre)
							xhr.responseText = pre.innerHTML;
					}			  
				}
				else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
					xhr.responseXML = toXml(xhr.responseText);
				}
				data = $.httpData(xhr, opts.dataType);
			}
			catch(e){
				log('error caught:',e);
				ok = false;
				xhr.error = e;
				$.handleError(opts, xhr, 'error', e);
			}

			// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
			if (ok) {
				opts.success(data, 'success');
				if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
			}
			if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
			if (g && ! --$.active) $.event.trigger("ajaxStop");
			if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

			// clean up
			setTimeout(function() {
				$io.removeData('form-plugin-onload');
				$io.remove();
				xhr.responseXML = null;
			}, 100);
		};

		function toXml(s, doc) {
			if (window.ActiveXObject) {
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = 'false';
				doc.loadXML(s);
			}
			else
				doc = (new DOMParser()).parseFromString(s, 'text/xml');
			return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
		};
	};
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *	is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *	used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
	return this.ajaxFormUnbind().bind('submit.form-plugin', function(e) {
		e.preventDefault();
		$(this).ajaxSubmit(options);
	}).bind('click.form-plugin', function(e) {
		var target = e.target;
		var $el = $(target);
		if (!($el.is(":submit,input:image"))) {
			// is this a child element of the submit el?  (ex: a span within a button)
			var t = $el.closest(':submit');
			if (t.length == 0)
				return;
			target = t[0];
		}
		var form = this;
		form.clk = target;
		if (target.type == 'image') {
			if (e.offsetX != undefined) {
				form.clk_x = e.offsetX;
				form.clk_y = e.offsetY;
			} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
				var offset = $el.offset();
				form.clk_x = e.pageX - offset.left;
				form.clk_y = e.pageY - offset.top;
			} else {
				form.clk_x = e.pageX - target.offsetLeft;
				form.clk_y = e.pageY - target.offsetTop;
			}
		}
		// clear form vars
		setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100);
	});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
	return this.unbind('submit.form-plugin click.form-plugin');
};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
	var a = [];
	if (this.length == 0) return a;

	var form = this[0];
	var els = semantic ? form.getElementsByTagName('*') : form.elements;
	if (!els) return a;
	for(var i=0, max=els.length; i < max; i++) {
		var el = els[i];
		var n = el.name;
		if (!n) continue;

		if (semantic && form.clk && el.type == "image") {
			// handle image inputs on the fly when semantic == true
			if(!el.disabled && form.clk == el) {
				a.push({name: n, value: $(el).val()});
				a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
			}
			continue;
		}

		var v = $.fieldValue(el, true);
		if (v && v.constructor == Array) {
			for(var j=0, jmax=v.length; j < jmax; j++)
				a.push({name: n, value: v[j]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: n, value: v});
	}

	if (!semantic && form.clk) {
		// input type=='image' are not found in elements array! handle it here
		var $input = $(form.clk), input = $input[0], n = input.name;
		if (n && !input.disabled && input.type == 'image') {
			a.push({name: n, value: $input.val()});
			a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
		}
	}
	return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
	//hand off to jQuery.param for proper encoding
	return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
	var a = [];
	this.each(function() {
		var n = this.name;
		if (!n) return;
		var v = $.fieldValue(this, successful);
		if (v && v.constructor == Array) {
			for (var i=0,max=v.length; i < max; i++)
				a.push({name: n, value: v[i]});
		}
		else if (v !== null && typeof v != 'undefined')
			a.push({name: this.name, value: v});
	});
	//hand off to jQuery.param for proper encoding
	return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *	  <input name="A" type="text" />
 *	  <input name="A" type="text" />
 *	  <input name="B" type="checkbox" value="B1" />
 *	  <input name="B" type="checkbox" value="B2"/>
 *	  <input name="C" type="radio" value="C1" />
 *	  <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *	   array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
	for (var val=[], i=0, max=this.length; i < max; i++) {
		var el = this[i];
		var v = $.fieldValue(el, successful);
		if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
			continue;
		v.constructor == Array ? $.merge(val, v) : val.push(v);
	}
	return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
	var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
	if (typeof successful == 'undefined') successful = true;

	if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
		(t == 'checkbox' || t == 'radio') && !el.checked ||
		(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
		tag == 'select' && el.selectedIndex == -1))
			return null;

	if (tag == 'select') {
		var index = el.selectedIndex;
		if (index < 0) return null;
		var a = [], ops = el.options;
		var one = (t == 'select-one');
		var max = (one ? index+1 : ops.length);
		for(var i=(one ? index : 0); i < max; i++) {
			var op = ops[i];
			if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
					v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
				if (one) return v;
				a.push(v);
			}
		}
		return a;
	}
	return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
	return this.each(function() {
		$('input,select,textarea', this).clearFields();
	});
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
	return this.each(function() {
		var t = this.type, tag = this.tagName.toLowerCase();
		if (t == 'text' || t == 'password' || tag == 'textarea')
			this.value = '';
		else if (t == 'checkbox' || t == 'radio')
			this.checked = false;
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
	return this.each(function() {
		// guard against an input with the name of 'reset'
		// note that IE reports the reset function as an 'object'
		if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
			this.reset();
	});
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
	if (b == undefined) b = true;
	return this.each(function() {
		this.disabled = !b;
	});
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
	if (select == undefined) select = true;
	return this.each(function() {
		var t = this.type;
		if (t == 'checkbox' || t == 'radio')
			this.checked = select;
		else if (this.tagName.toLowerCase() == 'option') {
			var $sel = $(this).parent('select');
			if (select && $sel[0] && $sel[0].type == 'select-one') {
				// deselect all other options
				$sel.find('option').selected(false);
			}
			this.selected = select;
		}
	});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
	if ($.fn.ajaxSubmit.debug) {
		var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,'');
		if (window.console && window.console.log)
			window.console.log(msg);
		else if (window.opera && window.opera.postError)
			window.opera.postError(msg);
	}
};

})(jQuery);

// End ~/Scripts/jquery.form.js


