/*
This file includes the following:

jquery-ui.slider
jquery-ui.effects.transfer
jquery.ui.effects.blind
jquery.easing (part of ui)
jquery.color (part of ui)
jquery.hoverintent
jquery.aop
jquery.cookie
ally
ally.pagestate
swfobject.2.2
jquery.liveselectcombobox

*/

/*!
 * jQuery UI Effects 1.7.2
 *
 * 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.2",

	// 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])) ||
			($.isFunction(arguments[0]) || typeof arguments[0] == 'boolean')) {
			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);








/*!
 * jQuery UI Effects Transfer 1.7.2
 *
 * 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);









/*!
 * jQuery UI Effects Blind 1.7.2
 *
 * 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);











/*
 * jQuery UI Slider 1.7.2
 *
 * 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/Slider
 *
 * Depends:
 *	ui.core.js
 */

(function($) {

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

	_init: function() {

		var self = this, o = this.options;
		this._keySliding = false;
		this._handleIndex = null;
		this._detectOrientation();
		this._mouseInit();

		this.element
			.addClass("ui-slider"
				+ " ui-slider-" + this.orientation
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all");

		this.range = $([]);

		if (o.range) {

			if (o.range === true) {
				this.range = $('<div></div>');
				if (!o.values) o.values = [this._valueMin(), this._valueMin()];
				if (o.values.length && o.values.length != 2) {
					o.values = [o.values[0], o.values[0]];
				}
			} else {
				this.range = $('<div></div>');
			}

			this.range
				.appendTo(this.element)
				.addClass("ui-slider-range");

			if (o.range == "min" || o.range == "max") {
				this.range.addClass("ui-slider-range-" + o.range);
			}

			// note: this isn't the most fittingly semantic framework class for this element,
			// but worked best visually with a variety of themes
			this.range.addClass("ui-widget-header");

		}

		if ($(".ui-slider-handle", this.element).length == 0)
			$('<a href="#"></a>')
				.appendTo(this.element)
				.addClass("ui-slider-handle");

		if (o.values && o.values.length) {
			while ($(".ui-slider-handle", this.element).length < o.values.length)
				$('<a href="#"></a>')
					.appendTo(this.element)
					.addClass("ui-slider-handle");
		}

		this.handles = $(".ui-slider-handle", this.element)
			.addClass("ui-state-default"
				+ " ui-corner-all");

		this.handle = this.handles.eq(0);

		this.handles.add(this.range).filter("a")
			.click(function(event) {
				event.preventDefault();
			})
			.hover(function() {
				if (!o.disabled) {
					$(this).addClass('ui-state-hover');
				}
			}, function() {
				$(this).removeClass('ui-state-hover');
			})
			.focus(function() {
				if (!o.disabled) {
					$(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus');
				} else {
					$(this).blur();
				}
			})
			.blur(function() {
				$(this).removeClass('ui-state-focus');
			});

		this.handles.each(function(i) {
			$(this).data("index.ui-slider-handle", i);
		});

		this.handles.keydown(function(event) {

			var ret = true;

			var index = $(this).data("index.ui-slider-handle");

			if (self.options.disabled)
				return;

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
				case $.ui.keyCode.END:
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					ret = false;
					if (!self._keySliding) {
						self._keySliding = true;
						$(this).addClass("ui-state-active");
						self._start(event, index);
					}
					break;
			}

			var curVal, newVal, step = self._step();
			if (self.options.values && self.options.values.length) {
				curVal = newVal = self.values(index);
			} else {
				curVal = newVal = self.value();
			}

			switch (event.keyCode) {
				case $.ui.keyCode.HOME:
					newVal = self._valueMin();
					break;
				case $.ui.keyCode.END:
					newVal = self._valueMax();
					break;
				case $.ui.keyCode.UP:
				case $.ui.keyCode.RIGHT:
					if(curVal == self._valueMax()) return;
					newVal = curVal + step;
					break;
				case $.ui.keyCode.DOWN:
				case $.ui.keyCode.LEFT:
					if(curVal == self._valueMin()) return;
					newVal = curVal - step;
					break;
			}

			self._slide(event, index, newVal);

			return ret;

		}).keyup(function(event) {

			var index = $(this).data("index.ui-slider-handle");

			if (self._keySliding) {
				self._stop(event, index);
				self._change(event, index);
				self._keySliding = false;
				$(this).removeClass("ui-state-active");
			}

		});

		this._refreshValue();

	},

	destroy: function() {

		this.handles.remove();
		this.range.remove();

		this.element
			.removeClass("ui-slider"
				+ " ui-slider-horizontal"
				+ " ui-slider-vertical"
				+ " ui-slider-disabled"
				+ " ui-widget"
				+ " ui-widget-content"
				+ " ui-corner-all")
			.removeData("slider")
			.unbind(".slider");

		this._mouseDestroy();

	},

	_mouseCapture: function(event) {

		var o = this.options;

		if (o.disabled)
			return false;

		this.elementSize = {
			width: this.element.outerWidth(),
			height: this.element.outerHeight()
		};
		this.elementOffset = this.element.offset();

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);

		var distance = this._valueMax() - this._valueMin() + 1, closestHandle;
		var self = this, index;
		this.handles.each(function(i) {
			var thisDistance = Math.abs(normValue - self.values(i));
			if (distance > thisDistance) {
				distance = thisDistance;
				closestHandle = $(this);
				index = i;
			}
		});

		// workaround for bug #3736 (if both handles of a range are at 0,
		// the first is always used as the one with least distance,
		// and moving it is obviously prevented by preventing negative ranges)
		if(o.range == true && this.values(1) == o.min) {
			closestHandle = $(this.handles[++index]);
		}

		this._start(event, index);

		self._handleIndex = index;

		closestHandle
			.addClass("ui-state-active")
			.focus();
		
		var offset = closestHandle.offset();
		var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle');
		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
			left: event.pageX - offset.left - (closestHandle.width() / 2),
			top: event.pageY - offset.top
				- (closestHandle.height() / 2)
				- (parseInt(closestHandle.css('borderTopWidth'),10) || 0)
				- (parseInt(closestHandle.css('borderBottomWidth'),10) || 0)
				+ (parseInt(closestHandle.css('marginTop'),10) || 0)
		};

		normValue = this._normValueFromMouse(position);
		this._slide(event, index, normValue);
		return true;

	},

	_mouseStart: function(event) {
		return true;
	},

	_mouseDrag: function(event) {

		var position = { x: event.pageX, y: event.pageY };
		var normValue = this._normValueFromMouse(position);
		
		this._slide(event, this._handleIndex, normValue);

		return false;

	},

	_mouseStop: function(event) {

		this.handles.removeClass("ui-state-active");
		this._stop(event, this._handleIndex);
		this._change(event, this._handleIndex);
		this._handleIndex = null;
		this._clickOffset = null;

		return false;

	},
	
	_detectOrientation: function() {
		this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal';
	},

	_normValueFromMouse: function(position) {

		var pixelTotal, pixelMouse;
		if ('horizontal' == this.orientation) {
			pixelTotal = this.elementSize.width;
			pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0);
		} else {
			pixelTotal = this.elementSize.height;
			pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0);
		}

		var percentMouse = (pixelMouse / pixelTotal);
		if (percentMouse > 1) percentMouse = 1;
		if (percentMouse < 0) percentMouse = 0;
		if ('vertical' == this.orientation)
			percentMouse = 1 - percentMouse;

		var valueTotal = this._valueMax() - this._valueMin(),
			valueMouse = percentMouse * valueTotal,
			valueMouseModStep = valueMouse % this.options.step,
			normValue = this._valueMin() + valueMouse - valueMouseModStep;

		if (valueMouseModStep > (this.options.step / 2))
			normValue += this.options.step;

		// Since JavaScript has problems with large floats, round
		// the final value to 5 digits after the decimal point (see #4124)
		return parseFloat(normValue.toFixed(5));

	},

	_start: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("start", event, uiHash);
	},

	_slide: function(event, index, newVal) {

		var handle = this.handles[index];

		if (this.options.values && this.options.values.length) {

			var otherVal = this.values(index ? 0 : 1);

			if ((this.options.values.length == 2 && this.options.range === true) && 
				((index == 0 && newVal > otherVal) || (index == 1 && newVal < otherVal))){
 				newVal = otherVal;
			}

			if (newVal != this.values(index)) {
				var newValues = this.values();
				newValues[index] = newVal;
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: this.handles[index],
					value: newVal,
					values: newValues
				});
				var otherVal = this.values(index ? 0 : 1);
				if (allowed !== false) {
					this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true);
				}
			}

		} else {

			if (newVal != this.value()) {
				// A slide can be canceled by returning false from the slide callback
				var allowed = this._trigger("slide", event, {
					handle: this.handles[index],
					value: newVal
				});
				if (allowed !== false) {
					this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate ));
				}
					
			}

		}

	},

	_stop: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("stop", event, uiHash);
	},

	_change: function(event, index) {
		var uiHash = {
			handle: this.handles[index],
			value: this.value()
		};
		if (this.options.values && this.options.values.length) {
			uiHash.value = this.values(index);
			uiHash.values = this.values();
		}
		this._trigger("change", event, uiHash);
	},

	value: function(newValue) {

		if (arguments.length) {
			this._setData("value", newValue);
			this._change(null, 0);
		}

		return this._value();

	},

	values: function(index, newValue, animated, noPropagation) {

		if (arguments.length > 1) {
			this.options.values[index] = newValue;
			this._refreshValue(animated);
			if(!noPropagation) this._change(null, index);
		}

		if (arguments.length) {
			if (this.options.values && this.options.values.length) {
				return this._values(index);
			} else {
				return this.value();
			}
		} else {
			return this._values();
		}

	},

	_setData: function(key, value, animated) {

		$.widget.prototype._setData.apply(this, arguments);

		switch (key) {
			case 'disabled':
				if (value) {
					this.handles.filter(".ui-state-focus").blur();
					this.handles.removeClass("ui-state-hover");
					this.handles.attr("disabled", "disabled");
				} else {
					this.handles.removeAttr("disabled");
				}
			case 'orientation':

				this._detectOrientation();
				
				this.element
					.removeClass("ui-slider-horizontal ui-slider-vertical")
					.addClass("ui-slider-" + this.orientation);
				this._refreshValue(animated);
				break;
			case 'value':
				this._refreshValue(animated);
				break;
		}

	},

	_step: function() {
		var step = this.options.step;
		return step;
	},

	_value: function() {

		var val = this.options.value;
		if (val < this._valueMin()) val = this._valueMin();
		if (val > this._valueMax()) val = this._valueMax();

		return val;

	},

	_values: function(index) {

		if (arguments.length) {
			var val = this.options.values[index];
			if (val < this._valueMin()) val = this._valueMin();
			if (val > this._valueMax()) val = this._valueMax();

			return val;
		} else {
			return this.options.values;
		}

	},

	_valueMin: function() {
		var valueMin = this.options.min;
		return valueMin;
	},

	_valueMax: function() {
		var valueMax = this.options.max;
		return valueMax;
	},

	_refreshValue: function(animate) {

		var oRange = this.options.range, o = this.options, self = this;

		if (this.options.values && this.options.values.length) {
			var vp0, vp1;
			this.handles.each(function(i, j) {
				var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100;
				var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
				$(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);
				if (self.options.range === true) {
					if (self.orientation == 'horizontal') {
						(i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate);
						(i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
					} else {
						(i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate);
						(i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate });
					}
				}
				lastValPercent = valPercent;
			});
		} else {
			var value = this.value(),
				valueMin = this._valueMin(),
				valueMax = this._valueMax(),
				valPercent = valueMax != valueMin
					? (value - valueMin) / (valueMax - valueMin) * 100
					: 0;
			var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%';
			this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate);

			(oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate);
			(oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
			(oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate);
			(oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate });
		}

	}
	
}));

$.extend($.ui.slider, {
	getter: "value values",
	version: "1.7.2",
	eventPrefix: "slide",
	defaults: {
		animate: false,
		delay: 0,
		distance: 0,
		max: 100,
		min: 0,
		orientation: 'horizontal',
		range: false,
		step: 1,
		value: 0,
		values: null
	}
});

})(jQuery);

/*!
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
*/
/*
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
*  
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 7,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut
			var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget;
			while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } }
			if ( p == this ) { return false; }

			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// else e.type == "onmouseover"
			if (e.type == "mouseover") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "onmouseout"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.mouseover(handleHover).mouseout(handleHover);
	};
})(jQuery);





/*!
* jQuery Aspect Oriented Plugin v1.0
*
* Copyright (c) 2009 Aaron Heckmann
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/

/**
* Provides aspect oriented programming for jQuery. 
*
* Pass in a string or array of jQuery methods you want 
* to fire methods for onbefore, on, and onafter.
*
* Example: 
* 	$.aop(['show','hide']);
*
*	$(selector).bind('onbeforeshow', function (e) { alert(e.type);});
*   $(selector).show() -> alerts 'onbeforeshow'
*/
;(function($){
	$.aop = function (fns) {
		jQuery.each( $.makeArray(fns), function (i, meth) {
			var old = jQuery.fn[ meth ];
			if (!old.__aop) {
				jQuery.fn[ meth ] = function () {
					this.triggerHandler('onbefore'+meth);
					this.triggerHandler('on'+meth);
					old.apply(this,arguments);
					this.triggerHandler('onafter'+meth);
					return this;
				};
				jQuery.fn[ meth ].__aop = 1;
			}
		});		
	};
})(jQuery);



/*!
 * Cookie plugin
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var ALLY = {
	version: '0.6.1',
	ns: function (namespaces) {
		var names = namespaces.split('.'), len, ns = ALLY, i;
		
		if (names[0].toUpperCase() == 'ALLY') {
			names.splice(0,1);
		}
		
		len = names.length;
		
		for (i = 0; i < len; i++) {	
			( !ns[names[i]] && (ns[names[i]] = {}) );
			ns = ns[names[i]];
		}
	},
	init: function () {
		ALLY.global_drivers.init();	
	},
	util: {
		
		evalScripts: (function () {
			var rgxBase = '<script[^>]*>([\\s\\S]+?)<\/script>',
				scriptsRgx = new RegExp(rgxBase, 'img'),
				scriptRgx = new RegExp(rgxBase, 'im'),
				gEval = jQuery.globalEval;

			return function (str) {
				if (typeof str != 'string') {
					return;
				}
				var i, scripts;
				if ( scripts = str.match(scriptsRgx) ) {
					for (i = 0; i < scripts.length; i++) {
						gEval(scripts[i].match(scriptRgx)[1]);
					}
				}
			};
		})(),
		
		/*updateWebClientLinks: function (root) {
			
			var loggedIn = ALLY.util.user.isLoggedIn(),
				rgx = loggedIn ? /customerCreation.do/ : /accountCreation.do/,
				newHref = loggedIn ? 'accountCreation.do' : 'customerCreation.do';
			
			$("a[href*=customerCreation.do]", root).each( function() { 
				$(this).attr('href', $(this).attr('href').replace(rgx, newHref));
			});
			
		},*/
		
		/**
		* Map an href to the correct directory to be used in an ajax call.
		*
		*   @href {jquery object | DOMElement | string} This href will be mapped over to it's ajax version, or, the
		* 												the name of the WiPro method you want to call ( saveprefdata, productrates, etc)
		*   @product {string} Used for mapping over special cases like WiPro rates/prefs calls,
		*		example: "cd" "ncd" "osav"
		*		note: it will attempt to figure out the correct product if not specified. if 
		*			  no match is found an error will be thrown.
		*		note: passing in "default" will allow you to use the global 
		*/		
		getHrefForAjax: function (o, prod) {
						
			var h = (o.jquery ? o.attr('href') : o.nodeType ? $(o).attr('href') : o);			
			var methodMap = {
				calculatorrates:{
					cd: "/system/getcalculatorrates.json",
					osav: "/system/getcalculatorrates.json"
				},
				saveprefdata: {
					def: "/saveprefdata.json"
				}			
			};
			
			// check for WiPro method	
			if ( h in methodMap && !(h in Object.prototype) ) {
				return contextPath + methodMap[ h ][ h != "saveprefdata" && prod && prod.toLowerCase() || "def" ];				
			}

			return h.indexOf('#') > -1 ? h : 
				(h.indexOf('?') > -1 ? h.replace('?', '?type=content&') : h + '?type=content');
		
		},
		
		user: (function(){
						
			var _lastPoll = 0,
				_now = function () { return +new Date; },
				_lastInteraction = _now(),
				_cookie = jQuery.cookie,
				
				_update = function () {
					
					_lastInteraction = _now();
					
					// if it's been more than 20 secs since the last attempt
					if ( _lastInteraction - _lastPoll > 20000 ) { 

						_tryUpdateLogoutButton();

					}
				},
			
			
				/*
				* Check if the user logged out. If so, update the UI to a logged out state
				* Returns true if the update was successful
				*/				
				/*_tryUpdateLogoutButton = function () {				
					
					_lastPoll = _now();

					if ( !_isLoggedIn() ) {

						_initState.loggedOut();
					
						return true;

					} 		
					return false;
									
				},*/
			
			
				/*_isLoggedIn = function () {	
					return !!(_cookie('loggedIntoWebClient') && _cookie('loggedIntoWebClientSession'));
				},*/

				_loggedOutMsg = function () {
					
					var $modal = ALLY.util._$wmodal;
					
					$modal.find('.con-body').empty().html('You have successfully logged out of your Ally account.');
					
					$modal.removeClass().addClass('loginbox loggingout')
						.find('>.toptab>*')
							.not('.bmp')
								.remove();
	
					$modal.find('.toptab')
						.append( $('#loginbox').html() )
							.find('a')
								.attr('href','#');
								
					// IE only
					$modal.find('.bgiframe').css('height','30px');
								
					$modal.show().find('.con').animate({top: '-34px'},{ duration: 700 });
					
					setTimeout(function(){
						$modal.find('.con').animate({top: '-120px'}, {
							complete: function () {
								$modal
									.hide()
									.removeClass('loggingout loginbox')
									.find('.con')
										.css('top','').end()
									.find('.con-body')
										.empty().end()
									.find('.bgiframe')
										.css('height','');
							}
						});
					}, 5000);
			
				},
								
				/*_createLogOutImg = function () {
					(document.createElement("img")).src="https://"+ ALLY.util.getWebClientHost() + "/allyWebClient/logout.do?"+_now(); 
				},*/
								
						
				// allow user to log out of secure site by clicking logout			
				/*_logOut = function () {	
					
					if (_logOut.inprocess) {
						return;
					}
					
					_logOut.inprocess = 1;
					
					$('#loginbox').addClass("loggingout").removeClass("logout").find("a").text("");

					// now keep checking the cookies until they are logged out
					// so the logout button gets updated	
					var f = function () {

						if (!_tryUpdateLogoutButton()) {
							// fix bug where IE wasn't always making the logout img request (try multiple times)
							_createLogOutImg();
							setTimeout(f, 2000);
							return;
						}

						delete _logOut.inprocess;
						
						// they are now logged out
						// show logged out confirmation
						_loggedOutMsg();
					};
				
					f();
				
				},*/
			
			
				// Pings the secure site to keep secure session alive 
				/*_stayLoggedIn = function () {
				
					(document.createElement("img")).src="https://"+ ALLY.util.getWebClientHost() + "/allyWebClient/keepSessionAlive.do?"+_now();
				
				},*/
			
			
				_activityEvents = {
					
					bind: function () {
						jQuery(document).bind('keydown.activityCheck mousedown.activityCheck scroll.activityCheck', _update);
						jQuery(window).bind('focus.activityCheck scroll.activityCheck resize.activityCheck', _update);
					},
					
					unbind: function () {
						$(document).unbind('keydown.activityCheck mousedown.activityCheck scroll.activityCheck');
						$(window).unbind('focus.activityCheck scroll.activityCheck resize.activityCheck');
					}
				},
			
			
				_initState = {
				
					/*
					* Update the UI to reflect a logged in status
					*/
					/*loggedIn: function () {				
					
						$('#loginbox').addClass("logout").find("a").text("log out").bind('click.logout', function () {
							_logOut();
							return false;
						});
							
						_activityEvents.bind();
						
						//ALLY.util.updateWebClientLinks();
					
						_update();
						
						_loginStateObserver.start();
					
					},*/
				
					/*
					* Update the UI to reflect a logged out status
					*/	
					/*loggedOut: function () {
					
						_loginStateObserver.stop();
						
						$('#loginbox').removeClass('logout loggingout').find('a').text('log in').unbind('click.logout');							

						_activityEvents.unbind();

						//ALLY.util.updateWebClientLinks();

						var d = document.domain.split('.'),
							dom = d.length == 1 ? d[0] : (d[d.length-2]+'.'+d[d.length-1]);

						_cookie('secureFrameHeight', null, {
							domain: dom,
							path:'/'
						});
						
						// secure.ally.com should have removed these but as of 7/20/09 both were not
						_cookie('loggedIntoWebClient',  null, {
							domain: dom,
							path:'/'
						});
						
						_cookie('loggedIntoWebClientSession',  null, {
							domain: dom,
							path:'/'
						});
																		
					}*/
				
				},
				
				
				_loginStateObserver = {
					
					_timer: null,
					
					start: function () {
						
						/*
						15 minute soft timeout

						After 14 mins of no interaction prompt msg
							if user wishes to stay logged in
								close box (escape key too)
								ping the keepalive url // ALLY.util.user.stayLoggedIn()
							else if logging out
								close box  (escape key too)
								ping the loggout url   // ALLY.util.user.logOut() - unbind all of the loggedIn code
								keep checking the cookie until they're logged out and then update the login button
							else no action is taken and after 10 mins of no interaction...
								//logOut()
								change the 14 min msg to the "you've been logged out" msg
								update the login button text to "log in"
								if user clicks login button in modal
									close box
									scrollTo top of window
									open login widget
						Else they've been interacting
							ping the keepalive url
						*/
						
						
						var warningTime = 60000*14, 
							forceLogoutTime = 60000*15,  
							warningMsgShown = false,
							aboutToBeloggedOutHTML = "<div id='logoutstate' class='section'>"+
												"<h2>You are about to be logged out</h2>"+
												"<p>For your safety and protection, access to your account will end in one minute due to inactivity.</p>"+
                                                "<p>If you want to continue accessing your accounts and not be logged out, please click ok below.</p>"+
												"<div class='buttons'>"+
													"<div class='btn_close btn'><a href='#'>ok, keep me logged in</a></div>"+
												"</div>"+
											"</div>",
                     
							loggedOutHTML = "<div id='logoutstate' class='section'>"+
												"<h2>You have been logged out</h2>"+
												"<p>For your safety and protection, you have been logged out due to inactivity.</p>"+
                                                "<p>You must log in again to access your account.</p>"+
												"<div class='buttons'>"+
													"<div class='btn_close btn btn_purple'><a href='#'>log in</a></div>"+
												"</div>"+
											"</div>",
											
							checkIdleTime = function () {
															
								idleTime = _now() - _lastInteraction;
								
								// if no interactions
								if ( idleTime >= warningTime ) {
																		
									if ( idleTime < forceLogoutTime ) {
										
										handleWarningReached();
																			
									} else {
										
										handleForceLogoutReached();
																				
									}
															
								} else {

									// less than 14mins since last interaction
									
									_stayLoggedIn();
									
									_loginStateObserver._timer = setTimeout(checkIdleTime, warningTime-idleTime+1000)
									
								}
								
							},
							
							handleWarningReached = function () {
															
								var lightbox = ALLY.ui.lightbox;
								
								if ( !warningMsgShown ) {
				
									warningMsgShown = true;
								
									lightbox.show( aboutToBeloggedOutHTML, {
										className: "small logoutpromt",
										complete: function () {
											
											lightbox.element()
												.find('.btn_close a').click(function () {							
													_stayLoggedIn();
													lightbox.hide();
													_activityEvents.bind();
													return warningMsgShown = false;					
												});
							
											$(lightbox).bind('hide.logoutMsg', function () {
												_stayLoggedIn();
												$(lightbox).unbind('hide.logoutMsg');
												_activityEvents.bind();
												return warningMsgShown = false;
											});	
														
										}
									});
									
									/*
									we don't want to reset the lastInteraction time anymore since
									at this point, if the user is truly interacting with the page
									they are going to explicitly interact with the warningMessage
									lightbox. This also fixes the case where the user accidently
									focuses the window or scrolls the window, thereby resetting
									the lastInteraction and causing the warning message to
									continue to be displayed. 	*/
									_activityEvents.unbind();							
								
								}
																		
								// check again when we're in the idle timeframe
								_loginStateObserver._timer = setTimeout(checkIdleTime, forceLogoutTime-idleTime+1000);
								
							},
							
							handleForceLogoutReached = function () {
								
								var lightbox = ALLY.ui.lightbox;
								
								_loginStateObserver._timer = null;
								
								// it's been 15 mins										
								_logOut();
								
								_activityEvents.bind();
								
								lightbox.element().fadeOut(function(){
									lightbox.update( loggedOutHTML );
									lightbox.element().fadeIn();
									
									lightbox.element()
										.find('.btn_close a')
											.click(function(){
			
												lightbox.hide({
													complete: function () {
														var doc = $.browser.safari || document.compatMode == 'BackCompat' ?
															document.body : 
															document.documentElement;
															
														// scrollTo top of window
														$(doc).animate({ scrollTop: 0 }, { 
																duration: 650, 
																complete: function () {

																	// can't open the loggin widget until they are logged out so
																	// wait for logout process to complete
																	var f = function () {

																		if ( _isLoggedIn() ) {
																			setTimeout(f, 50);
																			return;
																		}

																		$('#loginbox a').triggerHandler('click');

																	};
																	f();			
																}
															});
												}});
											
												return false;
											});
								});
								
								warningMsgShown = false;
																				
								// dont start another timer since they're logged out now
								
							};
							
						_loginStateObserver._timer = setTimeout(checkIdleTime, warningTime);	
							
					},
														
					stop: function () {
						
						clearInterval( _loginStateObserver._timer );
						
					}
					
				},
				
				
				_updateLoginUI = function () {
				
					if ( _isLoggedIn() ) {
						
						_initState.loggedIn();	
					
					} else {
					
						_initState.loggedOut();
					
					}
				
				};
			
			
			// initialize on DOM Ready
			/*jQuery(function () {
				_updateLoginUI(); 
			});*/
			
			
				/*jQuery(window).bind('load', function () {				
				if ( _isLoggedIn() ) {					
					_stayLoggedIn();				
				}				
			});*/
			
		
			// public
				/*return {
				isLoggedIn: _isLoggedIn,
				logOut: _logOut,
				stayLoggedIn: _stayLoggedIn
			};*/
			
		})()
	
			
	},
	browser: {	

		cookiesEnabled: (function(){
			var en = false,
				c = jQuery.cookie,
				key = "ally_checkCookies";
				
			c(key,1);
			en = !!c(key);
			c(key, null);
			
			return en;
			
		})() 
		
	},
	
	global_drivers: {
		initUIComponents: function() {
			this.initUITabs();
		},
		initUITabs: function () {
						
			ALLY.pageState.bind('ready', function (e) {

				$(".tabs").each(function (i,elem) {
					
					// NOTE: tabs must have an #id to be tracked in pageState
					
					var $tab = $(elem),
						id = $tab.attr('id'),
						animTabText = false;
					
					// fix urls so tabs gets the ajax version of the page
					// - can't update the urls from within tabs before the ajax call without hacking jquery.ui
					// - can't clean the response from within tabs without hacking jquery.ui
					$tab.find(">ul>li>a").ajaxifyHref().end();
						
						
					// Set up tabs
					$('#tabs.tabs ul li:last').addClass('ui-last');
					$tab.tabs({
						load: function(event, ui) {
							// tabs will die here if an error occurs
							try {
								
								$("#" + ui.panel.id).find(".tabs>ul").remove();
								$('.ui-tabs-panel:has(#ctbl)').css('padding','1em 0');
								ALLY.global_drivers.dejargonator.prepDJ(ui.panel);
								ALLY.global_drivers.enhanceButtons(ui.panel);
								//ALLY.util.updateWebClientLinks(ui.panel);
								
								// update chat
								lpSendData('page','PageName', s.pageName);

							} catch( e ) {
								// todo : need a server side reporting service set up
							}
						},
						select: function(event, ui) {
							//$("#" + ui.panel.id).hide(); // don't hide or flash content will redownload after every tab change
							
							// make sure no request for tabs is in process
							$tab.data('tabs').abort();
											
							$tab.data('tabs').element.queue('tabs', []);
							
							// remove the .ui-state-processing class 
							$tab.find('> ul li.ui-state-processing').removeClass('ui-state-processing');
							
							$(ui.tab).stop();
							
							animTabText = true;
							
							var 
								start = function(){ 
									$(ui.tab)
										.animate({'color':'#bbb'}, { duration: 400, complete: function(){
											if ( !animTabText ) {
												finish(this);
											} 
										}})
										.animate({'color':'#2c2162'}, { duration: 1300, complete: function(){
											if ( animTabText ) {
												start();
											} else {
												finish(this);
											}
										}})
								},
								finish = function (a) {
									$(a).css('color','');
								};
							
							start();
							
							
						}, 
						show: function(event, ui) {
							
							document.title = $(ui.tab).attr('title') + " | Ally Bank";
							
					 		animTabText = false;
							
							$(ui.tab).stop(true, true);
							
							$('.ui-tabs-nav li').css('padding-left','').removeClass('ui-tabs-selected-last').filter('.ui-tabs-selected').next().css('padding-left','0px');
							$('.ui-tabs-selected.ui-last').addClass('ui-tabs-selected-last');
							
							$("#" + ui.panel.id)
								.css('opacity',0.01)
								.css('display','') // set opacity before allowing display
								.fadeTo(400, 1, function () {
									if ($.browser.msie) {
										this.style.removeAttribute('filter');
									}
								});
						},
						ajaxOptions: { 
							
							error: function () {
								animTabText = false;
								
								$(ui.tab).stop(true, true);
																
								// when ajax fails, ui.tabs needs some help cleaning up
							
								// remove the .ui-state-processing class 
								$tab.find('> ul li.ui-state-processing').removeClass('ui-state-processing');
							
								// make sure to clear out the queue or the wrong tab will be shown going forward
								$tab.data('tabs').element.queue('tabs', []);
							} 
						},
						selected: id ? $tab.find('> ul:first a').index(   
											getSelectedTab( id, ALLY.pageState.get(id) || 'default' ) 
											) : "",
						cache:true
					});
					
					
					// .tabs with #id are tracked in pageState
					if (id) {
						// update the selected tab whenever it's pageState changes
						ALLY.pageState.register({
							name: id,
							stateChange: function (state) {
								state = state || 'default'; 
												
								// select the tab with a matching "state"
								$tab.data('tabs').select( getSelectedTab(id, state).attr('href') );
							}
						});
					}								
				});
		
				$(".tabs .ui-tabs-panel:not(.localtab)").css("display","none");
				$(".ui-tabs-nav li").each(function(i){$(this).css("z-index", 200 + -(i));});
			
			});
			
			function getSelectedTab (id, state) {
				return $('> ul:first a[rel=pageState:'+ id + '=' + state +']', '#'+id );
			}
			
		},
		
		enhanceNav: function() {
			/*if ( ALLY.util.user.isLoggedIn() ) {

				jQuery("#global").find("a:contains('my accounts')")
					.attr('href', '#')
					.closest('li')
						.addClass('expandable closed')
						.append([
						"<ul>",
						'<li class="first"><a href="https://secure.ally.com/allyWebClient/accountList.do">account list</a></li>',
						'<li><a href="https://secure.ally.com/allyWebClient/transferFunds.do">transfer funds</a></li>',
						'<li><a href="https://secure.ally.com/allyWebClient/messageInbox.do">secure email</a></li>',
						'<li><a href="https://secure.ally.com/allyWebClient/myProfile.do">my profile</a></li>',
						"</ul>"
						].join('') );
			}*/
			
			$('#global li.expandable h3 a').bind('click', function() {
				if ($(this).parents('li.open').length > 0) {
					$('ul', $(this).parent().parent()).slideUp('normal', function() {
						$(this).parent().removeClass('open').addClass('closed');
					});
				} else {
					$(this).parent().parent().removeClass('closed').addClass('open').find('ul').css('display','none').slideDown('normal');
				}
				return false;
			});
		},
		
		setupSIFR: function() {
			$('#content h1 span').remove();
			$('#content h1').each(function() {
				var text = $(this).text().toLowerCase()
					.replace(/fdic/gi,'FDIC')
					.replace(/ cd/gi,' CD')
					.replace(/cd /gi,'CD ')
					.replace(/\(cd\)/gi,'(CD)');
				$(this).text(text);
			});
			if(typeof sIFR == "function"){
				sIFR.replaceElement(named({sSelector:"#content h1", sFlashSrc:"/files/swf/h1_header.swf", sColor:"#333333", sLinkColor:"#3798C7", sHoverColor:"#3798C7", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0", sWmode:"transparent"}));
				//sIFR.replaceElement(named({sSelector:".product-name", sFlashSrc:"files/pres/flash/prod_name.swf", sColor:"#3798C7", sLinkColor:"#3798C7", sHoverColor:"#3798C7", nPaddingTop:0, nPaddingBottom:0, sCase:"upper", sFlashVars:"textalign=center&offsetTop=0", sWmode:"transparent"}));
				setTimeout(function() {$('.sIFR-replaced a[title*=Adblock]').remove();},350);
			}
		},
		recycleSIFR: function() {
			//Recycle sIFR for H1
			$("#content").find("h1.sIFR-replaced").each(function() {$(this).html($(this).find("span").html());}).removeClass("sIFR-replaced");
			ALLY.global_drivers.setupSIFR();
		},
		
		setupTextSizeTools: function() {
			$("#textsize-tools a").click( function() {
				var size = $(this).attr("id").replace("textsize-", "");
				var cls = "font" + size;
				
				$("body").not("."+cls)
					.removeClass("fontsmall fontmedium fontlarge").addClass("font" + size)
					.each( function() {
						ALLY.prefs.set(this, "categoryCode", "FONT", 1);
						ALLY.prefs.set(this, "sitePreference", "font" + size, 1);
		
						ALLY.global_drivers.recycleSIFR();
				});

				return false;
			});
		},
		
		setupPrintTool: function() {
			$("#print").click(function() {
				var printWin = window.open(contextPath + "/en/print.html","printWin","width=700,height=550,location=0,menubar=0,status=0,scrollbars=1");
				return false;
			});
			$("#print_fr").click(function() {
				var printWin = window.open(contextPath + "/fr/print.html","printWin","width=700,height=550,location=0,menubar=0,status=0,scrollbars=1");
				return false;
			});
		},
		
		enhancePopupLinks: function() {
			$('a.popup').makePopups();
		},
		
		enhanceZebraTables: function() {
			$("table.zebra").each(function() {$(this).find("tr").filter("tr:odd").addClass("rowa").end().filter("tr:even").addClass("rowb");});
		},
		
		enableInlinePNG24: function(elImg) {
			var arVersion = navigator.appVersion.split("MSIE"), version = parseFloat(arVersion[1]);
			if(((version >= 5.5) && (version < 7)) && (document.body.filters)) {
				var imgs = elImg ? [elImg] : document.images;
				for(var i=0; i<imgs.length; i++) {
					var img = imgs[i], imgName = img.src.toUpperCase();
					if(imgName.substring(imgName.length-3, imgName.length) == "PNG") {
						var imgID = (img.id) ? "id='" + img.id + "' " : "";
						var imgClass = (img.className) ? "class='" + img.className + "' " : "";
						var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
						var imgStyle = "display:inline-block;" + img.style.cssText;
						if(img.align == "left") { imgStyle = "float:left;" + imgStyle; }
						if(img.align == "right") { imgStyle = "float:right;" + imgStyle; }
						if(img.parentElement.href) { imgStyle = "cursor:hand;" + imgStyle; }
						var strNewHTML = "<span " + imgID + imgClass + imgTitle + 
						" style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";" +
						"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader" +
						"(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
						img.outerHTML = strNewHTML;
					}
			   }
			}
		},
		
		enhanceButtons: function(root) {

			// Remove the outline from buttons (addclass)		
			$(root).find(".btn")
				.addClass("btn_active")
				.bind("click.button", function (e) { 

					//If the button parent was clicked, refire on the child.		 
					if (e.target == this) {
		
						var element = $(this).find("a,input")[0];
						
						if (!element) {
							// allow event to continue naturally
							return;
						}	
							
						// use native event firing b/c jQuery.trigger won't fire native anchor clicks
						
						if (document.createEventObject) { // IE
							element.fireEvent('onclick', document.createEventObject() );
							
						} else {					
							var evt = document.createEvent("HTMLEvents");
							evt.initEvent('click', true, true); // type,bubbling,cancelable
							element.dispatchEvent(evt);					
						}
						
						return false;							
							 
					} 

				});

		},
		
		fixBackgroundImgs: function () {
			// enables background image cache for internet explorer 6
			// http://www.mister-pixel.com/
			if (jQuery.browser.msie && jQuery.browser.version < 7) {
				try {document.execCommand("BackgroundImageCache", false, true);} catch(e){}
			}
		},
		
		searchBoxFocus: function() {
			// Search box focus coloration (since the box has two different colored parts... thanks, IE!).
			
			var defaultsearch = "search ally.com";
			$("#searchbox").bind("click.search", function() { 
				$(this).find("input.text").focus(); 
			}).find("input.text").val(defaultsearch);
			
			$("form.search input.text")
				.bind("focus.search blur.search", function(e) {
					var $search = $(this),
						val = $search.val();
	
					if (e.type == "focus") {
						// Focus event
						$search.closest("form").addClass("searchfocus");
						
						if ($.trim(val) == defaultsearch) {
							$search.val("").removeClass("default");
						}
						$search.select();
					} else {
						// Blur event
						$search.closest("form").removeClass("searchfocus");
						
						if ($.trim(val) == "") {
							$search.val(defaultsearch).addClass("default");
						}
					}
			
				}).val(defaultsearch).addClass("default");
		},
				
		externalLinks: function () {
			/*
			* If javascript is enabled, open the appropriate "leaving" page.
			* Otherwise, just follow the link normally.
			*/			
			jQuery('a[rel=external]').live('click', function () {

				var $this = $(this),
					href = $this.attr('href'),
					fdic = /fdic.gov/i.test(href),
					lightbox = ALLY.ui.lightbox;
				
				jQuery.ajax({
					url: ALLY.util.getHrefForAjax( fdic ? "/fdic/fdicBridge.html" : "/leaving/generic.html" ),
					timeout: 8000, 
					success: function ( response ) {
						lightbox.show( response );
						lightbox
							.element()
								.find('.btn_close a')
									.click(function(){
										lightbox.hide();
										return false;
									}).end()
								.find('.btn:not(.btn_close) a')
									.attr('href', href).attr('target', '_blank')
									.click(function(){
										lightbox.hide();
									});
					},
					error: function () {
						window.location = href;
					}
				});	
								
				return false;
	
			});
			
			jQuery('a[rel^=video]').live('click', function () {

				var $this = $(this),
					href = $this.attr('href'),
					parts = $this.attr('rel').split(':'),
					params = parts.length > 1 && parts[1],
					rWidth = /width=(\d+)/,
					rHeight= /height=(\d+)/,
					lightbox = ALLY.ui.lightbox,
					html = '<div id="hide-flash-alt-content" class="flash-commercial invisible">'+
								'<div id="flashbucket" class="flash-commercial"></div></div>'
				;

				lightbox.show( html, {
					className: 'big', 
					complete: function() {
						// if the anchor has formatting in it's rel attr use it: rel="video:height=234&width=777"
						var width = params && params.indexOf("width") > -1 ? rWidth.exec(params)[1] : '775',
							height = params && params.indexOf("height") > -1 ? rHeight.exec(params)[1] : '260'
						;
						swfobject.embedSWF(href, 'flashbucket', width, height, '9.0.0', 'expressInstall.swf', {}, {wmode: 'transparent'});
						$('#hide-flash-alt-content').removeClass('invisible');
					}
				});
				
				lightbox
					.element()
						.find('.btn_close a')
							.click(function(){
								lightbox.hide();
								return false;
							}).end()
						.find('.btn:not(.btn_close) a')
							.attr('href', href).attr('target', '_blank')
							.click(function(){
										lightbox.hide();
							})
				;	
	
				return false;
	
			});
			
		},
		/*
		setupKeyboardNav: function () {		
			var t;
			
			$("#logo")
				.focus(function () { 					
					t = setTimeout(function () {						
						$('#limiter').addClass('keyboardnav');						
					}, 150);
					
				}).mousedown(function () { 
					 setTimeout(function () {
						( t && clearTimeout(t) );
					}, 150);

				}).attr('tabIndex', "1"); // Be kind to Opera users 
	
		},
		*/
		dejargonator: {
			prepDJ: function(scope) {
				scope = scope || "";
				$('a.dejargonator', scope).hoverIntent({
					over: function(event) {
						$(this).data('mouseout',false);
						if ($(".dj-layer").length > 0) { $(".dj-layer").remove(); }
						if ($(this).attr("href") != "" && $(this).attr("href") != "#" && $(this).attr("href") != location.href + "#") {
							var origAnchor = this;
							if (typeof $('body').data('glossaryContent') == 'undefined') {
								var arrURL = $(this).attr("href").split('#');
								var glossaryXHR = $.ajax({
									type: "GET",
									url: arrURL[0] + '?type=content',
									success: function(responseText) {
										$('body').data('glossaryContent',responseText);
										ALLY.global_drivers.dejargonator.createDJBubble(origAnchor, event);
									}
								});
							} else {
								ALLY.global_drivers.dejargonator.createDJBubble(origAnchor, event);
							}
						}
					},
					out: function() {
						$(this).data('mouseout',true);
					}
				}).removeAttr('title').filter('[target="_new"]').attr('target','_blank');
			},
			createDJBubble: function(origAnchor, event) {
				if ($(origAnchor).data('mouseout') !== true) {
					var $djStruct = $('<div class="dj-layer"><div class="dj-inner"></div><div class="dj-point"></div></div>').children(".dj-inner");
					if ($($('body').data('glossaryContent')).filter('#' + $(origAnchor).attr("href").split('#')[1]).length) {
						$djStruct.append($($('body').data('glossaryContent')).filter('#' + $(origAnchor).attr("href").split('#')[1]));
						
						var $dj = $djStruct.parent();
						$dj.appendTo($("body"));
						
						var left = event.pageX - 65;
						var top = event.pageY - $dj.height() + 22;
						$dj.css({
							 left: left,
							 top: top
						 });
						
						var v = function() {
							return {
								x: parseInt($(window).scrollLeft(),10),
								y: parseInt($(window).scrollTop(),10),
								cx: parseInt($(window).width(),10),
								cy: parseInt($(window).height(),10)
							};
						}();
						if (v.x + v.cx < left + $dj.width()) {
							left = event.pageX - 250;
							$dj.css({left: left + 'px'}).addClass("viewport-right");
						}
						if (top - v.y < $dj.height()) {
							top = event.pageY - 14;
							$dj.css({top: top + 'px'}).addClass("viewport-top").children(".dj-point").prependTo($dj);
						}
						if ($dj.hasClass(".viewport-top") && $dj.hasClass(".viewport-right")) {
							$dj.addClass("viewport-both");
						}
						
						$dj.stop(true).fadeIn().mouseleave(function(event) {
							$(this).stop(true).fadeOut("fast", function(){
								$(this).remove();
							});
						});
					}
				}
			},
			initDJ: function(origAnchor, event) {
				ALLY.global_drivers.dejargonator.prepDJ();
				$(window).resize(function() {
					$(".dj-layer").remove();
				});
			}
		},		
		/*
		emailThisPage: function () {
		
			// lazy load
			$(window).bind('load', function () {

				// $.getScript doesn't allow caching so use $.ajax
				$.ajax({ 
					type: "GET", 
					url: "/files/pres/js/emailthispage.js", 
					dataType: "script", 
					cache: true
				});
			});
			
		},
		*/
		survey: function () {
			
			if (!jQuery.browser.msie) return;
			
			// lazy load
			$(window).bind('load', function () {
				
				// $.getScript doesn't allow caching so use $.ajax
				$.ajax({ 
					type: "GET", 
					url: "/files/pres/js/ally.util.survey.js", 
					dataType: "script", 
					cache: true
				});
						
			});
		
		},
		
		init: function() {
			//this.setupKeyboardNav();
			//this.setupTextSizeTools();
			this.setupPrintTool();
			//this.emailThisPage();
			//this.enhanceNav();
			//this.setupSIFR();
			//this.enableInlinePNG24();
			//this.initUIComponents();
			//this.enhancePopupLinks();
			//this.enhanceZebraTables();
			this.enhanceButtons(); 
			//this.fixBackgroundImgs();
			//this.searchBoxFocus();
			//this.externalLinks();
			//this.dejargonator.initDJ();
			//this.survey();
		}
	}
};



$(function() {
	ALLY.init();
});


/**
* Transforms anchors to pop up window
*/
$.fn.makePopups = function () {
	
	return this.click(function () {
		
		var params = "", popwidth, popheight, popleft, poptop;
		
		if ($(this).hasClass("feedback")) {
			
			popwidth = 720,
			popheight = 690,
			popleft = (screen.width) ? (screen.width - popwidth)/2 : 100,
			poptop = (screen.height) ? (screen.height - popheight)/2 : 100,
			params = "status=0,toolbar=0,location=0,menubar=0,dependent=1,top=" + poptop + ",left=" + popleft + 
				",directories=0,resizable=0,scrollbars=1,height=" + popheight + ",width=" + popwidth;
			
		} 	
			
		window.open(this.href, "_blank", params);	
				
		return false;	
	});
}
		

/**
* Converts anchor href attr to their ajax directory counterparts
*/
$.fn.ajaxifyHref = function () {
	return this.filter('a').each(function (i,elem) {	
		$(elem).attr('href', ALLY.util.getHrefForAjax( elem ) );		
	});
}


/* ------------------------------------------------------- */
/* Function to store user preferences. Receives an  
   object and sends its $.data().preferences values to CP. */ 
/* ------------------------------------------------------- */
ALLY.ns("prefs");

ALLY.prefs.interval = 10000; // Amount of time to wait before committing your user preferences after an update (default is 10 seconds).

ALLY.prefs.set = function (obj, name, value, interval) {
	var current = obj,
		$cur = $(obj),
		prefs = $cur.data("preferences") || {};
		
	clearTimeout($cur.data("timer"));
	
	if (typeof interval == "undefined") {
		interval = ALLY.prefs.interval;
	} else {
		interval = parseInt(interval) * 1000;
	}
	
	prefs[name] = value;

	$cur
		.data("preferences", prefs)
		.data("timer", setTimeout(function(){ 
				$.post(ALLY.util.getHrefForAjax( "saveprefdata", "default" ), $cur.data("preferences")); 
			}, interval));

	return this;
}

// enable hooks for show and hide jQuery methods
jQuery.aop( ['show','hide'] );

// ALLY.ui.Containiner, ALLY.ui.Overlay 
ALLY.ns('ui');
ALLY.ui = { 
	Container: (function (uid) {	
		return function (options) {
			var id = options.id  || 'uiContainerId_' + (uid++),
				parent = options.parent||'body',
				$el = jQuery('<div/>')
						.attr({id: id });
			
			if ( options.injectNow ) {
				$el.hide()[ options.prepend ? 'prependTo' : 'appendTo'](parent);	
			}

			$el.bind('onbeforeshow', function () {
				if (!jQuery('#'+id).length) {
					$el.hide()[ options.prepend ? 'prependTo' : 'appendTo'](parent);
				}
			});

			return $el;
		};
	})(0),
	Overlay: {
		make: function () {
			
			var $overlay = jQuery('#'+ALLY.ui.Overlay.id);
			if ($overlay.length) {
				return $overlay;
			}
			 
			$overlay = jQuery('<div/>')
				.attr('id', ALLY.ui.Overlay.id)
				.css({
					backgroundColor:'#222',
					height:'100%',
					left:0,
					position:'fixed',
					top:0,
					width:'100%',
					zIndex:1001,
					opacity: ALLY.ui.Overlay.opacity
				})
				.hide();
				
			// IE6 is my hero
			if ( jQuery.browser.msie && jQuery.browser.version < 7 ) {
				$overlay.css({
					position:'absolute',
					zoom:1																
				}).append('<iframe class="bgiframe" frameborder="0" tabindex="-1" src="/files/pres/blank.txt" '+
								'style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\'); '+
								'width:100%; height:100%; left:0px; top:0px"/>');
									
				jQuery('body').css('height', '100%');
				
				// work around for IE6 overlay size matching doc size
				$overlay.bind('onbeforeshow', function () {
					
					$overlay.css('height', $(document).height() );
					
					$(window).bind('resize.overlayResizer, scroll.overlayResizer', function () {
						$overlay.css('height', $(document).height() );
					});
					
				}).bind('onafterhide', function () {
					$(window).unbind('resize.overlayResizer, scroll.overlayResizer');
				});	
			}
			
			return $overlay.prependTo('body');
			
		},
		id: 'ALLYoverlay',
		opacity: 0.5
	}
};



/**
 * ALLY.ui.lightbox
 * 
 * Use: 
 * 	ALLY.ui.lightbox.show(html|selector|element)
 *  ALLY.ui.lightbox.hide()
 *  ALLY.ui.lightbox.center - centers the box on the page by animation
 *
 *  Note: if html is passed into .show(), any 
 *  <script>s will be globally evaled.
 */
(function(){
	
	var overlay, lightboxContainer, isShown, evalScripts = ALLY.util.evalScripts;
	ALLY.ns('ui');
	
	ALLY.ui.lightbox = {
		_config: {
			overlayOpacity: 0.7
		},
		element: function () {
			return lightboxContainer;
		},
		update: function (content, options) {
			
			if (content) {
				lightboxContainer.find('.con-body').empty().append( content );
				evalScripts( content ); // todo, remove this and test. jQuery append() already evals scripts
			}
			
			if (options && options.className) {
				lightboxContainer.addClass( options.className );
			}
			
		},
		append: function (content) {
			
			if (content) {
				lightboxContainer.find('.con-body').append( content );
				evalScripts( content );// todo, remove this and test. jQuery append() already evals scripts
			}
			 
		},
		show: function (content, options) {	
			// lightbox is a sigleton, only one per page.
			var lightbox = ALLY.ui.lightbox;
			
			if ( isShown ) {
				lightbox.hide({complete: _show});
			} else {
				_show();
			}
			
			function _show () {
				isShown = true;
			
				$(lightbox).triggerHandler('show');
			
				if (!overlay) {			
					lightbox._make();
				}
			
				overlay
					.bind('click.lightboxOverlay', lightbox.hide)
					.css({ opacity: lightbox._config.overlayOpacity });
				
				$(document).bind('keydown.lightboxOverlay', function (e) {
					( jQuery.ui.keyCode.ESCAPE == e.keyCode && lightbox.hide() );
				});
						
				// make sure any custom classnames are removed from last displayed lightbox
				lightboxContainer.removeClass();
				
				lightbox.update( content, options );
			
				overlay.fadeIn(100, function () {													 
								
					var ie6 = jQuery.browser.msie && jQuery.browser.version < 7;
					
					lightboxContainer.css( lightbox._getCenter() );

					if ( ie6 ) {
						lightboxContainer.find('.bgiframe')[0].style.setExpression('height', "this.parentNode.offsetHeight+19+'px'");
					}
				
					lightboxContainer.show('blind', function () {
						if ( ie6 ) {
							lightboxContainer.find('.bgiframe')[0].style.removeExpression('height');
						}	
						options && options.complete && options.complete();
					});
					
					$(window).bind('resize.lightbox, scroll.lightbox', lightbox._dampenCenter);
					$(document).bind('scroll.lightbox', lightbox._dampenCenter);
				
				});
			}

		},
		hide: function (options) {
			if ( !isShown ) {
				return;
			}
			
			$(ALLY.ui.lightbox).triggerHandler('hide');
			
			$(document).unbind('keydown.lightboxOverlay');
			overlay.unbind('click.lightboxOverlay');
			$(window).unbind('resize.lightbox, scroll.lightbox');
			$(document).unbind('scroll.lightbox');
			
			lightboxContainer.hide('blind', 200, null, function () {
				overlay.fadeOut(400, function () {
					isShown = false;
					options && options.complete && options.complete();
				});	
			});
			
		},
		center: function () { 
				lightboxContainer.stop().animate(ALLY.ui.lightbox._getCenter(), 1000);
		},
		_dampenCenter: function () {
			// use a damper for IE scroll events - they fire too fast
			var l = ALLY.ui.lightbox;
			window.clearTimeout(l._dampenCenter.t);
			l._dampenCenter.t = window.setTimeout( l.center, 500 );		
		},
		_getCenter: function () {
						
			var $window = $(window),
				windowHeight = $window.height(),
				$doc = $(document),	
				docScrollTop = 	$doc.scrollTop(),
				windowCenter = { top: windowHeight/2 + docScrollTop },
				lightBoxHeight = lightboxContainer.height(),
				halfLightbox = { height: lightBoxHeight/2 + 10},
				top = windowCenter.top - halfLightbox.height,
				place = Math.max(docScrollTop, top) - 10;
			
			// make sure that the lightbox doesn't scroll off the bottom of screen
			return lightBoxHeight + 30 > windowHeight ?
				{ top: place - (lightBoxHeight + 30 - windowHeight)  } :
				{ top: place };
			
		},
		_make: function () {	
			lightboxContainer = ALLY.ui.Container({id: 'ALLYlightbox', injectNow: true, parent: '#pageOverlay'});

			// use innerHTML b/c .append() is failing in IE
			lightboxContainer[0].innerHTML = '<div class="con">'+
												'<div class="bmp">&nbsp;</div>'+
												'<div class="con-body"></div>'+
											'</div>'+
											'<a href="#" class="close">Close Window</a>';
																				
			if (jQuery.browser.msie && jQuery.browser.version < 7) {
				var iframeHtml = '<iframe class="bgiframe" frameborder="0" tabindex="-1" src="/files/pres/blank.txt" '+
									 'style="display:block;position:absolute;z-index:-1;filter:Alpha(Opacity=\'0\'); '+
									 'width:574px;left:17px;"/>';
			
				lightboxContainer[0].insertBefore( document.createElement(iframeHtml), lightboxContainer[0].firstChild );
			}							
			
			lightboxContainer.find('> a.close').bind('click', function () {
				ALLY.ui.lightbox.hide();
				return false;
			});
			
			overlay = ALLY.ui.Overlay.make(); 

			lightboxContainer.css({
				zIndex: 1002 
			});
					
		}
	};
	
})();

/**
 * MenuWidgets
 */
jQuery(function () {
		
		if ( !jQuery('#pageOverlay').length ) {
			// IE is confused and gives pageOverlay height.
			// Using font-size 0 or overflow hidden are not options b/c
			// it messes up the children that get appended. Adding and then
			// removing the styles later just adds more complexity to this
			// already overly complex widget holder, so, appending a hidden
			// element also fixes the problem.
			jQuery('<div id="pageOverlay"/>').append('<b style="display:none"/>').appendTo('body');
		}
		
		var menuWidgetContainer = ALLY.util._$wmodal = new ALLY.ui.Container({id: 'wmodal', parent: '#pageOverlay'}),
			overlay = ALLY.ui.Overlay.make(),
			msie6 = $.browser.msie && $.browser.version < 7,
			util = ALLY.util;
	
		menuWidgetContainer.append('<div class="toptab">'+
								   		'<div class="bmpl bmp">&nbsp;</div>'+
								        '<div class="bmpr bmp">&nbsp;</div>'+
									'</div>'+
									'<div class="con">'+
								   		'<div class="bmp"> </div>'+
										'<div class="con-body"></div>'+
										'<a class="close" href="#">Close Window</a>'+
									'</div>');
							
		if (msie6) {
			var iframeHtml = '<iframe class="bgiframe" frameborder="0" tabindex="-1" src="/files/pres/blank.txt" '+
								'style="display:block;position:absolute;z-index:-1;filter:mask(); width:100%;" />'; 
			
			menuWidgetContainer.find('>.con').prepend(iframeHtml);
		}
							
							
		menuWidgetContainer.find('a.close').click(function(){
			//ALLY.pageState.setAll({
			//	contactus: '',
			//	login: ''
			//});
			hideMenuWidget();
			//e.preventDefault();
			return false;
		});
	
	
		// this is only for IE 
		var menuWidgetHeight = ALLY.util._$wmodal.menuWidgetHeight = {
			prepare: function (show) {
				// must set height for IE to fade
				if (jQuery.browser.msie) {	
					
					if (show) {
						
						// can't use jQuery.swap() here
						var old = {
							visibility: '',
							display: 'none',
							position: ''
						};
						menuWidgetContainer.css({
							visibility: 'hidden',
							display: 'block',
							position: 'absolute',
							zoom: 1
						});
						
						menuWidgetContainer
							.show()
							.css({
							height: menuWidgetContainer.find('>.con').height() + 
									menuWidgetContainer.find('>.toptab').height() 
						});
						
						// restore orig props
						menuWidgetContainer.css(old);					
						
					} else {
				
						menuWidgetContainer.css({
							height: menuWidgetContainer.find('>.con').height() + 
									menuWidgetContainer.find('>.toptab').height() 
						});
					}
				} 							
			},
			restore: function () {
				( jQuery.browser.msie && menuWidgetContainer.css({height: ''}) );
			}
		};


		function hideMenuWidget () {		
			
			overlay.stop();
			
			if (msie6) {
							
				menuWidgetContainer.hide().find('.con-body').empty();			
				cleanUp();
				
			} else {
			
				menuWidgetHeight.prepare();	
					
				function killContainer () {
					menuWidgetContainer
						.hide()
						.css('opacity', '')
						.find('.con-body')
							.empty();
				
					cleanUp();			
					menuWidgetHeight.restore();
				}
						
				if ( menuWidgetContainer.css('display').toLowerCase() == "none" ) {
					menuWidgetContainer.stop();
					killContainer();
					
				} else {
					menuWidgetContainer.stop().fadeTo(400,0, killContainer);
					
				}
				
			}

			return false;
			
			
			function cleanUp () {		
				//reset the height cookie for next time it's opened
				var d = document.domain.split('.');
				jQuery.cookie('secureFrameHeight', null, {
					domain: d.length == 1 ? d[0] : (d[d.length-2]+'.'+d[d.length-1]),
					path:'/'
				});

				overlay
					.fadeOut(300, function(){
						overlay.css('opacity', '0.5');
					})
					.unbind('click.menuWidgetOverlay');

				$(document).unbind('keydown.menuWidgetOverlay');
				
				overlay.find('iframe').contents().unbind('click.contactusWidget click.loginWidget');
				
				
				// fix bug in IE7 vista where cursor continues blinking in space after
				// the login iframe fades out.
				$('#logo').focus().blur();
			}	
				
		}
		
		

		//ALLY.pageState.register({
		//	name: 'contactus',
		//	stateChange: function (state) {	
		//		contactUs[state == 'show' ? state : 'hide']();		
		//	}
		//});	
			
				
		/*var contactUs = {
			
			show: function () {
				
				// check page cache, if none, ajax request
				var $this = $('#contactusbox > a'),
					// href = ALLY.util.getHrefForAjax( $this.attr('href') ),
					href = $this.attr('href'),
					page = $this.data(href);
					
				if (page) {
					menuWidgetContainer.find('.con-body').empty().append( page.replace(/<script(.|\s)*?\/script>/g, "") ).end();
					contactUs._show();
					
				} else {
					
					// do a pulse animation
					$this.stop();
					
					animTabText = true;
					
					var start = function () { 
							$this
								.animate({'color':'#bbb'}, { 
									duration: 400, 
									complete: function () {
										if ( !animTabText ) {
											finish(this);
										} 
									} 
								})
								.animate({'color':'#006899'}, { 
									duration: 1300, 
									complete: function () {
										if ( animTabText ) {
											start();
										} else {
											finish(this);
										}
									} 
								})
						},
						finish = function (a) {
							$(a).css('color','');
						};
					
					start();
					
						
					jQuery.ajax({
						type: 'get',
						url: href,
						success: function (response) {	
							response = /<!-- Tab Navigation -->([\s\S]*)<!-- End Tab Navigation -->/igm.exec(response)[1];	
							response = $.trim(response);
							menuWidgetContainer.find('.con-body').empty().append( response.replace(/<script(.|\s)*?\/script>/g, "") ).end();
							$this.data(href, response);	
							
							// stop the pulse animation	
							animTabText = false;				
							$this.stop(true, true);
											
							contactUs._show();
						},
						error: function () {
							window.location = href;
						},
						timeout: 8000
					});
				}
			},
			
			_show: function () {
				
				var $this = $('#contactusbox > a'),
					response = $this.data($this.attr('href'));
				
				overlay.fadeIn(function () {	
			
					if (msie6) {
						menuWidgetContainer.css('opacity',0.01).show();
						util.evalScripts( response );
						menuWidgetContainer[0].style.removeAttribute('filter');
						return;
					}
					
					menuWidgetHeight.prepare(true);
					menuWidgetContainer.animate({opacity:'show'},{ 
						step: function(step){
							if (arguments.callee.done) {
								return;
							}
							arguments.callee.done = true;
							setTimeout(function(){
									util.evalScripts( response );
								},1);		
						}, 
						duration: 700,
						complete: menuWidgetHeight.restore
					});					

				});

				overlay.bind('click.menuWidgetOverlay', function () {
					//ALLY.pageState.set('contactus', '');
					contactUs.hide();
				});
				
				overlay.find('iframe').contents().bind('click.contactusWidget', function(){
					//ALLY.pageState.set('contactus', '');
					contactUs.hide();
				});	

				$(document).bind('keydown.menuWidgetOverlay', function(e){
					//( jQuery.ui.keyCode.ESCAPE == e.keyCode && ALLY.pageState.set('contactus', '') ); contactUs.show();
					( jQuery.ui.keyCode.ESCAPE == e.keyCode && contactUs.hide() );	
				});

				var $widget = $this.closest('.widget');

				menuWidgetContainer.removeClass().addClass( $widget[0].id );
				menuWidgetContainer.find('> .toptab > *').not('.bmp').remove();
				menuWidgetContainer.find('.toptab')
						.append( $widget.html() ).find('a').attr('href','#').end();
				
			},
			
			hide: function () {			
				hideMenuWidget();				
			}
		};*/
		

		/*jQuery('#contactusbox a').bind('click.contactus', function(){			
			
			//ALLY.pageState.set('contactus', 'show');
			contactUs.show();	
			return false;
			
		});*/
		
		
				
				
		//ALLY.pageState.register({
		//	name: 'login',
		//	stateChange: function (state) {	
		//		login[state == 'show' ? state : 'hide']();		
		//	}
		//});
		
		
		var login = {
			frameHeightTimer: null,
			show: function () {
				
				if ( util.user.isLoggedIn() ) {
					return;
				}
				
				var $this = $('#loginbox a'),
					href = $this.attr('href'),
					$widget = $this.closest('.widget'),
					$frame = jQuery('<iframe border="0" frameborder="0"/>').attr({
						id: 'loginframe',
						src: href + '?' + (new Date()).getTime(),
						height: '60px',
						scrolling: 'no'
					}).css({opacity: 0.01}),
					curHeight = null,
					firstLoad = true;

				if ( $.browser.msie ) {
					$frame.attr("allowTransparency","true");
				}
				
				
				if (!login.frameHeightTimer) {

					var f = function () {
							// adjust the height of the iframe, if this fires before 
							// the frame was able to retrieve it's height, keep
							// trying until it's set.
						var newHeight = jQuery.cookie('secureFrameHeight');
						if (1 > newHeight || curHeight == newHeight) {
							//console.log('dont open', curHeight, newHeight);
								return;
							}
						
							// also see if this load is the one that just logged them in
						if ( util.user.isLoggedIn() ) {		
							//clearTimeout(login.frameHeightTimer);
							//login.frameHeightTimer = null;
							//window.location = "https://secure.ally.com/allyWebClient/accountList.do";
								return;
							}
						
						curHeight = newHeight;

							// not logged in yet, animate
							menuWidgetContainer.find('.loadingLogin').remove();
						
						var $loginFrame = $("#loginframe"); // IE6 intermittently loses the ref to $frame in here
						
							if (msie6) {
							$loginFrame.css('filter','');
							menuWidgetContainer.find('.bgiframe').animate({height: newHeight-0+117+'px' }, 700);
							}

						$loginFrame.stop().animate({ height: newHeight-0+30+'px' }, 700, function () {
							if (!msie6 && firstLoad) {
								firstLoad = false;
								$loginFrame.fadeTo(300, 1, function(){
									$loginFrame.css('filter','');
				});
							}
						});	
			
					};

					login.frameHeightTimer = setInterval(f, 500);					
				}


				menuWidgetContainer.find('.con-body').empty()
					.append( $frame )
					.append('<span class="loadingLogin" style="left:124px;top:100px;font-size:13px;color:#757575;">We\'re making a secure connection...</span>')
					.append('<img src="/files/pres/images/ajax-loader.gif" class="loadingLogin" alt="loading ajax login window"/>');
				
			
				overlay.bind('click.menuWidgetOverlay', function () {
					//ALLY.pageState.set('login', '');
					overlay.stop();
					login.hide();
				});
				
				overlay.find('iframe').contents().bind('click.loginWidget', function(){
					//ALLY.pageState.set('login', '');
					login.hide();
				});

				$(document).bind('keydown.menuWidgetOverlay', function(e) {
					//( jQuery.ui.keyCode.ESCAPE == e.keyCode && ALLY.pageState.set('login', '') ); 
					( jQuery.ui.keyCode.ESCAPE == e.keyCode && login.hide() );
				});

			
				menuWidgetContainer.find('a.close').bind('click.menuWidgetOverlay',function(e){
					login.hide();
					return false;
				});

				overlay.fadeIn(function () { 			
					menuWidgetHeight.prepare(true);
					menuWidgetContainer.fadeIn(700);	
				});

				menuWidgetContainer.removeClass().addClass( $widget[0].id );
				menuWidgetContainer.find('>.toptab>*').not('.bmp').remove();
				menuWidgetContainer
					.find('.toptab')
						.append( $widget.html() )
							.find('a').attr('href','#').end();

			},
			
			hide: function () {
				//console.info("login.hide");
				clearTimeout(login.frameHeightTimer);
				login.frameHeightTimer = null;
				hideMenuWidget();
				menuWidgetContainer.find('a.close').unbind('click.menuWidgetOverlay');
			}
		};
		
});







/**
* ALLY.pageState - Another page state manager
*
* Public Methods
* register
* unregister
* init
* set
* setAll
* get
*
* Events
* ready() - fires after ALLY.pageState is initialized and ready to go
* stateChange(event, whatChanged, currentState)
* scrollTo(event, keyThatIsSetToScroll)
*
* jQuery API 
* $(selector).pageState()
* Events listed above only jQuery(ALLY.pageState)
*
*/

ALLY.ns('pageState');

ALLY.pageState = (function ($) {
	
	var _$histFrame,
		_histFrameID,
		_components = {},
		_initialized = false,
		_pollSpeed = 100,
		_equalsChar = '=',
		
		/**
		* The value used to track if the user clicked a "traditional" #anchor.
		* This value is assigned to the key in the url hash which will trigger
		* the scrollTo event on ALLY.pageState later on. You can subscribe to
		* this event by: jQuery(ALLY.pageState).bind('scrollTo', fn);
		*/
		_scrollParam = (function(){
			var param = 'scroll', counter = 0;
			
			return {
				gen: function () {
					return param+ (++counter);
				},
				get: function () {
					return param + counter;
				}
			};
			
		})(),
		
			
		// specifies if the browser can handle hashchange events
		_hashChangeEventAvailable = $.browser.msie && !!document.documentMode && document.documentMode == 8,
		
		
		// get the current hash
		_getHash = function () {
			var href = top.location.href,
				index = href.indexOf("#");
			
	        return index >= 0 ? href.substr(index + 1) : '';
		},
		
		
		// translate the hash string into an object
		// Pass true as decode to return an object with keys/vals uri decoded
		_parseHash = function (hash, decode) {

			if (!hash) {
				return {};
			}
			
			var hashparts = hash.split('&'), hashLength = hashparts.length, i, pair, newState = {};

			for ( i = 0; i < hashLength; i++ ) {
				pair = hashparts[i].split(_equalsChar);
				
				if (decode) {
					newState[ decodeURIComponent(pair[0]) ] = decodeURIComponent(pair[1] || '');
					continue;
				}
				
				newState[ pair[0] ] = pair[1] || '';
			}

			return newState;
			
		},
		
				
		// Notify all components of the new state
		// Also note: we track if any components are assigned 'scroll(\d)' as their value. the
		// first one we detect with this value gets a special event fired for it ('scrollTo').
		// This can/should be handled to scroll the users browser to the correct position.
		// We do this b/c if a user clicks a #hash normally it would wipe out all state in
		// the url (which we obviously don't want). So we watch for these and assign this 
		// value to trigger the scroll event. The first one we detect with this value per
		// state change is the key passed to the event.
		_handleStateChange = function ( newstates ) {

			var key, comp, objNewHash = _parseHash( newstates ), changed = {}, alreadyScrolled = false;

			// notify all components if their state changed
			for (key in _components) {
	
				comp = _components[ key ];
									
				if ( !(key in objNewHash) ) {
					objNewHash[ key ] = '';
				}
				
				if ( objNewHash[ key ] !== comp.state) {				
					
					changed[ key ] = comp.state = objNewHash[ key ]; 
					
					_fireIndividualStateChange( comp );
					
					if ( comp.state == _scrollParam.get() && !alreadyScrolled ) {
						alreadyScrolled = true;
						$(ALLY.pageState).triggerHandler('scrollTo', comp.name);
					}
				}	
			}	

			_proclaimStateChange(changed, objNewHash);
		},
		
		// fires state change for a single component
		_fireIndividualStateChange = function (comp) {
			( comp.stateChange && comp.stateChange.call(comp, decodeURIComponent( comp.state ) || '') );
		},
		
		_proclaimStateChange = function () {
			$(ALLY.pageState).triggerHandler('stateChange', arguments );
		},
		
		
		// msie only, writes the state to a hidden iframe which allows us to use back/forward buttons
		_updateIframe = function ( state ) {
			var iframe = _$histFrame[0].contentWindow.document;
			iframe.open("javascript:'<html></html>'"); //http://weblogs.asp.net/bleroy/archive/2007/09/07/how-to-build-a-cross-browser-history-management-system.aspx
			iframe.write('<html><body>' + state + '</body></html>');
			iframe.close();
			iframe = null;
		},
		
		
		// initialize iframe tracking for IE < 8 or IE8 compatibility/7 mode
		_initIframe = function () {
			
			//	IE iframes: store original hash and original iframe content...
			var hash = _getHash(), iframeState;

			iframeState = _$histFrame[0].contentWindow.document.body.innerText;
				
			window.setInterval(function () {
				
				var newhash = _getHash(), newiframeState = _$histFrame[0].contentWindow.document.body.innerText;
							
				// check if iframe content != last iframe content (back/forward button clicked, setAll() ), handle state change
				if (newiframeState !== iframeState) {

					iframeState = newiframeState;
					_handleStateChange( newiframeState );					
					hash = newiframeState;
					top.location.hash = newiframeState;
									
				} else if (newhash !== hash) {

					// the location.hash changed manually or by clicking link or by bookmark, update the iframe
					hash = newhash;
					_updateIframe( newhash );
					
				}
			}, _pollSpeed);
			
			// clean up
			$(window).bind('unload', function () {
				_$histFrame = null;
			});
			
		},
		
		
		// Initializes ALLY.pageState by parsing out location.hash
		// called once on jQuery.ready
		_init = function () {
		
			// hide iframe, also add hidefocus and tabindex so users can't focus on it
			_$histFrame = $('#'+ _histFrameID)
				.attr({frameBorder: '0', scrolling: 'no', hidefocus: 'true', tabindex: '-1'})
				.css({
					position:'absolute', 
					left: '-9999em', 
					top: '-9999em'
				});
			
			if ( $.browser.msie && !_hashChangeEventAvailable && ! _$histFrame.is('iframe')) {
				throw new Error('Invalid ALLY.pageState histFrame argument');
			}
							
			// on init, check the location.hash for state to restore
			var hash = _getHash(), 
				states = hash.split('&'), 
				stateLength = hash.length > 0 ? states.length : 0, 
				pair, i, component, name, state, ief;
			
			// update all of the _components with that state (if any);
			for ( i = 0; i < stateLength; i++ ) {
				
				pair = states[i].split(_equalsChar);
				name = decodeURIComponent( pair[0] );
				
				// if the component wasn't registered yet, add it
				component = _components[ name ] || {}; 
				component.name = name;
				
				component.state = decodeURIComponent( pair[1] );		
				_components[ name ] = component;
				
			}
			
			
			/**
			* Hook into all anchors that contain a "#" so they don't break url state.
			* UI tabs prevents it's tab click events from bubbling up the dom so 
			* we hook into those directly. For all others our live handler will capture.
			*/
			jQuery("a[rel*=pageState:]").bind('click', _hookAnchors).live('click', _hookAnchors);		
			jQuery("a[href*=#]").live('click', _hookAnchors);
		
		
			function ready () {
				_initialized = true;
				$(ALLY.pageState).triggerHandler('ready');	
			}
			
				
			// wire up hash change listeners (hashchangeBrowsers, ie<8, others)			
			if (_hashChangeEventAvailable) {
				
				$(window).bind('hashchange', function () {
					_handleStateChange( _getHash() );
				});
					
				ready();
				
			} else if ( $.browser.msie && ( !document.documentMode || document.documentMode < 8 ) ) {
				
				ief = function () {

					if (!_$histFrame[0].contentWindow || !_$histFrame[0].contentWindow.document || !_$histFrame[0].contentWindow.document.body) {
						window.setTimeout(ief, 10);
						return;
					}

					_initIframe();				
					ready();
						
				};			
				ief();
				
			} else {
				
				window.setInterval(function(){
					var newhash = _getHash();
					
					if (hash !== newhash) {
						hash = newhash;
						_handleStateChange( newhash );
					}
					
				}, _pollSpeed);
				
				ready();
				
			}
			
			
		},
		
		// the anchor handler
		_hookAnchors = function (e) {
			
			// don't want to overwrite existing url hash page state
			e.stopImmediatePropagation();
			
			var $this = $(this), 
				rel = $this.attr('rel'),
				href= $this[0].href, //$this.attr('href'),
				pair,
				hparts;
			
			/*	
			if ($.browser.msie) {
				alert( [
					rel,
					href,
					top.location.href, 
					(hparts = href.split('#')) && hparts[0] == top.location.href.split('#')[0], 
					hparts[1]
					].join('\n') );
			}
			*/
				
			// handle rel="pageState:key=val"
			if ( /^pageState:/.test(rel) ) {
				// Check for the existence of _equalsChar to see if user is 
				// updating a component's pageState ( the val can be an empty string ).
				if (rel.indexOf(_equalsChar)>-1) {

					pair = rel.replace(/^pageState:/,'').split(_equalsChar);

					ALLY.pageState.set(pair[0], pair[1] || '');
					
					return false;

				}
				 
			} else if ( (hparts = href.split('#')) && hparts[0] == top.location.href.split('#')[0] ) {
				
				if ( hparts[1] ) {
					ALLY.pageState.set(hparts[1], _scrollParam.gen() );
				} 
				
				return false;
				
			}
			
		};
		
		
		/**
		* jQuery method to hook into anchors. Useful for jQuery UI tabs.
		*/
		$.fn.pageState = function () {
			this.filter('a').bind('click', _hookAnchors);
		}
				
		
	return {
		
		version: '1.1.0',
		
				
		/**
		* Call this to initialize ALLY.pageState
		* histFrameID (string) #id of iframe used for internet explorer
		*/
		init: function (histFrameID) {
			
			if (_initialized) {
				return;
			}
			
			_histFrameID = histFrameID;
			
			// on documentReady, initialize ALLY.pageState
			$(_init);
		},
		
		/**
		* Registers a component to listen for state changes.
		* A component must have two properties:
		* 	"name" : a string key which uniquely identifies the component
		*	"stateChange" : a callback which will be called whenever it's state changes
		*/
		register: function (component) {
			
			if (!component.name || !component.stateChange) {
				throw new Error("ALLY.pageState.register error: invalid component property detected");
			}
			
			if ( _components[component.name] ) {
				
				// component already registered. components without a stateChange property
				// were auto registered during ALLY.pageState.init. If the
				// component has a stateChange callback, we're done, else, assign
				// it and fire a change event
				
				if ( _components[component.name].stateChange ) {
					return ALLY.pageState; 
				}
				
				_components[component.name].stateChange = component.stateChange;
				_fireIndividualStateChange( component );

				return ALLY.pageState; 
			}
			
			component.name = window.encodeURIComponent(component.name);
			component.state = '';
		
			_components[component.name] = component;
			
			return ALLY.pageState;
				
		},
		
		/**
		* 
		*/
		unregister: function (name) {
			if (name in _components) {
				delete _components[ name ];
			}
			return ALLY.pageState;
		},
		
		/**
		* Sets the component with the named key to the supplied val.
		*/
		set: function (key, val) {
			
			if (typeof key !== "string") {
				throw new Error("ALLY.pageState.store error: key must be a string");
			}
			
			var newstate = {};
			newstate[key] = val || '';
			
			return ALLY.pageState.setAll(newstate);
		},
		
		/**
		* Set multiple components value at once.
		* newstates (object) An object of key/value pairs to set. Keys are component names.
		*/
		setAll: function (newstates) {
			
			if (typeof newstates !== "object") {
				return ALLY.pageState;
			}
			
			var curhash, newhash, objNewHash, key, s, hasKeys;
			
			// check to see if newstates has any keys at all
			for (hasKeys in newstates) {
				break;
			}
			
			if (!hasKeys) {
				return ALLY.pageState;
			}
			
			// create a new hash being careful not to overwrite any keyvals in the current hash if not in newstates
			curhash = _parseHash( _getHash(), true );
			
			// merge the objects together, overwriting the current hash values if necessary
			objNewHash = $.extend(curhash, newstates); 
	
			// remove empty keys to save url space
			var s = [];
			for (key in objNewHash) {	
				// leave the = sign in even if there is no value to prevent browsers from natively scrolling to the hash
				s[ s.length ] = encodeURIComponent(key) + _equalsChar + encodeURIComponent( objNewHash[ key ] );
			}; 		
			newhash = s.join('&');
			
			// update the hash. the hash change detector will pick this up and update the _components
			if ( $.browser.msie && ( !document.documentMode || document.documentMode < 8 ) ) {
				
				// IE<8 or IE8 in compatability/ie7 mode
				_updateIframe( newhash );
				
			} else {
				
				top.location.hash = newhash;
				
			}
			
			return ALLY.pageState;
		},
		
		/**
		* Returns the saved state for the given component
		*/
		get: function (name) {
					
			var compName = encodeURIComponent( name );
			
			if (!_components[ compName ]) {
				return null;
			}

			return decodeURIComponent( _components[ compName ].state );
		},
		
		bind: function (type, fn) {
			
			// ready only fires once. if user tries to register after
			// ready fired, just execute now
			if (type == 'ready' && _initialized) {
				
				fn();
				
			} else {
				
				$(ALLY.pageState).bind(type, fn);
					
			}
	
			return ALLY.pageState;
		}
	};

})(jQuery);

//ALLY.pageState.init("jshistory-frame");



/*!
 * jQuery LiveSelectCombo Plugin 0.9.8
 *
 * This plugin, like jQuery, is currently available for use in all personal or commercial projects under both MIT and GPL licenses. 
 * This means that you can choose the license that best suits your project, and use it accordingly.
 *  MIT License - http://www.opensource.org/licenses/mit-license.php
 *  GPL License - http://www.opensource.org/licenses/gpl-2.0.php
 */

;(function($) {
	var isOn = false;
	$.custombox = {
		dsName: 'custombox', /* Data store name */
		defaults: {
			boxType: 'select', /* Available Options: select, selectlive, combo, combolive, searchlive */
			boxClass: 'custombox', /* The class to apply to the replacement box element */
			containerClass: 'custombox-wrapper', /* The class to apply to the box element's wrapper div */
			contextMenuDisabled: true, /* Default to disabling context menu on replacement box */
			openOnTab: false, /* Default to not opening on tab into field */
			menuOpen: false, /* State of menu */
			menuNumItems: 10, /* Number of menu items to display */
			menuMaxHeight: '200px', /* Default height of menu */
			calculateMenuMaxHeight: false, /* Dynamically calculate the menu height and use instead of menuMaxHeight */
			debug: false, /* Display debug statements */
			shimUrl: "/files/pres/blank.txt"
		},
		/* Get or Set defaults for the specified data store (dsName) */
		settings: function(element) {
				if(arguments.length > 0) {
					// Setter
					var updatedSettings = {}, currentSettings = element.data($.custombox.dsName), newSettings = arguments[1];
					$.extend(updatedSettings, currentSettings, newSettings);
					element.data($.custombox.dsName, updatedSettings);
					return element.data($.custombox.dsName);
				} else {
					// Getter
					return element.data($.custombox.dsName);
				}
		},
		/* Enable context menu option on target */
		enableContextMenu: function(element) {
			element[0].oncontextmenu = function() { return true; };
			$.custombox.settings(element,{contextMenuDisabled: false});
			return $.custombox.settings(element);		
		},
		/* Disable context menu option on target */
		disableContextMenu: function(element) {
			element[0].oncontextmenu = function() { return false; };
			$.custombox.settings(element, {contextMenuDisabled: true});
			return $.custombox.settings(element);
		}
	};
	/* Accessible Hide */
	$.fn.extend({
		accessibleHide: function() {return $(this).each(function() {$(this).addClass('accessibleHide')});}
		//accessibleHide: function() {return $(this).each(function() {$(this).css({'position':'absolute','top':'0','left':'350px','outline':'none'});});}
	});
/*
Look into {
Namspaced Events:  http://docs.jquery.com/Namespaced_Events,
Event Data: http://docs.jquery.com/Events/jQuery.Event#event.type,
Event Data: http://docs.jquery.com/Events
}
Note: input, radio, checkbox, image, file, reset, & submit - Need to have the outline removed upon selection...
IE Only outline hack - Attribute: hidefocus="true"
Research Mac Halo disablement using something similar
*/
	$.fn.extend({
		custombox: function(options) {
			var boxoptions = $.extend({}, $.custombox.defaults, options);

			/* Setup general click & focus handlers */
			$('html').click(function() { 
				$('div.' + $.custombox.defaults.boxClass).each(function() {
					if($(this).settings().menuOpen) { 
						closeMenu($(this));
					}
				});
				clearFocus();
			});
			$('textarea, :text, :password, :radio, :checkbox, :button').focus(function() { clearFocus(); closePreviousMenus(); });
			return $(this).each(function() {
				var $select = $(this);
				var menuWidth = ($select.width()+10);
				var selectWidth = menuWidth + 5; /* Required for IE */
				if($select.children().length < 1) { $('<option/>').appendTo($select); } /* Fix for empty select objects */
				/* Setup CustomBox */
				var $control = $('<div/>')
				.addClass(boxoptions.boxClass)
				.removeData($.custombox.dsName) /* Clear Legacy Data */
				.data($.custombox.dsName, boxoptions) /* Store New Data */
				.settings({sourceID: $select.attr('id')}) /* Set the source control's ID */
				.css('width', selectWidth+'px');
				var $list = $('<ul class="list"/>'); buildMenu($select, $control, $list, $control.settings().sourceID);
				var $menu = $('<div class="menu"/>').append($list);
				var $wrapper = $('<div id="'+'cb_'+$control.settings().sourceID+'" class="'+$control.settings().containerClass+'"/>').append($menu).css('width', menuWidth+'px').hide();
				var $controlanchor = $('<a href="#" tabindex="-1" hidefocus="true"><span></span></a>');
				if($select.attr('disabled')) { $select.parents('.item').children().addClass('disabled'); } // Dynamically set Disabled state
				$controlanchor.children('span').text($list.find('li a.selected').text());
				$control.append($controlanchor);
				if($.browser.msie && parseInt($.browser.version) <= 7) {
					// Fix IE Select Z-index bug
					$controlanchor.after('<iframe src="'+boxoptions.shimUrl+'" tabindex="-1" hidefocus="true" border="1"/>');			
				}
				$select.after($control).accessibleHide();
				$control.after($wrapper);
				if($control.settings().contextMenuDisabled) {$control.disableContextMenu();} /* Disable context menu based on defaults */
				if($control.settings().calculateMenuMaxHeight) {
					var menuMaxHeight = ($control.settings().menuNumItems * parseInt($list.find('li.first a span').css('height'))) + 'px';
				} else {
					var menuMaxHeight = $control.settings().menuMaxHeight;
				}
				if($select.children('option').length <= $control.settings().menuNumItems) { $wrapper.height('auto'); } else { $wrapper.height(menuMaxHeight); } // Setup for Dynamic Height Control

				/* Event Bindings */
				/* Control Anchor Bindings */
				$controlanchor.click(function() {
					if(!$select.parents('.control').hasClass('disabled')) {
						$('.hasfocus :input').trigger('blur');
						$select.triggerHandler('click'); } return false; })
				.mousedown(function() { return false; });

				/* Select Bindings */
				$select.focus(function() {
					clearFocus(); closePreviousMenus(); setFocus($control);
					if($control.settings().openOnTab) { openMenu($control); }
				})
				.click(function() {
					if($control.settings().menuOpen) {
						closeMenu($control);
					} else {
						setFocus($control);
						openMenu($control);
					}
					$select.trigger('focus'); return false;
				}).blur(function() {
					// var nextControlDisabled = $(this).parents('.item').next().hasClass('disabled');
					// if($(this).parents('.item').next().find('.control :input')[0].type != 'select-one' || nextControlDisabled) { closePreviousMenus(); }
					/* Legacy Method - Now Direct binding to Click & Tab focus loss */
				})
				.change(function() {
	 				$list.find('li a.selected').removeClass('selected');
					var $active = $list.children().eq($(this)[0].selectedIndex).children('a');
					$active.addClass('selected');
					$control.settings({selectedMenuItemID: $active.attr('id')});
					$select.next().find('a span').text($active.text()); //  Update Text
				}).keyup(function(event) {
					$(this).trigger('change'); // Textual matching
				}).keypress(function(event,data) {
					if(event.keyCode) {
						var kc = event.keyCode;
						if(kc == 40 || kc == 39) { // Down Arrow && Right Arrow
							$(this).moveMenuSelectionDown();
						} else if(kc == 38 || kc == 37) { // Up Arrow && Left Arrow
							$(this).moveMenuSelectionUp();
						} else if(kc == 35 || kc == 34) { // Move Last && Page Down
							if($list.find('li a.selected').length == 1) { $list.find('li a.selected').removeClass('selected'); }
							var $lastCousin = $list.find('li.last a');
							$lastCousin.addClass('selected');
							$control.settings({selectedMenuItemID: $lastCousin.attr('id')});
							$control.find('a span').text($lastCousin.text());
						} else if(kc == 36 || kc == 33) { // Move First && Page Up
							if($list.find('li a.selected').length == 1) { $list.find('li a.selected').removeClass('selected'); }
							var $firstCousin = $list.find('li.first a');
							$firstCousin.addClass('selected');
							$control.settings({selectedMenuItemID: $firstCousin.attr('id')});
							$control.find('a span').text($firstCousin.text());
						} else if(kc == 13 || kc == 27 || kc == 9) { // Enter || Escape
							closeMenu($control);
						}
					} else { // Correct IE's problem with left and right arrow keys in selects & keypress repeats
						var kc = data;
						if(kc == 40) {$(this).moveMenuSelectionDown(); }
						else if (kc == 38) {$(this).moveMenuSelectionUp(); }
						else if(kc == 39) { window.event.keyCode = 40; $(this).moveMenuSelectionDown(); } 
						else if(kc == 37) { window.event.keyCode = 38; $(this).moveMenuSelectionUp(); }
						else if(kc == 9) {
							//closeMenu($control);
						}
					}
				});
			});
		},
		/* Usage:
			Getter:  $(this).settings(); Returns: Current Settings List
			Setter:  $(this).settings({containerClass: 'custombox-wrapper4', boxType: 'combo'}); Returns: Chainable Object
		*/
		settings: function() { if(arguments.length > 0) {$.custombox.settings($(this), arguments[0]); return $(this);} else {return $.custombox.settings($(this));} },
		enableContextMenu: function() { $.custombox.enableContextMenu($(this)); return $(this); },
		disableContextMenu: function() { $.custombox.disableContextMenu($(this)); return $(this); },
		updateOptions: function() {
			$(this).each(function(i) {
				var sourceID = $(this)[i].id, $select = $(this), $control = $select.next(), $wrapper = $control.next();
				if($select.children('option').length <= 10) { $wrapper.height('auto'); } else { $wrapper.height($control.settings().menuMaxHeight); } // Setup for Dynamic Height Control
				var $list = $control.next('#cb_'+$(this)[i].id).find('.list');
				$list.empty(); buildMenu($select, $control, $list, sourceID);
				var $active = $list.children().eq($(this)[0].selectedIndex).children('a');
				$select.next().find('a span').text($active.text()); //  Update Text
			});
		},
		toggleError: function() { $(this).each(function(i) { $(this).closest('.control').toggleClass('error'); }); },
		disableControl: function() {
			/* Optional Argument: clear - Wipe Data from text, password, and resets selects to the defaultselected */
			if(arguments.length > 0) { var clearFields = arguments[0].clearFields; } else { var clearFields = false; }
			$(this).each(function() {
				$(this).attr('disabled','disabled').parents('.item').children().addClass('disabled');
				$(this).parents('.item').find('label').addClass('disabled');
				
				if(clearFields) {
					if($(this)[0].type == 'select-one') {
						$(this).children('option').each(function() {
							if($(this)[0].defaultSelected) { $(this).attr('selected','selected'); } else { $(this).removeAttr('selected'); }
						});
						$(this).updateOptions();
					} else if($(this).is(':text') || $(this).is(':password')) { $(this).val(''); }
				}
			});
		},
		enableControl: function() { $(this).each(function(i) { 
			$(this).removeAttr('disabled').closest('.item').find('.disabled').removeClass('disabled'); });
		},
		moveMenuSelectionDown: function() {
			var sourceID = $(this)[0].id, $select = $(this), $control = $select.next();
			var $menu = $control.next('#cb_'+$(this)[0].id);
			var $list = $menu.find('.list');
			if($list.find('li a.selected').parent().next().is('li')) {
				if($list.find('li a.selected').length == 1) { // Selected Item Exists
					var $nextCousin = $list.find('li a.selected').parent().next().children();
				} else { // No Selected Item Exists
					var $nextCousin = $list.find('li:first a').parent().next().children();
				}
				$list.find('li a.selected').removeClass('selected');
				$nextCousin.addClass('selected');
				$control.settings({selectedMenuItemID: $nextCousin.attr('id')});
				$control.find('a span').text($nextCousin.text()); // Update Text
				if($control.settings().menuOpen) { /* Scroll Menu Entry Into View */
					var currentVOffset = $nextCousin.position().top + $nextCousin.innerHeight() - 10;
					if(currentVOffset > $menu.innerHeight()) { $menu.scrollTop($menu.scrollTop() + 20); }
				}
			}
		},
		moveMenuSelectionUp: function() {
			var sourceID = $(this)[0].id, $select = $(this), $control = $select.next();
			var $menu = $control.next('#cb_'+$(this)[0].id);
			var $list = $menu.find('.list');
			if($list.find('li a.selected').parent().prev().is('li')) {
				if($list.find('li a.selected').length == 1) { // Selected Item Exists
					var $prevCousin = $list.find('li a.selected').parent().prev().children();
					$list.find('li a.selected').removeClass('selected');
				} else { // No Selected Item Exists
					$current = $list.find('li a')[0];
					var $prevCousin = $current.parent().prev().children();
				}
				$prevCousin.addClass('selected');
				$control.settings({selectedMenuItemID: $prevCousin.attr('id')});
				$control.find('a span').text($prevCousin.text()); // Update Text
				if($control.settings().menuOpen) { /* Scroll Menu Entry Into View */
					var currentVOffset = $prevCousin.position().top;
					if(currentVOffset < $menu.scrollTop()) { $menu.scrollTop($menu.scrollTop() - 20); }
				}

			}
		}
	});

/* Private Functions */
	function buildMenu($select, $control, $list, srcID) {
		$select.children('option').each(function(i) {
			if(i == 0){ var $li = $('<li class="first"></li>'); }
			else if(i == ($select[0].options.length - 1)){ var $li = $('<li class="last"></li>'); }
			else { var $li = $('<li></li>'); }
			if($(this).is(':selected')) { $control.settings({selectedMenuItemID: $(this).attr('id')}); } else { $control.settings({selectedMenuItemID: srcID + '_1'}); }

			var $itemanchor = $('<a href="#" tabindex="-1" hidefocus="true" id="'+srcID+'_'+$(this).val()+'"'+(($(this).is(':selected')) ? ' class="selected"' : '')+'><span>'+$(this).text()+'</span></a>')
			.mousedown(function() { $list.find('li a.selected').removeClass('selected'); })
			.mouseup(function(event) {
				$(this).addClass('selected');
				$control.settings({selectedMenuItemID: $(this).attr('id')});/* Store Selected Menu Item */
				$select.next().find('a span').text($(this).text()); //  Update Div Text
				var keyTxt = $(this).text(), keyID = $(this).attr('id');
				$('#'+keyID.substring(0, keyID.lastIndexOf('_'))+' > option').each(function(i) { if($(this).text() === keyTxt) { $select[0].selectedIndex = i; } }); // Set Select Status
				closeMenu($control);
				$select.trigger('change').trigger('focus');
				return false;
			}).mouseover(function() {
				$list.find('li a.selected').removeClass('selected').addClass('wasselected');
			})
			.click(function() {return false;});
			$li.append($itemanchor);
			$list.append($li);
		});
	}
	function closeMenu($custombox) {	
		var $menu = $custombox.next('.'+$custombox.settings().containerClass);
		if($menu.find('li a.selected').length > 0) {
			$menu.find('li a.wasselected').removeClass('wasselected');
		} else {
			$menu.find('li a.wasselected').addClass('selected').removeClass('wasselected');
		}
		$custombox.next('.'+$custombox.settings().containerClass).slideUp(100, function() {
			$custombox.settings({menuOpen: false}).parents('.item').css('z-index','1');
		});
	}
	function openMenu($custombox) {
		$custombox.parents('.item').css('z-index','99');
		$custombox.next('.'+$custombox.settings().containerClass).stop(false,true).slideDown('fast', function() {
			$custombox.settings({menuOpen: true});
			var $menu = $custombox.next('.'+$custombox.settings().containerClass);
			if($menu.find('li a.selected').length > 0) { var currentVOffset = $menu.find('li a.selected').position().top; } 
			else if ($menu.find('li a.wasselected').length > 0) { var currentVOffset = $menu.find('li a.wasselected').position().top; } 
			else { var currentVOffset = 0; }
			if(currentVOffset >= $menu.innerHeight()) { $menu.scrollTop(currentVOffset); } else { $menu.scrollTop(0); }
		});// Scroll Selected Item into view 
	}
	function closePreviousMenus() { $('div.' + $.custombox.defaults.boxClass).each(function() { if($(this).settings().menuOpen) { closeMenu($(this)); } }); }
	function clearFocus() {
		$('div.' + $.custombox.defaults.boxClass).each(function() { 
			removeFocus($(this));
		});
	}
	function setFocus($obj) {
		$obj.parents('.control').addClass('hasfocus');
	}
	function removeFocus($obj) {
		$obj.parents('.control').removeClass('hasfocus');
	}
/* End Closure */
})(jQuery);

$(function() {
	/* Correct IE Support Issues */
	if($.browser.msie && parseInt($.browser.version) <= 7) {
		var preloadSelectImages = [contextPath + '/docroot/ally-storefront/images/textinput-400.png',contextPath + '/docroot/ally-storefront/images/textinput-left-mask.png',contextPath + '/docroot/ally-storefront/images/textinput-dollar-mask.png',contextPath + '/docroot/ally-storefront/images/select-right.png',contextPath + '/docroot/ally-storefront/images/instructional-text-bg.png'];
		jQuery.each(preloadSelectImages, function() {
			var tmpImg = new Image();
			tmpImg.src = this;
		});
		// Correct IE's problem with attribute selectors
//		$('form input:text, form input:password').focus(function() {setFocus($(this));}).blur(function() {removeFocus($(this));});
		// Correct IE's problem with left and right arrow keys in selects & keypress repeats
		$('form select').keydown(function(event) { $(this).triggerHandler('keypress',[event.keyCode]); });
	}
});