/* Start of http://www.mentorsphere.com/scripts/json.js */
/*
Copyright (c) 2005 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*
    The global object JSON contains two methods.

    JSON.stringify(value) takes a JavaScript value and produces a JSON text.
    The value must not be cyclical.

    JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
    return false if there is an error.
*/
var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'boolean': function (x) {
                return String(x);
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            },
            object: function (x) {
                if (x) {
                    var a = [], b, f, i, l, v;
                    if (x instanceof Array) {
                        a[0] = '[';
                        l = x.length;
                        for (i = 0; i < l; i += 1) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a[a.length] = v;
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = ']';
                    } else if (x instanceof Date) {
                        function p(n) { return n < 10 ? '0' + n : n; };
                        var tz = x.getTimezoneOffset();
                        if (tz != 0) {
                            var tzh = Math.floor(Math.abs(tz) / 60);
                            var tzm = Math.abs(tz) % 60;
                            tz = (tz < 0 ? '+' : '-') + p(tzh) + ':' + p(tzm);
                        }
                        else {
                            tz = 'Z';
                        }
                        return '"' + 
                                x.getFullYear() + '-' +
                                p(x.getMonth() + 1) + '-' +
                                p(x.getDate()) + 'T' +
                                p(x.getHours()) + ':' +
                                p(x.getMinutes()) + ':' +
                                p(x.getSeconds()) + tz + '"';
                    } else if (x instanceof Object) {
                        a[0] = '{';
                        for (i in x) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a.push(s.string(i), ':', v);
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = '}';
                    } else {
                        return;
                    }
                    return a.join('');
                }
                return 'null';
            }
        };
    return {
        copyright: '(c)2005 JSON.org',
        license: 'http://www.crockford.com/JSON/license.html',
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v == 'string') {
                    return v;
                }
            }
            return null;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        eval: function (text) {
            try {
                if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(text)) {
                    return eval('(' + text + ')');
                }
            } catch (e) {
            }
            throw new SyntaxError("eval");
        },

        parse: function (text) {
            var at = 0;
            var ch = ' ';

            function error(m) {
                throw {
                    name: 'JSONError',
                    message: m,
                    at: at - 1,
                    text: text
                };
            }

            function next() {
                ch = text.charAt(at);
                at += 1;
                return ch;
            }

            function white() {
                while (ch) {
                    if (ch <= ' ') {
                        next();
                    } else if (ch == '/') {
                        switch (next()) {
                            case '/':
                                while (next() && ch != '\n' && ch != '\r') {}
                                break;
                            case '*':
                                next();
                                for (;;) {
                                    if (ch) {
                                        if (ch == '*') {
                                            if (next() == '/') {
                                                next();
                                                break;
                                            }
                                        } else {
                                            next();
                                        }
                                    } else {
                                        error("Unterminated comment");
                                    }
                                }
                                break;
                            default:
                                error("Syntax error");
                        }
                    } else {
                        break;
                    }
                }
            }

            function string() {
                var i, s = '', t, u;

                if (ch == '"') {
    outer:          while (next()) {
                        if (ch == '"') {
                            next();
                            return s;
                        } else if (ch == '\\') {
                            switch (next()) {
                            case 'b':
                                s += '\b';
                                break;
                            case 'f':
                                s += '\f';
                                break;
                            case 'n':
                                s += '\n';
                                break;
                            case 'r':
                                s += '\r';
                                break;
                            case 't':
                                s += '\t';
                                break;
                            case 'u':
                                u = 0;
                                for (i = 0; i < 4; i += 1) {
                                    t = parseInt(next(), 16);
                                    if (!isFinite(t)) {
                                        break outer;
                                    }
                                    u = u * 16 + t;
                                }
                                s += String.fromCharCode(u);
                                break;
                            default:
                                s += ch;
                            }
                        } else {
                            s += ch;
                        }
                    }
                }
                error("Bad string");
            }

            function array() {
                var a = [];

                if (ch == '[') {
                    next();
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    }
                    while (ch) {
                        a.push(value());
                        white();
                        if (ch == ']') {
                            next();
                            return a;
                        } else if (ch != ',') {
                            break;
                        }
                        next();
                        white();
                    }
                }
                error("Bad array");
            }

            function object() {
                var k, o = {};

                if (ch == '{') {
                    next();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    }
                    while (ch) {
                        k = string();
                        white();
                        if (ch != ':') {
                            break;
                        }
                        next();
                        o[k] = value();
                        white();
                        if (ch == '}') {
                            next();
                            return o;
                        } else if (ch != ',') {
                            break;
                        }
                        next();
                        white();
                    }
                }
                error("Bad object");
            }

            function number() {
                var n = '', v;
                if (ch == '-') {
                    n = '-';
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
                if (ch == '.') {
                    n += '.';
                    while (next() && ch >= '0' && ch <= '9') {
                        n += ch;
                    }
                }
                if (ch == 'e' || ch == 'E') {
                    n += 'e';
                    next();
                    if (ch == '-' || ch == '+') {
                        n += ch;
                        next();
                    }
                    while (ch >= '0' && ch <= '9') {
                        n += ch;
                        next();
                    }
                }
                v = +n;
                if (!isFinite(v)) {
                    ////error("Bad number");
                } else {
                    return v;
                }
            }

            function word() {
                switch (ch) {
                    case 't':
                        if (next() == 'r' && next() == 'u' && next() == 'e') {
                            next();
                            return true;
                        }
                        break;
                    case 'f':
                        if (next() == 'a' && next() == 'l' && next() == 's' &&
                                next() == 'e') {
                            next();
                            return false;
                        }
                        break;
                    case 'n':
                        if (next() == 'u' && next() == 'l' && next() == 'l') {
                            next();
                            return null;
                        }
                        break;
                }
                error("Syntax error");
            }

            function value() {
                white();
                switch (ch) {
                    case '{':
                        return object();
                    case '[':
                        return array();
                    case '"':
                        return string();
                    case '-':
                        return number();
                    default:
                        return ch >= '0' && ch <= '9' ? number() : word();
                }
            }

            return value();
        }
    };
}();/* End of http://www.mentorsphere.com/scripts/json.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.bgiframe.min.js */
/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2010-05-21 08:51:40 -0400 (Fri, 21 May 2010) $
 * $Rev: 7 $
 *
 * Version 2.1.1
 */
(function($){$.fn.bgIframe=$.fn.bgiframe=function(s){if($.browser.msie&&/6.0/.test(navigator.userAgent)){s=$.extend({top:'auto',left:'auto',width:'auto',height:'auto',opacity:true,src:'javascript:false;'},s||{});var prop=function(n){return n&&n.constructor==Number?n+'px':n;},html='<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+'style="display:block;position:absolute;z-index:-1;'+(s.opacity!==false?'filter:Alpha(Opacity=\'0\');':'')+'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+'"/>';return this.each(function(){if($('> iframe.bgiframe',this).length==0)this.insertBefore(document.createElement(html),this.firstChild);});}return this;};})(jQuery);/* End of http://www.mentorsphere.com/scripts/jquery.bgiframe.min.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.corner.js */
/*!
 * jQuery corner plugin: simple corner rounding
 * Examples and documentation at: http://jquery.malsup.com/corner/
 * version 1.98 (02-JUN-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

/**
 *  corner() takes a single string argument:  $('#myDiv').corner("effect corners width")
 *
 *  effect:  name of the effect to apply, such as round, bevel, notch, bite, etc (default is round). 
 *  corners: one or more of: top, bottom, tr, tl, br, or bl. 
 *           by default, all four corners are adorned. 
 *  width:   width of the effect; in the case of rounded corners this is the radius. 
 *           specify this value using the px suffix such as 10px (and yes, it must be pixels).
 *
 * @name corner
 * @type jQuery
 * @param String options Options which control the corner style
 * @cat Plugins/Corner
 * @return jQuery
 * @author Dave Methvin (http://methvin.com/jquery/jq-corner.html)
 * @author Mike Alsup   (http://jquery.malsup.com/corner/)
 */
;(function($) { 

var expr = (function() {
	if (! $.browser.msie) return false;
    var div = document.createElement('div');
    try { div.style.setExpression('width','0+0'); }
    catch(e) { return false; }
    return true;
})();
    
function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};
function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
    for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {    
        var v = $.css(node,'backgroundColor');
        if (v != undefined && v != null){
        if (v == 'rgba(0, 0, 0, 0)')
            continue; // webkit
        if (v.indexOf('rgb') >= 0) { 
            var rgb = v.match(/\d+/g); 
            return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
        }
        if ( v && v != 'transparent' )
            return v;
       }     
    }
    return '#ffffff';
};

function getWidth(fx, i, width) {
    switch(fx) {
    case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
    case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
    case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
    case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
    case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
    case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
    case 'curl':   return Math.round(width*(Math.atan(i)));
    case 'tear':   return Math.round(width*(Math.cos(i)));
    case 'wicked': return Math.round(width*(Math.tan(i)));
    case 'long':   return Math.round(width*(Math.sqrt(i)));
    case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
    case 'dog':    return (i&1) ? (i+1) : width;
    case 'dog2':   return (i&2) ? (i+1) : width;
    case 'dog3':   return (i&3) ? (i+1) : width;
    case 'fray':   return (i%2)*width;
    case 'notch':  return width; 
    case 'bevel':  return i+1;
    }
};

$.fn.corner = function(o) {
    // in 1.3+ we can fix mistakes with the ready state
	if (this.length == 0) {
        if (!$.isReady && this.selector) {
            var s = this.selector, c = this.context;
            $(function() {
                $(s,c).corner(o);
            });
        }
        return this;
	}

    o = (o||"").toLowerCase();
    var keep = /keep/.test(o);                       // keep borders?
    var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
    var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
    var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
    var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
    var fx = ((o.match(re)||['round'])[0]);
    var edges = { T:0, B:1 };
    var opts = {
        TL:  /top|tl/.test(o),       TR:  /top|tr/.test(o),
        BL:  /bottom|bl/.test(o),    BR:  /bottom|br/.test(o)
    };
    if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
        opts = { TL:1, TR:1, BL:1, BR:1 };
    var strip = document.createElement('div');
    strip.style.overflow = 'hidden';
    strip.style.height = '1px';
    strip.style.backgroundColor = sc || 'transparent';
    strip.style.borderStyle = 'solid';
    return this.each(function(index){
        var pad = {
            T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
            B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
        };

        if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = $.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            // only add stips if needed
            if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
                strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
                var d = document.createElement('div');
                $(d).addClass('jquery-corner');
                var ds = d.style;

                bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

                if (bot && cssHeight != 'auto') {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.bottom = ds.left = ds.padding = ds.margin = '0';
                    if (expr)
                        ds.setExpression('width', 'this.parentNode.offsetWidth');
                    else
                        ds.width = '100%';
                }
                else if (!bot && $.browser.msie) {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
                    if (expr) {
                        var bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
                        ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
                    }
                    else
                        ds.width = '100%';
                }
                else {
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
                }

                for (var i=0; i < width; i++) {
                    var w = Math.max(0,getWidth(fx,i, width));
                    var e = strip.cloneNode(false);
                    e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                    bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
                }
            }
        }
    });
};

$.fn.uncorner = function() { 
	$('div.jquery-corner', this).remove();
	return this;
};
    
})(jQuery);/* End of http://www.mentorsphere.com/scripts/jquery.corner.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.callout.js */
;(function($) { 

$.fn.callout = function(options){	
	var opts = $.extend({}, $.fn.callout.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		
		var calloutElement = $this.data("calloutElement") ;
		if (calloutElement == null || calloutElement.size() == 0 || calloutElement.length == 0){
			var co = $("<div/>").css("display", "none") ;		
			$this.data("calloutElement", co) ;
			
			var position = $this.offset() ;			
		
		
			var dummy = $("<div/>")
				.addClass(o.displayClass)
				.css({
					"position"	: "absolute",
					"visibility": "hidden",
					"width"		: o.width,
					top			: -9999,
					left		: -9999
					
				})
				.append(o.content)
				.append(o.text)				
				.appendTo("body")
				.show() ;
			
			var borderColor = dummy.css("border-top-color") ;
			var backColor = dummy.css("background-color") ;
			var borderWidth = parseInt(dummy.css("border-top-width")) ;
			var padding = parseInt(dummy.css("padding-top")) ;
			var color = dummy.css("color") ;
			var coHeight = dummy.height() ;
			var coWidth = dummy.width() ;
			
			dummy.remove() ;
			
			var top = position.top  ;
			var left = position.left ;		
			
			switch(o.orient){
				case "top":
					top += $this.height() + o.pointerLength ;
					break ;
				case "bottom": 
					top -= (coHeight + (o.pointerLength + 20)); //$this.height() + o.pointerLength ;
					break ;
				case "left":
					left += $this.width() + o.pointerLength ;
					break ;
				case "right":
					left -= (coWidth + o.pointerLength) ;
					break ;			
			}
			
			
			co	.addClass(o.displayClass)
				.css({
					"padding"			: borderWidth,
					"position"			: "absolute",
					"width"				: o.width,
					"top"				: top,
					"left"				: left,
					"display"			: "block",
					"background-color"	: borderColor,
					"z-index"			: o.zIndex				
				})
				.appendTo("body");
			
			var innerTube = $("<div/>")
				.append(o.content)
				.append(o.text)
				.appendTo(co)
				.css({
					"padding"			: padding,
					"background-color"	: backColor,
					"color"				: color,
					"display"			: "block",					
					"z-index"			: o.zIndex + 1
				});
			
				
			if (o.cornerRadius != null && o.cornerRadius.length > 0){
				co.corner(o.cornerRadius) ;
				innerTube.corner(o.cornerRadius) ;
			}		
			
			var pointer = $("<div/>")
				.appendTo(co) 
				.css({
					"width"				: 0,
					"height"			: 0,
					"position"			: "absolute",						
					"display"			: "block",
					"z-index"			: o.zIndex						
					}) ;
					
			var innerPointer = $("<div/>")
				.appendTo(innerTube) 
				.css({
					"width"				: 0,
					"height"			: 0,
					"position"			: "absolute",						
					"display"			: "block",
					"z-index"			: o.zIndex + 1						
					}) ;		
			
			switch(o.orient){
				case "top":
				    pointer.css({
				        "left"			: o.pointerOffset + "px" ,
				        //"border-left"	: (o.pointerWidth + 1) + "px solid transparent" ,   //commented out to create angled arrow effect
				        "border-right"	: (o.pointerWidth + 2) + "px solid transparent" ,
				        "border-bottom"	: (o.pointerLength + 1) + "px solid " + borderColor,
				        "top"			: (o.pointerLength) + "px",
                        "margin-top"	: (o.pointerLength * -2) + "px"
				    });
				    innerPointer.css({
					    "left"			: o.pointerOffset + "px" ,
					    //"border-left"	: o.pointerWidth + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-right"	: o.pointerWidth + "px solid transparent" ,
					    "border-bottom"	: o.pointerLength + "px solid " + backColor,	
					    "top"			: (o.pointerLength) + "px",					
					    "margin-top"	: (o.pointerLength * -2) + "px"
				    });
					break ;
				case "bottom":
				    pointer.css({
					    "left"			: o.pointerOffset + "px" ,
					    //"border-left"	: (o.pointerWidth + 1) + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-right"	: (o.pointerWidth + 2) + "px solid transparent" ,
					    "border-top"	: (o.pointerLength + 1) + "px solid " + borderColor,	
					    "bottom"		: "0px",					
					    "margin-bottom"	: (o.pointerLength * -1) + "px"
				    });
				    innerPointer.css({
					    "left"			: o.pointerOffset + "px" ,
					    //"border-left"	: o.pointerWidth + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-right"	: o.pointerWidth + "px solid transparent" ,
					    "border-top"	: o.pointerLength + "px solid " + backColor,	
					    "bottom"		: "0px",						
					    "margin-bottom"	: (o.pointerLength * -1) + "px"
				    });
					break ;
				case "left":
				    pointer.css({
					    "left"          : "0px",
					    "border-top"	: "1px solid " + borderColor, //(o.pointerWidth + 1) + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-bottom"	: (o.pointerWidth + 1) + "px solid transparent" ,
					    "border-right"	: (o.pointerLength + 1) + "px solid " + borderColor,	
					    "top"			: o.pointerOffset + "px" ,				
					    "margin-left"	: (o.pointerLength * -1) + "px"
				    });
					
				    innerPointer.css({
					    "left"	        : "0px",						
					    //"border-top"	: o.pointerWidth + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-bottom"	: o.pointerWidth + "px solid transparent" ,
					    "border-right"	: o.pointerLength + "px solid " + backColor,	
					    "top"			: o.pointerOffset + "px" ,
					    "margin-left"	: (o.pointerLength * -1) + "px"
				    });
					break ;
				case "right":
				    pointer.css({
					    "right"			: "0px",
					    //"border-top"	: (o.pointerWidth + 1) + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-bottom"	: (o.pointerWidth + 2) + "px solid transparent" ,
					    "border-left"	: (o.pointerLength + 1) + "px solid " + borderColor,	
					    "top"			: o.pointerOffset + "px" ,				
					    "margin-right"	: (o.pointerLength * -1) + "px"
				    });
				    innerPointer.css({
					    "right"			: "0px",
					    //"border-top"	: o.pointerWidth + "px solid transparent" ,   //commented out to create angled arrow effect
					    "border-bottom"	: o.pointerWidth + "px solid transparent" ,
					    "border-left"	: o.pointerLength + "px solid " + backColor,	
					    "top"			: o.pointerOffset + "px" ,				
					    "margin-right"	: (o.pointerLength * -1) + "px"
				    });
					break ;			
			}
			
			// add close button to callout
			var closeMe = $("<div/>").appendTo(innerTube).css({
				"display" : "block",
				"position" : "absolute",
				"top" : 3,
				"left" : parseInt( o.width ) - 11,
				"cursor" : "pointer",
				"z-index" : o.zIndex
			
			}).click(function() {
				$this.closeCallout(o);
			});
			var closeBox = $("<div/>").appendTo(closeMe).css({
				"display" : "block",
				"width" : "16px",
				"height" : "16px",
				"z-index" : o.zIndex
			
			}).addClass("closeWidgetButton");
			co.fadeIn("slow") ;
		}
	});
};

$.fn.closeCallout = function(options){	
	var opts = $.extend({}, $.fn.callout.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		
		var calloutElement = $this.data("calloutElement") ;
		if (calloutElement != null && calloutElement.size() > 0 ){
			calloutElement.remove() ;
			$this.data("calloutElement", null);
		}
		
	});
};

$.fn.callout.defaults = {	
	orient			: "top",
	pointerLength	: 10,
	pointerWidth	: 10,
	pointerOffset	: 10,
    text			: null,
    content			: null,
    cornerRadius	: "5px",   
    displayClass	: null,    
    width			: "100px",
    zIndex			: 350
};

})(jQuery);/* End of http://www.mentorsphere.com/scripts/jquery.callout.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.resizable.js */
/// <reference path="jquery.js"/>
/*
* resizable
* version: 1.0.0 (05/15/2009)
* @ jQuery v1.2.*
*
* Licensed under the GPL:
*   http://gplv3.fsf.org
*
* Copyright 2008, 2009 Jericho [ thisnamemeansnothing[at]gmail.com ] 
*/
//(function($) {
    $.extend($.fn, {
        getCss: function(key) {
            var v = parseInt(this.css(key));
            if (isNaN(v))
                return false;
            return v;
        }
    });
    $.fn.resizable = function(opts) {
        var ps = $.extend({
            handler: null,
            min: { width: 0, height: 0 },
            max: { width: $(document).width(), height: $(document).height() },
            onResize: function() { },
            onStop: function() { }
        }, opts);
        var resize = {
            resize: function(e) {
                var resizeData = e.data.resizeData;

                var w = Math.min(Math.max(e.pageX - resizeData.offLeft + resizeData.width, resizeData.min.width), ps.max.width);
                var h = Math.min(Math.max(e.pageY - resizeData.offTop + resizeData.height, resizeData.min.height), ps.max.height);
                resizeData.target.css({
                    width: w,
                    height: h
                });
                resizeData.onResize(e);
            },
            stop: function(e) {
                e.data.resizeData.onStop(e);

                document.body.onselectstart = function() { return true; }
                e.data.resizeData.target.css('-moz-user-select', '');

                $().unbind('mousemove', resize.resize)
                    .unbind('mouseup', resize.stop);
            }
        }
        return this.each(function() {
            var me = this;
            var handler = null;
            if (typeof ps.handler == 'undefined' || ps.handler == null)
                handler = $(me);
            else
                handler = (typeof ps.handler == 'string' ? $(ps.handler, this) : ps.handle);
            handler.bind('mousedown', { e: me }, function(s) {
                var target = $(s.data.e);
                var resizeData = {
                    width: target.width() || target.getCss('width'),
                    height: target.height() || target.getCss('height'),
                    offLeft: s.pageX,
                    offTop: s.pageY,
                    onResize: ps.onResize,
                    onStop: ps.onStop,
                    target: target,
                    min: ps.min,
                    max: ps.max
                }

                document.body.onselectstart = function() { return false; }
                target.css('-moz-user-select', 'none');

                $().bind('mousemove', { resizeData: resizeData }, resize.resize)
                    .bind('mouseup', { resizeData: resizeData }, resize.stop);
            });
        });
    }
//})(jQuery); /* End of http://www.mentorsphere.com/scripts/jquery.resizable.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.watermark-2.0.js */
/*
 * jquery.watermark.js
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 * 
 */
;(function($) {

	$.extend($,{
		clearwatermarks : function() {
			$("[wmwrap='true']").find("input,textarea").watermark({remove:true});
		},
		addwatermarks : function() {
			$("[watermark]").each(function(num,el) {
				$(el).watermark($(el).attr("watermark"));
			});
		},
		watermark : function(o) {
			o.el = $(o.el);
			if(o.remove) {
				if(o.el.parent().attr("wmwrap") == 'true') {
					o.el.parent().replaceWith(o.el);
				}
			} else {
				if(o.el.parent().attr("wmwrap") != 'true') {
					o.el = o.el.wrap("<span wmwrap='true' style='position:relative;'/>");
					var l = $("<label/>");
					
					if(o.html) { l.html(o.html); }
					if(o.cls) { l.addClass(o.cls); }
					if(o.css) { l.css(o.css); }
					
					l.css({
						position:"absolute",
						left:"3px",
						top : parseInt(o.el.css("paddingTop")),
						display:"inline",
						cursor:"text"
					});
					
					if(o.el.is("TEXTAREA")) {
						if($.browser.msie) {
							l.css("width",o.el.width());
						}
						if($.browser.mozilla || $.browser.safari) {
							l.css("top","");
						}
					}
					
					if(!o.cls && !o.css) {
						l.css("color","#ccc");
					}
					
					var focus = function() {
						l.hide();
					};
					
					var blur = function() {
						if(!o.el.val()) {
							l.show();
						} else {
							l.hide();
						}
					};
					
					var click = function() {
						o.el.focus();
					};
					
					if(o.inherit) {
						if(typeof o.inherit == "string") {
							l.css(o.inherit,o.el.css(o.inherit));
						} else {							
							for(var x=0;x<o.inherit.length;x++) {
								l.css(o.inherit[x],o.el.css(o.inherit[x]));
							}							
						}
					}
					
					o.el.focus(focus).blur(blur);
					l.click(click);
					o.el.before(l);
					if(o.el.val()) { l.hide(); }
				}
			}
			return o.el;
		}
	});
	
	$.fn.watermark = function(o) {
		return this.each(function() {
			if(typeof(o) == "string") {
				try {o = eval("(" + o + ")");} catch(ex) {o = {html:o};}
			}
			o.el = this;
			return $.watermark(o);
		});
	};
})(jQuery);

$().ready(function(){
	$.addwatermarks();
});
/* End of http://www.mentorsphere.com/scripts/jquery.watermark-2.0.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.bdc.ddmenu.js */
/*
 * BDC DrillDown Menu - http://www.barandis.com/dev/jquery/ddmenu
 *
 * A UI component implementing a compact, multi-level sliding menu.
 *
 * Requires:
 *     * jQuery 1.2
 *     * jQuery Dimensions 1.2 (unless jQuery is version 1.2.6+)
 * Optional:
 *     * jQuery Easing 1.3
 *
 * TERMS OF USE
 *
 * Copyright (C) 2008, Thomas J. Otterson (dev@barandis.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
 * conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 *       following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Version 0.3, 28.06.2008
 */

;(function($){

	$.fn.ddMenu = function(options) {
		DDMenu(this, options);
	};

	function DDMenu(root, opts) {

		opts = options(opts);						// default options overridden by user-supplied options

		/*
		 * Function: object
		 *
		 * Standard library function to produce a new object.
		 *
		 * Parameters:
		 * 		parent -> the object which will act as the parent of the new object.
		 * Returns:
		 * 		a new object parented to the supplied object.
		 */
		function object(parent) {
			function F() {}
			F.prototype = parent;
			return new F();
		}

		/*
		 * Function: options
		 *
		 * Merges a supplied options object with the default one (see $.fn.ddMenu.defaults). This is used instead of $.extend
		 * because $.extend modifies the parent object (in this case, the default options). Used here, that would cause options to
		 * bleed into other menus on the same page.
		 *
		 * Parameters:
		 * 		opts -> the user-supplied options object whose properties will override those of the default options object.
		 * Returns:
		 * 		a new options object containing the default options, except where overridden by the user-supplied options.
		 */
		function options(opts) {
			var that = object($.fn.ddMenu.defaults);
			for (var i in opts) {
				that[i] = opts[i];
			}
			return that;
		}

		/*
		 * Function: init
		 *
		 * Sets up the DrillDown Menu on the object supplied as the root in the constructor. This function adds divs and classes to
		 * the user-supplied structure like this (* indicates a user-supplied menu tag, while ** indicates a user-supplied item
		 * tag and *** a user-supplied label tag):
		 *
		 * div.menuClass
		 * +-- div.menuPanelClass
		 *     +-- div.titleRootClass (on first menu panel) or div.titleClass (on second and subsequent menu panels)
		 *     |   |-- div.titleIconClass (on second and subsequent menu panels)
		 *     |   +-- div.titleLabelClass
		 *     +-- div.scrollPaneClass
		 *         |-- div.scrollUpClass (if *.subMenuClass has > height than div.scrollPaneClass)
		 *         |-- div.scrollDownClass (if *.subMenuClass has > height than div.scrollPaneClass)
		 *         +-- *.subMenuClass
		 *             +-- **.itemClass
		 *                 +-- div.labelClass
		 *                     |-- div.iconClass (if **.itemClass has *.subMenuClass child)
		 *                     |-- ***.textClass
		 *                     +-- (*.subMenuClass)?...
		 *
		 * When drilldown occurs, the next div.menuPanelClass is formed in the same manner from the *.subMenuClass child of the
		 * selected **.itemClass element and is placed as a following sibling to the current deepest div.menuPanelClass.
		 */
		function init() {
			

			// wrap the outer user-supplied menu with div.menuClass and div.menuPanelClass
			var self = $(root).wrap('<div class="' + opts.menuClass + '"><div class="' + opts.menuPanelClass + '"><div class="' +
					opts.scrollPaneClass + '"></div></div></div>');
			
			// Bug #2847: the :first-child selector will select a comment if it happens to be the first child, but only
			// in IE. So in IE we're going to remove all of the comments first. This affects jQuery 1.2.3, but is due to
			// be fixed in 1.2.4.
			if ($.browser.msie) {
				removeComments(self.get(0));
			}		
			var pane = self.parents('.' + opts.scrollPaneClass);
			var panel = self.parents('.' + opts.menuPanelClass);
			var menu = self.parents('.' + opts.menuClass);

			// add .subMenuClass to all * and .itemClass to all **
			decorateMenu(self);

			// set the height and width of div.menuPanelClass to fit exactly into div.menuClass
			setOuterHeight(panel, menu.height(), true);
			setOuterWidth(panel, menu.width(), true);

			// wrap each *** (first child of **.itemClass) in div.labelClass and add .textClass to the ***
			self.find('.' + opts.itemClass + ' > *:first-child')
				.wrap('<div class="' + opts.labelClass + '"></div>')
				.addClass(opts.textClass);

			// if the **.itemClass came with a *.subMenuClass child, then add div.iconClass as div.labelClass's first child and
			// adjust the corresponding ***.textClass's width to accomodate. This means that the node is a branch.
			self.find('.' + opts.itemClass + ':has(.' + opts.subMenuClass + ') > div.' + opts.labelClass).each(function() {
				var label = $(this);
				var height = label.height();
				label.prepend('<div class="' + opts.iconClass + '">&nbsp;</div>');

				// This next line is a hack to fix a rounding error in Firefox 2.0. If FF2 calculates an element
				// height of, say, 23.7, then $(this).height() will return 24...but the element will be displayed
				// with a height of 23px. Calling setOuterHeight with the returned value of 24 will then cause
				// the icon div to be larger than the wrapper div, and then all of the icons are skewed.
				label.height(height);
				var iconDiv = label.children('.' + opts.iconClass);
				setOuterHeight(iconDiv, height, true);
				setOuterWidth(label.children('.' + opts.textClass), label.outerWidth() - iconDiv.outerWidth(true));
			});


			// add the proper hover/click behavior to each label
			self.find('.' + opts.labelClass).each(function() {
				addInteraction($(this));
			});

			self.find('.' + opts.subMenuClass).hide();			// hide all submenus that are not the root submenu
			addTitle(panel, opts.rootTitle, true);				// add div.titleClass, div.titleIconClass, and div.titleLabelClass
			setScrollPaneDimensions(panel);						// set div.scrollPaneClass height and width
			addScrollButtons(pane);

			choosePanel(menu);									// recursively create subpanels until reaching the one holding the
																// initial label
			highlight(menu);									// apply .labelInitialClass to the initial label

			// recursively adds .subMenuClass and .itemClass to all of the appropriate elements
			function decorateMenu(element) {
				element.addClass(opts.subMenuClass).css('position', 'relative');
				element.children().addClass(opts.itemClass).each(function() {
					if ($(this).children().size() > 1) {
						decorateMenu($(this).children(':last'));
					}
				});
			}
		}

		/*
		 * Function: drillDown
		 *
		 * Drills down to the next submenu according to the selected **.itemClass. This is done by wrapping that item's
		 * *.subMenuClass child in a div.menuPanelClass, sizing and positioning it, and then animating it into the main menu.
		 *
		 * Parameters:
		 * 		item -> the **.itemClass whose child *.subMenuClass element will be cloned and displayed.
		 */
		function drillDown(item) {
			var panel = cloneSubmenu(item);
			var title = item.children(':first').children(':last').text();
			var dir = opts.inDirection ? opts.inDirection : opts.direction;

			// adds the new div.menuPanelClass to the end inside the div.menuClass.
			var menu = item.parents('.' + opts.menuClass).append(panel);
			setOuterHeight(panel, menu.height(), true);
			setOuterWidth(panel, menu.width(), true);

			var pos = getPanelPosition(menu, panel, dir);

			panel.css({ position: 'relative', left: pos.outside.left, top: pos.outside.top });
			panel.show();
			addTitle(panel, title, false);

			setScrollPaneDimensions(panel);
			addScrollButtons(panel.children('.' + opts.scrollPaneClass));

			// this must be done with each drilldown because there's a good chance that the submenu with the initial label has been
			// destroyed at some point (on a drillup).
			highlight(item.parents('.' + opts.menuClass));

			panel.animate({ left: pos.inside.left, top: pos.inside.top },
					opts.inDuration ? opts.inDuration : opts.duration,
					opts.inEasing ? opts.inEasing : opts.easing);
		}

		/*
		 * Function: drillUp
		 *
		 * Drills up to the parent submenu of the currently displayed submenu. This is simpler than drilling down because no menu
		 * need be cloned and positioned; the current div.menuPanel need only be animated out of sight in the appropriate direction
		 * and then destroyed once out of sight.
		 *
		 * Parameters:
		 * 		panel -> the div.menuPanel to animate out and destroy.
		 */
		function drillUp(panel) {
			var menu = panel.parent();
			var dir = opts.outDirection ? opts.outDirection : opts.direction;

			var pos = getPanelPosition(menu, panel, dir);

			// slides the div.menuPanel out of sight and then deletes it.
			panel.animate({ left: pos.outside.left, top: pos.outside.top },
					opts.outDuration ? opts.outDuration : opts.duration,
					opts.outEasing ? opts.outEasing : opts.easing, function(){
						panel.remove();
					});
		}

		/*
		 * Function: choosePanel
		 *
		 * Recursively displays each submenu in the path indicated by the 'initial' property. Each menu is on top of the next, so at
		 * the end, the result is the same as if the menus had been drilled into (except that there is no animation). If the
		 * 'initial' path is invalid, this will drill down as far as it can and then stop, so be careful to get the paths right.
		 *
		 * Parameters:
		 * 		menu -> the div.menuClass object that encapsulates the entire menu whose initial panel is being selected.
		 */
		function choosePanel(menu) {
			if (opts.initial != null) {
				var parts = opts.initial.split(opts.separator);
				var current = menu.children(':first');

				for (var i in parts) {
					// ignore if we're on the last part of the path; highlight() handles this instead
					if (i < parts.length - 1) {
						var label = current
							.find('.' + opts.labelClass + ' .' + opts.textClass + ":contains('" + parts[i] + "')");
						if (label) {
							var submenu = label.parents('.' + opts.itemClass).children('.' + opts.subMenuClass);
							if (submenu) {
								// this section does pretty much the same thing as drillDown(), except that it always places the
								// menu panel atop the current one and does no animation.
								var panel = cloneSubmenu(submenu.parent());
								menu.append(panel);
								setOuterHeight(panel, menu.height(), true);
								setOuterWidth(panel, menu.width(), true);

								var dir = opts.inDirection ? opts.inDirection : opts.direction;
								var pos = getPanelPosition(menu, panel, dir);

								panel.css({ position: 'relative', top: pos.inside.top, left: pos.inside.left });
								panel.show();
								addTitle(panel, parts[i], false);

								setScrollPaneDimensions(panel);
								addScrollButtons(panel.children('.' + opts.scrollPaneClass));

								current = panel;
							}
						}
					}
				}
			}
		}

		/*
		 * Function: getPanelPosition
		 *
		 * Calculates the expected positions at the beginnings and ends of animations for the supplied panel in the given menu when
		 * the panel is to be animated in the selected direction. This function takes borders, paddings, and margins into account
		 * properly. The calcualted positions are relative to where the panel would be placed by natural page layout, and therefore
		 * they are appropriate to use as 'top' and 'left' properties in a 'position: relative' panel.
		 *
		 * Parameters:
		 * 		menu -> the div.menuClass to which the panel belongs.
		 * 		panel -> the div.menuPanelClass whose positions are being calculated.
		 * 		dir -> the direction from which the drilldown animation starts.
		 * Returns: Object
		 * 		an object of two properties, 'inside' and 'outside'. Each of these properties are in turn objects, each with two
		 * 		properties, 'top' and 'left'. Thus, 'value.inside.top' is the expected 'top' offset if the panel is positioned
		 * 		inside the div.menuClass (i.e., if it's visible), while 'value.outside.left' would be the 'left' offset if the panel
		 * 		is placed outside the div.menuClass; i.e., where it begins its drilldown animation.
		 */
		function getPanelPosition(menu, panel, dir) {
			var left, top;
			var index = panel.prevAll().size();		// this is important because even when a panel is placed relatively, the next
													// panel is by default positioned where it would be if the first panel was
													// placed normally. Thus, we need to determine how many times to multiply the
													// offset, which is based on how deep the submenu is in the hierarchy.
			var offset = (panel.outerHeight() + getMarginGap(panel)) * index;
			switch (dir) {
				case 'west':
					left = -panel.outerWidth(true);
					top = -offset;
					break;
				case 'north':
					left = 0;
					top = -(menu.outerHeight() + offset);
					break;
				case 'south':
					left = 0;
					top = panel.outerHeight(true) - offset;
					break;
				default:
					left = menu.outerWidth();
					top = -offset;
					break;
			}
			return {
				outside: { top: top, left: left },
				inside: { top: -offset, left: 0 }
			}
		}

		/*
		 * Function: getMarginGap
		 *
		 * Calculates the actual displayed margin gap between two panels. This calculation must be made because the margins collapse
		 * when placed against one another; i.e., the largest margin becomes the total margin between the two panels.
		 *
		 * Parameters:
		 * 		panel -> any panel with the proper div.menuPanelClass, whose effective margin between it and a preceding or
		 * 				following panel of the same class is calculated.
		 * Returns: Number
		 * 		the number of pixels in the effective margin.
		 */
		function getMarginGap(panel) {
			var top = getWidth(panel, 'margin-top');
			var bottom = getWidth(panel, 'margin-bottom');
			return top > bottom ? top : bottom;
		}

		/*
		 * Function: highlight
		 *
		 * Traces the 'initial' property path along the menu hierarchy, locates the designated menu label, and applies
		 * .labelInitialClass to it. This only happens if the menu does not already have a highlighted label; there can only be one
		 * at a time.
		 *
		 * Parameters:
		 * 		menu -> the div.menuClass object that encapsulates the entire menu whose initial label is being highlighted.
		 */
		function highlight(menu) {
			// it's only necessary to do this if there isn't already an initial class present somewhere, as the initial item
			// remains properly classed until its menu is deleted (by sliding out).
			if (opts.initial != null && menu.find('.' + opts.labelInitialClass).size() == 0) {
				var parts = opts.initial.split(opts.separator);
				var current = menu.children('.' + opts.menuPanelClass + ':first');		// the first menu panel
				for (var i = 0, count = parts.length; i < count; i++) {
					if (i == count - 1) {
						current.children('.' + opts.scrollPaneClass)
							.children('.' + opts.subMenuClass).children('.' + opts.itemClass).children('.' + opts.labelClass)
							.each(function(){	// each label wrapper in the current menu panel
								if ($(this).find('.' + opts.textClass).text() == parts[i]) {
									replaceClass($(this), opts.labelClass, opts.labelInitialClass);
									$(this).hover(
										function() {
											replaceClass($(this), opts.labelInitialClass, opts.labelInitialHoverClass);
										},
										function() {
											replaceClass($(this), opts.labelInitialHoverClass, opts.labelInitialClass);
										}
									);
								}
							});
					}
					else {
						var next = current.next();
						if (!next)
							return;
						var present = false;
						next.children('.' + opts.titleClass).find('.' + opts.titleLabelClass).each(function() {
							if ($(this).text() == parts[i]) {
								present = true;
								return false;
							}
						});
						if (!present)
							return;
						else
							current = next;
					}
				}
			}
		}

		/*
		 * Function: cloneSubmenu
		 *
		 * Clones the *.subMenuClass associated with the given **.itemClass, wraps it in a div.menuPanelClass, and returns the full
		 * panel.
		 *
		 * Parameters:
		 * 		item -> the **.itemClass whose *.subMenuClass child is being cloned and processed.
		 * Returns: jQuery
		 * 		the newly formed div.menuPanelClass with the selected submenu inside.
		 */
		function cloneSubmenu(item) {
			var panel = $('<div class="' + opts.menuPanelClass + '"><div class="' + opts.scrollPaneClass + '"></div</div>');
			var menu = item.children('.' + opts.subMenuClass + ':last').clone(true).show();
			panel.children('.' + opts.scrollPaneClass).append(menu);

			return panel;
		}

		/*
		 * Function: addTitle
		 *
		 * Adds a title consisting of div.titleCLass or div.titleRootClass wrapping div.titleLabelClass and (if necessary)
		 * div.titleIconClass as the first child of the supplied div.menuPanelClass.
		 *
		 * Parameters:
		 * 		panel -> the div.menuPanelClass having a title added.
		 * 		title -> the text of the title.
		 * 		root -> a Boolean indicating whether this menu is the root. This determines which class is added to the new title
		 * 				element and also whether it has an icon.
		 */
		function addTitle(panel, title, root) {
			var markup = '<div class="' + opts.titleClass + '">';
			if (!root) {
				markup += '<div class="' + opts.titleIconClass + '">&nbsp;</div>';
			}
			markup += '<div class="' + opts.titleLabelClass + '">' + title + '</div></div>';
			panel.prepend(markup);

			var titleDiv = panel.find('.' + opts.titleClass);
			if (root) {
				replaceClass(titleDiv, opts.titleClass, opts.titleRootClass);
				titleDiv.hover(
					function() {
						replaceClass($(this), opts.titleRootClass, opts.titleRootHoverClass);
					},
					function() {
						replaceClass($(this), opts.titleRootHoverClass, opts.titleRootClass);
					}
				);
			}
			else {
				var label = titleDiv.find('.' + opts.titleLabelClass);
				var icon = titleDiv.find('.' + opts.titleIconClass);

				titleDiv.hover(function() {
					replaceClass($(this), opts.titleClass, opts.titleHoverClass);
				}, function() {
					replaceClass($(this), opts.titleHoverClass, opts.titleClass);
				}).click(function() {
					drillUp(panel);
				});

				setOuterHeight(icon, label.outerHeight(), true);
				setOuterWidth(label, titleDiv.outerWidth() - (icon.size() == 0 ? 0 : icon.outerWidth(true)));
				label.css('margin-right', icon.outerWidth({ margin: true }));
			}
		}

		/*
		 * Function: addInteraction
		 *
		 * Adds all of the hover and click functionalities to parts of a label. This is a set up function, running only once upon
		 * the menu setup.
		 *
		 * Parameters:
		 * 		label -> the label being set up with interactive functionality.
		 */
		function addInteraction(label) {
			// Used when the div.labelClass has one child, meaning that there is no icon and therefore that there is no submenu
			// anchored here. In this case, the div.labelClass gets the hover. No click is added because presumably
			// ***.textClass came with an action already (<a href="*">, onclick, etc.).
			if (label.children().size() == 1) {
				label.hover(function() {
					replaceClass($(this), opts.labelClass, opts.labelHoverClass);
				}, function() {
					replaceClass($(this), opts.labelHoverClass, opts.labelClass);
				});
			}
			else {
				var link = label.find('a[href].' + opts.textClass);

				// Used when the div.labelClass has two children (icon and text) and the ***.textClass child is an <a> element
				// with an href attribute. In this case, div.textClass and div.iconClass get separate hover behaviors and the
				// div.iconClass gets a click action that drills down to the next menu. This is a split branch, and the already-
				// existent a.textClass provides the action for the text part of the branch.
				if (link.size() == 1) {
					link.hover(function() {
						replaceClass($(this), opts.textClass, opts.textHoverClass);
					}, function(){
						replaceClass($(this), opts.textHoverClass, opts.textClass);
					});
					label.find('div.' + opts.iconClass).hover(function() {
						replaceClass($(this), opts.iconClass, opts.iconHoverClass);
					}, function() {
						replaceClass($(this), opts.iconHoverClass, opts.iconClass);
					}).click(function() {
						drillDown(label.parent());
					});
				}

				// Used when the div.labelClass has two children (icon and text) but the ***.textClass is not an <a> element
				// with an href attribute. In this case, the div.labelClass receives both the hover and a click action which
				// drills down to the next menu. This is an unsplit branch.
				else {
					label.hover(function(){
						replaceClass($(this), opts.labelClass, opts.labelHoverClass);
					}, function(){
						replaceClass($(this), opts.labelHoverClass, opts.labelClass);
					}).click(function(){
						drillDown(label.parent());
					});
				}
			}
		}

		/*
		 * Function: addScrollButtons
		 *
		 * As the name suggests, this function adds the up and down scroll buttons to a scroll pane. This function is run only once
		 * per submenu, when it's created, and it only acts if the submenu is longer than the menu itself (i.e., if scrolling might
		 * be necessary). The "scroll up" button is initially hidden, since the menu starts in its topmost position anyway.
		 *
		 * Parameters:
		 * 		pane -> the scroll pane for the submenu, where the scroll buttons will be added.
		 */
		function addScrollButtons(pane) {
			var submenu = pane.children('.' + opts.subMenuClass);

				
			if (submenu.height() > pane.height()) {
				var up = $('<div class="' + opts.scrollUpClass + '">&nbsp;</div>');
				var down = $('<div class="' + opts.scrollDownClass + '">&nbsp;</div>');
				pane.prepend(down).prepend(up);
				var position = getScrollPosition(pane, submenu);

				up
					.hover(
						function() {
							replaceClass($(this), opts.scrollUpClass, opts.scrollUpHoverClass);
						},
						function() {
							replaceClass($(this), opts.scrollUpHoverClass, opts.scrollUpClass);
							replaceClass($(this), opts.scrollUpClickClass, opts.scrollUpClass);
							up.scroll = false;
						})
					.mousedown(
						function() {
							replaceClass($(this), opts.scrollUpHoverClass, opts.scrollUpClickClass);
							up.scroll = true;
							scrollUp(submenu, up, down, position);
						})
					.mouseup(
						function() {
							replaceClass($(this), opts.scrollUpClickClass, opts.scrollUpHoverClass);
							up.scroll = false;
						});
				down.
					hover(
						function() {
							replaceClass($(this), opts.scrollDownClass, opts.scrollDownHoverClass);
						},
						function() {
							replaceClass($(this), opts.scrollDownHoverClass, opts.scrollDownClass);
							replaceClass($(this), opts.scrollDownClickClass, opts.scrollDownClass);
							down.scroll = false;
						})
					.mousedown(
						function() {
							replaceClass($(this), opts.scrollDownHoverClass, opts.scrollDownClickClass);
							down.scroll = true;
							scrollDown(submenu, up, down, position);
						})
					.mouseup(
						function() {
							replaceClass($(this), opts.scrollDownClickClass, opts.scrollDownHoverClass);
							down.scroll = false;
						});

				up.hide();
			}
		}

		/*
		 * Function: scrollUp
		 *
		 * Scrolls the supplied menu panel up. This is presumably done in response to a click on the "scroll up" button. This
		 * automatically handles the display of each of the buttons in relation to the current position of the submenu.
		 *
		 * Parameters:
		 * 		submenu -> the submenu that is actually being scrolled.
		 * 		up -> the "scroll up" button element.
		 * 		down -> the "scroll down" button element.
		 * 		position -> an object denoting the starting and ending position for scrolling the submenu. This comes directly from
		 * 				getScrollPosition().
		 */
		function scrollUp(submenu, up, down, position) {
			if (up.scroll) {
				var newTop = getWidth(submenu, 'top') + 2;
				submenu.css('top', newTop);
				down.show();
				if (newTop >= position.start) {
					submenu.css('top', position.start);
					up.hide();
					up.scroll = false;
				}
				else {
					setTimeout(function() { scrollUp(submenu, up, down, position) }, opts.scrollSpeed);
				}
			}
		}

		/*
		 * Function: scrollDown
		 *
		 * Scrolls the supplied menu panel down. This is presumably done in response to a click on the "scroll down" button. This
		 * automatically handles the display of each of the buttons in relation to the current position of the submenu.
		 *
		 * Parameters:
		 * 		submenu -> the submenu that is actually being scrolled.
		 * 		up -> the "scroll up" button element.
		 * 		down -> the "scroll down" button element.
		 * 		position -> an object denoting the starting and ending position for scrolling the submenu. This comes directly from
		 * 				getScrollPosition().
		 */
		function scrollDown(submenu, up, down, position) {
			if (down.scroll) {
				var newTop = getWidth(submenu, 'top') - 2;
				submenu.css('top', newTop);
				up.show();
				if (newTop <= position.end) {
						submenu.css('top', position.end);
					down.hide();
					down.scroll = false;
				}
				else {
					setTimeout(function() { scrollDown(submenu, up, down, position) }, opts.scrollSpeed);
				}
			}
		}

		/*
		 * Function: getScrollPosition
		 *
		 * Returns an object detailing the starting and ending "top" parameters for the given submenu within the supplied pane. Note
		 * that if the submenu is smaller than the scroll pane, 'start' and 'end' will have the same values.
		 *
		 * Parameters:
		 * 		pane -> the scroll pane in which a submenu is being scrolled.
		 * 		submenu -> the submenu whose starting and ending scroll position is being queried.
		 * Returns: Object
		 * 		an object with two members: 'start', which gives the value of the 'top' property of the submenu when it is at its
		 * 		starting scroll position, and 'end', which is the value of the same property when the submenu is scrolled all the
		 * 		way up.
		 */
		function getScrollPosition(pane, submenu) {
			var initialTop = getWidth(submenu, 'top');
			var submenuHeight = submenu.outerHeight(true);
			var paneHeight = pane.height();
			if (submenuHeight <= paneHeight) {
				return { start: initialTop, end: initialTop	};
			}
			return { start: initialTop, end: initialTop - (submenuHeight - paneHeight) };
		}

		/*
		 * Function: setOuterHeight
		 *
		 * Sets the height of a set of elements by taking their borders, paddings, and (possibly) margins into account by
		 * subtracting them from the supplied height. The end result will be an element whose outerHeight() method will return the
		 * supplied height.
		 *
		 * NOTE: Due to the goofy way that IE handles border widths (see the ranting comment in getWidth() below), it is suggested
		 * that you NEVER set a border to 'thin', 'medium', or 'thick'. Those will all be counted as 0 for border-widths by this
		 * function. Use numerical values instead.
		 *
		 * Parameters:
		 * 		elements -> the set of elements to set to the supplied height.
		 * 		height -> the value that the outer height of all of the elements should be set to.
		 * 		margins -> a Boolean indicating whether to include margins in the calculation. If false, only paddings and borders
		 * 				will be taken into account.
		 */
		function setOuterHeight(elements, height, margins) {
			elements.each(function() {
				var element = $(this);
				var outside = 0;
				var props = [ 'padding-top', 'padding-bottom'];

				if (margins) {
					props.push('margin-top');
					props.push('margin-bottom');
				}

				for (var i in props) {
					outside += getWidth(element, props[i]);
				}
				element.height(height - outside);
			});
		}

		/*
		 * Function: setOuterWidth
		 *
		 * Sets the width of a set of elements by taking their borders, paddings, and (possibly) margins into account by
		 * subtracting them from the supplied width. The end result will be an element whose outerWidth() method will return the
		 * supplied width.
		 *
		 * NOTE: Due to the goofy way that IE handles border widths (see the ranting comment in getWidth() below), it is suggested
		 * that you NEVER set a border to 'thin', 'medium', or 'thick'. Those will all be counted as 0 for border-widths by this
		 * function. Use numerical values instead.
		 *
		 * Parameters:
		 * 		elements -> the set of elements to set to the supplied width.
		 * 		width -> the value that the outer width of all of the elements should be set to.
		 * 		margins -> a Boolean indicating whether to include margins in the calculation. If false, only paddings and borders
		 * 				will be taken into account.
		 */
		function setOuterWidth(elements, width, margins) {
			elements.each(function() {
				var element = $(this);
				var outside = 0;
				var props = [ 'padding-left', 'padding-right'];

				if (margins) {
					props.push('margin-left');
					props.push('margin-right');
				}

				for (var i in props) {
					outside += getWidth(element, props[i]);
				}
				element.width(width - outside);
			});
		}

		function setScrollPaneDimensions(panel) {
			var pane = panel.children('.' + opts.scrollPaneClass);
			setOuterHeight(pane,
					panel.height() - panel.children('.' + opts.titleClass + ', .' + opts.titleRootClass).outerHeight(true),
					true);
			setOuterWidth(pane, panel.width(), true);
		}

		/*
		 * Function: removeComments
		 *
		 * Removes all of the comments from the supplied node and all of its children. This is included due to a bug in jQuery
		 * versions 1.2.3 and earlier...in IE, a comment node will be returned from a :first-child selector if it is indeed the
		 * first child (comments are ignored in other browsers). Best way to be sure is to eliminate the comments.
		 *
		 * Parameters:
		 * 		node -> the node to remove comments from.
		 */
		function removeComments(node) {
			var i = 0;
			var children = node.childNodes;
			var x;

			while ((x = children[i++])) {
				switch (x.nodeType) {
					case 1: // Element type, for recursing
						removeComments(x);
						break;
					case 8: // Comment type
						node.removeChild(x);
						i--;
						break;
				}
			}
		}

		/*
		 * Function: replaceClass
		 *
		 * A convenience function that simply removes the supplied old class and adds the supplied new class to a given element.
		 * However, note that no replacement is done if the element does not already have the old class.
		 *
		 * Parameters:
		 *		element -> the element whose class is to be replaced.
		 *		oldClass -> the class being removed from the element.
		 *		newClass -> the class being added to the element.
		 */
		function replaceClass(element, oldClass, newClass) {
			if (element.hasClass(oldClass)) {
				element.removeClass(oldClass);
				element.addClass(newClass);
			}
		}

		/*
		 * Function: getWidth
		 *
		 * Determines the numerical pixel value for the supplied property on a given element. This discards any 'px' suffixes and
		 * returns a number. If the value returned by the browser does not start with a number (like IE returning 'medium'), this
		 * function will return 0. Best to set borders and the like to numerical values rather than the keyword values.
		 *
		 * Parameters:
		 * 		element -> the element whose property's value is being returned.
		 * 		property -> the property whose value is being returned.
		 * Returns: Number
		 * 		the numerical value of the property supplied, stripped of any of its textual component (like 'px').
		 */
		function getWidth(element, property) {
			var value = element.css(property).replace(/\D\-/g, '');

			// This conditional is a hack to account for some truly outstanding IE7 behavior.
			//
			// For any other browser, element.css('border-top-width') (for instance) will return a number.
			// If, for example, the border width is 'medium', FF will return '3px', which gets chopped
			// down to '3' by the above replace. IE returns 'medium'. Worse yet, if no border at all is
			// set, all browsers return '0px'...except IE, which returns 'medium'. Even if you set
			// 'border: none', IE returns...you guessed it...'medium'. Presumably the border-width wasn't
			// set, so it's still the improper non-numeric default value.
			//
			// Then, just for the fun of it, parseInt is supposed to return NaN if it tries to parse a
			// string that isn't a number. In IE, it errors out instead. Nice.
			if (value != NaN && value != '' && value != 'auto') {
				return parseInt(value, 10);
			}
			return 0;
		}

		init();
		return this;
	}

	/*
	 * These are the default values, or more appropriately, the "default default" values. If you have mulriple menus in your page
	 * and wish to change the default values for any of them, you can do so like this example:
	 *
	 * $.fn.ddMenu.defaults.duration = 1000
	 *
	 * Any DDMenu created after that point will have a default duration of 1000 instead of 500.
	 */
	$.fn.ddMenu.defaults = {
		rootTitle: 'Menu', 								// the text to appear as the title of the top-level menu.
		initial: null, 									// the path to the initial menu item.
		separator: '|',									// the separator used in the path of the 'initial' property above.
		scrollSpeed: 10,								// the scrolling speed for the menu (lower is faster)
		duration: 500, 									// the time taken to complete the drill down/up animation.
		inDuration: null,								// the time taken to complete the drill down animation.
		outDuration: null,								// the time taken to complete the drill up animation.
		easing: 'swing', 								// the easing used at the start and/or end of the animation. This default
														// value is available with or without the jQuery Easing plugin, so said
														// plugin isn't necessary. However, many more options are available with it.
		inEasing: null,									// easing specifically for drilldown down.
		outEasing: null,								// easing specifically for drilldown up.
		direction: 'east',								// the direction from and to which a new menu panel slides in and out.
		inDirection: null, 							    // the direction from which a new menu panel should slide in.
		outDirection: null, 							// the direction to which an old menu panel should slide out.

		menuClass: 'bdc-dd-menu', 						// the CSS class for the entire menu.
		menuPanelClass: 'bdc-dd-menu-panel', 			// the CSS class for each individual menu panel.
		scrollPaneClass: 'bdc-dd-scroll-pane',			// the CSS class for the scroll pane. This element appears whether the
														// menu panel is scrollable or not.
		scrollUpClass: 'bdc-dd-scroll-up',				// the CSS class for the div that acts as a "scroll up" button. This element
														// only appears when a scrollable menu panel is not in its highest position.
		scrollUpHoverClass: 'bdc-dd-scroll-up-hover',	// the CSS class for the scroll up button when it's hovered over.
		scrollUpClickClass: 'bdc-dd-scroll-up-click',	// the CSS class for the scroll up button when it's clicked.
		scrollDownClass: 'bdc-dd-scroll-down',			// the CSS class for the div that acts as a "scroll down" button. This
														// element only appears when a scrollable menu panel is not in its lowest
														// position.
		scrollDownHoverClass: 'bdc-dd-scroll-down-hover',	// the CSS class for the scroll down button when it's hovered over.
		scrollDownClickClass: 'bdc-dd-scroll-down-click',	// the CSS class for the scroll down button when it's clicked.
		subMenuClass: 'bdc-dd-sub-menu', 				// the CSS class for each submenu within the whole menu. This class is
														// applied to whatever tag is used for menus.
		titleClass: 'bdc-dd-title',			 			// the CSS class for the title.
		titleRootClass: 'bdc-dd-title-root',			// the CSS class for the title added to the root menu panel.
		titleHoverClass: 'bdc-dd-title-hover',			// the CSS class for the title when it's hovered over.
		titleRootHoverClass: 'bdc-dd-title-root-hover',	// the CSS class for the title added to the root menu panel when it's
														// hovered over.
		titleLabelClass: 'bdc-dd-title-label',			// the CSS class for the label title of each menu panel.
		titleIconClass: 'bdc-dd-title-icon', 			// the CSS class for the icon to appear next to the title label.
		itemClass: 'bdc-dd-item', 						// the CSS class for each menu item. This class is applied to whatever
														// tag is used for menu items.
		labelClass: 'bdc-dd-label',				 		// the CSS class for the element that wraps both label text and icon.
		labelHoverClass: 'bdc-dd-label-hover',			// the CSS class for the label when it's hovered over.
		labelInitialClass: 'bdc-dd-label-initial',		// the CSS class for the label when it is on the initial item.
		labelInitialHoverClass: 'bdc-dd-label-initial-hover',
														// the CSS class for the label when it's the initial item and hovered over.
		textClass: 'bdc-dd-text',						// the CSS class for the label text in each menu item.
		textHoverClass: 'bdc-dd-text-hover',			// the CSS class for the label text when it's hovered over (used ONLY in
														// split branches).
		iconClass: 'bdc-dd-icon', 						// the CSS class for the icon to appear next to the label (if necessary).
		iconHoverClass: 'bdc-dd-icon-hover'				// the CSS class for the icon when it's hovered over (used ONLY in split
														// branches).
	};

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/jquery.bdc.ddmenu.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.autocomplete.js */
/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, JÃ¶rn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 7 2010-05-21 12:51:40Z terry.weiss $
 *
 */

;(function($) {
	
$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150
		}, options);
		
		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };
		
		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;
		
		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);
	
	var blockSubmit;
	
	// prevent form submit in opera when selecting with return key
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});
	
	// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {
		
			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;
				
			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;
			
			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;
				
			case KEY.ESC:
				select.hide();
				break;
				
			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});
	
	
	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;
		
		var v = selected.result;
		previousValue = v;
		
		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
			}
			v += options.multipleSeparator;
		}
		
		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}
	
	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}
		
		var currentValue = $input.val();
		
		if ( !skipPrevCheck && currentValue == previousValue )
			return;
		
		previousValue = currentValue;
		
		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};
	
	function trimWords(value) {
		if ( !value ) {
			return [""];
		}
		var words = value.split( options.multipleSeparator );
		var result = [];
		$.each(words, function(i, value) {
			if ( $.trim(value) )
				result[i] = $.trim(value);
		});
		return result;
	}
	
	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		return words[words.length - 1];
	}
	
	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue){
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else
							$input.val( "" );
					}
				}
			);
		}
		if (wasVisible)
			// position cursor at end of input field
			$.Autocompleter.Selection(input, input.value.length, input.value.length);
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data && data.length) {
			success(term, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){
			
			var extraParams = {
				timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});
			
			$.ajax({
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				data: $.extend({
					q: lastWord(term),
					limit: options.max
				}, extraParams),
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			failure(term);
		}
	};
	
	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: false,
	cacheLength: 10,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { return row[0]; },
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;
	
	function matchSubset(s, sub) {
		if (!options.matchCase) 
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};
	
	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){ 
			length++;
		}
		data[q] = value;
	}
	
	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;
		
		// track all options for minChars = 0
		stMatchSets[""] = [];
		
		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
			
			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;
				
			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] ) 
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};
			
			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}
	
	// populate any existing data
	setTimeout(populate, 25);
	
	function flush(){
		data = {};
		length = 0;
	}
	
	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/* 
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}				
				return csub;
			} else 
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};
	
	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;
	
	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);
	
		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);            
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});
		
		if( options.width > 0 )
			element.css("width", options.width);
			
		needsInit = false;
	} 
	
	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};
	
	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}
	
	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}
	
	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}
	
	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});
				
                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }
                
            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.Autocompleter.Selection = function(field, start, end) {
	if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	} else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

})(jQuery);/* End of http://www.mentorsphere.com/scripts/jquery.autocomplete.js */
/* Start of http://www.mentorsphere.com/scripts/ui.core.js */
/*
 * jQuery UI 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
;jQuery.ui || (function($) {

var _remove = $.fn.remove,
	isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9);

//Helper functions and ui object
$.ui = {
	version: "1.7.1",

	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
	plugin: {
		add: function(module, option, set) {
			var proto = $.ui[module].prototype;
			for(var i in set) {
				proto.plugins[i] = proto.plugins[i] || [];
				proto.plugins[i].push([option, set[i]]);
			}
		},
		call: function(instance, name, args) {
			var set = instance.plugins[name];
			if(!set || !instance.element[0].parentNode) { return; }

			for (var i = 0; i < set.length; i++) {
				if (instance.options[set[i][0]]) {
					set[i][1].apply(instance.element, args);
				}
			}
		}
	},

	contains: function(a, b) {
		return document.compareDocumentPosition
			? a.compareDocumentPosition(b) & 16
			: a !== b && a.contains(b);
	},

	hasScroll: function(el, a) {

		//If overflow is hidden, the element might have extra content, but the user wants to hide it
		if ($(el).css('overflow') == 'hidden') { return false; }

		var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop',
			has = false;

		if (el[scroll] > 0) { return true; }

		// TODO: determine which cases actually cause this to happen
		// if the element doesn't have the scroll set, see if it's possible to
		// set the scroll
		el[scroll] = 1;
		has = (el[scroll] > 0);
		el[scroll] = 0;
		return has;
	},

	isOverAxis: function(x, reference, size) {
		//Determines when x coordinate is over "b" element axis
		return (x > reference) && (x < (reference + size));
	},

	isOver: function(y, x, top, left, height, width) {
		//Determines when x, y coordinates is over "b" element
		return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width);
	},

	keyCode: {
		BACKSPACE: 8,
		CAPS_LOCK: 20,
		COMMA: 188,
		CONTROL: 17,
		DELETE: 46,
		DOWN: 40,
		END: 35,
		ENTER: 13,
		ESCAPE: 27,
		HOME: 36,
		INSERT: 45,
		LEFT: 37,
		NUMPAD_ADD: 107,
		NUMPAD_DECIMAL: 110,
		NUMPAD_DIVIDE: 111,
		NUMPAD_ENTER: 108,
		NUMPAD_MULTIPLY: 106,
		NUMPAD_SUBTRACT: 109,
		PAGE_DOWN: 34,
		PAGE_UP: 33,
		PERIOD: 190,
		RIGHT: 39,
		SHIFT: 16,
		SPACE: 32,
		TAB: 9,
		UP: 38
	}
};

// WAI-ARIA normalization
if (isFF2) {
	var attr = $.attr,
		removeAttr = $.fn.removeAttr,
		ariaNS = "http://www.w3.org/2005/07/aaa",
		ariaState = /^aria-/,
		ariaRole = /^wairole:/;

	$.attr = function(elem, name, value) {
		var set = value !== undefined;

		return (name == 'role'
			? (set
				? attr.call(this, elem, name, "wairole:" + value)
				: (attr.apply(this, arguments) || "").replace(ariaRole, ""))
			: (ariaState.test(name)
				? (set
					? elem.setAttributeNS(ariaNS,
						name.replace(ariaState, "aaa:"), value)
					: attr.call(this, elem, name.replace(ariaState, "aaa:")))
				: attr.apply(this, arguments)));
	};

	$.fn.removeAttr = function(name) {
		return (ariaState.test(name)
			? this.each(function() {
				this.removeAttributeNS(ariaNS, name.replace(ariaState, ""));
			}) : removeAttr.call(this, name));
	};
}

//jQuery plugins
$.fn.extend({
	remove: function() {
		// Safari has a native remove event which actually removes DOM elements,
		// so we have to use triggerHandler instead of trigger (#3037).
		$("*", this).add(this).each(function() {
			$(this).triggerHandler("remove");
		});
		return _remove.apply(this, arguments );
	},

	enableSelection: function() {
		return this
			.attr('unselectable', 'off')
			.css('MozUserSelect', '')
			.unbind('selectstart.ui');
	},

	disableSelection: function() {
		return this
			.attr('unselectable', 'on')
			.css('MozUserSelect', 'none')
			.bind('selectstart.ui', function() { return false; });
	},

	scrollParent: function() {
		var scrollParent;
		if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
			scrollParent = this.parents().filter(function() {
				return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		} else {
			scrollParent = this.parents().filter(function() {
				return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1));
			}).eq(0);
		}

		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
	}
});


//Additional selectors
$.extend($.expr[':'], {
	data: function(elem, i, match) {
		return !!$.data(elem, match[3]);
	},

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
			// the element and all of its ancestors must be visible
			// the browser may report that the area is hidden
			&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
function getter(namespace, plugin, method, args) {
	function getMethods(type) {
		var methods = $[namespace][plugin][type] || [];
		return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods);
	}

	var methods = getMethods('getter');
	if (args.length == 1 && typeof args[0] == 'string') {
		methods = methods.concat(getMethods('getterSetter'));
	}
	return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
	var namespace = name.split(".")[0];
	name = name.split(".")[1];

	// create plugin method
	$.fn[name] = function(options) {
		var isMethodCall = (typeof options == 'string'),
			args = Array.prototype.slice.call(arguments, 1);

		// prevent calls to internal methods
		if (isMethodCall && options.substring(0, 1) == '_') {
			return this;
		}

		// handle getter methods
		if (isMethodCall && getter(namespace, name, options, args)) {
			var instance = $.data(this[0], name);
			return (instance ? instance[options].apply(instance, args)
				: undefined);
		}

		// handle initialization and non-getter methods
		return this.each(function() {
			var instance = $.data(this, name);

			// constructor
			(!instance && !isMethodCall &&
				$.data(this, name, new $[namespace][name](this, options))._init());

			// method call
			(instance && isMethodCall && $.isFunction(instance[options]) &&
				instance[options].apply(instance, args));
		});
	};

	// create widget constructor
	$[namespace] = $[namespace] || {};
	$[namespace][name] = function(element, options) {
		var self = this;

		this.namespace = namespace;
		this.widgetName = name;
		this.widgetEventPrefix = $[namespace][name].eventPrefix || name;
		this.widgetBaseClass = namespace + '-' + name;

		this.options = $.extend({},
			$.widget.defaults,
			$[namespace][name].defaults,
			$.metadata && $.metadata.get(element)[name],
			options);

		this.element = $(element)
			.bind('setData.' + name, function(event, key, value) {
				if (event.target == element) {
					return self._setData(key, value);
				}
			})
			.bind('getData.' + name, function(event, key) {
				if (event.target == element) {
					return self._getData(key);
				}
			})
			.bind('remove', function() {
				return self.destroy();
			});
	};

	// add widget prototype
	$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);

	// TODO: merge getter and getterSetter properties from widget prototype
	// and plugin prototype
	$[namespace][name].getterSetter = 'option';
};

$.widget.prototype = {
	_init: function() {},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
	},

	option: function(key, value) {
		var options = key,
			self = this;

		if (typeof key == "string") {
			if (value === undefined) {
				return this._getData(key);
			}
			options = {};
			options[key] = value;
		}

		$.each(options, function(key, value) {
			self._setData(key, value);
		});
	},
	_getData: function(key) {
		return this.options[key];
	},
	_setData: function(key, value) {
		this.options[key] = value;

		if (key == 'disabled') {
			this.element
				[value ? 'addClass' : 'removeClass'](
					this.widgetBaseClass + '-disabled' + ' ' +
					this.namespace + '-state-disabled')
				.attr("aria-disabled", value);
		}
	},

	enable: function() {
		this._setData('disabled', false);
	},
	disable: function() {
		this._setData('disabled', true);
	},

	_trigger: function(type, event, data) {
		var callback = this.options[type],
			eventName = (type == this.widgetEventPrefix
				? type : this.widgetEventPrefix + type);

		event = $.Event(event);
		event.type = eventName;

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if (event.originalEvent) {
			for (var i = $.event.props.length, prop; i;) {
				prop = $.event.props[--i];
				event[prop] = event.originalEvent[prop];
			}
		}

		this.element.trigger(event, data);

		return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false
			|| event.isDefaultPrevented());
	}
};

$.widget.defaults = {
	disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
	_mouseInit: function() {
		var self = this;

		this.element
			.bind('mousedown.'+this.widgetName, function(event) {
				return self._mouseDown(event);
			})
			.bind('click.'+this.widgetName, function(event) {
				if(self._preventClickEvent) {
					self._preventClickEvent = false;
					event.stopImmediatePropagation();
					return false;
				}
			});

		// Prevent text selection in IE
		if ($.browser.msie) {
			this._mouseUnselectable = this.element.attr('unselectable');
			this.element.attr('unselectable', 'on');
		}

		this.started = false;
	},

	// TODO: make sure destroying one instance of mouse doesn't mess with
	// other instances of mouse
	_mouseDestroy: function() {
		this.element.unbind('.'+this.widgetName);

		// Restore text selection in IE
		($.browser.msie
			&& this.element.attr('unselectable', this._mouseUnselectable));
	},

	_mouseDown: function(event) {
		// don't let more than one widget handle mouseStart
		// TODO: figure out why we have to use originalEvent
		event.originalEvent = event.originalEvent || {};
		if (event.originalEvent.mouseHandled) { return; }

		// we may have missed mouseup (out of window)
		(this._mouseStarted && this._mouseUp(event));

		this._mouseDownEvent = event;

		var self = this,
			btnIsLeft = (event.which == 1),
			elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false);
		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
			return true;
		}

		this.mouseDelayMet = !this.options.delay;
		if (!this.mouseDelayMet) {
			this._mouseDelayTimer = setTimeout(function() {
				self.mouseDelayMet = true;
			}, this.options.delay);
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted = (this._mouseStart(event) !== false);
			if (!this._mouseStarted) {
				event.preventDefault();
				return true;
			}
		}

		// these delegates are required to keep context
		this._mouseMoveDelegate = function(event) {
			return self._mouseMove(event);
		};
		this._mouseUpDelegate = function(event) {
			return self._mouseUp(event);
		};
		$(document)
			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		// preventDefault() is used to prevent the selection of text here -
		// however, in Safari, this causes select boxes not to be selectable
		// anymore, so this fix is needed
		($.browser.safari || event.preventDefault());

		event.originalEvent.mouseHandled = true;
		return true;
	},

	_mouseMove: function(event) {
		// IE mouseup check - mouseup happened when mouse was out of window
		if ($.browser.msie && !event.button) {
			return this._mouseUp(event);
		}

		if (this._mouseStarted) {
			this._mouseDrag(event);
			return event.preventDefault();
		}

		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
			this._mouseStarted =
				(this._mouseStart(this._mouseDownEvent, event) !== false);
			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
		}

		return !this._mouseStarted;
	},

	_mouseUp: function(event) {
		$(document)
			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

		if (this._mouseStarted) {
			this._mouseStarted = false;
			this._preventClickEvent = (event.target == this._mouseDownEvent.target);
			this._mouseStop(event);
		}

		return false;
	},

	_mouseDistanceMet: function(event) {
		return (Math.max(
				Math.abs(this._mouseDownEvent.pageX - event.pageX),
				Math.abs(this._mouseDownEvent.pageY - event.pageY)
			) >= this.options.distance
		);
	},

	_mouseDelayMet: function(event) {
		return this.mouseDelayMet;
	},

	// These are placeholder methods, to be overriden by extending plugin
	_mouseStart: function(event) {},
	_mouseDrag: function(event) {},
	_mouseStop: function(event) {},
	_mouseCapture: function(event) { return true; }
};

$.ui.mouse.defaults = {
	cancel: null,
	distance: 1,
	delay: 0
};

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/ui.core.js */
/* Start of http://www.mentorsphere.com/scripts/effects.core.js */
/*
 * jQuery UI Effects 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/
 */
;jQuery.effects || (function($) {

$.effects = {
	version: "1.7.1",

	// Saves a set of properties in a data storage
	save: function(element, set) {
		for(var i=0; i < set.length; i++) {
			if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]);
		}
	},

	// Restores a set of previously saved properties from a data storage
	restore: function(element, set) {
		for(var i=0; i < set.length; i++) {
			if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i]));
		}
	},

	setMode: function(el, mode) {
		if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle
		return mode;
	},

	getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value
		// this should be a little more flexible in the future to handle a string & hash
		var y, x;
		switch (origin[0]) {
			case 'top': y = 0; break;
			case 'middle': y = 0.5; break;
			case 'bottom': y = 1; break;
			default: y = origin[0] / original.height;
		};
		switch (origin[1]) {
			case 'left': x = 0; break;
			case 'center': x = 0.5; break;
			case 'right': x = 1; break;
			default: x = origin[1] / original.width;
		};
		return {x: x, y: y};
	},

	// Wraps the element around a wrapper that copies position properties
	createWrapper: function(element) {

		//if the element is already wrapped, return it
		if (element.parent().is('.ui-effects-wrapper'))
			return element.parent();

		//Cache width,height and float properties of the element, and create a wrapper around it
		var props = { width: element.outerWidth(true), height: element.outerHeight(true), 'float': element.css('float') };
		element.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>');
		var wrapper = element.parent();

		//Transfer the positioning of the element to the wrapper
		if (element.css('position') == 'static') {
			wrapper.css({ position: 'relative' });
			element.css({ position: 'relative'} );
		} else {
			var top = element.css('top'); if(isNaN(parseInt(top,10))) top = 'auto';
			var left = element.css('left'); if(isNaN(parseInt(left,10))) left = 'auto';
			wrapper.css({ position: element.css('position'), top: top, left: left, zIndex: element.css('z-index') }).show();
			element.css({position: 'relative', top: 0, left: 0 });
		}

		wrapper.css(props);
		return wrapper;
	},

	removeWrapper: function(element) {
		if (element.parent().is('.ui-effects-wrapper'))
			return element.parent().replaceWith(element);
		return element;
	},

	setTransition: function(element, list, factor, value) {
		value = value || {};
		$.each(list, function(i, x){
			unit = element.cssUnit(x);
			if (unit[0] > 0) value[x] = unit[0] * factor + unit[1];
		});
		return value;
	},

	//Base function to animate from one class to another in a seamless transition
	animateClass: function(value, duration, easing, callback) {

		var cb = (typeof easing == "function" ? easing : (callback ? callback : null));
		var ea = (typeof easing == "string" ? easing : null);

		return this.each(function() {

			var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || '';
			if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */
			if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; }

			//Let's get a style offset
			var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove);
			var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle));
			if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove);

			// The main function to form the object for animation
			for(var n in newStyle) {
				if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */
				&& n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */
				&& newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */
				&& (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */
				&& (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */
				) offset[n] = newStyle[n];
			}

			that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object
				// Change style attribute back to original. For stupid IE, we need to clear the damn object.
				if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr);
				if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove);
				if(cb) cb.apply(this, arguments);
			});

		});
	}
};


function _normalizeArguments(a, m) {

	var o = a[1] && a[1].constructor == Object ? a[1] : {}; if(m) o.mode = m;
	var speed = a[1] && a[1].constructor != Object ? a[1] : (o.duration ? o.duration : a[2]); //either comes from options.duration or the secon/third argument
		speed = $.fx.off ? 0 : typeof speed === "number" ? speed : $.fx.speeds[speed] || $.fx.speeds._default;
	var callback = o.callback || ( $.isFunction(a[1]) && a[1] ) || ( $.isFunction(a[2]) && a[2] ) || ( $.isFunction(a[3]) && a[3] );

	return [a[0], o, speed, callback];
	
}

//Extend the methods of jQuery
$.fn.extend({

	//Save old methods
	_show: $.fn.show,
	_hide: $.fn.hide,
	__toggle: $.fn.toggle,
	_addClass: $.fn.addClass,
	_removeClass: $.fn.removeClass,
	_toggleClass: $.fn.toggleClass,

	// New effect methods
	effect: function(fx, options, speed, callback) {
		return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: options || {}, duration: speed, callback: callback }) : null;
	},

	show: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])))
			return this._show.apply(this, arguments);
		else {
			return this.effect.apply(this, _normalizeArguments(arguments, 'show'));
		}
	},

	hide: function() {
		if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])))
			return this._hide.apply(this, arguments);
		else {
			return this.effect.apply(this, _normalizeArguments(arguments, 'hide'));
		}
	},

	toggle: function(){
		if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])) || (arguments[0].constructor == Function))
			return this.__toggle.apply(this, arguments);
		else {
			return this.effect.apply(this, _normalizeArguments(arguments, 'toggle'));
		}
	},

	addClass: function(classNames, speed, easing, callback) {
		return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames);
	},
	removeClass: function(classNames,speed,easing,callback) {
		return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames);
	},
	toggleClass: function(classNames,speed,easing,callback) {
		return ( (typeof speed !== "boolean") && speed ) ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames, speed);
	},
	morph: function(remove,add,speed,easing,callback) {
		return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]);
	},
	switchClass: function() {
		return this.morph.apply(this, arguments);
	},

	// helper functions
	cssUnit: function(key) {
		var style = this.css(key), val = [];
		$.each( ['em','px','%','pt'], function(i, unit){
			if(style.indexOf(unit) > 0)
				val = [parseFloat(style), unit];
		});
		return val;
	}
});

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

// We override the animation for all of these color styles
$.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		$.fx.step[attr] = function(fx) {
				if ( fx.state == 0 ) {
						fx.start = getColor( fx.elem, attr );
						fx.end = getRGB( fx.end );
				}

				fx.elem.style[attr] = "rgb(" + [
						Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0],10), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1],10), 255), 0),
						Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2],10), 255), 0)
				].join(",") + ")";
			};
});

// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/

// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
				return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
				return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
				return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
				return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
				return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Look for rgba(0, 0, 0, 0) == transparent in Safari 3
		if (result = /rgba\(0, 0, 0, 0\)/.exec(color))
				return colors['transparent'];

		// Otherwise, we're most likely dealing with a named color
		return colors[$.trim(color).toLowerCase()];
}

function getColor(elem, attr) {
		var color;

		do {
				color = $.curCSS(elem, attr);

				// Keep going until we find an element that has color, or we hit the body
				if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") )
						break;

				attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
};

// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/

var colors = {
	aqua:[0,255,255],
	azure:[240,255,255],
	beige:[245,245,220],
	black:[0,0,0],
	blue:[0,0,255],
	brown:[165,42,42],
	cyan:[0,255,255],
	darkblue:[0,0,139],
	darkcyan:[0,139,139],
	darkgrey:[169,169,169],
	darkgreen:[0,100,0],
	darkkhaki:[189,183,107],
	darkmagenta:[139,0,139],
	darkolivegreen:[85,107,47],
	darkorange:[255,140,0],
	darkorchid:[153,50,204],
	darkred:[139,0,0],
	darksalmon:[233,150,122],
	darkviolet:[148,0,211],
	fuchsia:[255,0,255],
	gold:[255,215,0],
	green:[0,128,0],
	indigo:[75,0,130],
	khaki:[240,230,140],
	lightblue:[173,216,230],
	lightcyan:[224,255,255],
	lightgreen:[144,238,144],
	lightgrey:[211,211,211],
	lightpink:[255,182,193],
	lightyellow:[255,255,224],
	lime:[0,255,0],
	magenta:[255,0,255],
	maroon:[128,0,0],
	navy:[0,0,128],
	olive:[128,128,0],
	orange:[255,165,0],
	pink:[255,192,203],
	purple:[128,0,128],
	violet:[128,0,128],
	red:[255,0,0],
	silver:[192,192,192],
	white:[255,255,255],
	yellow:[255,255,0],
	transparent: [255,255,255]
};

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
$.easing.jswing = $.easing.swing;

$.extend($.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert($.easing.default);
		return $.easing[$.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 *
 * TERMS OF USE - EASING EQUATIONS
 *
 * Open source under the BSD License.
 *
 * Copyright 2001 Robert Penner
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/effects.core.js */
/* Start of http://www.mentorsphere.com/scripts/effects.blind.js */
/*
 * jQuery UI Effects Blind 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Blind
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.blind = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this), props = ['position','top','left'];

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode
		var direction = o.options.direction || 'vertical'; // Default direction

		// Adjust
		$.effects.save(el, props); el.show(); // Save & Show
		var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper
		var ref = (direction == 'vertical') ? 'height' : 'width';
		var distance = (direction == 'vertical') ? wrapper.height() : wrapper.width();
		if(mode == 'show') wrapper.css(ref, 0); // Shift

		// Animation
		var animation = {};
		animation[ref] = mode == 'show' ? distance : 0;

		// Animate
		wrapper.animate(animation, o.duration, o.options.easing, function() {
			if(mode == 'hide') el.hide(); // Hide
			$.effects.restore(el, props); $.effects.removeWrapper(el); // Restore
			if(o.callback) o.callback.apply(el[0], arguments); // Callback
			el.dequeue();
		});

	});

};

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/effects.blind.js */
/* Start of http://www.mentorsphere.com/scripts/effects.pulsate.js */
/*
 * jQuery UI Effects Pulsate 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Pulsate
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.pulsate = function(o) {

	return this.queue(function() {

		// Create element
		var el = $(this);

		// Set options
		var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode
		var times = o.options.times || 5; // Default # of times
		var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2;

		// Adjust
		if (mode == 'hide') times--;
		if (el.is(':hidden')) { // Show fadeIn
			el.css('opacity', 0);
			el.show(); // Show
			el.animate({opacity: 1}, duration, o.options.easing);
			times = times-2;
		}

		// Animate
		for (var i = 0; i < times; i++) { // Pulsate
			el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing);
		};
		if (mode == 'hide') { // Last Pulse
			el.animate({opacity: 0}, duration, o.options.easing, function(){
				el.hide(); // Hide
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		} else {
			el.animate({opacity: 0}, duration, o.options.easing).animate({opacity: 1}, duration, o.options.easing, function(){
				if(o.callback) o.callback.apply(this, arguments); // Callback
			});
		};
		el.queue('fx', function() { el.dequeue(); });
		el.dequeue();
	});

};

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/effects.pulsate.js */
/* Start of http://www.mentorsphere.com/scripts/effects.transfer.js */
/*
 * jQuery UI Effects Transfer 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Effects/Transfer
 *
 * Depends:
 *	effects.core.js
 */
(function($) {

$.effects.transfer = function(o) {
	return this.queue(function() {
		var elem = $(this),
			target = $(o.options.to),
			endPosition = target.offset(),
			animation = {
				top: endPosition.top,
				left: endPosition.left,
				height: target.innerHeight(),
				width: target.innerWidth()
			},
			startPosition = elem.offset(),
			transfer = $('<div class="ui-effects-transfer"></div>')
				.appendTo(document.body)
				.addClass(o.options.className)
				.css({
					top: startPosition.top,
					left: startPosition.left,
					height: elem.innerHeight(),
					width: elem.innerWidth(),
					position: 'absolute'
				})
				.animate(animation, o.duration, o.options.easing, function() {
					transfer.remove();
					(o.callback && o.callback.apply(elem[0], arguments));
					elem.dequeue();
				});
	});
};

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/effects.transfer.js */
/* Start of http://www.mentorsphere.com/scripts/ui.draggable.js */
/*
 * jQuery UI Draggable 1.7.1
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.draggable", $.extend({}, $.ui.mouse, {

	_init: function() {

		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
			this.element[0].style.position = 'relative';

		(this.options.addClasses && this.element.addClass("ui-draggable"));
		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));

		this._mouseInit();

	},

	destroy: function() {
		if(!this.element.data('draggable')) return;
		this.element
			.removeData("draggable")
			.unbind(".draggable")
			.removeClass("ui-draggable"
				+ " ui-draggable-dragging"
				+ " ui-draggable-disabled");
		this._mouseDestroy();
	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
			return false;

		//Quit if we're not on a valid handle
		this.handle = this._getHandle(event);
		if (!this.handle)
			return false;

		return true;

	},

	_mouseStart: function(event) {

		var o = this.options;

		//Create and append the visible helper
		this.helper = this._createHelper(event);

		//Cache the helper size
		this._cacheHelperProportions();

		//If ddmanager is used for droppables, set the global draggable
		if($.ui.ddmanager)
			$.ui.ddmanager.current = this;

		/*
		 * - Position generation -
		 * This block generates everything position related - it's the core of draggables.
		 */

		//Cache the margins of the original element
		this._cacheMargins();

		//Store the helper's css position
		this.cssPosition = this.helper.css("position");
		this.scrollParent = this.helper.scrollParent();

		//The element's absolute position on the page minus margins
		this.offset = this.element.offset();
		this.offset = {
			top: this.offset.top - this.margins.top,
			left: this.offset.left - this.margins.left
		};

		$.extend(this.offset, {
			click: { //Where the click happened, relative to the element
				left: event.pageX - this.offset.left,
				top: event.pageY - this.offset.top
			},
			parent: this._getParentOffset(),
			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
		});

		//Generate the original position
		this.originalPosition = this._generatePosition(event);
		this.originalPageX = event.pageX;
		this.originalPageY = event.pageY;

		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
		if(o.cursorAt)
			this._adjustOffsetFromHelper(o.cursorAt);

		//Set a containment if given in the options
		if(o.containment)
			this._setContainment();

		//Call plugins and callbacks
		this._trigger("start", event);

		//Recache the helper size
		this._cacheHelperProportions();

		//Prepare the droppable offsets
		if ($.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(this, event);

		this.helper.addClass("ui-draggable-dragging");
		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
		return true;
	},

	_mouseDrag: function(event, noPropagation) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		//Call plugins and callbacks and use the resulting position if something is returned
		if (!noPropagation) {
			var ui = this._uiHash();
			this._trigger('drag', event, ui);
			this.position = ui.position;
		}

		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		return false;
	},

	_mouseStop: function(event) {

		//If we are using droppables, inform the manager about the drop
		var dropped = false;
		if ($.ui.ddmanager && !this.options.dropBehaviour)
			dropped = $.ui.ddmanager.drop(this, event);

		//if a drop comes from outside (a sortable)
		if(this.dropped) {
			dropped = this.dropped;
			this.dropped = false;
		}

		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
			var self = this;
			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
				self._trigger("stop", event);
				self._clear();
			});
		} else {
			this._trigger("stop", event);
			this._clear();
		}

		return false;
	},

	_getHandle: function(event) {

		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
		$(this.options.handle, this.element)
			.find("*")
			.andSelf()
			.each(function() {
				if(this == event.target) handle = true;
			});

		return handle;

	},

	_createHelper: function(event) {

		var o = this.options;
		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone() : this.element);

		if(!helper.parents('body').length)
			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));

		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
			helper.css("position", "absolute");

		return helper;

	},

	_adjustOffsetFromHelper: function(obj) {
		if(obj.left != undefined) this.offset.click.left = obj.left + this.margins.left;
		if(obj.right != undefined) this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
		if(obj.top != undefined) this.offset.click.top = obj.top + this.margins.top;
		if(obj.bottom != undefined) this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
	},

	_getParentOffset: function() {

		//Get the offsetParent and cache its position
		this.offsetParent = this.helper.offsetParent();
		var po = this.offsetParent.offset();

		// This is a special case where we need to modify a offset calculated on start, since the following happened:
		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
			po.left += this.scrollParent.scrollLeft();
			po.top += this.scrollParent.scrollTop();
		}

		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
			po = { top: 0, left: 0 };

		return {
			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
		};

	},

	_getRelativeOffset: function() {

		if(this.cssPosition == "relative") {
			var p = this.element.position();
			return {
				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
			};
		} else {
			return { top: 0, left: 0 };
		}

	},

	_cacheMargins: function() {
		this.margins = {
			left: (parseInt(this.element.css("marginLeft"),10) || 0),
			top: (parseInt(this.element.css("marginTop"),10) || 0)
		};
	},

	_cacheHelperProportions: function() {
		this.helperProportions = {
			width: this.helper.outerWidth(),
			height: this.helper.outerHeight()
		};
	},

	_setContainment: function() {

		var o = this.options;
		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
		if(o.containment == 'document' || o.containment == 'window') this.containment = [
			0 - this.offset.relative.left - this.offset.parent.left,
			0 - this.offset.relative.top - this.offset.parent.top,
			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
		];

		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
			var ce = $(o.containment)[0]; if(!ce) return;
			var co = $(o.containment).offset();
			var over = ($(ce).css("overflow") != 'hidden');

			this.containment = [
				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
			];
		} else if(o.containment.constructor == Array) {
			this.containment = o.containment;
		}

	},

	_convertPositionTo: function(d, pos) {

		if(!pos) pos = this.position;
		var mod = d == "absolute" ? 1 : -1;
		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		return {
			top: (
				pos.top																	// The absolute mouse position
				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
			),
			left: (
				pos.left																// The absolute mouse position
				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
				- ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
			)
		};

	},

	_generatePosition: function(event) {

		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);

		// This is another very weird special case that only happens for relative elements:
		// 1. If the css position is relative
		// 2. and the scroll parent is the document or similar to the offset parent
		// we have to refresh the relative offset during the scroll so there are no jumps
		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
			this.offset.relative = this._getRelativeOffset();
		}

		var pageX = event.pageX;
		var pageY = event.pageY;

		/*
		 * - Position constraining -
		 * Constrain the position to a mix of grid, containment.
		 */

		if(this.originalPosition) { //If we are not dragging yet, we won't check for options

			if(this.containment) {
				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
			}

			if(o.grid) {
				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;

				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
			}

		}

		return {
			top: (
				pageY																// The absolute mouse position
				- this.offset.click.top													// Click offset (relative to the element)
				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
			),
			left: (
				pageX																// The absolute mouse position
				- this.offset.click.left												// Click offset (relative to the element)
				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
				+ ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
			)
		};

	},

	_clear: function() {
		this.helper.removeClass("ui-draggable-dragging");
		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
		this.helper = null;
		this.cancelHelperRemoval = false;
	},

	// From now on bulk stuff - mainly helpers

	_trigger: function(type, event, ui) {
		ui = ui || this._uiHash();
		$.ui.plugin.call(this, type, [event, ui]);
		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
		return $.widget.prototype._trigger.call(this, type, event, ui);
	},

	plugins: {},

	_uiHash: function(event) {
		return {
			helper: this.helper,
			position: this.position,
			absolutePosition: this.positionAbs, //deprecated
			offset: this.positionAbs
		};
	}

}));

$.extend($.ui.draggable, {
	version: "1.7.1",
	eventPrefix: "drag",
	defaults: {
		addClasses: true,
		appendTo: "parent",
		axis: false,
		cancel: ":input,option",
		connectToSortable: false,
		containment: false,
		cursor: "auto",
		cursorAt: false,
		delay: 0,
		distance: 1,
		grid: false,
		handle: false,
		helper: "original",
		iframeFix: false,
		opacity: false,
		refreshPositions: false,
		revert: false,
		revertDuration: 500,
		scope: "default",
		scroll: true,
		scrollSensitivity: 20,
		scrollSpeed: 20,
		snap: false,
		snapMode: "both",
		snapTolerance: 20,
		stack: false,
		zIndex: false
	}
});

$.ui.plugin.add("draggable", "connectToSortable", {
	start: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options,
			uiSortable = $.extend({}, ui, { item: inst.element });
		inst.sortables = [];
		$(o.connectToSortable).each(function() {
			var sortable = $.data(this, 'sortable');
			if (sortable && !sortable.options.disabled) {
				inst.sortables.push({
					instance: sortable,
					shouldRevert: sortable.options.revert
				});
				sortable._refreshItems();	//Do a one-time refresh at start to refresh the containerCache
				sortable._trigger("activate", event, uiSortable);
			}
		});

	},
	stop: function(event, ui) {

		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
		var inst = $(this).data("draggable"),
			uiSortable = $.extend({}, ui, { item: inst.element });

		$.each(inst.sortables, function() {
			if(this.instance.isOver) {

				this.instance.isOver = 0;

				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)

				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
				if(this.shouldRevert) this.instance.options.revert = true;

				//Trigger the stop of the sortable
				this.instance._mouseStop(event);

				this.instance.options.helper = this.instance.options._helper;

				//If the helper has been the original item, restore properties in the sortable
				if(inst.options.helper == 'original')
					this.instance.currentItem.css({ top: 'auto', left: 'auto' });

			} else {
				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
				this.instance._trigger("deactivate", event, uiSortable);
			}

		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), self = this;

		var checkPos = function(o) {
			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
			var itemHeight = o.height, itemWidth = o.width;
			var itemTop = o.top, itemLeft = o.left;

			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
		};

		$.each(inst.sortables, function(i) {
			
			//Copy over some variables to allow calling the sortable's native _intersectsWith
			this.instance.positionAbs = inst.positionAbs;
			this.instance.helperProportions = inst.helperProportions;
			this.instance.offset.click = inst.offset.click;
			
			if(this.instance._intersectsWith(this.instance.containerCache)) {

				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
				if(!this.instance.isOver) {

					this.instance.isOver = 1;
					//Now we fake the start of dragging for the sortable instance,
					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
					this.instance.currentItem = $(self).clone().appendTo(this.instance.element).data("sortable-item", true);
					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
					this.instance.options.helper = function() { return ui.helper[0]; };

					event.target = this.instance.currentItem[0];
					this.instance._mouseCapture(event, true);
					this.instance._mouseStart(event, true, true);

					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
					this.instance.offset.click.top = inst.offset.click.top;
					this.instance.offset.click.left = inst.offset.click.left;
					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;

					inst._trigger("toSortable", event);
					inst.dropped = this.instance.element; //draggable revert needs that
					//hack so receive/update callbacks work (mostly)
					inst.currentItem = inst.element;
					this.instance.fromOutside = inst;

				}

				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
				if(this.instance.currentItem) this.instance._mouseDrag(event);

			} else {

				//If it doesn't intersect with the sortable, and it intersected before,
				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
				if(this.instance.isOver) {

					this.instance.isOver = 0;
					this.instance.cancelHelperRemoval = true;
					
					//Prevent reverting on this forced stop
					this.instance.options.revert = false;
					
					// The out event needs to be triggered independently
					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
					
					this.instance._mouseStop(event, true);
					this.instance.options.helper = this.instance.options._helper;

					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
					this.instance.currentItem.remove();
					if(this.instance.placeholder) this.instance.placeholder.remove();

					inst._trigger("fromSortable", event);
					inst.dropped = false; //draggable revert needs that
				}

			};

		});

	}
});

$.ui.plugin.add("draggable", "cursor", {
	start: function(event, ui) {
		var t = $('body'), o = $(this).data('draggable').options;
		if (t.css("cursor")) o._cursor = t.css("cursor");
		t.css("cursor", o.cursor);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if (o._cursor) $('body').css("cursor", o._cursor);
	}
});

$.ui.plugin.add("draggable", "iframeFix", {
	start: function(event, ui) {
		var o = $(this).data('draggable').options;
		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
			.css({
				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
				position: "absolute", opacity: "0.001", zIndex: 1000
			})
			.css($(this).offset())
			.appendTo("body");
		});
	},
	stop: function(event, ui) {
		$("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //Remove frame helpers
	}
});

$.ui.plugin.add("draggable", "opacity", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data('draggable').options;
		if(t.css("opacity")) o._opacity = t.css("opacity");
		t.css('opacity', o.opacity);
	},
	stop: function(event, ui) {
		var o = $(this).data('draggable').options;
		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
	}
});

$.ui.plugin.add("draggable", "scroll", {
	start: function(event, ui) {
		var i = $(this).data("draggable");
		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
	},
	drag: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options, scrolled = false;

		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {

			if(!o.axis || o.axis != 'x') {
				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
			}

			if(!o.axis || o.axis != 'y') {
				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
			}

		} else {

			if(!o.axis || o.axis != 'x') {
				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
			}

			if(!o.axis || o.axis != 'y') {
				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
			}

		}

		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
			$.ui.ddmanager.prepareOffsets(i, event);

	}
});

$.ui.plugin.add("draggable", "snap", {
	start: function(event, ui) {

		var i = $(this).data("draggable"), o = i.options;
		i.snapElements = [];

		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
			var $t = $(this); var $o = $t.offset();
			if(this != i.element[0]) i.snapElements.push({
				item: this,
				width: $t.outerWidth(), height: $t.outerHeight(),
				top: $o.top, left: $o.left
			});
		});

	},
	drag: function(event, ui) {

		var inst = $(this).data("draggable"), o = inst.options;
		var d = o.snapTolerance;

		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;

		for (var i = inst.snapElements.length - 1; i >= 0; i--){

			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;

			//Yes, I know, this is insane ;)
			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
				inst.snapElements[i].snapping = false;
				continue;
			}

			if(o.snapMode != 'inner') {
				var ts = Math.abs(t - y2) <= d;
				var bs = Math.abs(b - y1) <= d;
				var ls = Math.abs(l - x2) <= d;
				var rs = Math.abs(r - x1) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
			}

			var first = (ts || bs || ls || rs);

			if(o.snapMode != 'outer') {
				var ts = Math.abs(t - y1) <= d;
				var bs = Math.abs(b - y2) <= d;
				var ls = Math.abs(l - x1) <= d;
				var rs = Math.abs(r - x2) <= d;
				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
			}

			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);

		};

	}
});

$.ui.plugin.add("draggable", "stack", {
	start: function(event, ui) {

		var o = $(this).data("draggable").options;

		var group = $.makeArray($(o.stack.group)).sort(function(a,b) {
			return (parseInt($(a).css("zIndex"),10) || o.stack.min) - (parseInt($(b).css("zIndex"),10) || o.stack.min);
		});

		$(group).each(function(i) {
			this.style.zIndex = o.stack.min + i;
		});

		this[0].style.zIndex = o.stack.min + group.length;

	}
});

$.ui.plugin.add("draggable", "zIndex", {
	start: function(event, ui) {
		var t = $(ui.helper), o = $(this).data("draggable").options;
		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
		t.css('zIndex', o.zIndex);
	},
	stop: function(event, ui) {
		var o = $(this).data("draggable").options;
		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
	}
});

})(jQuery);
/* End of http://www.mentorsphere.com/scripts/ui.draggable.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.updnvalidatorcallout.js */
/*
* jQuery (ASP.NET) Validator Callout plugin
*   http://updatepanel.net/2009/04/19/jquery-aspnet-validator-callout-plugin/
*
* Copyright (c) 2009 Ting Zwei Kuei
*
* Dual licensed under the MIT and GPL licenses.
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.opensource.org/licenses/gpl-3.0.html
*/
(function($) {
    $.fn.updnValidatorCallout = function(options) {
        // Prepare options.
        options = $.extend({}, $.fn.updnValidatorCallout.defaults, options);
        // Currently open callout.
        var _current = null;
        // Overrides ValidatorOnChange in WebUIValidation.js to ensure input and label styles are updated.
        if (window.ValidatorOnChange && !window._ValidatorOnChange) {
            window._ValidatorOnChange = window.ValidatorOnChange;
            window.ValidatorOnChange = function(ev) {
                window._ValidatorOnChange(ev);
                ev = $.event.fix(ev);   // Normalizes browser event object.
                var $input = $(ev.target);
                // Selects all labels associated with the input element.
                var $label = $("label[for='" + $input.attr("id") + "']");
                var $callout = $input.data("callout");
                var vals = $input.attr("Validators");
                if (window.AllValidatorsValid && window.AllValidatorsValid(vals)) {
                    if ($input.hasClass(options.errorInputCssClass)) {
                        $input.removeClass(options.errorInputCssClass);
                        $label.removeClass(options.errorLabelCssClass);
                    }
                    if ($callout) {
                        $callout.trigger("close");
                    }
                } else {
                    if (!$input.hasClass(options.errorInputCssClass)) {
                        $input.addClass(options.errorInputCssClass);
                        $label.addClass(options.errorLabelCssClass);
                    }
                    if ($callout) {
                        $callout.trigger("open");
                    }
                }
            };
        }
        // Plugin implementation.
        return this.each(function() {
            var val = this;
            // Only create callout if controltovalidate has a value.
            if (this.controltovalidate) {
                var $input = $(document.getElementById(this.controltovalidate));
                // Create a separate callout for each input element.
                var $callout = $input.data("callout");
                if (!$callout) {
                    $callout = $("<div/>")
                    .appendTo(document.body)
                    .addClass(options.calloutCssClass)
                    .hide()
                    .bind("open", function(ev) {
                        if (_current) {
                            _current.trigger("close");
                        }
                        var pos = $input.offset();
                        _current = $(this).css({
                            position: "absolute",
                            left: Math.floor(pos.left + $input.outerWidth() + options.offsetX),
                            top: Math.floor(pos.top + options.offsetY)
                        }).fadeIn("fast");
                    })
                    .bind("close", function(ev) {
                        $(this).hide();
                        _current = null;
                    });
                    // Add callout pointer
                    $("<span/>").appendTo($callout).addClass(options.pointerCssClass);
                }
                // Move validator inside of callout.
                $callout.append(this);
                // Force "SetFocusOnError" property of the validator to true.
                // This will display the callout for the first validator in error state.
                this.focusOnError = "t";
                // Open callout when input element gains focus.
                $input.focus(function(ev) {
                    if (!val.isvalid) {
                        $callout.trigger("open");
                    }
                });
                // Associate the callout element with the validator.
                $input.data("callout", $callout);
                // Helper function to open/close callout and add/remove error state styles.
                var updateDisplay = function(isValid) {
					
                    // For non-IE browsers, ValidatorUpdateDisplay sets visibility to
                    // show/hide validators, so I use jQuey toggle to set display as well.
                    $(val).toggle(!isValid);
                    // Selects all labels associated with the input element.
                    var $label = $("label[for='" + $input.attr("id") + "']");
                    if (!isValid) {
                        if (!$input.hasClass(options.errorInputCssClass)) {
                            $input.addClass(options.errorInputCssClass);
                            $label.addClass(options.errorLabelCssClass);
                            $label.effect("pulsate", null, 200, null);
                        }
                        if (!_current) {
                            $callout.trigger("open");
                        }
                    } else {
                        var vals = $input.attr("Validators");
                        if (window.AllValidatorsValid && window.AllValidatorsValid(vals)) {
                            if ($input.hasClass(options.errorInputCssClass)) {
                                $input.removeClass(options.errorInputCssClass);
                                $label.removeClass(options.errorLabelCssClass);
                            }
                            $callout.trigger("close");
                        }
                    }
                };
                // Overrides evaluationfunction of each validator to update
                // input and label styles according to the validation result.
                if (this.evaluationfunction) {
                    var _evaluationfunction = this.evaluationfunction;
                    
                    this.evaluationfunction = function(val) {
						var isValid = false ;
						if (typeof(_evaluationfunction) == "function"){
							isValid = _evaluationfunction(val);
						}else if (typeof(_evaluationfunction) == "string"){
							var func =  _evaluationfunction + "(val);" ;
							isValid=eval(func) ;
						}
                        
                        updateDisplay(isValid);
                        return isValid;
                    };
                }
                // Set initial state.
//                updateDisplay(val.isvalid);
            }
        });
    };
    $.fn.updnValidatorCallout.defaults = {
        calloutCssClass: "updnValidatorCallout",
        pointerCssClass: "updnValidatorCalloutPointer",
        errorInputCssClass: "updnValidationErrorInput",
        errorLabelCssClass: "updnValidationErrorLabel",
        offsetX: 0,
        offsetY: 0
    };
    $.updnValidatorCallout = {
        attachAll: function(options) {
            if (window.Page_Validators) {
                $(window.Page_Validators).updnValidatorCallout(options);
            }
        }
    };
})(jQuery);/* End of http://www.mentorsphere.com/scripts/jquery.updnvalidatorcallout.js */
/* Start of http://www.mentorsphere.com/scripts/jquery.tabs.js */
/**
 * tools.tabs 1.0.1 - Tabs done rigth.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/tabs.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : November 2008
 * Date: 2009-06-12 11:02:45 +0000 (Fri, 12 Jun 2009)
 * Revision: 1911 
 */ 
(function($) {
		
	// static constructs
	$.tools = $.tools || {version: {}};
	
	$.tools.version.tabs = '1.0.1';
	
	$.tools.addTabEffect = function(name, fn) {
		effects[name] = fn;
	};		
	
	
	var effects = { 
		'default': function(i) { 
			this.getPanes().hide().eq(i).show(); 
		}, 
		
		// custom configuration variable: fadeInSpeed
		fade: function(i) {
			this.getPanes().hide().eq(i).fadeIn(this.getConf().fadeInSpeed);	
		},
		
		slide: function(i) {
			this.getCurrentPane().slideUp("fast");
			this.getPanes().eq(i).slideDown();			 
		},

		horizontal: function(i) {
			
			// store original width of a pane into memory
			if (!$._hW) { $._hW = this.getPanes().eq(0).width(); }
			
			// set current pane's width to zero
			this.getCurrentPane().animate({width: 0}, function() { $(this).hide(); });
			
			// grow opened pane to it's original width
			this.getPanes().eq(i).animate({width: $._hW}, function() { $(this).show(); });			 
		}		
	};   	
	 

	function Tabs(tabs, panes, opts) { 
		
		var self = this;
		var current;

		// generic binding function
		function bind(name, fn) {
			$(self).bind(name, function(e, args)  {
				if (fn && fn.call(this, args.index) === false && args) {
					args.proceed = false;	
				}	
			});
			return self;
		}
		
		// bind all callbacks from configuration
		$.each(opts, function(name, fn) {
			if ($.isFunction(fn)) { bind(name, fn); }
		});
		
		
		// public methods
		$.extend(this, {				
			click: function(i) {
				
				if (i === current) { return self; }
				
				var pane = self.getCurrentPane();				
				var tab = tabs.eq(i);												 
				
				if (typeof i == 'string') {
					tab = tabs.filter("[href=" +i+ "]");
					i = tabs.index(tab);
				}
				
				if (!tab.length) { 
					if (current >= 0) { return self; }
					i = opts.initialIndex;
					tab = tabs.eq(i);
				}				
				
				// possibility to cancel click action
				var args = {index: i, proceed: true};
				$(self).triggerHandler("onBeforeClick", args);				
				if (!args.proceed) { return self; }				
				
				tab.addClass(opts.current);
				
				// call the effect
				effects[opts.effect].call(self, i);
				
				// onClick callback
				$(self).triggerHandler("onClick", args);	
				
				tabs.removeClass(opts.current);	
				tab.addClass(opts.current);											
				current = i;
				return self;
			},
			
			getConf: function() {
				return opts;	
			},

			getTabs: function() {
				return tabs;	
			},
			
			getPanes: function() {
				return panes;	
			},
			
			getCurrentPane: function() {
				return panes.eq(current);	
			},
			
			getCurrentTab: function() {
				return tabs.eq(current);	
			},
			
			getIndex: function() {
				return current;	
			},
			
			next: function() {
				return self.click(current + 1);
			},
			
			prev: function() {
				return self.click(current - 1);	
			}, 
			
			onBeforeClick: function(fn) {
				return bind("onBeforeClick", fn);	
			},
			
			onClick: function(fn) {
				return bind("onClick", fn);	
			}			
		
		});
		
		
		// setup click actions for each tab
		tabs.each(function(i) { 
			$(this).bind(opts.event, function(e) {
				self.click(i);
				if (!opts.history) { 
					return e.preventDefault();
				}
			});			
		});
		
		// enable history plugin
		if (opts.history) {
			tabs.history(function(evt, hash) {
				self.click(hash || 0);		
			});
		}

		// if no pane is visible --> click on the first tab
		if (location.hash) {
			self.click(location.hash);	
		} else {
			self.click(opts.initialIndex);	
		}		
		
		// cross tab anchor link
		panes.find("a[href^=#]").click(function() {
			self.click($(this).attr("href"));		
		});
		
	}
	
	
	// jQuery plugin implementation
	$.fn.tabs = function(query, arg) {
		
		// return existing instance
		var el = this.eq(typeof conf == 'number' ? conf : 0).data("tabs");
		if (el) { return el; }

		
		// setup options
		var opts = {
			tabs: 'a',
			current: 'current',
			onBeforeClick: null,
			onClick: null, 
			effect: 'default',
			history: false,
			initialIndex: 0,			
			event: 'click',
			api:false
		};
		
		if ($.isFunction(arg)) {
			arg = {onBeforeClick: arg};
		}
		
		$.extend(opts, arg);
		
		// install tabs for each items in jQuery		
		this.each(function() {				
			var els = $(this).find(opts.tabs);
			
			if (!els.length) {
				els = $(this).children();	
			}
			
			var panes = query.jquery ? query : $(query);

			el = new Tabs(els, panes, opts);
			$(this).data("tabs", el);	 
		});		
		
		return opts.api ? el: this;		
	};		
		
}) (jQuery); 


//{{{ history plugin

/**
 *	tools.history plugin. execute a callback when browser's 
 * back/forward buttons are pressed.
 *	
 *	Can be used as a separate tool. Example:
 *	
 *	$("ul.tabs a").history(function(hash) {		
 *		
 *	});	
 */
(function($) {
	
	var hash, iframe;		

	// jQuery plugin implementation
	$.prototype.history = function(fn) {
			
		var el = this;
		
		// IE
		if ($.browser.msie) {
			
			// create iframe that is constantly checked for hash changes
			if (!iframe) {
				iframe = $("<iframe />").hide().get(0);
				$("body").append(iframe);
				
				setInterval(function() {
					var idoc = iframe.contentWindow.document;
					var h = idoc.location.hash;
				
					if (hash !== h) {						
						$.event.trigger("hash", h);
						hash = h;
					}
				}, 100);					
			}
			
			// when link is clicked the iframe hash updated
			el.bind("click.hash", function(e) {	
				var doc = iframe.contentWindow.document;
				doc.open().close();				
				doc.location.hash = $(this).attr("href");
			}); 
			
			// pseudoclick of the first item 
			el.eq(0).triggerHandler("click.hash");
			
			
		// other browsers scans for location.hash changes directly withou iframe hack
		} else { 
			setInterval(function() {
				var h = location.hash;
				
				if (el.filter("[href*=" + h + "]").length && h !== hash) {
					hash = h;
					$.event.trigger("hash", h);
				}						
			}, 100);
		}
		 
		// bind a history listener
		$(window).bind("hash", fn);
		
		// return jQuery
		return this;		
	};	
	

})(jQuery); 

//}}}

/* End of http://www.mentorsphere.com/scripts/jquery.tabs.js */
/* Start of http://www.mentorsphere.com/scripts/uif.utilites.js */
/* Cookie Management */
function CreateCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function ReadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function LogoffUser(){
	
	var service = new Identity() ;
	service.LogOff() ;
	CreateCookie("UIFSessionToken", "" );
	var st = document.getElementById("SessionToken") ;
	st.value = "" ;
	window.location.href = "/" ;
}

function EraseCookie(name) {
	CreateCookie(name,"",-1);
}
/* URL Management */
function urlencode( str ) {
    // *     note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Encode Me');
    // *     returns 1: 'Encode+Me%21'
    // *     example 2: urlencode('http://www.google.com/');
    // *     returns 2: 'http%3A%2F%2Fwww.google.com%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {}, tmp_arr = [];
    var ret = (str+'').toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u00DC'] = '%DC';
    histogram['\u00FC'] = '%FC';
    histogram['\u00C4'] = '%D4';
    histogram['\u00E4'] = '%E4';
    histogram['\u00D6'] = '%D6';
    histogram['\u00F6'] = '%F6';
    histogram['\u00DF'] = '%DF';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';

    // Begin with encodeURIComponent
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}
function urldecode( str ) {
    // *     note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Decode+Me%21');
    // *     returns 1: 'Decode Me!'
    // *     example 2: urldecode('http%3A%2F%2Fwww.google.com%2F');
    // *     returns 2: 'http://www.google.com/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    
    var histogram = {};
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u00DC'] = '%DC';
    histogram['\u00FC'] = '%FC';
    histogram['\u00C4'] = '%D4';
    histogram['\u00E4'] = '%E4';
    histogram['\u00D6'] = '%D6';
    histogram['\u00F6'] = '%F6';
    histogram['\u00DF'] = '%DF'; 
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
 
    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing   
    }
    
    // End with decodeURIComponent
    ret = decodeURIComponent(ret);
 
    return ret;
}


function JQueryChannel(options) {            
	options = options || {};            
	this.rpc = function(call) {                
		if (call.request.params.constructor === Array)                    
			throw new Error('Positional parameters are not supported.');                
		var params = [];                
		$.each(call.request.params, function(k, v) {                    
			if (v) params.push(k + '=' + encodeURIComponent(v));                
		});                
		var ajax_REQ = $.ajax({                    
			url: call.url + '/' + call.request.method,                    
			type: 'GET',                    
			jsonp: options.jsonp ? 'jsonp' : null,                    
			cache: options.cache,                    
			data: params.join('&'),                    
			dataType: options.jsonp ? 'jsonp' : 'json',                    
			timeout: 10000,                    
			// TODO error: ...                    
			success: function(data) {                        
				if (ajax_REQ) { ajax_REQ.abort(); }                        
				call.callback(data);                    
			}                
		});            
	}        
}

function ReloadForm(controlID){	
	window.location.reload() ;	
}


// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

;/* End of http://www.mentorsphere.com/scripts/uif.utilites.js */
/* Start of http://www.mentorsphere.com/scripts/uif.loadingpanel.js */

;(function($) { 

$.fn.loadingPanel = function(lpOptions){	
	var lpOpts = $.extend({}, $.fn.loadingPanel.defaults, lpOptions);
	return this.each(function() {
	
		var $lpThis = $(this);
		var lpo = $.meta ? $.extend({}, lpOpts, $lpThis.data()) : lpOpts;
		
		var loadingText = GetStringResource("LoadingPanelText") ;
		var loadingMessage = lpo.loadingMessage ? lpo.loadingMessage : loadingText ;
		
		var panelid = $lpThis.attr("id");
		if (panelid == null || panelid == "") {
			panelid = "loadingPanel" ;
		} else {
			panelid += "overlay" ;
		}
		var panel = $("<div/>")
		    .attr("id", panelid)
			.css({
				"display"	: "block",
				"position"	: "absolute",
                "padding"   : "0px",
                "z-index"   : "3000"
			});
		$lpThis.data("lploadingPanel", panelid);
		
		var imagePanel = $("<div/>")
			.css({
                "text-align"        : "center",
                "vertical-align"    : "middle"
			}) 
			.appendTo(panel);

		var img	= $("<img/>")
			.attr("alt", loadingMessage)
			.appendTo(panel) ;
			
		if (lpo.imageSize == "small"){
			img.attr("src", "http://images.mentorsphere.com/Images/LoaderSmall.gif") ;
		} else if (lpo.imageSize == "medium") {
			img.attr("src", "http://images.mentorsphere.com/Images/LoaderMedium.gif") ;
		}else{
			img.attr("src", "http://images.mentorsphere.com/Images/LoaderLarge.gif") ;		
		}
		
		var textPanel = $("<div/>")
			.css({
                "color"             : "#0071aa",	
                "text-align"        : "center",
                "vertical-align"    : "middle"
			})
			.html(loadingMessage)
			.appendTo(panel) ;
		
		var pos = $lpThis.position();
        var left = pos.left;
        var top = pos.top;
        var height = $lpThis.height();
        var width = $lpThis.width();
                		
		var id = $lpThis.attr("id");
		if (id == null || id == ""){
			id = "loadingPanelOverlay" ;
		}else{
			id += "overlay" ;
		}

        var overlay = $("<div/>")
            .attr("id", id)
            .css({
                "top"               : 0,
                "left"              : 0,
                "height"            : "100%",
                "width"             : "100%",
                "filter"            : "Alpha(Opacity=90)",
                "-moz-opacity"      : "0.9",
                "opacity"           : "0.9",
                "min-height"        : 100,
                "background-color"  : "#FFFFFF",
                "position"          : "absolute",
                "z-index"           : "2000"
            })
            .corner()
            .appendTo($lpThis);

		$lpThis.data("lpOpenedOverlay", id);
					
        panel.appendTo(overlay);
        
	    var panelTop = ($lpThis.height() / 2) - (panel.height() / 2);
	    var panelLeft = ($lpThis.width() / 2) - (panel.width() / 2);
		panel.css({				
			"top"	: panelTop,
			"left"	: panelLeft
		});
	});

};

$.fn.closeLoadingPanel = function(lpOptions){	
	var lpOpts = $.extend({}, $.fn.loadingPanel.defaults, lpOptions);
	return this.each(function() {
		var $lpThis = $(this);
		$("#" + $lpThis.data("lploadingPanel")).remove();
		$("#" + $lpThis.data("lpOpenedOverlay")).remove();
	}) ;
};

$.fn.loadingPanel.defaults = {
	imageSize			: "medium",
	displayMessage		: true ,
	modal				: true
	
};

})(jQuery);/* End of http://www.mentorsphere.com/scripts/uif.loadingpanel.js */
/* Start of http://www.mentorsphere.com/scripts/uif.dialog.js */
var dialogOptions = new Object() ;

;(function($) { 

$.fn.dialog = function(options){	
	var opts = $.extend({}, $.fn.dialog.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
//		var o  = opts;
		
		/*
		| Cap		|
		| Title		|
		| Body		|
		| Footer	|
		
		Cap:
		|Cap Left	| Cap Center | Cap Right |
		
		Title:
		|Title Left	| Title Center	| Title Right |
		
		Title Center:
		| <span> Caption </span>	|
		 
		Title Right:
		| Close Button (anchor) |
		 
		Body:
		
		
		Footer:
		| Footer Left | Footer Center | Footer Right |
					
		*/
	
		// we start the work here
		
		// 0 set up the control's context so that we can close it later on
		var status = $this.data("uifdialog") ;
		if (status == "on"){
			return ;
		}
		$this.data("layoutParent", $this.parent()) ;
		$this.data("uifdialog", "on") ;
		
		
		// 1 Build the container
		var container = $("<div/>")
			.addClass(o.containerCss)
			.css({
				"overflow-x": "hidden",
				"overflow-y": "hidden",
				"z-index"	: o.zIndex,
				"position"	: "absolute",
				"display"	: "none"
			})
			.attr("tabindex", "-1")
			.attr("unselectable", "on") 
			.css('outline', 0)
			.data("dialogSelector", "#" + this.id)
			.keydown(function(event) {
					if (options.closeOnEscape && event.keyCode
						&& event.keyCode == $.ui.keyCode.ESCAPE ){
						$($(this).data("dialogSelector")).dialogClose() ;
					}
				})
			.attr("role", "dialog")  ;
			
			
		// 2 Build the cap that will be the top of the dialog
		var cap = $("<div/>")
			.addClass(o.capCss)
			.appendTo(container) ;		
			
		var capLeft	= $("<div/>")
			.addClass(o.capLeftCss)
			.appendTo(cap) ;
			
		var capRight = $("<div/>")
			.addClass(o.capRightCss)
			.appendTo(cap) ;
		
		var capCenter = $("<div/>")
			.addClass(o.capCenterCss)
			.appendTo(cap) ;	
		
		// 3 Build the title bar
		var titleBar = $("<div/>")
			.addClass(o.titleBarCss)
			.appendTo(container) ;
		
		var titleBarLeft = $("<div/>")
			.addClass(o.titleLeftCss)
			.appendTo(titleBar) ;
			
		var titleBarRight = $("<div/>")
			.addClass(o.titleRightCss)
			.appendTo(titleBar) ;
		
		var titleBarCenter = $("<div/>")
			.addClass(o.titleCenterCss)
			.appendTo(titleBar) ;	
			
		if (o.draggable){
			titleBar.addClass(o.titleBarCenter) ;
		}		
		
		var title = $("<span/>")
			.addClass(o.titleCaptionCss)			
			.html(o.title)
			.appendTo(titleBarCenter);		
			
		// 4 Attach the close button to the box
		var closeButton = $("<a/>") 
			.addClass(o.dialogCloseCss) 
			.attr("unselectable", "on") 
			.html("&nbsp;")
			.data("dialogSelector", "#" + this.id)
			.click(function () {
				var selector = $(this).data("dialogSelector") ;
				$(selector).dialogClose(o) ;
			})
			.appendTo(titleBarRight) ;
		
		// 5 Layout the body
		var body = $("<div/>")
			.addClass(o.dialogBodyCss) 
			.appendTo(container) ;
		
		container.appendTo($this.parent()) ;
		$this.appendTo(body) ;
		
		// 6 Add resize handler to the body object
		
		var resizer = $("<div/>")
			.addClass(o.resizeHandlerCss) 
			.appendTo(body) ;
		
		// 7 Build the footer	
		var footer = $("<div/>")
			.addClass(o.footerCss)
			.appendTo(container) ;		
			
		var footerLeft	= $("<div/>")
			.addClass(o.footerLeftCss)
			.appendTo(footer) ;
			
		var footerRight = $("<div/>")
			.addClass(o.footerRightCss)
			.appendTo(footer) ;
		
		var footerCenter = $("<div/>")
			.addClass(o.footerCenterCss)
			.appendTo(footer) ;				
		
		
		// 8 set the body height
		var containerHeight = container.css({
				height: 'auto',
				width: o.width
			}).height();
			
		body.height(o.height - containerHeight) ;
		dialogOptions["bodyHeight"] = o.height - containerHeight -20;
			
		if (o.center){
			var win  = $(window) ;
			var left = ((win.width() - o.width) / 2) + win.scrollLeft();
			var top = ((win.height() - o.height) / 2) + win.scrollTop();
		
			container.css({ left : left, top : top }) ;
		}else{
			container.css({ left : o.left, top : o.top }) ;
		}		
				
		// 20 Compose all of the objects and show the durn thing
		if (o.draggable){	
			container.draggable({ handle: "." + o.titleBarCss }) ;
		}
		
		if (o.resizable) {
			body.resizable(
				{
					handler : "." + o.resizeHandlerCss,
					min		: { width: o.minWidth, height: o.minHeight } ,
					max		: { width: o.maxWidth, height: o.maxHeight } ,
					onResize: function(e) {
						var targetSize = e.data.resizeData.target.width() + 4 ;
						var targetHeight = e.data.resizeData.target.height() - 4 ;
						var parent = e.data.resizeData.target.parent();						
	                    var frame = parent.find("iframe") ;
	                    if (frame.length > 0){
							
							var frameBody = frame.contents().find("body") ;
							frameBody.width(targetSize) ;
							frameBody.height(targetHeight) ;
							frame.width(targetSize) ;
							frame.height(targetHeight) ;
	                    }
	                    
						parent.width(targetSize) ;
					} 
				}
			) ;
		}		
		
		if (o.autoOpen){

			$this.dialogOpen(o) ;
		} 
		
	});

};
$.fn.dialogClose = function(options){	
	var opts = $.extend({}, $.fn.dialog.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
	
		var status = $this.data("uifdialog") ;
		var clear = $this.data("clearContent") ;
		if (status == "on"){
			var container = $this.parent().parent() ;
			var layoutParent = $this.data("layoutParent") ;
			
			var overlayId = $this.data("openedOverlay") ;
			if (overlayId != null && overlayId != ""){
				$("#" + overlayId).remove() ;
//				$this.closeOverlay() ;			
			}
			
			container.hide() ;
			if (clear == "yes"){
				$this.html("") ;
			}
			$this.css("display", "none") ;
			$this.appendTo(layoutParent) ;
			container.remove() ;
			$this.removeData("uifdialog") ;
			if (o.onclose != null && typeof(o.onclose) == "function"){
				
				o.onclose() ;
			}
		}			
	});

};

$.fn.dialogOpen = function(options){	
	var opts = $.extend({}, $.fn.dialog.defaults, options);
	return this.each(function() {
		var $this = $(this);
		$this.css("height", "100%") ;
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		
		var status = $this.data("uifdialog") ;
		if (status == "on"){
			
			var container = $this.parent().parent() ;
			var body = $this.parent() ;
			if (o.modal){				
				var id = $this.id ;
				
				if (id == null || id == ""){
					id = "dialogOverlay" ;
				}else{
					id += "overlay" ;
				}
			
				$this.data("openedOverlay", id) ;
				
				$("<div/>")
					.attr("id", id)
					.addClass(o.modalOverlayCss)
					.appendTo(document.body) ;
//				$this.jOverlay() ;
			}	
			
			container.show(o.showEffect) ;	
			if (o.showLoadingPanel == true){
				$this.loadingPanel() ;			
			}
			
			container.bgiframe() ;		
			if (o.content != null){
				$this.data("clearContent", "yes") ;
				$this.html(o.content) ;
			}else if (o.contentId != null){
				$this.data("clearContent", "yes") ;
				$this.html($(o.contentId).html()) ;
			}else if (o.contentUrl != null){
				$this.data("clearContent", "yes") ;
				var frame = '<iframe id="popupFrame" frameborder="0" scrolling="none"' + 
				'style="height:' + body.height() + 'px;width:100%" src="' + o.contentUrl + '">' + 
				'</iframe>' ;
				$(frame).appendTo($this) ;				

			}
			$this.show(o.showEffect)
		}
		
	});

};

$.fn.dialog.defaults = {
	height				: 200,
	width				: 200,
	zIndex				: 2000,
	title				: "Dialog",
	containerCss		: "dialog",
	capCss				: "dialogCap",
	capLeftCss			: "dialogCapLeft",
	capRightCss			: "dialogCapRight",
	capCenterCss		: "dialogCapCenter",
	titleBarCss			: "dialogTitlebar",
	titleLeftCss		: "dialogTitleLeft",
	titleCenterCss		: "dialogTitleCenter",
	titleRightCss		: "dialogTitleRight",
	titleCaptionCss		: "dialogCaption",
	dialogCloseCss		: "dialogCloseButton",
	dialogBodyCss		: "dialogContainerBody",
	footerCss			: "dialogFooter",
	footerLeftCss		: "dialogFooterLeft",
	footerRightCss		: "dialogFooterRight",
	footerCenterCss		: "dialogFooterCenter",
	resizeHandlerCss	: "dialogResizeHandler"	,
	minWidth			: 100,
	minHeight			: 100,
	maxWidth			: 1024,
	maxHeight			: 768,
	draggableCss		: "dialogDraggable",
	draggable			: true,
	resizable			: true,
	showEffect			: "",
	hideEffect			: "",
	closeOnEscape		: true,
	center				: true,
	left				: 100,
	top					: 100,
	autoOpen			: true ,
	modal				: true,
	modalOverlayCss		: "dialogModalOverlay",
	showLoadingPanel	: true,
	onclose				: null
	
	
};

})(jQuery);/* End of http://www.mentorsphere.com/scripts/uif.dialog.js */
/* Start of http://www.mentorsphere.com/scripts/uif.buttons.js */

;(function($) { 

$.fn.linkButton = function(options){	
	var opts = $.extend({}, $.fn.linkButton.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		$this.empty() ;
		var buttonSpan = $("<span/>")
			//.html(o.caption)
			.appendTo($this)
			.css("cursor", "pointer")
			.css("text-decoration", "none") 
			.hover(
				function(){
					$(this).css("text-decoration", "underline") ;
				},
				function(){
					$(this).css("text-decoration", "none") ;
				}
			)
			.data("orient", o.orient) 
			.data("align", o.align);
			
		var captionDiv = $("<span/>")
		    .appendTo(buttonSpan)
		    .css("width", "99%")
		    .html(o.caption);
		    
		var tooltip = o.tooltip	? o.tooltip : "" ;
		if (tooltip != null && tooltip.length > 0){
			$this.attr("title", tooltip) ;
			
			buttonSpan
				.data("tip", tooltip)
				.hover(
					function() {
						var $this = $(this);
						var or = $this.data("orient") ? $this.data("orient") : "above" ;
						var al = $this.data("align") ? $this.data("align") : "right" ;
						var tt = $this.data("tip") ? $this.data("tip") : "Press this button" ;
						$this.callout(
						{						
		                    text	        : tt,
		                    cornerRadius    : "5px",
		                    displayClass    : "testCallout", //"validationMessage"
		                    orient	        : "top",
		                    width           : "200px"
						}
						)
						.click(function() {
							$(this).closeCallout() ;
						}
						);
									
					},
					function() {
						$(this).closeCallout() ;
					}
				);
		}			
		
	});

	
};

$.fn.iconButton = function(options){	
	var opts = $.extend({}, $.fn.linkButton.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		$this.empty() ;
		
		var iconClass = o.iconClass ? o.iconClass : "" ;
		var iconHoverClass = o.iconHoverClass ? o.iconHoverClass : "" ;		
		var tooltip = o.tooltip	? o.tooltip : "" ;
		if (iconClass != null && iconClass.length > 0){						
			var buttonSpan = $("<span/>")				
				.prependTo($this)
				.addClass("iconButton")
				.addClass(iconClass)
				.data("orient", o.orient) 
				.data("align", o.align)
				.data("iconClass", iconClass)
				.data("iconHoverClass", iconHoverClass)
				.data("tip", tooltip)
				.hover(
					function(){
						var $this = $(this);
						
						var tt = $this.data("tip") ? $this.data("tip") : "" ;
						var iconClass = $this.data("iconClass") ? $this.data("iconClass") : "" ;
						var iconHoverClass = $this.data("iconHoverClass") ? $this.data("iconHoverClass") : "" ;
						
						if (tt != null && tt.length > 0){
							var or = $this.data("orient") ? $this.data("orient") : "above" ;
							var al = $this.data("align") ? $this.data("align") : "right" ;
							
							$this.callout({
		                        text	        : tt,
		                        cornerRadius    : "5px",
		                        displayClass    : "testCallout", //"validationMessage"
		                        orient	        : "top",
		                        width           : "200px"						
							})
							.click(function() {
								$(this).closeCallout() ;
							}
							);		
						}
						if (iconHoverClass != null && iconHoverClass.length > 0){
							$this.removeClass(iconClass) ;
							$this.addClass(iconHoverClass) ;
						}
					},
					function(){
						var $this = $(this);
						
						var tt = $this.data("tip") ? $this.data("tip") : "" ;
						var iconClass = $this.data("iconClass") ? $this.data("iconClass") : "" ;
						var iconHoverClass = $this.data("iconHoverClass") ? $this.data("iconHoverClass") : "" ;
						
						if (tt != null && tt.length > 0){							
							$this.closeCallout();
						}
						if (iconHoverClass != null && iconHoverClass.length > 0){
							$this.addClass(iconClass) ;
							$this.removeClass(iconHoverClass) ;
						}
					}
				)
				.css("cursor", "pointer") ;
				
			
			
		}
		
	});	
};

$.fn.iconFormButton = function(options){	
	var opts = $.extend({}, $.fn.linkButton.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		$this.empty() ;
		
		var iconClass = o.iconClass ? o.iconClass : "" ;
		var iconHoverClass = o.iconHoverClass ? o.iconHoverClass : "" ;
		
		$this
			.addClass(o.cssClass)
			.css("text-decoration", "none") 
			.data("iconClass", iconClass)
			.data("iconHoverClass", iconHoverClass)
			.data("cssClass", o.cssClass)
			.data("cssClassHover", o.cssClassHover)
			.hover(
				function(){
					var $this = $(this);
					$this												
						.css({							
							"cursor" : "pointer"
						})
						.addClass($this.data("cssClassHover")) 
						.corner("5px top bottom") ;
						
					var iconClass = $this.data("iconClass");
					var iconHoverClass = $this.data("iconHoverClass");
					if (iconClass != null && iconClass.length > 0 &&
						iconHoverClass != null && iconHoverClass.length > 0){
						var childSpan = $this.children("." + iconClass) ;
						if (childSpan.length > 0){
							childSpan.removeClass(iconClass) ;
							childSpan.addClass(iconHoverClass) ;
						}
					}
				},
				function(){
					var $this = $(this);
					$this
						.removeClass($this.data("cssClassHover"))
						
						.css({							
							"cursor" : "pointer"
						})						
						.uncorner() 
					;
					var iconClass = $this.data("iconClass");
					var iconHoverClass = $this.data("iconHoverClass");
					if (iconClass != null && iconClass.length > 0 &&
						iconHoverClass != null && iconHoverClass.length > 0){
						var childSpan = $this.children("." + iconHoverClass) ;
						if (childSpan.length > 0){
							childSpan.removeClass(iconHoverClass) ;
							childSpan.addClass(iconClass) ;
						}
					}
				}
			)
			.linkButton(o) ;
			
		var iconClass = o.iconClass ? o.iconClass : "" ;
		if (iconClass != null && iconClass.length > 0){						
			var buttonSpan = $("<span/>")				
				.prependTo($this)
				.addClass("iconButton")
				.addClass(iconClass)
				.data("orient", o.orient) 
				.data("align", o.align)
				.css("cursor", "pointer") ;
				
			var tooltip = o.tooltip	? o.tooltip : "" ;
			if (tooltip != null && tooltip.length > 0){
				buttonSpan
					.data("tip", tooltip)
					.hover(
					function() {
						var $this = $(this);
						var or = $this.data("orient") ? $this.data("orient") : "above" ;
						var al = $this.data("align") ? $this.data("align") : "right" ;
						var tt = $this.data("tip") ? $this.data("tip") : "Press this button" ;
						$this.callout(
						{
		                    text	        : tt,
		                    cornerRadius    : "5px",
		                    displayClass    : "testCallout", //"validationMessage"
		                    orient	        : "top",
		                    width           : "200px"						
						}
						);			
					},
					function() {
						$(this).closeCallout() ;
					}
				);
			}				
		}	
	});	
};

$.fn.formButton = function(options){	
	var opts = $.extend({}, $.fn.linkButton.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		$this.empty() ;
		
		$this
			.addClass(o.cssClass)
			.data("cssClass", o.cssClass)
			.data("cssClassHover", o.cssClassHover)
			.hover(
				function(){
					var $this = $(this);
					$this
						.addClass($this.data("cssClassHover"))
						.corner("5px top bottom") 
						
					;
				},
				function(){
					var $this = $(this);
					$this
						.removeClass($this.data("cssClassHover"))						
						.uncorner() 
					;
				}
			)
			.linkButton(o) ;
		
	});	
};


$.fn.formOkButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "okCheck", iconHoverClass : "okCheckHover", caption : GetStringResource("OKCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};
$.fn.formCancelButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "cancelButton", iconHoverClass : "cancelButtonHover", caption : GetStringResource("CancelCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formEditButton = function(options){		
	return this.each(function() {
		var o = $.extend(options, {iconClass : "editButton", iconHoverClass : "editButtonHover", caption : GetStringResource("EditButtonToken"), tooltip: GetStringResource("EditRecordTooltip"), align: "right"});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formDeleteButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "deleteButton", iconHoverClass : "deleteButtonHover", caption : GetStringResource("DeleteCaption"), tooltip: GetStringResource("DeleteRecordTooltip"), align: "right"});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formSaveButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "saveButton", iconHoverClass : "saveButtonHover", caption : GetStringResource("SaveRecordCaption")});
		var $this = $(this);			
		$this.iconFormButton(o) ;
	});	
};

$.fn.formAddButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "addButton", iconHoverClass : "addButtonHover", caption : GetStringResource("AddRecordCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formFilterButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "filterButton", iconHoverClass : "filterButtonHover", caption : GetStringResource("GridSearchCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};
$.fn.formClearFilterButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "clearFilterButton", iconHoverClass : "clearFilterButtonHover", caption : GetStringResource("ClearGridSearchCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formExpandButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "expandButton", iconHoverClass: "expandButtonHover", caption : GetStringResource("ExpandButtonCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formCollapseButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "collapseButton", iconHoverClass: "collapseButtonHover", caption : GetStringResource("CollapseButtonCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formMoreButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "moreButton", iconHoverClass: "moreButtonHover", caption : GetStringResource("MoreButtonCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formDetailsButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "detailsButton", iconHoverClass: "detailsButtonHover", caption : GetStringResource("DetailsButtonCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formMailButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "mailButton", iconHoverClass: "mailButtonHover", caption : GetStringResource("SendMessageCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.formReplyButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "replyMessageButton", iconHoverClass: "replyMessageButtonHover", caption : GetStringResource("ReplyToMessageCaption")});
		var $this = $(this);
		$this.iconFormButton(o) ;
	});	
};

$.fn.iconOkButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "okCheck", iconHoverClass : "okCheckHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};
$.fn.iconCancelButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "cancelButton", iconHoverClass : "cancelButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconEditButton = function(options){		
	return this.each(function() {
		var o = $.extend(options, {iconClass : "editButton", iconHoverClass : "editButtonHover", tooltip: GetStringResource("EditRecordTooltip"), align: "right"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconDeleteButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "deleteButton", iconHoverClass : "deleteButtonHover", tooltip: GetStringResource("DeleteRecordTooltip"), align: "right"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconSaveButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "saveButton", iconHoverClass : "saveButtonHover"});
		var $this = $(this);			
		$this.iconButton(o) ;
	});	
};

$.fn.iconAddButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "addButton", iconHoverClass : "addButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconFilterButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "filterButton", iconHoverClass : "filterButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};
$.fn.iconClearFilterButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "clearFilterButton", iconHoverClass : "clearFilterButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconExpandButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "expandButton", iconHoverClass : "expandButtonHover", toolTip: GetStringResource("CollapseButtonToolTip")});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconCollapseButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "collapseButton", iconHoverClass : "collapseButtonHover", toolTip: GetStringResource("ExpandButtonToolTip")});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconMoreButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "moreButton", iconHoverClass : "moreButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconDetailsButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "detailsButton", iconHoverClass : "detailsButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconMailButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "sendMessageButton", iconHoverClass: "sendMessageButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};

$.fn.iconReplyButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "replyMessageButton", iconHoverClass: "replyMessageButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};


$.fn.closeWidgetButton = function(options){	
	return this.each(function() {
		var o = $.extend(options, {iconClass : "closeWidgetButton", iconHoverClass : "closeWidgetButtonHover"});
		var $this = $(this);
		$this.iconButton(o) ;
	});	
};



$.fn.linkButton.defaults = {
	caption			: "Button",
	orient			: "above",
    align			: "left",
    cssClass		: "formButton",
    cssClassHover	: "formButtonHover"
};

})(jQuery);/* End of http://www.mentorsphere.com/scripts/uif.buttons.js */
/* Start of http://www.mentorsphere.com/scripts/uif.part.js */
;(function($) { 

$.fn.part = function(options){	
	var opts = $.extend({}, $.fn.part.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		
		var partName = o.name ? o.name : "uifWebPart" ;
		
		var isOpen = $this.data("isOpenPart") ;
		var partDiv ;
		
		if (isOpen){
			partDiv = $("#" + partName) ;
			if (o.sourceControlId != null && o.sourceControlId != undefined && o.sourceControlId.length > 0){
				$("#" + o.sourceControlId)
					.effect('transfer',{to: "#" + partName }, 500) ;
			}
			
			if (o.scrollTo){
				$("html,body").animate({scrollTop: partDiv.offset().top}, 500) ;	
			}	
			return ;
		}
		$this.loadingPanel() ;
		$this.data("isOpenPart", true);
		
		var contentUrl = o.contentUrl ;
		
		var userSettingRoot = o.settingName ;
		if (o.autoSaveSettings && userSettingRoot != null && userSettingRoot != undefined && userSettingRoot.length > 0){
			
			SaveUserSettingValue(userSettingRoot + ".Open","true") ;
		}
		
		var parentContainerName  = o.parentContainer ? o.parentContainer : "form" ;
		var parentContainer = null ;
		if (parentContainerName == "form"){
			parentContainer = $("form") ;
		}else{
			parentContainer = $("#" + parentContainerName) ;
		}
		
		var columnCount = 0 ;
		
		partDiv = $("<div>")
			.attr("id", partName)
			.css({
				width	: o.width,
				display	: "none",
				padding	: o.padding,
				"z-index": 300
			})
			.appendTo(parentContainer) ;	
			
		if (o.partClass != null){
			partDiv.addClass(o.partClass) ;
		}		
		
		var layoutTable = $("<table/>")
			.attr("cellspacing", "0")
			.attr("cellpadding", "0")
			.attr("border", "0")
			.attr("width", "99%")
			.attr("id", partName + "LayoutTable") 
			.appendTo(partDiv);	
					
		var layoutTopRow = $("<tr/>")
			.appendTo(layoutTable) ;				
			
		var iconClass = o.iconClass ;
		if (iconClass != null && iconClass != undefined && iconClass.length > 0){			
			var iconCell = $("<td/>")
				.css({
					width				: "24px",
					"vertical-align"	: "middle"
				})
				.appendTo(layoutTopRow) ;
				
			var iconSpan = $("<span/>")
				.css({
					width	: "22px",
					height	: "20px",
					display	: "inline-block",
					padding	: "0"
					
				})
				.attr("id", partName + "Icon")
				.addClass("partIcon")
				.addClass(iconClass)				
				.data('tooltip', o.caption)
				.data('ttalign', 'left').tooltip()
				.appendTo(iconCell) ;
				
			columnCount++ ;	
		}
		
		var captionCell = $("<td/>")
			.css({
					"vertical-align"	: "middle", width: o.captionWidth
				})		
			.attr("id", partName + "CaptionColumn")		
			.appendTo(layoutTopRow) ;
			
		columnCount++ ;	
		
		var headerDiv = $("<div/>").appendTo(captionCell) ;
		
		if (o.dock != null && o.dock instanceof Array) {
			headerDiv.addClass("yui-gb") ;
		}else{
			headerDiv.addClass("yui-gc") ;
		}
		var headerLeftDiv = $("<div/>")
								.addClass("yui-u")
								.addClass("first")
								.css({"margin-top": "8px", "width" : "45%"})
								.appendTo(headerDiv) ;			
		
		var expandedSetting = o.defaultExpand ;
		if (o.allowCollapse){
        } else {
            headerLeftDiv.html("<h" + o.captionDepth + ">" + o.caption + "</h" + o.captionDepth + ">") ;
        }
		    
		var dockDiv = $("<div/>")  ;
		if (o.dock != null && o.dock instanceof Array) {
			dockDiv.addClass("yui-u")
				.css({"margin-bottom": "5px"})
				.appendTo(headerDiv) ;	
		}
										
		var headerRightDiv = $("<div/>") 
								.addClass("yui-u")
								.css({"text-align": "right", "margin-bottom": "5px", "width": "50%"})
								.appendTo(headerDiv) ;
		
		var buttonDiv = $("<div/>").addClass("yui-gc").css({"width": "99%"}).appendTo(headerRightDiv) ;
		var buttonLeftDiv = $("<div/>") 
								.addClass("yui-u")
								.addClass("first")
								.appendTo(buttonDiv) ;
							
								
		var buttonRightDiv = $("<div/>") 
								.addClass("yui-u")
								.css({"text-align": "right", "margin-bottom": "5px"})
								.appendTo(buttonDiv) ;
				
		var buttonPane = $("<div/>").addClass("formButtonPane").appendTo(buttonRightDiv);
		var buttonContainer = $("<ul/>").addClass("formButtonContainer").appendTo(buttonPane);
		
		if (o.buttons != null && o.buttons instanceof Array) {
			var customButtonPane = $("<div/>").addClass("formButtonPane").appendTo(buttonLeftDiv);
			var customButtonContainer = $("<ul/>").addClass("formButtonContainer").appendTo(customButtonPane);
			
			for (var i = 0; i < o.buttons.length; i++){			
				var li = $("<li/>").appendTo(customButtonContainer) ;
				o.buttons[i].appendTo(li);
			}
		}
		
		
		
								
								
		if (o.dock != null && o.dock instanceof Array) {
			for (var i = 0; i < o.dock.length; i++){
				o.dock[i].prependTo(dockDiv);
			}
		}
		if (o.fullPageUrl != null && o.fullPageUrl != undefined && o.fullPageUrl.length > 0){
			var fullPageCell = $("<li/>")				
				.appendTo(buttonContainer) ;					
				
			var fullPageButton = $("<a/>")				
				.attr("href", o.fullPageUrl)
				.appendTo(fullPageCell)
				.iconMoreButton() ;
				
		}
		
		//var expandedSetting = o.defaultExpand ;
		
		if (o.allowCollapse){
			var expandCell = $("<li/>")				
				.appendTo(buttonContainer) ;
			
			if (userSettingRoot != null && userSettingRoot.length > 0){				
				expandedSetting = GetUserSettingValue(userSettingRoot + ".Expanded") ;
				
				if (expandedSetting == null || expandedSetting.length == 0){				
					expandedSetting = o.defaultExpand ;
				}	
			}
		
			var expandButton = $("<a/>")					
				.data("IsExpanded", expandedSetting) 
				.data("userSettingRoot", userSettingRoot)
				.data("fullCollapse", o.fullCollapse) 
				.data("bodyName", partName + "Body") 
				.data("partName", partName)
				.data("partWidth", o.width)
				.data("bodyRowName", partName + "BodyRow")
				.data("iconButton", partName + "Icon")
				.data("captionColumnName", partName + "CaptionColumn")				
				.attr("id", partName + "CollapseButton")	
				.click( function(){
						var $this = $(this) ;
						var userSettingRoot = $this.data("userSettingRoot") ;
						var expanded = $this.data("IsExpanded") ;
						var fullCollapse = $this.data("fullCollapse") ;
						var part = $("#" + $this.data("partName") );
						if (expanded == "true"){
							$this.data("IsExpanded", "false");
							$("#" + partName + "CaptionCollapseButton").data("IsExpanded", "false");
							if (fullCollapse){
								$("#" + $this.data("bodyRowName")).hide();
								$("#" + $this.data("captionColumnName")).hide();
								part.css("width", "25px") ;
								part.css("height", "20px") ;
								part.removeClass(o.partClass);
//								if (o.corner){
//									part.uncorner();
//								}
							} else {
								$("#" + $this.data("bodyName")).hide("blind");
								
							}
							$this.empty().iconExpandButton();
							
							if (userSettingRoot != null && userSettingRoot != undefined && userSettingRoot.length > 0){								
								SaveUserSettingValue(userSettingRoot + ".Expanded","false") ;
							}
							if (o.oncollapse != null && typeof(o.oncollapse) == "function"){
								o.oncollapse() ;
							}	
						}else{
							$this.data("IsExpanded", "true");
							$("#" + partName + "CaptionCollapseButton").data("IsExpanded", "true");
							if (fullCollapse){
								part.css("width", $this.data("partWidth")) ;
								part.addClass(o.partClass);
								part.css("height", "auto") ;
								$("#" + $this.data("bodyRowName")).show();
								$("#" + $this.data("captionColumnName")).show();
//								if (o.corner){
//									part.uncorner().corner();
//								}
							}else{
								$("#" + $this.data("bodyName")).show("blind");								
							}
							$this.empty().iconCollapseButton();
									
							if (userSettingRoot != null && userSettingRoot != undefined && userSettingRoot.length > 0){								
								SaveUserSettingValue(userSettingRoot + ".Expanded","true") ;
							}	
							if (o.onexpand != null && typeof(o.onexpand) == "function"){
								o.onexpand() ;
							}	
						}	
					}
				)			
				.appendTo(expandCell);
				
			//caption expand/collapse
		    var captionDiv = $("<div/>")
		        .css("cursor", "pointer")
		        .appendTo(headerLeftDiv)
		        .html("<h" + o.captionDepth + ">" + o.caption + "</h" + o.captionDepth + ">")
			    .data("IsExpanded", expandedSetting) 
			    .data("userSettingRoot", userSettingRoot)
			    .data("fullCollapse", o.fullCollapse) 
			    .data("bodyName", partName + "Body") 
			    .data("partName", partName)
			    .data("partWidth", o.width)
			    .data("bodyRowName", partName + "BodyRow")
			    .data("iconButton", partName + "Icon")
			    .data("captionColumnName", partName + "CaptionColumn")				
			    .attr("id", partName + "CaptionCollapseButton")	
			    .click( function(){
					    var $this = $(this) ;
					    var userSettingRoot = $this.data("userSettingRoot") ;
					    var expanded = $this.data("IsExpanded") ;
					    var fullCollapse = $this.data("fullCollapse") ;
					    var part = $("#" + $this.data("partName") );
					    if (expanded == "true"){
						    $this.data("IsExpanded", "false");
						    $("#" + partName + "CollapseButton").data("IsExpanded", "false");
						    if (fullCollapse){
							    $("#" + $this.data("bodyRowName")).hide();
							    $("#" + $this.data("captionColumnName")).hide();
							    part.css("width", "25px") ;
							    part.css("height", "20px") ;
							    part.removeClass(o.partClass);
						    } else {
							    $("#" + $this.data("bodyName")).hide("blind");
						    }
						    if (userSettingRoot != null && userSettingRoot != undefined && userSettingRoot.length > 0){								
							    SaveUserSettingValue(userSettingRoot + ".Expanded","false") ;
						    }
						    if (o.oncollapse != null && typeof(o.oncollapse) == "function"){
							    o.oncollapse() ;
						    }	
					    }else{
						    $this.data("IsExpanded", "true");
						    $("#" + partName + "CollapseButton").data("IsExpanded", "true");
						    if (fullCollapse){
							    part.css("width", $this.data("partWidth")) ;
							    part.addClass(o.partClass);
							    part.css("height", "auto") ;
							    $("#" + $this.data("bodyRowName")).show();
							    $("#" + $this.data("captionColumnName")).show();
						    }else{
							    $("#" + $this.data("bodyName")).show("blind");								
						    }
						    if (userSettingRoot != null && userSettingRoot != undefined && userSettingRoot.length > 0){								
							    SaveUserSettingValue(userSettingRoot + ".Expanded","true") ;
						    }	
						    if (o.onexpand != null && typeof(o.onexpand) == "function"){
							    o.onexpand() ;
						    }	
					    }
				    });
			
			$("#" + partName + "Icon").click( function() { expandButton.click(); }) ;
			
			if (expandedSetting == "true"){
				expandButton.iconCollapseButton();
			}else{
				expandButton.iconExpandButton();
			}
		}
        else {
            headerLeftDiv.html("<h" + o.captionDepth + ">" + o.caption + "</h" + o.captionDepth + ">") ;
        }
		
		if (o.allowClose) {
			var closeCell = $("<li/>")	
						
				.appendTo(buttonContainer) ;
						
			var closeButton = $("<a/>")
				.data("partName", partName) 
				.data("userSettingRoot", userSettingRoot)
				.data("contentID", $(this).attr("id"))			
				.appendTo(closeCell) 
				.click(function()
					{					
						var $this = $(this) ;
						var partDiv = $("#" + $this.data("partName")) ;
						
						var userSettingRoot = $this.data("userSettingRoot") ;
						
	
						var contentDiv = $("#" + $this.data("contentID")) ;
						if (contentDiv != null && contentDiv != undefined && contentDiv.length > 0) {
							contentDiv
								.data("isOpenPart", false)
								.hide()
								.appendTo(partDiv.parent()) ;
								
							
						}
						
						partDiv.remove() ;
						if (o.autoSaveSettings && userSettingRoot != null && userSettingRoot != undefined && userSettingRoot.length > 0){
							
							SaveUserSettingValue(userSettingRoot + ".Open","false") ;
						}	
					}
				)
				.closeWidgetButton();
						
			columnCount++ ;	
		}	
		
		var bodyRow = $("<tr/>")
			.attr("id", partName + "BodyRow")
			.appendTo(layoutTable) ;		
					
		var bodyCell = $("<td/>")			
			.attr("colSpan", columnCount)
//			.css("width", "100%")
			.appendTo( bodyRow ) ;	
			
		var bodyDiv = $("<div/>")
			.attr("id", partName + "Body")
			.appendTo( bodyCell ) ;					
		
		if (contentUrl != null && contentUrl != undefined && contentUrl.length > 0){
			var contentFrame = $("<iframe/>")
				.attr("frameBorder", "0")
				.attr("id", partName + "ContentFrame")	
				.data("expanded", false) 
				.css({
					width	:"99%",
					height	:"99%"
				})
				.attr( "src", contentUrl ) 					
				.appendTo( bodyDiv ) ;
		}
		
		if (o.allowCollapse && (expandedSetting == "false" || !expandedSetting)){
			
			if (o.fullCollapse){
				
				$("#" + partName + "BodyRow").hide();
				$("#" + partName + "CaptionColumn").hide();
				$("#" + partName).css("width", "25px") ;
				$("#" + partName).css("width", "20px") ;
				$("#" + partName).removeClass(o.partClass);
//				if (o.corner){					
//					$("#" + partName).uncorner();
//				}
			}else{
				bodyDiv.hide() ;
			}
			if (o.oncollapse != null && typeof(o.oncollapse) == "function"){
				o.oncollapse() ;
			}
		}else{
			if (o.onexpand != null && typeof(o.onexpand) == "function"){
				o.onexpand() ;
			}		
		}
		// now we can show this thing
		if (contentUrl != null && contentUrl != undefined && contentUrl.length > 0){
//			partDiv.appendTo(parentContainer) ;
		}else{
//			partDiv.appendTo(parentContainer) ;
			$this.appendTo(bodyDiv) ;			
		}
		
		if (o.onload != null && o.onload != undefined && typeof(o.onload) == "function"){
			o.onload() ;
		}
		
		$(this).css({display:"block"});			
		partDiv.css({display:"block"});
		if (o.sourceControlId != null && o.sourceControlId != undefined && o.sourceControlId.length > 0){
			$("#" + o.sourceControlId)
				.effect('transfer',{to: "#" + partName }, 500) ;
		}
		if (o.scrollTo){
			$("html,body").animate({scrollTop: partDiv.offset().top}, 500) ;	
		}
		
		if (!o.fullCollapse){
			if (o.corner){
				partDiv.uncorner().corner();
			}
		}else if (o.fullCollapse && (expandedSetting == true || expandedSetting == "true")){			
			if (o.corner){
				partDiv.uncorner().corner();
			}
		}
		
		if (contentUrl != null && contentUrl != undefined && contentUrl.length > 0){
		}else{
			$this.closeLoadingPanel() ;
		}
		
		
		
	});
};

$.fn.part.defaults = {
	name			: "uifWebPart",	
	caption			: "UIF",
	captionDepth	: "3",
	settingName		: null,
	parentContainer	: null,
	iconClass		: null,
	allowCollapse	: true,
	fullPageUrl		: null,	
	contentUrl		: null,	
	scrollTo		: true,
	sourceControlId	: null,	
	width			: "95%",
	allowClose		: true,
	padding			: "5px",	
	defaultExpand	: "true",
	autoSaveSettings: true,
	buttons			: null,
	captionWidth	: "98%",
	buttonWidth		: 100,
	onload			: null,
	fullCollapse	: false,
	partClass		: null,
	corner			: true,
	oncollapse		: null,
	onexpand		: null,
	dock			: null
};

})(jQuery);	
	/* End of http://www.mentorsphere.com/scripts/uif.part.js */
/* Start of http://www.mentorsphere.com/scripts/uif.ui.js */


/* Utilities */
function GetStringResource(token){
	if (resStrings[token] != null){
		return resStrings[token] ;
	}else{
		var service = new ResourceManager() ;
		resStrings[token] = service.GetStringResource(token) ;
		return resStrings[token] ;
	}	
}

function GetUserSettingValue(settingName){
	if (userSettings[settingName] != undefined && userSettings[settingName] != null){
		return userSettings[settingName] ;
	}else{
		var service = new Identity() ;
		return service.GetUserSettingValue(settingName) ;
	}	
}

function SaveUserSettingValue(settingName, settingValue){
	if (userSettings[settingName] != undefined && userSettings[settingName] != null){
		if (userSettings[settingName] == settingValue){
			return ;
		}
	}
	var service = new Identity() ;
	service.SaveUserSettingValue(settingName, settingValue, function(){}) ;
	userSettings[settingName] = settingValue ;
}

/* Modal Management */
function ShowModal( options  ) {
	var name = options.name ? options.name : 'popup' ;
	var sel = "#" + name ;
	var modal = options.modal ? options.modal : true ;
	
	var modalDiv = $(sel) ;
	if (modalDiv.length == 0){
		modalDiv = $("<div/>")
			.addClass("dialogBody") 
			.attr("id", name)
			.appendTo("form") ;
	}
	
	modalDiv.dialog({		
		autoOpen		: true,
		closeOnEscape	: true,
		draggable		: true,
		modal			: modal,
		position		: 'center',
		resizable		: true,		
		title			: options.title,
		height			: options.height,
		width			: options.width,
		contentUrl		: options.contentUrl,
		content			: options.content,
		contentId		: options.contentId
	});
	
}

function CloseModal(modalName){
	var name = modalName ? modalName : 'popup' ;
	var sel = "#" + name ;
	$(sel).dialogClose() ;
}

function ShowMessageBox(options){
	var okText = options.OKText ? options.OKText : GetStringResource("AreYouSureYesCaption") ;
	var cancelText =  options.cancelText ? options.cancelText :  GetStringResource("AreYouSureNoCaption");
	var modalName = options.name ? options.name : 'ShowMessageBox' ;
	
	var showCancel = true ;
	if (options.showNoButton != null && options.showNoButton == false){
		showCancel = false;
	}
		
	var modalContents = options.content ? options.content : 'Do you wish to continue?' ;
	
	var content = $("<div/>")
		.html(modalContents) ;
	
	
	
	var buttonPane = $("<div/>")
		.css({
			"position"		: "absolute",
			"padding-right" : "10px"
		})
		.addClass("dialogButtonPane") 
		.appendTo(content);
	
	var buttonContainer = $("<div/>")
		.addClass("dialogButtonContainer") 
		.appendTo(buttonPane);
	
	var okButton = $("<a/>")
		.iconFormButton({iconClass : "okCheck", iconHoverClass : "okCheckHover", caption : okText}) 
		.appendTo(buttonContainer) ;
	
	var yesCallBack = options.yesButtonCallback ;
	
	if (typeof(yesCallBack) == "function") {
		okButton.click(yesCallBack) ;
	}else if (typeof(yesCallBack) == "string") {
		if (options.yesButtonArgument != null){
			okButton.click(
				function(){
					var func = 'CloseModal("' + modalName + '");' + options.yesButtonCallback + '("' + options.yesButtonArgument + '");'
					eval(func);
				}
			);
		}else{
			okButton.click(
				function(){
					var func = 'CloseModal("' + modalName + '");' + options.yesButtonCallback + '();'
					eval(func);
				}
			);
		}
	}else{
		okButton.click(
			function(){
				CloseModal(modalName) ;	
			}
		);
	}
	
	if (showCancel){
		var noButton = $("<a/>")
			.iconFormButton({iconClass : "cancelButton", iconHoverClass : "cancelButtonHover", caption : cancelText}) 
			.appendTo(buttonContainer) ;
			
		var noCallBack = options.noButtonCallback ;
		
		if (typeof(noCallBack) == "function") {
			noButton.click(noCallBack) ;
		}else if (typeof(noCallBack) == "string") {
			if (options.noButtonArgument != null){
				noButton.click(
					function(){
						var func = 'CloseModal("' + modalName + '");' + options.noButtonCallback + '("' + options.noButtonArgument + '");'
						eval(func);
					}
				);
			}else{
				noButton.click(
					function(){
						var func = 'CloseModal("' + modalName + '");' + options.noButtonArgument + '();'
						eval(func);
					}
				);
			}
		}else{
			noButton.click(
				function(){
					CloseModal(modalName) ;	
				}
			);
		}
	}
	


	var modalTitle = options.title ? options.title : 'Are you sure?' ;
	
	ShowModal({
		title	: modalTitle,
		height	: options.height,
		width	: options.width,	
		content : content,	
		modal	: false,	
		name	: modalName
	}) ;
	
	$(".dialogButton").corner("5px");
}



/* String Management */
function EditStringResource(controlId, token, tokenValue, locale){
	var dialogDiv = $("#stringEditDialog") ;
	if (dialogDiv.length == 0){
		dialogDiv = $("<div/>")
			.attr("id", "stringEditDialog")			
			.appendTo($("body")) ;
						
	}else{
		dialogDiv.html("") 
	}
	
	dialogDiv.data("origin", controlId) ;
	
	var tokenToken = GetStringResource("TokenCaption") ;
	var valueToken = GetStringResource("ValueCaption") ;
	var langToken = GetStringResource("LanguageCaption") ;
	var saveToken = GetStringResource("SaveRecordCaption") ;
	
	
	var body = $("<div/>")
		.addClass("dialogBody")
		.appendTo(dialogDiv) ;
	
	var tokenRow = $("<div/>")
		.addClass("formRow")
		.css("margin-bottom", "3px") 
		.appendTo(body) ;
	
	var tokenCaptionDiv = $("<div/>")
		.addClass("formCaptionContainer") 
		.appendTo(tokenRow) ;
		
	var tokenDataDiv = $("<div/>")
		.addClass("formDataContainer") 		
		.appendTo(tokenRow) ;
		
	var tokenTextBox = $("<label/>")
		.addClass("standardTextBox")
		.attr("id", "stringEditTokenTextBox")
		.attr("type", "text")
		.html(token)
		.appendTo(tokenDataDiv) ;
		
	var tokenCaption = $("<label/>")
		.addClass("formCaption")
		.attr("for", "stringEditTokenTextBox")
		.html(tokenToken + " :") 
		.appendTo(tokenCaptionDiv) ;
		
	var valueRow = $("<div/>")
		.addClass("formRow") 
		.css("margin-bottom", "3px")
		.appendTo(body) ;
	
	var valueCaptionDiv = $("<div/>")
		.addClass("formCaptionContainer") 
		.appendTo(valueRow) ;
		
	var valueDataDiv = $("<div/>")
		.addClass("formDataContainer") 		
		.appendTo(valueRow) ;
		
	var valueTextBox = $("<textarea/>")
		.addClass("standardTextBox")
		.attr("id", "stringEditValueTextBox")
		.attr("rows", 5)		
		.val(tokenValue)
		.appendTo(valueDataDiv) ;
		
	var valueCaption = $("<label/>")
		.addClass("formCaption")
		.attr("for", "stringEditvalueTextBox")
		.html(valueToken + " :") 
		.appendTo(valueCaptionDiv) ;
		
	var langRow = $("<div/>")
		.addClass("formRow") 
		.css("margin-bottom", "3px")
		.appendTo(body) ;
	
	var langCaptionDiv = $("<div/>")
		.addClass("formCaptionContainer") 
		.appendTo(langRow) ;
		
	var langDataDiv = $("<div/>")
		.addClass("formDataContainer") 		
		.appendTo(langRow) ;
		
	var langTextBox = $("<input/>")
		.addClass("standardTextBox")
		.attr("id", "stringEditLangTextBox")
		.attr("type", "text")
		.val(locale)
		.appendTo(langDataDiv) ;
		
	var langCaption = $("<label/>")
		.addClass("formCaption")
		.attr("for", "stringEditLangTextBox")
		.html(langToken + " :") 
		.appendTo(langCaptionDiv) ;	
		
	var buttonPane = $("<div/>")
		.addClass("dialogButtonPane")
		.attr("style", "padding-right:10px;position:absolute;")
		.appendTo(body) ;
	
	var buttonContainer = $("<div/>")
		.addClass("dialogButtonContainer")		
		.appendTo(buttonPane) ;
		
	var buttonList = $("<ul/>")
		.addClass("dialogButtonContainer")			
		.appendTo(buttonContainer) ;
	
	var buttonItem = $("<li/>")
		.appendTo(buttonList) ;
	
	var saveButton = $("<a/>")
		.appendTo(buttonItem)		
		.click(function() {
				var service = new ResourceManager() ;
				var t = $("#stringEditTokenTextBox").html() ;
				var l = $("#stringEditLangTextBox").val() ;
				var v = $("#stringEditValueTextBox").val() ;
				service.SaveStringResource(t, l, v) ;
				
				var dialogDiv = $("#stringEditDialog") ;
				var id = dialogDiv.data("origin") ;
				$("#" + id).html(v) ;
				dialogDiv.dialogClose() ;
			}
		)
		.formSaveButton() ;	
			
		
	dialogDiv.dialog({
		width				: 500,
		height				: 300,
		showLoadingPanel	:false
	}) ;
}

$(document).ready(function(){
	
	var rb = document.getElementById("RebindAllDataFlag") ;
		rb.value = "nope" ;
}) ;


function ShowInspirations(sourceControlId){
	var inDynamicPage = $("#CanOpenResourcesDynamically") ;
	if (inDynamicPage.length == 0){
		window.location.href = "/My/Inspirations/Default.aspx";
	} else {
		var resourcesContent = $("#homeResourcesContent") ;
		if (resourcesContent.length > 0){
			var service = new InspirationsProvider() ;
			var markup = service.Get(1, 6, null, "200px", "auto") ;
				
			$("#inspirationsPanel")
				.html(markup)
				.part({				
					name			: "InspirationsWebPart",
					caption			: GetStringResource("InspirationPanelCaption"),
					parentContainer	: "homeResourcesContent",
					captionDepth	: "5",
					settingName		: "InspirationsPanel",
					iconClass		: "inspirationIcon",
					allowCollapse	: true,
					fullPageUrl		: "/My/Inspirations/",
					scrollTo		: true,
					sourceControlId	: sourceControlId,
					width			: "98%" 					
				}) ;
		}		
	}
}

function ShowBuzz(sourceControlId){
	var inDynamicPage = $("#CanOpenResourcesDynamically") ;
	if (inDynamicPage.length == 0){
		window.location.href = "/Blog";
	} else {
		var resourcesContent = $("#homeBuzzContent") ;
		if (resourcesContent.length > 0){
			GetServerMarkup('buzzPanel', '/Blog/Posts.aspx' );
				
			$("#buzzPanel")				
				.part({				
					name			: "BuzzWebPart",
					caption			: GetStringResource("BuzzPanelCaption"),
					parentContainer	: "homeBuzzContent",
					captionDepth	: "5",
					settingName		: "BuzzPanel",
					iconClass		: "buzzIcon",
					allowCollapse	: true,
					fullPageUrl		: "/Blog/",
					scrollTo		: true,
					sourceControlId	: sourceControlId,
					width			: "98%" 					
				}) ;
		}		
	}
}

function ShowToolTip(control){
	var tt = control.data("tooltip") ;
	if (tt != null && tt.length > 0){	
		control.hover(
			function() {
				var $this = $(this);
				var tt = $this.data("tooltip") ? $this.data("tooltip") : "Press this button" ;
				
				var or = $this.data("ttorient") ? $this.data("ttorient") : "above" ;
				var al = $this.data("ttalign") ? $this.data("ttalign") : "right" ;
				
				var tw = $this.data("ttwidth") ? $this.data("ttwidth") : "200" ;
				$this.callout(
				{
                    text	        : tt,
                    cornerRadius    : "5px",
                    displayClass    : "testCallout", //"toolTip"
                    orient	        : "top",
                    width           : tw + "px"
				}
				)
				.click(function() {
					$(this).closeCallout() ;
				}
				);
							
			},
			function() {
				$(this).closeCallout() ;
			}
		);
	}
} 


function GlobalEditArticle(sourceControlID, articleKey){
	$("#genericModalForm").dialog(
		{
			name		: "genericModalForm",
			title		:"Edit Article",		
			height		:500,
			width		:800,
			contentUrl	:"/Content/Articles/ModalEdit.aspx?PostAction=window.parent.ReloadForm()&ModalName=genericModalForm&ArticleKey=" + articleKey
		}
	);
	
}

function ChangesSavedMessage(){
	ShowMessageBox({
		showNoButton: false,
		title		: GetStringResource("ChangesSavedDialogTitle"),
		OKText		: GetStringResource("OKCaption"),
		content		: GetStringResource("ChangesSavedMessage")
	}) ;
}
function ChangesSavedMessageEx(){
	alert(GetStringResource("ChangesSavedMessage")) ;
}
function SaveFailedMessage(){
	ShowMessageBox({
		showNoButton: false,
		title		: GetStringResource("ChangesFailedDialogTitle"),
		OKText		: GetStringResource("OKCaption"),
		content		: GetStringResource("ChangesNotSaved")
	}) ;
}
function SaveFailedMessageEx(){
	alert(GetStringResource("ChangesNotSaved")) ;
}

function ShowWelcomeWizard(){
	GetServerMarkup('genericModalForm', '/WelcomeWizard.aspx' );
	
}
function ShowDropMenu(button, menu, options){
	
	if (options == null){
		options = {
			width		: null,
			height		: null,
			color		: "black",
			background	: "transparent",
			padding		: "4px",
			position	: "absolute",
			measureBy	: "position",
			"zindex"	: 300
		};
	}
	button
		.data("expanded", "false")
		.click( function() {
			var $this = $(this) ;
			
			var pos = null ;
			
			var measureBy = options.measureBy ? options.measureBy : "position" ;
			if (measureBy == "position"){
				pos = $this.position() ;
			} else {
				pos = $this.offset() ;
			}	
			var width = $this.width() ;
			var height = $this.height() ;
			
			menu.css({top:-9000, left: -9000}).show(); // to get the width
			
			
			
			var menuWidth = options.width ? options.width : menu.width() ;
			var menuLeft = options.left ? options.left : pos.left ;	
			var menuTop = options.top ? options.top : pos.top + height - 1;
			
			var position = options.position ? options.position : "absolute" ;
			
			var color = options.color ? options.color : "black" ;
			var background = options.background ? background : "transparent" ;
			var padding = options.padding ? options.padding : "4px";
			
			var zindex = options.zindex ? options.zindex : 300;
						
			menu
				.hide()	
				.attr('tabIndex', -1)
				.css({
						"outline"	: "0", 			
						"display"	: "block",
						"position"	: position,		
						"left"		: menuLeft ,
						"top"		: menuTop,
						"width"		: menuWidth,						
						"color"		: color,
						"padding"	: padding,
						"z-index"	: zindex
					})	
				.bgiframe()
						
				;
			var expanded = $this.data("expanded") ;
			
			if (expanded == "false"){
				
				$("<div/>")
					.attr("id", menu.attr("id") + "overlay")
					.css({
						left		: 0,
						top			: 0,
						height		: "100%",
						width		: "100%",
						position	: "fixed",
						"z-index"	: zindex-1,
						"background": "transparent",
						"display"	: "block"	
					})
					.click( function(){		
						menu.hide("blind");			
						button
							.data("expanded", "false") 
							.children(".documentMenuExpanded").removeClass("documentMenuExpanded").addClass("documentMenuCollapsed") ;
						
						$(this).remove();
					})
					.appendTo("body");
			
			
				menu.show("blind").uncorner().corner("bl br");
				
				$this
					.data("expanded", "true")
					.children(".documentMenuCollapsed").removeClass("documentMenuCollapsed").addClass("documentMenuExpanded") ;	
				
			}else{
				$("#" + menu.attr("id") + "overlay").remove() ;
				menu.hide("blind");
				$this
					.data("expanded", "false") 
					.children(".documentMenuExpanded").removeClass("documentMenuExpanded").addClass("documentMenuCollapsed") ;
			}
		}) 
	;
}

var writeToConsole = function (log_txt) {
    if (window.console != undefined) {
        console.log(log_txt);
    }
};
    
function CreateDockedWidget(widgetID, options){
	
	var name = name ? name : widgetID + "Part" ;
	var container = options.container ? options.container : widgetID + "Container" ;
	var settingRoot = options.settingRoot ? options.settingRoot : widgetID  ;
	var caption = options.caption ? options.caption : widgetID  ;
	var captionDepth = options.captionDepth ? options.captionDepth :"5"  ;
	var scrollTo = options.scrollTo ? options.scrollTo :false  ;
	var width = options.width ? options.width :"97%";
	var wrapper = options.wrapper ? options.wrapper :  widgetID + "InnerTube" ;
	
	var expandedSetting = GetUserSettingValue(settingRoot + ".Expanded");
	if (expandedSetting == null || expandedSetting.length == 0){
	    //default Pursuits and Inspirations widgets to Expanded if no UserSettings found
	    if(settingRoot == "HomePursuitsWidget" || settingRoot == "HomeInspirationsWidget") {
	        userSettings[settingRoot + ".Expanded"] = 'true';
	    } else {
		    userSettings[settingRoot + ".Expanded"] = 'false';
		}
	}
	
	$("#" + widgetID).wrap("<div id='"+ wrapper+ "' style='background-color:white; padding:4px;'></div>");
	$("#" + wrapper).wrap("<div id='" + container  + "' style='margin-bottom:2px;'></div>") ;

	$("#" + wrapper)				
		.part({				
			name			: name,
			caption			: caption,
			parentContainer	: container,
			allowClose		: false,
			captionDepth	: captionDepth,
			settingName		: settingRoot,	
			fullPageUrl		: options.fullPageUrl,			
			allowCollapse	: true,				
			scrollTo		: scrollTo,	
			fullCollapse	: true,				
			width			: width ,	
			iconClass		: options.iconClass,		
			autoSaveSettings: false,							
			partClass		: options.partClass,
			oncollapse		: options.onCollapse,
			onload			: options.onLoad,
			onexpand		: options.onExpand,
			buttons			: options.buttons,
			dock			: options.dock
		})
	;
}

function CreateWidget(widgetID, options){

	var name = name ? name : widgetID + "Part" ;
	var container = options.container ? options.container : widgetID + "Container" ;
	var settingRoot = options.settingRoot ? options.settingRoot : widgetID  ;
	var caption = options.caption ? options.caption : widgetID  ;
	var captionDepth = options.captionDepth ? options.captionDepth :"5"  ;
	var scrollTo = options.scrollTo ? options.scrollTo : false  ;
	var allowCollapse = options.allowCollapse ? options.allowCollapse : true  ;
	var allowClose = options.allowClose ? options.allowClose : false  ;
	var corner = options.corner ? options.corner : true  ;
	var width = options.width ? options.width :"97%";
	var wrapper = options.wrapper ? options.wrapper :  widgetID + "InnerTube" ;
	var fullCollapse = options.fullCollapse ? options.fullCollapse : false  ;
	
	var expandedSetting = GetUserSettingValue(settingRoot + ".Expanded");
	if (expandedSetting == null || expandedSetting.length == 0){
		userSettings[settingRoot + ".Expanded"] = 'false';
	}
	
	$("#" + widgetID).wrap("<div id='"+ wrapper+ "' style='background-color:white; padding:4px;'></div>");
	$("#" + wrapper).wrap("<div id='" + container  + "' style='margin-bottom:2px;'></div>") ;

	$("#" + wrapper)				
		.part({				
			name			: name,
			caption			: caption,
			parentContainer	: container,
			allowClose		: allowClose,
			captionDepth	: captionDepth,
			settingName		: settingRoot,	
			fullPageUrl		: options.fullPageUrl,			
			allowCollapse	: allowCollapse,				
			scrollTo		: scrollTo,	
			fullCollapse	: fullCollapse,				
			width			: width ,	
			iconClass		: options.iconClass,		
			autoSaveSettings: false,							
			partClass		: options.partClass,
			oncollapse		: options.onCollapse,
			onload			: options.onLoad,
			onexpand		: options.onExpand,
			buttons			: options.buttons,
			corner			: corner,
			dock			: options.dock
		})
	;

}
/* End of http://www.mentorsphere.com/scripts/uif.ui.js */
/* Start of http://www.mentorsphere.com/scripts/uif.login.js */

var cometApp = null;


/* Login */
function ProcessLoginResponse( response ) {
	if ( response.result != "" ) {
		$( "#signUpForm" ).loadingPanel( );
		var st = document.getElementById( "SessionToken" );
		st.value = response.result;
		CreateCookie( "UIFSessionToken", response.result );
		var rb = document.getElementById( "RebindAllDataFlag" );
		rb.value = "yesbyallmeans";
		// $("form").submit() ;
		// form.submit() ;
		window.location.href = window.location.href;
		return false;
		// window.location.href = ref ;
	} else {
		var failedLoginText = GetStringResource( "LoginFailedText" );
		$( "#loginStatusText" ).text( failedLoginText ).show( );
		$( "#signUpForm" ).closeLoadingPanel( );
		$( "#loginWidget" ).closeLoadingPanel( );
	}
}

function LoginNewUser( sessionToken ) {
	var st = document.getElementById( "SessionToken" );
	st.value = sessionToken;
	CreateCookie( "UIFSessionToken", sessionToken );
	// $("form").submit() ;
	// window.location.reload() ;
	window.location.href = window.location.href;
}
function TestForLoginEnterKey( e, utbName, ptbName, remCB, cookieName ) {
	e = e || window.event;
	var code = e.keyCode || e.which;
	if ( code == 13 ) {
		TryToLogin( utbName, ptbName, remCB, cookieName );
		
		return false;
	}
}

function ShowLoginPanel( ) {
	
	var pos = $( "#loginViewWrapper" ).offset( );
	var width = $( "#loginViewWrapper" ).width( );
	if ( width < 300 ) {
		width = 300;
	}
	$( "#loginPanelWrapper" ).css( {
		left : pos.left,
		top : ( pos.top + 26 ),
		width : width,
		"min-height" : "100px"
	} );
	
	$( "#loginWidget" ).html( "&nbsp;" );
	
	$( "#loginWidget" ).loadingPanel( );
	
	$( "#loginViewWrapper" ).hide( "blind" );
	$( "#loginPanelWrapper" ).show( "blind" );
	
	var service = new Identity( );
	service.GetLoginMarkup( RenderLoginMarkup );
}

function RenderLoginMarkup( response ) {
	$( "#loginWidget" ).html( response.result );
	$( "#loginPanelWrapper" ).css( "height", "auto" );
	$( "#loginWidget" ).closeLoadingPanel( );
}

function HideLoginPanel( ) {
	$( "#loginPanelWrapper" ).hide( "blind" );
	$( "#loginViewWrapper" ).show( "blind" );
	$( "#loginStatusText" ).text( "" );
	$( "#loginWidget" ).html( "" );
}

function TryToLogin( utbName, ptbName, rmcbName, cookieName ) {
	$( "#loginWidget" ).loadingPanel( );
	
	var utb = document.getElementById( utbName );
	var ptb = document.getElementById( ptbName );
	
	var userName = utb.value;
	var password = ptb.value;
	
	SetupLoginRememberMeCheckBox( rmcbName, utbName, cookieName );
	
	var service = new Identity( );
	service.Authenticate( userName, password, ProcessLoginResponse );
}

function ValidateLogin( utbName, ptbName ) {
	var isvalid = false;
	
	var utb = document.getElementById( utbName );
	var ptb = document.getElementById( ptbName );
	
	var userName = utb.value;
	var password = ptb.value;
	
	isvalid = ( ( userName.length > 0 ) && ( password.length > 0 ) );
	if ( !isvalid ) {
		if ( userName.length == 0 ) {
			$( "#loginStatusText" ).text( GetStringResource( "UserNameRequiredToken" ) ).show( );
		} else if ( password.length == 0 ) {
			$( "#loginStatusText" ).text( GetStringResource( "PasswordRequiredToken" ) ).show( );
		} else {
			$( "#loginStatusText" ).text( GetStringResource( "LoginFailedText" ) ).show( );
		}
	}
	return isvalid;
}

function SetupLoginRememberMeCheckBox( rmcbName, utbName, cookieName ) {
	var cb = document.getElementById( rmcbName );
	// var val = cb.value ;
	var val = $( "#" + rmcbName ).attr( 'checked' );
	if ( val == true ) {
		var utb = document.getElementById( utbName );
		var userName = utb.value;
		CreateCookie( cookieName, userName, 365 );
	} else {
		EraseCookie( cookieName );
	}
}
/* Recover Password */

function RecoverPasswordTestEmailAddress( eatbID, eatbValidatorID, statusMessageID ) {
	var exists = SeeIfEmailAddressExists( eatbID, eatbValidatorID );
	var sel = "#" + statusMessageID;
	if ( exists == true ) {
		$( sel ).text( GetStringResource( "EmailAddressExistsMessage" ) );
		$( sel ).effect( "pulsate", null, 200, null );
	} else {
		$( sel ).text( GetStringResource( "EmailIsAvailable" ) );
	}
}
/* Sign Up */

function SeeIfUserNameExists( utbId, utbValidatorId ) {
	var retVal = false;
	var tb = document.getElementById( utbId );
	var un = tb.value;
	var validator = document.getElementById( utbValidatorId );
	ValidatorValidate( validator );
	
	if ( un != null && un != "" && validator.isvalid ) {
		var service = new Identity( );
		retVal = service.CheckUserNameExists( un );
	}
	return retVal;
}

function SeeIfEmailAddressExists( eatbID, eatbValidatorID ) {
	var retVal = false;
	var tb = document.getElementById( eatbID );
	var un = tb.value;
	var validator = document.getElementById( eatbValidatorID );
	ValidatorValidate( validator );
	if ( un != null && un != "" && validator.isvalid ) {
		var service = new Identity( );
		retVal = service.CheckEmailAddressExists( un );
	}
	return retVal;
}

function SignUpTestEmailAddress( eatbID, eatbValidatorID, statusMessageID ) {
	var exists = SeeIfEmailAddressExists( eatbID, eatbValidatorID );
	var sel = "#" + statusMessageID;
	if ( exists == true ) {
		$( sel ).text( GetStringResource( "EmailAddressExistsMessage" ) );
		$( sel ).effect( "pulsate", null, 200, null );
	} else {
		$( sel ).text( GetStringResource( "EmailIsAvailable" ) );
	}
}

function SignUpTestUserName( utbId, utbValidatorId, statusMessageID ) {
	var exists = SeeIfUserNameExists( utbId, utbValidatorId );
	var sel = "#" + statusMessageID;
	if ( exists == true ) {
		$( sel ).text( GetStringResource( "UserNameExistsMessage" ) );
		$( sel ).effect( "pulsate", null, 200, null );
	} else {
		$( sel ).text( GetStringResource( "UserNameIsAvailableMessage" ) );
	}
}
/* End of http://www.mentorsphere.com/scripts/uif.login.js */
/* Start of http://www.mentorsphere.com/scripts/uif.data.js */
function GetServerMarkup(targetControlId, url){
	$('#' + targetControlId).loadingPanel() ;
	var applyMarkup = function(result) {
		$('#' + targetControlId).html(result) ;
		$('#' + targetControlId).closeLoadingPanel() ;		
	} ;
	$.get(url, applyMarkup) ;
			 
} 

function FormatFullname(prefix, first, middle, last, suffix, controlId){
	var service = new Identity() ;
	service.FormatFullName(prefix, first, middle, last, suffix, function(response){
		$("#" + controlId).val(response.result) ;
	}) ;
}

function DeleteRecord(serverPostEvent){
	eval(serverPostEvent) ;
	
}

function ModifyRecord(title, message, postbackMethod, rowKey){
	
	ShowMessageBox({
		title				: title ,
		content				: message,
		width				: 300,
		height				: 180,		
		yesButtonCallback	: postbackMethod,
		yesButtonArgument	: rowKey
	});
}
function ModifyRecordEx(title, message, postbackMethod, rowKey, modalName){
	
	ShowMessageBox({
		title				: title ,
		content				: message,
		width				: 300,
		height				: 180,		
		yesButtonCallback	: postbackMethod,
		yesButtonArgument	: rowKey,
		name                : modalName
	});
}
function ShowAddPursuitForm(){
	$("#genericModalForm").dialog({				
		title			: GetStringResource("AddPursuitCaption"),
		height			: 450,
		width			: 700,	
		contentUrl		:'/My/Pursuits/NewPursuitWizard.aspx?ModalName=addPursuitForm&ModalName=genericModalForm'	
	});
}

function ShowSearchWidget(options){
	$(".pageContainer").loadingPanel() ;
	
	var widget = $(options.contentSelector) ;
	var searchButton = $(options.buttonSelector) ;
	var pos = searchButton.offset() ;
	var width = searchButton.width() ;
	var height = searchButton.height() ;
	var orientation = options.orient ? options.orient : "below" ;
	var align = options.align ? options.align : "right" ;
	var widgetClass = options.widgetClass ? options.widgetClass : "utility" ;
	var buttonClass = options.buttonClass ? options.buttonClass : "widgetButton" ;
	var buttonHoverClass = options.buttonHoverClass ? options.buttonHoverClass : "widgetButtonHover" ;
	
	var searchWidth = options.width ? options.width : 275 ;
	var searchLeft = options.left ? options.left : pos.left - (searchWidth - width) ;	
	var searchTop = options.top ? options.top : pos.top + height - 2;
	
	var okText = GetStringResource("ApplyFilterCaption") ;
	var cancelText = GetStringResource("CancelCaption") ;
	
	var buttonsTest = $(options.contentSelector + " .gridWidgetButtonContainer") ;	
	buttonsTest.remove() ;
	widget.uncorner() ;
		
	widget	.attr('tabIndex', -1)
			.addClass(widgetClass)
			.css({
					"outline"	: "0", 			
					"display"	: "block",
					"position"	: "absolute",		
					"left"		: searchLeft ,
					"top"		: searchTop + 10,
					"width"		: searchWidth,										
					"padding"	: "6px",
					"z-index"	: 300
				})		
			;
	
	var buttonsContainer = $("<div/>")
		.attr("class", "gridWidgetButtonContainer") 
		.appendTo(widget);
		
	var buttonsPane = $("<div/>")
		.attr("class", "gridWidgetButtonPaneContainer") 
		.appendTo(buttonsContainer);
	
	var clickText = null ;
	if (options.applyClicked != null && options.applyClicked != undefined && typeof(options.applyClicked == "function")){
		var okButton = $("<a/>")
			.attr("id", options.contentSelector.replace("#", "") + "_okButton")
			.iconFormButton({
				cssClass		: buttonClass,
				cssClassHover	: buttonHoverClass,
				iconClass		: "okCheck", 
				iconHoverClass	: "okCheckHover", 
				caption : GetStringResource("ApplyFilterCaption")
			}) 
			.click(options.applyClicked)
			.appendTo(buttonsPane) ;
	}else{	
		clickText = "onSearchWidgetOKButtonClicked('" + options.contentSelector + "','" + options.applySearchButton + "','" + 	options.buttonSelector + "');return false;" ;
		var okButton = $("<a onclick=" + clickText + "/>")
			.attr("id", options.contentSelector.replace("#", "") + "_okButton")
			.iconFormButton({
				cssClass		: buttonClass,
				cssClassHover	: buttonHoverClass,
				iconClass		: "okCheck", 
				iconHoverClass	: "okCheckHover", 
				caption : GetStringResource("ApplyFilterCaption")
			}) 
			.appendTo(buttonsPane) ;
	}	
	if (options.cancelClicked != null && options.cancelClicked != undefined && typeof(options.cancelClicked == "function")){
		var cancelButton = $("<a/>")
			.formCancelButton(
			{
				cssClass		: buttonClass,
				cssClassHover	: buttonHoverClass
			} 
			)
			.click(options.cancelClicked) 				
			.appendTo(buttonsPane);
	}else{
		clickText = "onSearchWidgetCancelButtonClicked('" + options.contentSelector + "','" + options.applySearchButton + "','" + 	options.buttonSelector + "');return false;" ;
		var cancelButton = $("<a onclick=" + clickText + "/>")
			.formCancelButton(
			{
				cssClass		: buttonClass,
				cssClassHover	: buttonHoverClass
			} 
			) 				
			.appendTo(buttonsPane);
	}		

	widget
		.bgiframe()
		.show("blind")
		.corner("bl br");
	

	$("<div/>")
		.attr("id", widget.attr("id") + "overlay")
		.css({
			left:0,
			top:0,
			height:"100%",
			width: "100%",
			position:"fixed",
			"z-index":299,
			"background": "transparent",
			"display":"block"	
		})
		.click( function(){
			var buttons = $(options.contentSelector + " .gridWidgetButtonContainer") ;	
						
			buttons.remove() ;
			widget.hide("blind") ;
			
			$(this).remove();
		})
		.appendTo("body");
	
	


	$(".pageContainer").closeLoadingPanel() ;
	
}
function onSearchWidgetOKButtonClicked(widgetId, applyId, searchButtonId){	
	var widget = $(widgetId) ;
	
	var buttons = $(widgetId + " .gridWidgetButtonContainer") ;	
	
	$(applyId).click() ;
	buttons.remove() ;
	widget.hide("blind") ;
	$(widgetId + 'overlay').remove();
	
}
function onSearchWidgetCancelButtonClicked(widgetId, applyId, searchButtonId){	
	var widget = $(widgetId) ;
	
	var buttons = $(widgetId + " .gridWidgetButtonContainer") ;
	buttons.remove() ;	
	
	widget.hide("blind") ;
	$(widgetId + 'overlay').remove();
}
function onSearchWidgetShow(settings) {			 
	// Now show the alert behind the overlay				
	$(this).css("display", "block");
	
}
function ShowGridSearchToolTips(gridSearchMessage, selector){
	if (gridSearchMessage != ""){
		$(selector).hover(
			function(){
				$(this).callout({
                    text	        : gridSearchMessage,
                    cornerRadius    : "5px",
                    displayClass    : "testCallout", //"toolTip"
                    orient	        : "top",
                    width           : "200px"
				}) ;
			},
			function(){
				$(this).closeCallout() ;
			}
		) ;
	}
}

function HideGridSearchToolTips(selector){
	$(selector).closeCallout() ;
	$(selector).unbind("hover") ;
	
}


function GetInspirationsPart(targetID, pageIndex, pageSize, sortBy, name){
	
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("Inspirations.PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("Inspirations.PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("Inspirations.SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("Inspirations.SortBy", sortBy) ;
	}

	GetServerMarkup(targetID, '/My/Inspirations/InspirationsList.aspx?PageIndex=' + pageIndex + "&PageSize=" + pageSize + "&RefreshMethod=GetInspirationsPart&SortBy=" + sortBy + "&RefreshControl=" + targetID + '&NameFilter=' + name) ;
}


function GetBlogPosts(targetID, blogKey, tagName, activityKey, allowPaging, includeDrafts, pageIndex, pageSize, sortBy){
   
	if (tagName == null){
		tagName = '';
	}
	if (blogKey == null){
		blogKey = '';
	}
	
	if (activityKey == null){
		activityKey = '';
	}
	
	
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}

		
	if (pageSize == null){
		if (blogKey != null && blogKey.length > 0){
			pageSize = GetUserSettingValue("BlogPosts." + blogKey + ".PageSize") ;
		}else if (tagName != null && tagName.length > 0){
			pageSize = GetUserSettingValue("BlogPosts." + tagName + ".PageSize") ;
		}	
		
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		if (blogKey != null && blogKey.length > 0){
			SaveUserSettingValue("BlogPosts." + blogKey + ".PageSize", pageSize) ;
		}else if (tagName != null && tagName.length > 0){			
			SaveUserSettingValue("BlogPosts." + tagName + ".PageSize", pageSize) ;
		}	
	}
	
	var params = '' ;
	
	if (includeDrafts != null && (includeDrafts == "True" || includeDrafts == true || includeDrafts == "true")){
		params += "&IncludeDrafts=true";
		
	}
	
	if (allowPaging != null && allowPaging == "false"){
		params += "&AllowPaging=false";
	}

	GetServerMarkup(targetID, '/Blog/Posts.aspx?BlogKey=' + blogKey + '&Tag=' + tagName + '&ActivityKey=' + activityKey + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + "&RefreshMethod=GetBlogPosts&SortBy=" + sortBy + "&RefreshControl=" + targetID + params) ;
}


function GetPursuitsPart(targetID, pageIndex, pageSize){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("Pursuits.PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("Pursuits.PageSize", pageSize) ;
	}
	
	GetServerMarkup(targetID, '/My/Pursuits/PursuitList.aspx?RefreshMethod=GetPursuitsPart&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize );
}

function GetPursuitDescription(widgetID, activityKey){
	var service = new Pursuit() ;
	$("#" + widgetID).html(service.GetDescription(activityKey)) ;
}	

function GetActivityNewsFeedPart(targetID, activityKey, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("ActivityNews." + activityKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("ActivityNews." + activityKey + ".PageSize", pageSize) ;
	}
	
	GetServerMarkup(targetID, '/My/Pursuits/News.aspx?PageIndex=' + pageIndex + "&PageSize=" + pageSize + "&RefreshMethod=GetActivityNewsFeedPart&SortBy=When&SortDirection=Descending&RefreshControl=" + targetID + "&ActivityKey=" + activityKey) ;
}


function GetActivityMembers(targetID, activityKey, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("ActivityMembers." + activityKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("ActivityMembers." + activityKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("ActivityMembers." + activityKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "FileAs";
		}
	}else{
		SaveUserSettingValue("ActivityMembers." + activityKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/My/Pursuits/ActivityMembers.aspx?ActivityKey=' + activityKey + '&RefreshMethod=GetActivityMembers&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy  );
}

var CurrentMessageKey = null ;
var CurrentInboxPageIndex = 1 ;
var CurrentInboxPagePageSize = 6 ;
var CurrentInboxOutbox = false ;

function RefreshInbox(inboxID, messageBoxID, pageSize, pageIndex, outbox){
	if (outbox == null){
		outbox = CurrentInboxOutbox ;
	}else{	
		CurrentInboxOutbox = outbox;
	}
	
	if (pageIndex == null){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue(inboxID + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue(inboxID + ".PageSize", pageSize) ;
	}
	
	CurrentInboxPagePageSize = pageSize;
	CurrentInboxPageIndex = pageIndex ;
	
	if (inboxID == null){
		inboxID = 'userInbox'
	}

	if (messageBoxID == null){
		messageBoxID = 'readMessageBox'
	}
	var inbox = $("#" + inboxID) ;
	var messageBox = $("#" + messageBoxID) ;	
	
	inbox.show() ;
	messageBox.hide() ;
	GetServerMarkup( inboxID, '/Messages/UserInbox.aspx?RefreshMethod=RefreshInbox&PageIndex=' + pageIndex + '&PageSize=' + pageSize + '&RefreshControl=' + inboxID + '&Service=' + messageBoxID + "&OutBox=" + outbox) ;
}
function RefreshActivityInbox(inboxID, activityKey, messageBoxID, pageSize, pageIndex, outbox){
	if (outbox == null){
		outbox = CurrentInboxOutbox ;
	}else{	
		CurrentInboxOutbox = outbox;
	}
	
	if (pageIndex == null){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue(inboxID + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue(inboxID + ".PageSize", pageSize) ;
	}
	
	CurrentInboxPagePageSize = pageSize;
	CurrentInboxPageIndex = pageIndex ;
	
	if (inboxID == null){
		inboxID = 'activityInbox'
	}

	if (messageBoxID == null){
		messageBoxID = 'readActivityMessageBox'
	}
	var inbox = $("#" + inboxID) ;
	var messageBox = $("#" + messageBoxID) ;	
	
	inbox.show() ;
	messageBox.hide() ;
	GetServerMarkup( inboxID, '/My/Pursuits/Inbox.aspx?RefreshMethod=RefreshActivityInbox&ActivityKey=' + activityKey + '&PageIndex=' + pageIndex + '&PageSize=' + pageSize + '&RefreshControl=' + inboxID + '&Service=' + messageBoxID + "&OutBox=" + outbox) ;
}
function SendActivityMessageToUser(userKey, activityKey){
	$("#genericModalForm").dialog({
		title		:'<%= StringManager.GetStringResource("CreateMessageModalCaption") %>',		
		height		:540,
		width		:700,
		contentUrl	:"/Messages/Create.aspx?ModalName=genericModalForm&PostAction=window.location.reload&ActivityKey=" + activityKey + "&RecipientKey=" + userKey
	}) ;
}

function SendMessageToUser(userKey){
	$("#genericModalForm").dialog({
		title		:'<%= StringManager.GetStringResource("CreateMessageModalCaption") %>',		
		height		:540,
		width		:700,
		contentUrl	:"/Messages/Create.aspx?ModalName=genericModalForm&PostAction=window.location.reload&RecipientKey=" + userKey
	}) ;
}

function ReplyToMessage(messageKey, replyAll){
	if (replyAll == null){
		replyAll = true ;
	}
	$("#genericModalForm").dialog({
		title		:'<%= StringManager.GetStringResource("CreateMessageModalCaption") %>',		
		height		:540,
		width		:700,
		contentUrl	:"/Messages/Create.aspx?ModalName=genericModalForm&ReplyKey=" + messageKey + "&ReplyAll=" + replyAll
	}) ;
}


var searchConditionPayload = new Object;
searchConditionPayload["PageIndex"] = 0;
searchConditionPayload["PageSize"] = null;
searchConditionPayload["SortBy"] = null;
searchConditionPayload["AddressBookKey"] = null;

function GetMemberDirectory(targetID, params){
	
	if (params == null){
		params = "";
	}
	if((searchConditionPayload.PageIndex != null) && (searchConditionPayload.PageIndex != 'undefined')) {
		params += "&PageIndex=" + searchConditionPayload.PageIndex;
	}
	
	if((searchConditionPayload.PageSize != null) && (searchConditionPayload.PageSize != 'undefined')) {
		params += "&PageSize=" + searchConditionPayload.PageSize;
		SaveUserSettingValue("MemberDirectory.PageSize", searchConditionPayload.PageSize) ;
	}else{
		var pageSize = GetUserSettingValue("MemberDirectory.PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
		params += "&PageSize=" + pageSize;
	}

	if((searchConditionPayload.SortBy != null) && (searchConditionPayload.SortBy != 'undefined') ) {
		params += "&SortBy=" + searchConditionPayload.SortBy;
		SaveUserSettingValue("MemberDirectory.SortBy", searchConditionPayload.SortBy) ;
	}else{
		var sortBy = GetUserSettingValue("MemberDirectory.SortBy") ;
		if (sortBy == null){
			sortBy = 0;			
		}
		params += "&SortBy=" + sortBy;
	}	
	if((searchConditionPayload.FirstName != null) && (searchConditionPayload.FirstName != 'undefined')) params += "&FirstName=" + searchConditionPayload.FirstName;
	if((searchConditionPayload.LastName != null) && (searchConditionPayload.LastName != 'undefined')) params += "&LastName=" + searchConditionPayload.LastName;
	if((searchConditionPayload.EmailAddress != null) && (searchConditionPayload.EmailAddress != 'undefined')) params += "&EmailAddress=" + searchConditionPayload.EmailAddress;
	if((searchConditionPayload.Tags != null) && (searchConditionPayload.Tags != 'undefined')) params += "&Tags=" + searchConditionPayload.Tags;
	if((searchConditionPayload.Interests != null) && (searchConditionPayload.Interests != 'undefined')) params += "&Interests=" + searchConditionPayload.Interests;
	if((searchConditionPayload.Categories != null) && (searchConditionPayload.Categories != 'undefined')) params += "&Categories=" + searchConditionPayload.Categories;
	if((searchConditionPayload.AddressBookKey != null) && (searchConditionPayload.AddressBookKey != 'undefined')) params += "&AddressBookKey=" + searchConditionPayload.AddressBookKey;
	if((searchConditionPayload.MatchSessionAddressBookKeys != null) && (searchConditionPayload.MatchSessionAddressBookKeys != 'undefined')) params += "&MatchSessionAddressBookKeys=" + searchConditionPayload.MatchSessionAddressBookKeys;
	if((searchConditionPayload.OrganizationKeys != null) && (searchConditionPayload.OrganizationKeys != 'undefined')) params += "&OrganizationKeys=" + searchConditionPayload.OrganizationKeys;

	GetServerMarkup(targetID, '/Members/MemberList.aspx?RefreshMethod=GetMemberDirectory&RefreshControl=' + targetID + params )
}
var unreadMessageCount = 0;
function ShowUnreadMessageCount(inboxButtonID, caption) {
    var inboxbutton = $("#" + inboxButtonID);
    if(inboxbutton != null)
    {
        var service = new Messages();
        var count = service.GetUnreadMessageCount();
        if(count > 0) {
            inboxbutton.html(caption + ' (' + count + ')');
        }
        else {
            inboxbutton.html(caption);
        }
//        if(count > unreadMessageCount)
//        {
//            unreadMessageCount = count;
//            ShowNewMessagePopup(inboxButtonID);
//        }
    }
}
function ShowNewMessagePopup(inboxButtonID)
{
    var inboxbutton = $("#" + inboxButtonID);
    if(inboxbutton != null)
    {
	    var pos = inboxbutton.offset();
        var left = pos.left;
        var top = pos.top;

		var toaster = $("<div/>")
			.css({
				"position"	: "absolute",	
				"top"       : top,
				"left"      : left,
				"opacity"   : "0.85",
				"color"		: "#fff",
				"width"		: "125px",
				"padding"	: "5px",
				"height"	: "5px"
			})
			.attr("id", "messageToaster")			
			.addClass("communications")
			.appendTo("body")
			.show()
			.animate({"height": "50px", "top": top-50}, "slow") 			
		;	
			
		var toasterContent = $("<div/>")
			.css({
				"color"				: "#000",				
				"background-color"  : "#fff",
				"height"				: "100%" 
			})
			.appendTo(toaster) ;
		
		var button = $("<a/>")
			.css({
				"color"				: "#000",				
				"background-color"  : "#fff"
			})
			.attr("href", "/Messages/Inbox.aspx")
			.html(GetStringResource("NewMailMessageCaption")) 
			.appendTo(toasterContent)
			.animate({"height": "40px" }, "slow") ;
		
		toasterContent.corner() ;
		setInterval("HideNewMessagePopup()", 8000);
    }
}
function HideNewMessagePopup()
{
    $("#messageToaster").fadeOut(3000).remove();
}


function GetUserOrganizations(targetID, userKey, name, parentKey, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("UserOrganizations." + userKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("UserOrganizations." + userKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("UserOrganizations." + userKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("UserOrganizations." + userKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Organizations/UserOrganizations.aspx?UserKey=' + userKey + '&RefreshMethod=GetUserOrganizations&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name + "&ParentKey=" + parentKey  );
}


function GetOrgPools(targetID, organizationKey, allowSelection, allowClickThrough, name, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("OrganizationPools." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("OrganizationPools." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("OrganizationPools." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("OrganizationPools." + organizationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Pools/PoolList.aspx?OrganizationKey=' + organizationKey + '&AllowSelection=' + allowSelection + '&AllowClickThrough=' + allowClickThrough + '&RefreshMethod=GetOrgPools&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name  );
}


function GetOrgAddressBooks(targetID, organizationKey, allowSelection, populationKey, name, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("OrganizationAddressBooks." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("OrganizationAddressBooks." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("OrganizationAddressBooks." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("OrganizationAddressBooks." + organizationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Organizations/AddressBooks/AddressBookList.aspx?OrganizationKey=' + organizationKey + '&PopulationKey=' + populationKey + '&RefreshMethod=GetOrgAddressBooks&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name + "&AllowSelection=" +  allowSelection);
}
function GetOrgAddressBooksForMatchSession(targetID, organizationKey, allowSelection, showReturnLink, name, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("OrganizationAddressBooks." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("OrganizationAddressBooks." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("OrganizationAddressBooks." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("OrganizationAddressBooks." + organizationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Organizations/AddressBooks/AddressBookList.aspx?OrganizationKey=' + organizationKey + '&RefreshMethod=GetOrgAddressBooks&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name + "&AllowSelection=" +  allowSelection + "&ShowReturnLink=" + showReturnLink + "&AllowClickThrough=false&HideButtons=true");
}

function GetOrgAddressBookEntries(targetID, addressBookKey, organizationKey, returnUrl, personKey, firstName, lastName, userName, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("AddressBookEntries." + addressBookKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("AddressBookEntries." + addressBookKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("AddressBookEntries." + addressBookKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("AddressBookEntries." + addressBookKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Controls/People/Entries.aspx?AddressBookKey=' + addressBookKey + '&RefreshMethod=GetOrgAddressBookEntries&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&LastName=" + lastName + "&FirstName=" + firstName + "&UserName=" + userName + "&ReturnUrl=" +  returnUrl + "&OrganizationKey=" + organizationKey);
}

function GetUserAddressBooks(targetID, userKey, userKeyToAdd, pageIndex, pageSize, sortBy, name){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("UserAddressBooks." + userKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("UserAddressBooks." + userKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("UserAddressBooks." + userKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("UserAddressBooks." + userKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Profiles/AddressBooks/AddressBookList.aspx?UserKey=' + userKey + '&UserKeyToAdd=' + userKeyToAdd + '&RefreshMethod=GetUserAddressBooks&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}

function GetOrgPopulations(targetID, organizationKey, allowSelection, isModal, name, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("Populations." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("Populations." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("Populations." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("Populations." + organizationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Populations/PopulationList.aspx?OrganizationKey=' + organizationKey + '&RefreshMethod=GetOrgPopulations&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name + "&AllowSelection=" + allowSelection + "&IsModal=" + isModal);
}


function GetOrgPopulationMembers(targetID, populationKey, organizationKey, firstName, lastName, userName, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("PopulationMembers." + populationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("PopulationMembers." + populationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("PopulationMembers." + populationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("PopulationMembers." + populationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Populations/Members.aspx?PopulationKey=' + populationKey + '&OrganizationKey=' + organizationKey + '&RefreshMethod=GetOrgPopulationMembers&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&LastName=" + lastName + "&FirstName=" + firstName + "&UserName=" + userName );
}

function GetPoolPopulations(targetID, poolKey, organizationKey, name, pageIndex, pageSize, sortBy){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("PoolPopulations." + poolKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("PoolPopulations." + poolKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("PoolPopulations." + poolKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("PoolPopulations." + poolKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Pools/PoolPopulations.aspx?PoolKey=' + poolKey + '&RefreshMethod=GetPoolPopulations&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&OrganizationKey=" + organizationKey + "&NameFilter=" + name);
}
function GetPoolMembers(targetID, matchSessionKey, poolKey, pageIndex, pageSize, sortBy, firstName, lastName, userName){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("PoolMembers." + poolKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("PoolMembers." + poolKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("PoolMembers." + poolKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "FileAs";
		}
	}else{
		SaveUserSettingValue("PoolMembers." + poolKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Manual/ProtegeList.aspx?MatchSessionKey=' + matchSessionKey + '&PoolKey=' + poolKey + '&RefreshMethod=GetPoolMembers&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&FirstName=" + firstName + "&LastName=" + lastName + "&UserName=" + userName);
}

function GetPoolMembersMentorList(targetID, matchSessionKey, poolKey, pageIndex, pageSize, sortBy, firstName, lastName, userName){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("PoolMembers." + poolKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("PoolMembers." + poolKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("PoolMembers." + poolKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "FileAs";
		}
	}else{
		SaveUserSettingValue("PoolMembers." + poolKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Manual/MentorList.aspx?MatchSessionKey=' + matchSessionKey + '&PoolKey=' + poolKey + '&RefreshMethod=GetPoolMembersMentorList&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&FirstName=" + firstName + "&LastName=" + lastName + "&UserName=" + userName);
}
function GetMatchSessions(targetID, organizationKey, poolKey, pageIndex, pageSize, sortBy, name){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("MatchSessions." + poolKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("MatchSessions." + poolKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("MatchSessions." + poolKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("MatchSessions." + poolKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Session/MatchSessionList.aspx?OrganizationKey=' + organizationKey + '&PoolKey=' + poolKey + '&RefreshMethod=GetMatchSessions&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetOrganizationSurveys(targetID, organizationKey, pageIndex, pageSize, sortBy, name, usage){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("OrganizationSurveys." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("OrganizationSurveys." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("OrganizationSurveys." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("OrganizationSurveys." + organizationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Surveys/SurveyList.aspx?OrganizationKey=' + organizationKey + '&RefreshMethod=GetOrganizationSurveys&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name + "&Usage=" + usage);
}
function GetUserSurveys(targetID, userKey, organizationKey, pageIndex, pageSize, sortBy, name, usage){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("UserSurveys." + userKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("UserSurveys." + userKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("UserSurveys." + userKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("UserSurveys." + userKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Surveys/User/UserSurveyList.aspx?UserKey=' + userKey + '&OrganizationKey=' + organizationKey + '&RefreshMethod=GetUserSurveys&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name + "&Usage=" + usage);
}
function GetUserSurvey(targetID, surveyKey, surveyPageKey, pageIndex, pageSize, sortBy, name){
	GetServerMarkup(targetID, '/Surveys/User/UserSurvey.aspx?SurveyKey=' + surveyKey + '&SurveyPageKey=' + surveyPageKey + '&RefreshMethod=GetUserSurvey&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetUserSurveyComplete(targetID, surveyKey){
	GetServerMarkup(targetID, '/Surveys/User/UserSurveyComplete.aspx?SurveyKey=' + surveyKey);
}
function GetSurveyQuestionValues(targetID, surveyQuestionKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("SurveyQuestionValues." + surveyQuestionKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("SurveyQuestionValues." + surveyQuestionKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("SurveyQuestionValues." + surveyQuestionKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("SurveyQuestionValues." + surveyQuestionKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Surveys/Questions/QuestionValuesList.aspx?SurveyQuestionKey=' + surveyQuestionKey + '&RefreshMethod=GetSurveyQuestionValues&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetOrganizationActivities(targetID, organizationKey, pageIndex, pageSize, sortBy, name){
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("OrganizationActivities." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("OrganizationActivities." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("OrganizationActivities." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("OrganizationActivities." + organizationKey + ".SortBy", sortBy) ;
	}

	GetServerMarkup(targetID, '/Organizations/OrganizationActivitiesList.aspx?OrganizationKey=' + organizationKey + '&RefreshMethod=GetOrganizationActivities&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetAutoMatchOrganizationSurveys(targetID, organizationKey, matchSessionKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("AutoMatchOrganizationSurveys." + organizationKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("AutoMatchOrganizationSurveys." + organizationKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("AutoMatchOrganizationSurveys." + organizationKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("AutoMatchOrganizationSurveys." + organizationKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/OrganizationSurveyList.aspx?OrganizationKey=' + organizationKey + '&MatchSessionKey=' + matchSessionKey + '&RefreshMethod=GetAutoMatchOrganizationSurveys&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetAutoMatchProtegeMatchCriteria(targetID, matchSessionKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("AutoMatchProtegeMatchCriteria." + matchSessionKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("AutoMatchProtegeMatchCriteria." + matchSessionKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("AutoMatchProtegeMatchCriteria." + matchSessionKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("AutoMatchProtegeMatchCriteria." + matchSessionKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/ProtegeMatchCriteriaList.aspx?MatchSessionKey=' + matchSessionKey + '&RefreshMethod=GetAutoMatchProtegeMatchCriteria&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetAutoMatchMentorMatchCriteria(targetID, matchSessionKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("AutoMatchMentorMatchCriteria." + matchSessionKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("AutoMatchMentorMatchCriteria." + matchSessionKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("AutoMatchMentorMatchCriteria." + matchSessionKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("AutoMatchMentorMatchCriteria." + matchSessionKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/MentorMatchCriteriaList.aspx?MatchSessionKey=' + matchSessionKey + '&RefreshMethod=GetAutoMatchMentorMatchCriteria&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetAutoMatchResultsMatchCriteria(targetID, matchSessionKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("AutoMatchResultsMatchCriteria." + matchSessionKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("AutoMatchResultsMatchCriteria." + matchSessionKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("AutoMatchResultsMatchCriteria." + matchSessionKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("AutoMatchResultsMatchCriteria." + matchSessionKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/MatchCriteriaResultsList.aspx?MatchSessionKey=' + matchSessionKey + '&RefreshMethod=GetAutoMatchResultsMatchCriteria&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
//GetAutoMatchResults
function GetAutoMatchResults(targetID, matchSessionKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("AutoMatchResults." + matchSessionKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("AutoMatchResults." + matchSessionKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("AutoMatchResults." + matchSessionKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("AutoMatchResults." + matchSessionKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/MatchResultsList.aspx?MatchSessionKey=' + matchSessionKey + '&RefreshMethod=GetAutoMatchResults&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetSurveyQuestions(targetID, surveyKey, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("SurveyQuestions." + surveyKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("SurveyQuestions." + surveyKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("SurveyQuestions." + surveyKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("SurveyQuestions." + surveyKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/SurveyQuestionsList.aspx?SurveyKey=' + surveyKey + '&RefreshMethod=GetSurveyQuestions&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetSurveyPageQuestions(targetID, surveyPageKey, surveyKey, organizationKey, pageIndex, pageSize, sortBy, name) {
	GetServerMarkup(targetID, '/Surveys/SurveyPageQuestionsList.aspx?SurveyPageKey=' + surveyPageKey + '&SurveyKey=' + surveyKey + '&OrganizationKey=' + organizationKey + '&RefreshMethod=GetSurveyPageQuestions&RefreshControl=' + targetID);
}
function GetMatchSessionSurveyQuestions(targetID, matchSessionKey, type, pageIndex, pageSize, sortBy, name) {
	if (pageIndex == null || pageIndex.length == 0){
		pageIndex = 1;
	}
	
	if (pageSize == null){
		pageSize = GetUserSettingValue("MatchSessionSurveyQuestions." + matchSessionKey + ".PageSize") ;
		if (pageSize == null || pageSize.length == 0){
			pageSize = 6;
		}
	}else{
		SaveUserSettingValue("MatchSessionSurveyQuestions." + matchSessionKey + ".PageSize", pageSize) ;
	}
	
	if (sortBy == null){
		sortBy = GetUserSettingValue("MatchSessionSurveyQuestions." + matchSessionKey + ".SortBy") ;
		if (sortBy == null || sortBy.length == 0){
			sortBy = "Name";
		}
	}else{
		SaveUserSettingValue("MatchSessionSurveyQuestions." + matchSessionKey + ".SortBy", sortBy) ;
	}
	
	GetServerMarkup(targetID, '/Coordinator/Matches/Auto/SurveyQuestionsList.aspx?MatchSessionKey=' + matchSessionKey + '&Type=' + type + '&RefreshMethod=GetMatchSessionSurveyQuestions&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}
function GetOrganizationCoordinators(targetID, organizationKey, allowSelection, allowClickThrough, pageIndex, pageSize, sortBy, name) {
	GetServerMarkup(targetID, '/Organizations/Coordinators/OrganizationCoordinatorsList.aspx?OrganizationKey=' + organizationKey + '&AllowSelection=' + allowSelection + '&AllowClickThrough=' + allowClickThrough + '&RefreshMethod=GetOrganizationCoordinators&RefreshControl=' + targetID + '&PageIndex=' + pageIndex + "&PageSize=" + pageSize + '&SortBy=' + sortBy + "&NameFilter=" + name);
}/* End of http://www.mentorsphere.com/scripts/uif.data.js */
/* Start of http://www.mentorsphere.com/scripts/uif.gridmanager.js */
;(function($) { 

$.fn.gridmanager = function(options){	
	var opts = $.extend({}, $.fn.gridmanager.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		var gridManagerName = o.name ? o.name : "uifGridManager";
		$this.empty();

// Containing div and table
// - all elements for the GirdManager will be appended to these
// ************************************************************************************************
        var div = $("<div/>")
            .attr("id", gridManagerName)
            .addClass("gridManager")
            .css("width", o.width)
            .appendTo($this);
            
        var table = $("<table/>")            
            .appendTo(div);
            
        if (o.tableWidth != "auto"){
			table.attr("width", o.tableWidth) ;
        }
            
        var tr = $("<tr/>")
            .appendTo(table);
        
        // Pager control(s)
        // - if the showPager option is set to true, display the pager control
        // *****************************************************************************************
        if(o.showPager)
        {
            var tdPager = $("<td/>")
				.attr("valign", "middle")
//				.css("width", "85%")
                .appendTo(tr);
                
            var divPager = $("<div/>")                
                .appendTo(tdPager)
                .pager(o);
               
        }
        
        // RecordControl control(s)
        // - if the showRecordControl option is set to true, display the RecordControl
        // *****************************************************************************************
        if(o.showRecordControl)
        {
            var tdRecordControl = $("<td/>")
				.attr("align", "right") 
				.css("width", o.recordControlWidth)				
				.attr("valign", "middle")
                .appendTo(tr);
                
            var divRecordControl = $("<div/>")                
                .appendTo(tdRecordControl)
                .gridManagerRecordControl(o) ;
        }
        
        // Filter control(s)
        // - if the showFilter option is set to true, display the Filter control
        // *****************************************************************************************
        if(o.showFilter)
        {
            var tdFilter = $("<td/>")
				.attr("align", "right") 
				.css("width", o.filterWidth)				
				.attr("valign", "middle")
                .appendTo(tr);
                
            var divFilter = $("<div/>")                
                .appendTo(tdFilter)
                .gridManagerFilterButton(o)
        }
	});
};

// Pager Button
// - implements a button for navigating through pages of records
// - raises PageChanged event on the click() event of the button
// *****************************************************************************************
$.fn.pagerButton = function(options){	
	var opts = $.extend({}, $.fn.gridmanager.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		var gridManagerName = o.name ? o.name : "uifGridManager";		
		
		var clickEvent = o.pageChanged ;
		if (clickEvent != null && clickEvent != undefined){
		    // check if value is set to a function pointer, anonymous function or a string
		    // if it's a function pointer or anonymous function, call the function
		    // if it's a string, eval the string to execute it
			if (typeof(clickEvent) == "function"){
				$this.click(
					function(){
						var $this = $(this);
						var pageSizer = $("#" + $this.data("pageSizeControlId") );
						var pageNumber = $this.data("pageNumber") ;
						var sorter = $("#" + $this.data("sortControlId") );
						
						var pageSize = pageSizer.val() ;
						//var sort = sorter.val() ;
						var sort = sorter.attr("selectedIndex") ;
						
						clickEvent(pageNumber, pageSize, sort) ;
					}
				)
			}else if (typeof(clickEvent) == "string" && clickEvent.length > 0){
				$this.click(
					function(){
						eval(clickEvent) ;
					}
				) ;
			}
		}
		
	});
};
// Pager Select
// - implements a <select> box on the Grid Manager to support Sort through a list of Sort values
// - raises PageChanged event on change() event of the <select>
// *********************************************************************************************
$.fn.pagerSelect = function(options){	
	var opts = $.extend({}, $.fn.gridmanager.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		var gridManagerName = o.name ? o.name : "uifGridManager";		
		
		var clickEvent = o.pageChanged ;
		if (clickEvent != null && clickEvent != undefined){
		    // check if value is set to a function pointer, anonymous function or a string
		    // if it's a function pointer or anonymous function, call the function
		    // if it's a string, eval the string to execute it
			if (typeof(clickEvent) == "function"){
				$this.change(
					function(){
						var $this = $(this);
						var pageSizer = $("#" + $this.data("pageSizeControlId") );
						var pageNumber = $this.data("pageNumber") ;
						var sorter = $("#" + $this.data("sortControlId") );
						
						var pageSize = pageSizer.val() ;
						//var sort = sorter.val() ;
						var sort = sorter.attr("selectedIndex") ;
						
						clickEvent(pageNumber, pageSize, sort) ;
					}
				)
			}else if (typeof(clickEvent) == "string" && clickEvent.length > 0){
				$this.change(
					function(){
						eval(clickEvent) ;
					}
				) ;
			}
		}
		
	});
};
// Pager control
// - implements a pager control on the Grid Manager to support navigating through pages by using First, Next, Prev and Last buttons, as well as page numbers.
// - Also, supports Sorting and ItemsPerPage drop-down boxes
// - raises PageChanged event on change() event of the <select>
// **************************************************************************************************************************************************************
$.fn.pager = function(options){	
	var opts = $.extend({}, $.fn.gridmanager.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		var gridManagerName = o.name ? o.name : "uifGridManager";
		
		var currentPage = o.pageIndex ? o.pageIndex : 1;
		var totalRecordCount = o.totalRecordCount ? o.totalRecordCount : 1 ;		
		var itemsPerPage = o.itemsPerPage ? o.itemsPerPage : 6 ;
		
		// get total page count by dividing totalRecordCount by itemsPerPage
		// if it does not divide evenly, increment pageCount by one to get accurate page count
		var pageCount = Math.floor(totalRecordCount / itemsPerPage) ;
		if ( (totalRecordCount % itemsPerPage) > 0 ){
			pageCount++;
		}
		
		// retrieve PageInfoMask for displaying the current page, total page count and total records
		var pagerMask = GetStringResource("PageInfoMask") ;
		pagerMask = pagerMask.replace("{0}", currentPage) ;
		pagerMask = pagerMask.replace("{1}", pageCount) ;
		pagerMask = pagerMask.replace("{2}", totalRecordCount) ;
		
		var summarySpan = $("<span/>")
			.css({				
				"padding-right"	: "10px",
				"padding-left"	: "0px" 
			})
			.html(pagerMask)
			.appendTo($this) ;
			
		// remove padding from top of summary span if browser is IE
		if ($.browser.msie){		
			summarySpan.css({"padding-top" : "0"}) ;
		}	
			
		// show First and Prev buttons if current Page is greater than 1
		if (currentPage > 1){
			var firstButton = $("<a/>")   
				.attr("id",  gridManagerName + "FirstPage")            
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", 1) 
                .pagerButton(o) 
                .appendTo($this) 
                .iconButton({iconClass: "firstPageButton"});
            
            var prevButton = $("<a/>")    
				.attr("id",  gridManagerName + "PrevPage")                 
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", currentPage - 1 ) 
                .pagerButton(o) 
                .appendTo($this) 
                .iconButton({iconClass: "prevPageButton"});    
                
		}
		
        // Page numbers
        // - displays a list of Page numbers for the user to click through to navigate from page to page, or skip pages
        // - the number of Page numbers to show on each side of the current page is controlled by the pageNumberCount option.
        //********************************************************************************************************************
		var pagesSpan = $("<span/>")
			.css({				
				"padding-right"	: "10px",
				"padding-left"	: "5px" 
			})
			.appendTo($this) ;
		
		// show left-side ellipsis
		// - show an ellipsis on the left of the page numbers if there are more pages below those already displayed
        if(currentPage - o.pageNumberCount > 1)
        {
			var pageNumberLeftEllipsis = $("<span/>")   
			    .html("&hellip;")
                .appendTo(pagesSpan)
        }
        
        // loop through left-side page numbers
        // - show additional page numbers below the current page, up to the pageNumberCount option
        var idx;
        for(idx = (currentPage - o.pageNumberCount); idx < currentPage; idx++)
        {
            if(idx >= 1)
            {
			    var pageNumber = $("<a/>")   
				.attr("id",  gridManagerName + "PageNumber" + idx)
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", idx)
				.pagerButton(o) 
                .appendTo(pagesSpan)
                .formButton({caption: idx, cssClass: o.buttonCssClass, cssClassHover: o.buttonCssHoverClass});
            }
        }

        // show current page
        // - current page displays bold, but non-clickable
		var pageNumberCurrent = $("<a/>")
			.html(currentPage)
			.css({
                "display" : "inline-block",
                "color" : "#042b6b",
                "padding-right" : "10px",
                "padding-left" : "10px",
                "padding-bottom" : "0",
                "padding-top" : "2px",
                "height" : "21px",
                "vertical-align" : "middle",
				"font-weight" : "bold"
			})
            .appendTo(pagesSpan)

        // loop through right-side page numbers
        // - show additional page numbers above the current page, up to the pageNumberCount option
        for(idx = (currentPage + 1); idx <= (currentPage + o.pageNumberCount); idx++)
        {
            if(idx <= pageCount)
            {
			    var pageNumber = $("<a/>")   
				.attr("id",  gridManagerName + "PageNumber" + idx)
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", idx)
				.pagerButton(o) 
                .appendTo(pagesSpan)
                .formButton({caption: idx, cssClass: o.buttonCssClass, cssClassHover: o.buttonCssHoverClass});
            }
        }

        //show right-side ellipsis
        // - show an ellipsis on the right of the page numbers if there are more pages above those already displayed
        if(currentPage + o.pageNumberCount < pageCount)
        {
			var pageNumberLeftEllipsis = $("<span/>")   
			    .html("&hellip;")
                .appendTo(pagesSpan)
        }
        
        // show Next and Last buttons if current Page is less than the total page count
		if (currentPage < pageCount){
			var nextButton = $("<a/>")   
				.attr("id",  gridManagerName + "NextPage")            
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", currentPage + 1) 
                .pagerButton(o) 
                .appendTo($this)                 
                .iconButton({iconClass: "nextPageButton"});
            
            var lastButton = $("<a/>")    
				.attr("id",  gridManagerName + "LastPage")                 
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", pageCount ) 
                .pagerButton(o) 
                .appendTo($this) 
                .iconButton({iconClass: "lastPageButton"});    
                
		}
		
		// Sorter box
		// - if allowSort option is true and sortByItemsList is not null, display the Sort drop-down list
		//********************************************************************************************************************
		if(o.allowSort && o.sortByItemsList != null)
        {
            var spanSorterCaption = $("<span/>")
                .html(GetStringResource("GridSortByCaption") + GetStringResource("FieldCaptionSeparator")) 
			    .css({
				    "padding-left"	: "10px" ,
				    "padding-right"	: "3px"
			    }) 
                .appendTo($this) ;
                
            var selSorterBox = $("<select/>").attr("id", gridManagerName + "Sorter");
           
            // loop through sortByItemsList and add them to the Sort drop-down list
            var sortByItemsList = new Array();
            sortByItemsList = o.sortByItemsList.split(",");
            for(var idx = 0; idx < sortByItemsList.length; idx++)
            {
                var optionSorterBox1 = $("<option/>")
		            .html(sortByItemsList[idx]);
		        if((o.sortBy != null) && (o.sortBy == sortByItemsList[idx]))
		        {
		            optionSorterBox1.attr("selected", "selected");
		        }
                optionSorterBox1.appendTo(selSorterBox);
            }

            selSorterBox
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", 1)
				.attr("selectedIndex", o.currentSort)
				.pagerSelect(o) ;
    		
            selSorterBox.appendTo($this) ;
        }
        
		// Items per Page
		// - if allowItemsPerPage option is true and itemsPerPageList is not null, display the ItemsPerPage drop-down list
		//********************************************************************************************************************
        if(o.allowItemsPerPage && o.itemsPerPageList != null)
        {
            var spanRowsCaption = $("<span/>")
                .html(GetStringResource("PageSizeCaption") + GetStringResource("FieldCaptionSeparator"))
			    .css({
				    "padding-left"	: "10px" ,
				    "padding-right"	: "3px"
			    }) 
                .appendTo($this) ;
            
            var selItemsPerPage = $("<select/>").attr("id", gridManagerName + "PageSizer");
            
            // loop through itemsPerPageList and add them to the ItemsPerPage drop-down list
            var itemsPerPageList = new Array();
            itemsPerPageList = o.itemsPerPageList.split(",");
            for(var idx = 0; idx < itemsPerPageList.length; idx++)
            {
                var optionItemsPerPage = $("<option/>")
		            .html(itemsPerPageList[idx]);
		        if((o.itemsPerPage != null) && (o.itemsPerPage == itemsPerPageList[idx]))
		        {
		            optionItemsPerPage.attr("selected", "selected");
		        }
	            optionItemsPerPage.appendTo(selItemsPerPage);
            }
            
            selItemsPerPage
				.data("sortControlId", gridManagerName + "Sorter")
				.data("pageSizeControlId", gridManagerName + "PageSizer")
				.data("pageNumber", 1) 
				.pagerSelect(o) ;
    		
            selItemsPerPage.appendTo($this) ;
        }

	});
};
// Filter button control
// - implements a filter control on the Grid Manager to support filtering records
// - raises filterClicked event on click() event of the button
// ***********************************************************************************
$.fn.gridManagerFilterButton = function(options){	
	var opts = $.extend({}, $.fn.gridmanager.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		var gridManagerName = o.name ? o.name : "uifGridManager";
		
		// filter button
		var filterButton = $("<a/>")
			.attr("id", gridManagerName + "FilterButton") 
			.appendTo($this)
			.formFilterButton() ;
			
		var clickEvent = o.filterClicked ;
		if (clickEvent != null && clickEvent != undefined){
		    // check if value is set to a function pointer, anonymous function or a string
		    // if it's a function pointer or anonymous function, call the function
		    // if it's a string, eval the string to execute it
			if (typeof(clickEvent) == "function"){	
				filterButton.click(clickEvent);
			}else if (typeof(clickEvent) == "string" && clickEvent.length > 0){
				filterButton.click(
					function(){
						eval(clickEvent) ;
					}
				) ;
			}
		}
		
		// clear filter button
		if (o.filterMessage != null && o.filterMessage != undefined && o.filterMessage.length > 0){
			var clearButton = $("<a/>")
				.attr("id", gridManagerName + "ClearFilterButton") 
				.appendTo($this)
				.formClearFilterButton() ;
				
			var clearFilterClicked = o.clearFilterClicked ;
			if (clearFilterClicked != null && clearFilterClicked != undefined){
		        // check if value is set to a function pointer, anonymous function or a string
		        // if it's a function pointer or anonymous function, call the function
		        // if it's a string, eval the string to execute it
				if (typeof(clearFilterClicked) == "function"){	
					clearButton.click(clearFilterClicked);
				}else if (typeof(clearFilterClicked) == "string" && clearFilterClicked.length > 0){
					clearButton.click(
						function(){
							eval(clearFilterClicked) ;
						}
					) ;
				}
			}
			ShowGridSearchToolTips( o.filterMessage, "#" + gridManagerName + "FilterButton" ) ;
		}
		
	});
};
// RecordControl button control
// - implements record controls on the Grid Manager to support adding records
// - raises addClicked event on click() event of the add button
// ***********************************************************************************
$.fn.gridManagerRecordControl = function(options){	
	var opts = $.extend({}, $.fn.gridmanager.defaults, options);
	return this.each(function() {
		var $this = $(this);
		var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
		var gridManagerName = o.name ? o.name : "uifGridManager";
		
		var addButton = $("<a/>")
			.attr("id", gridManagerName + "AddButton") 
			.appendTo($this)
			.formAddButton() ;
			
		var clickEvent = o.addClicked ;
		if (clickEvent != null && clickEvent != undefined){
		    // check if value is set to a function pointer, anonymous function or a string
		    // if it's a function pointer or anonymous function, call the function
		    // if it's a string, eval the string to execute it
			if (typeof(clickEvent) == "function"){	
				addButton.click(clickEvent);
			}else if (typeof(clickEvent) == "string" && clickEvent.length > 0){
				addButton.click(
					function(){
						eval(clickEvent) ;
					}
				) ;
			}
		}
	});
};		
// Default values for properties
// ************************************************************************************************
$.fn.gridmanager.defaults = {
    name                    : "uifGridManager",
    showPager               : true,
    showRecordControl       : true,
    showFilter              : true,
	pageChanged				: null,
	pageIndex				: 1,
	totalRecordCount		: 1,
	itemsPerPage			: 6,
	pageNumberCount         : 2,
	allowSort				: true,
	allowItemsPerPage       : true,
	sortByItemsList         : null,
	currentSort				: 0,
	itemsPerPageList        : "6,10,20,30,50,100",
	buttonCssClass          : $.fn.linkButton.defaults.cssClass,
	buttonCssHoverClass     : $.fn.linkButton.defaults.cssClassHover,
	addClicked				: null,
	filterMessage			: null,
	filterClicked			: null,
	clearFilterClicked		: null,
	width					: "99%",
	tableWidth				: "99%",
	filterWidth				: "200px",
	recordControlWidth		: "100px"
};

})(jQuery);/* End of http://www.mentorsphere.com/scripts/uif.gridmanager.js */
/* Start of http://www.mentorsphere.com/scripts/uif.tooltip.js?v=3.3.1.361 */

;(function($) { 

$.fn.tooltip = function(options){	
	
	return this.each(function() {
		var $this = $(this);
		
		var tt = $this.data("tooltip") ;
		if (tt != null && tt.length > 0){
			var hoover = $this.data("ttdisplay") ? $this.data("tthover") : "hover" ;	
			if (hoover == "hover"){ 
				$this.hover(
					function() {
						var $this = $(this);
						var tt = $this.data("tooltip") ? $this.data("tooltip") : "Press this button" ;
						
						var or = $this.data("ttorient") ? $this.data("ttorient") : "above" ;
						var al = $this.data("ttalign") ? $this.data("ttalign") : "right" ;
						
						var tw = $this.data("ttwidth") ? $this.data("ttwidth") : "225" ;
						$this
						.callout(
						{
                            text	        : tt,
                            cornerRadius    : "5px",
                            displayClass    : "testCallout", //"toolTip"
                            orient	        : "top",
                            width           : tw + "px"
						})
						.click(function() {
							$(this).closeCallout() ;
						});
					},
					function() {
						$(this).closeCallout() ;
					}
				);
			} else {
				$this.focus(
					function() {
						var $this = $(this);
						var tt = $this.data("tooltip") ? $this.data("tooltip") : "Press this button" ;
						
						var or = $this.data("ttorient") ? $this.data("ttorient") : "above" ;
						var al = $this.data("ttalign") ? $this.data("ttalign") : "right" ;
						
						var tw = $this.data("ttwidth") ? $this.data("ttwidth") : "200" ;
						$this
						.callout(
						{
                            text	        : tt,
                            cornerRadius    : "5px",
                            displayClass    : "testCallout", //"toolTip"
                            orient	        : "top",
                            width           : tw + "px"
						}
						)
						.click(function() {
							$(this).closeCallout() ;
						}
						);
						
						$this.blur(	function() {
								$(this).closeCallout() ;
							}
						);			
					}
				);	
				
				
			}	
		}
		
	});

};
})(jQuery);/* End of http://www.mentorsphere.com/scripts/uif.tooltip.js?v=3.3.1.361 */
