﻿/*******************************************************************************
 * dPassword v0.7 - Delayed Password Masking: iPhone jQuery Plugin
 * Usage: <code>$('input[type=password]').dPassword(options)</code>
 * Options parameter can have the following entries:
 *        delay:				Number of seconds after which to hide input. Defaults to 1.
 *        observeForm:			Whether to automatically deactivate when parent form is submitted (default: true).
 *        form:					Form element different from parent form to observe for submitting (forces observeForm == true).
 *        cloakingCharacter:	Character to replace entered characters with. Default is bullet (•).
 *        onChange:   			Handler when password has been changed.
 *        onStateChange:   		Handler when masking behaviour changes.
 *        switchToPasswordType:	Whether to switch input field back to password type on blur (looks bad in IE).
 *		  showIcon: 			Show a lock icon allowing the user to toggle masking behaviour (default == true).
 *								Options: ICON_TITLE_ON, ICON_TITLE_OFF, ICON_PATH, ICON_STYLES, ICON_STYLES_ON, ICON_STYLES_OFF
 * Licensed under MIT License*/
(function() { jQuery.fn.dPassword = function(options) {
	    if (this.length > 1) {// support multiple elements
	        this.each(function() {jQuery(this).dPassword(options);});
	        return this;
	    }
		var options = jQuery.extend(defaultOptions, options);
		options.cloakingCharacter = options.cloakingCharacter.charAt(0);
		var _input = $(this);
		var _value = null, _previousInputValue = null, _timeout = null, _previousSelection = null, _options = null, _observing = false, _form = null, _toggleIcon = null, _keysDown = {}, _inputFieldTypes = {};
		registerHandlers(_input);// register event listeners
		if (options.observeForm || options.form) {
			if (!_form) _form = options.form ? $(options.form) : _input.closest('form');
			if (_form) _form.bind("submit.dPassword", function(){deactivate(true);});
		}
		if (options.showIcon) {// create/handle toggle icon
			_toggleIcon = jQuery("<div class='dpassword-lock'></div>").insertAfter(_input);
			_toggleIcon.css({backgroundImage: "url(" + (options.iconPath || options.ICON_PATH) + ")"});
			_toggleIcon.css(options.ICON_STYLES);
			_toggleIcon.bind("click", function() {
				_observing ? deactivate() : activate();
				_input.focus();
			});
		}
		activate();
		return this;
		// ------- method declarations ----------
		function getValue() { return _observing ? _value : _input.val();} // return current value of password field
		/* Switches to active mode. Automatically called on initialization. getValue() retrieves field value once activated. */
		function activate() {
			_observing = true;
			_value = _input.val();
			_cloakInput();
			if (_toggleIcon) _switchToggleIcon(true);
			if (options.onStateChange) options.onStateChange(_observing, this, _toggleIcon);
		}
		/* Deactivates dPassword temporarily/permanently & switches back to normal password behaviour.
		 * IMPORTANT: If "temporarily" parameter == true, will auto-reactivate on any input.*/
		function deactivate(temporarily) {
			if (_observing) {
				if (_timeout) {
					clearTimeout(_timeout);
					_timeout = null;
				}
				var selection = _getFieldSelection(_input);
				jQuery.browser.msie ? _switchInputTypeIE("password") : _input.get(0).setAttribute("type", "password");	// override jQuery behaviour
				_input.val(getValue());
				if (document.activeElement && document.activeElement == _input) _setFieldSelection(_input, selection);
				if (temporarily !== true) {
					_observing = false;
					if (_toggleIcon) _switchToggleIcon(false);
					if (options.onStateChange) options.onStateChange(_observing, this, _toggleIcon);
				}
			}
		}
		function _keyDownHandler(event) {
			if (_observing) {
				if (!(_isSpecialKey(event.keyCode) || event.metaKey || event.ctrlKey)) {
					var keyCode = null;
					for (var keyCode in _keysDown) {
						_afterInputHandler(keyCode);
					}
					_storeSelection();
					if (!keyCode) _cloakInput();
					if (event.keyCode > 10) _keysDown[event.keyCode] = true;
				} else {
					_storeSelection();
					if (_timeout) {
						clearTimeout(_timeout);
						_timeout = null;
						_cloakInput();
					}
				}
			}
		}
		function _keyUpHandler(event) {
			if (_observing) {
				if (event.type == "paste") {
					setTimeout(_afterInputHandler, 0);
					return;
				}
		    	if (_isSpecialKey(event.keyCode) || event.metaKey || event.ctrlKey) return;
				if (_keysDown[event.keyCode] || event.keyCode < 11) _afterInputHandler(event);
			} else {
				var value = _input.val();
				if (value != _previousInputValue) {
					_previousInputValue = value;
					if (options.onChange) options.onChange(getValue());
				}
			}
		}
		function _afterInputHandler(keyCode) {
			delete _keysDown[keyCode];
			var value = _input.val();
			var selection = _getFieldSelection(_input);
			if (_previousInputValue != value) {
				var sStart = _previousSelection[0], sEnd =_previousSelection[1],sLength = _previousSelection[2],lengthDifference = value.length - _value.length, newValue;			
				if (lengthDifference < 0 && sLength == 0) {	 // single character deletion
					if (sStart == selection[0]) { newValue = _value.substring(0, sStart) + _value.substring(sEnd + 1); // forward deletion
					} else { newValue = _value.substring(0, selection[0]) + _value.substring(sEnd);} // has to be backward deletion
				} else { newValue = _value.substring(0, sStart) + value.substring(sStart, selection[1]) + _value.substring(sEnd);}
				_value = newValue;
				if (options.onChange) options.onChange(getValue());
				if (_timeout) {
					clearTimeout(_timeout);
					_timeout = null;
				}
				if (lengthDifference >= 0) { // leave newly written part uncloaked
					_cloakInput([sStart + 1, selection[1]]);
					_timeout = setTimeout(_cloakInput, options.delay * 1000);
				}
			} else { _previousSelection = selection;}
		}
		function registerHandlers(element) {
			element.bind("keydown.dPassword", _keyDownHandler);
			element.bind("keyup.dPassword paste.dPassword", _keyUpHandler);
			element.bind("select.dPassword focus.dPassword", _storeSelection);
			if (options.switchToPasswordType) { _input.bind("blur.dPassword", function() {deactivate(true);});}	
		}
		function _storeSelection() { if (_observing)	_previousSelection = _getFieldSelection(_input);}
		function _cloakInput(keepRange) {
			var selection = _getFieldSelection(_input);
			var value = _input.val();
			if (keepRange) {
				_input.val(value.substring(0, keepRange[0] - 1 ).replace(/./g, options.cloakingCharacter) + value.substring(keepRange[0] - 1, keepRange[1]) + value.substring(keepRange[1]).replace(/./g, options.cloakingCharacter));
			} else {
				_input.val(value.replace(/./g, options.cloakingCharacter));
				if (_input.attr("type") != "text") {
					if (jQuery.browser.msie) { _switchInputTypeIE("text");
					} else { _input.get(0).setAttribute("type", "text");}
					_input.attr("autocomplete", "off");
				}
			}
			if (document.activeElement && document.activeElement == _input.get(0)) _setFieldSelection(_input, selection);
			_previousInputValue = _input.val();
		}
		function _switchInputTypeIE(toType) {
			var newInput = _inputFieldTypes[toType]; // create input field (or retrieve from cache) with new type
			if (!newInput) {
				var tempDiv = _input.clone().wrap('<div></div>').parent();
				if (toType == "password") { tempDiv.html(tempDiv.html().replace(/>/, 'type="password">'));
				} else { tempDiv.html(tempDiv.html().replace(/type="?password"?/, 'type="text"'));}
				newInput = tempDiv.children();
				registerHandlers(newInput);
			}
			newInput.css('width', (_input.get(0).clientWidth - 2*parseInt(_input.get(0).currentStyle.padding, 10)) + "px"); // update field
			newInput.css('height', (_input.get(0).clientHeight - 2*parseInt(_input.get(0).currentStyle.padding, 10)) + "px"); // fix diff widths for pw & text inputs in IE
			var oldInput = _input;
			oldInput.get(0).replaceNode(newInput.get(0)); // jQuery's replaceWith method kills event handlers.
			_input = newInput;
			_input.val(oldInput.val());
			if (!_inputFieldTypes) { _inputFieldTypes = { password: (toType == "password") ? newInput : oldInput, text: (toType == "password") ? oldInput : newInput };}
		}
		function _switchToggleIcon(state) {
			if (state) {
				_toggleIcon.css(options.ICON_STYLES_OFF).css({className: "dpassword-lock-closed"});
				_toggleIcon.attr('title', options.ICON_TITLE_ON);
			} else {
				_toggleIcon.css(options.ICON_STYLES_ON).css({className: "dpassword-lock-closed"});
				_toggleIcon.attr('title', options.ICON_TITLE_OFF);
			}
		}
	};
	var defaultOptions = { delay: 1, observeForm: true, form: null, cloakingCharacter: (navigator.platform == "MacIntel") ? '\u2022' : '\u25CF', onChange: null, onStateChange: null, showIcon: true, switchToPasswordType: !jQuery.browser.msie, ICON_TITLE_ON: "[Deactivate Delayed Password Masking]", ICON_TITLE_OFF: "[Activate Delayed Password Masking]", ICON_STYLES: { display: "inline", position: "absolute", width: "32px", height: "32px", margin: "-10px 0 0 -12px", overflow: "hidden", cursor: "pointer", backgroundRepeat: "no-repeat" }, ICON_PATH: "../images/icons/ui-icon-circle-info.gif",ICON_STYLES_OFF: { backgroundPosition: "0 0" },ICON_STYLES_ON: { backgroundPosition: "0 -32px" }};
	function _getFieldSelection(element) {
		if (document.selection) {
			var range = document.selection.createRange();
			var length = range.text.length;
			range.moveStart('character', -element.val().length); // Move selection start to 0 position
			var cursorPos = range.text.length;	// The caret position is now the selection length
			return [cursorPos - length, cursorPos, length];
		} else {
			var el = element.get(0);
			return [el.selectionStart, el.selectionEnd, el.selectionEnd - el.selectionStart];
		}
	}
	function _setFieldSelection(element, selection) {
		var el = element.get(0);
		if (document.selection) {
			var range = el.createTextRange();
			range.collapse();
			range.moveStart('character', selection[0]);
			range.moveEnd('character', selection[1] - selection[0]);
			range.select();
		} else {
			el.selectionStart = selection[0];
			el.selectionEnd = selection[1];
		}
	}
	function _isSpecialKey(keyCode) { return (keyCode >= 9 && keyCode <= 20) || (keyCode >= 33 && keyCode <= 40) || keyCode == 224;}
})(jQuery);

/* jQuery plugin: customInput() by Maggie Wachs and Scott Jehl, http://www.filamentgroup.com
 * Copyright (c) 2009 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) & GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 * Article: http://www.filamentgroup.com/lab/accessible_custom_designed_checkbox_radio_button_inputs_styled_css_jquery/ */
/*  jQuery UI transParent Extensions: ui.button.js, ui.input.js, ui.menu.js, ui.selectmenu.js;
	Extended by Keith Parent (http://www.keithparent.com) */
jQuery(document).ready(function($){
	$("input").each(function(i){
		if($(this).is("input:checkbox,input:radio")){
			var input = $(this);
			$(this).addClass("hide");
			var label = $('label[for='+input.attr('id')+']');
			var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
			$('<div class="ui-'+ inputType +'"></div>').insertBefore(input).append(input, label);
			var allInputs = $('input[name='+input.attr('name')+']');
			label.hover(
				function(){ 
					$(this).addClass('hover'); 
					if(inputType == 'checkbox' && input.is(':checked')){ 
						$(this).addClass('checkedHover'); 
					} 
				},
				function(){ $(this).removeClass('hover checkedHover'); }
			);
			input.bind('updateState', function(){	
				if (input.is(':checked')) {
					if (input.is(':radio')) {				
						allInputs.each(function(){
							$('label[for='+$(this).attr('id')+']').removeClass('checked');
						});		
					};
					label.addClass('checked');
				}
				else { label.removeClass('checked checkedHover checkedFocus'); }						
			})
			.trigger('updateState')
			.click(function(){ 
				$(this).trigger('updateState'); 
			})
			.focus(function(){ 
				label.addClass('focus'); 
				if(inputType == 'checkbox' && input.is(':checked')){ 
					$(this).addClass('checkedFocus'); 
				} 
			})
			.blur(function(){ label.removeClass('focus checkedFocus'); });
		} else if($(this).is("input:submit, input:reset")){
			$("input:submit, input:reset").addClass("ui-button ui-state-default");
			$("input:submit:not(.ui-state-disabled),input:reset:not(.ui-state-disabled)")
				.hover(
					function() { $(this).addClass("ui-state-hover");},
					function() { $(this).removeClass("ui-state-hover");});
			$(".ui-buttonset #submit").addClass("ui-corner-left");
			$(".ui-buttonset #reset").addClass("ui-corner-right");
		} else if($(this).is("input:password")){
			$("input:password").dPassword({
				//cloakingCharacter: '%u00D7',
				duration: 10000,
				showIcon: true
			});
			$("#password").addClass("ui-corner-left");
			$("#show-password").click( function() {
				alert('PASSWORD: '+$("#password").val());
				return false;
			});
		} else {
			$("input:not(.ui-buttonset #submit,.ui-buttonset #reset,#password),select,textarea").addClass("ui-corner-all");
		};
		//$("input:text:first").focus();
		return i;
	});
});

/*-------------------------------------------------------------------- 
Scripts for creating and manipulating custom menus based on standard <ul> markup
Version: 3.0, 03.31.2009
By: Maggie Costello Wachs (maggie@filamentgroup.com) & Scott Jehl (scott@filamentgroup.com)
	http://www.filamentgroup.com/lab/jquery_ipod_style_drilldown_menu/
Copyright (c) 2009 Filament Group
Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) & GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
--------------------------------------------------------------------*/
var allUIMenus = [];
$.fn.menu = function(options){
	var caller = this;
	var options = options;
	var m = new Menu(caller, options);	
	allUIMenus.push(m);
	$(this)
	.mousedown(function(){
		if (!m.menuOpen) { m.showLoading(); };
	})	
	.click(function(){
		if (m.menuOpen == false) { m.showMenu(); }
		else { m.kill(); };
		return false;
	});	
};
function Menu(caller, options){
	var menu = this;
	var caller = $(caller);
	var container = $('<div class="ui-menu-container ui-widget ui-widget-content ui-corner-all">'+options.content+'</div>');
	this.menuOpen = false;
	this.menuExists = false;
	var options = jQuery.extend({
		content: null,
		width: 180, // width of menu container, must be set or passed in to calculate widths of child menus
		maxHeight: 180, // max height of menu (if a drilldown: height does not include breadcrumb)
		positionOpts: {
			posX: 'left', 
			posY: 'bottom',
			offsetX: 0,
			offsetY: 0,
			directionH: 'right',
			directionV: 'down', 
			detectH: true, // do horizontal collision detection  
			detectV: true, // do vertical collision detection
			linkToFront: false
		},
		showSpeed: 200, // show/hide speed in milliseconds
		callerOnState: 'ui-state-active', // class to change the appearance of the link/button when the menu is showing
		loadingState: 'ui-state-loading', // class added to the link/button while the menu is created
		linkHover: 'ui-state-hover', // class for menu option hover state
		linkHoverSecondary: 'li-hover', // alternate class, may be used for multi-level menus		
	// ----- multi-level menu defaults -----
		crossSpeed: 200, // cross-fade speed for multi-level menus
		crumbDefaultText: 'Choose an option:',
		backLink: true, // in the ipod-style menu: instead of breadcrumbs, show only a 'back' link
		backLinkText: 'BACK',
		flyOut: false, // multi-level menus are ipod-style by default; this parameter overrides to make a flyout instead
		flyOutOnState: 'ui-state-default',
		nextMenuLink: 'ui-icon-circle-triangle-e', // class to style the link (specifically, a span within the link) used in the multi-level menu to show the next level
		topLinkText: 'All',
		nextCrumbLink: 'ui-icon-carat-1-e'	
	}, options);
	var killAllMenus = function(){
		$.each(allUIMenus, function(i){
			if (allUIMenus[i].menuOpen) { allUIMenus[i].kill(); };	
		});
	};
	this.kill = function(){
		caller
			.removeClass(options.loadingState)
			.removeClass('ui-menu-open')
			.removeClass(options.callerOnState);	
		container.find('li').removeClass(options.linkHoverSecondary).find('a').removeClass(options.linkHover);		
		if (options.flyOutOnState) { container.find('li a').removeClass(options.flyOutOnState); };	
		if (options.callerOnState) { 	caller.removeClass(options.callerOnState); };			
		if (container.is('.ui-menu-ipod')) { menu.resetDrilldownMenu(); };
		if (container.is('.ui-menu-flyout')) { menu.resetFlyoutMenu(); };	
		container.parent().hide();	
		menu.menuOpen = false;
		$(document).unbind('click', killAllMenus);
		$(document).unbind('keydown');
	};
	this.showLoading = function(){
		caller.addClass(options.loadingState);
	};
	this.showMenu = function(){
		killAllMenus();
		if (!menu.menuExists) { menu.create() };
		caller
			.addClass('ui-menu-open')
			.addClass(options.callerOnState);
		container.parent().show().click(function(){ menu.kill(); return false; });
		container.hide().slideDown(options.showSpeed).find('.ui-menu:eq(0)');
		menu.menuOpen = true;
		caller.removeClass(options.loadingState);
		$(document).click(killAllMenus);
		// assign key events
		$(document).keydown(function(event){
			var e;
			if (event.which !="") { e = event.which; }
			else if (event.charCode != "") { e = event.charCode; }
			else if (event.keyCode != "") { e = event.keyCode; }
			var menuType = ($(event.target).parents('div').is('.ui-menu-flyout')) ? 'flyout' : 'ipod' ;
			switch(e) {
				case 37: // left arrow 
					if (menuType == 'flyout') {
						$(event.target).trigger('mouseout');
						if ($('.'+options.flyOutOnState).size() > 0) { $('.'+options.flyOutOnState).trigger('mouseover'); };
					};
					
					if (menuType == 'ipod') {
						$(event.target).trigger('mouseout');
						if ($('.ui-menu-footer').find('a').size() > 0) { $('.ui-menu-footer').find('a').trigger('click'); };
						if ($('.ui-menu-header').find('a').size() > 0) { $('.ui-menu-current-crumb').prev().find('a').trigger('click'); };
						if ($('.ui-menu-current').prev().is('.ui-menu-indicator')) {
							$('.ui-menu-current').prev().trigger('mouseover');							
						};						
					};
					return false;
					break;	
				case 38: // up arrow 
					if ($(event.target).is('.' + options.linkHover)) {	
						var prevLink = $(event.target).parent().prev().find('a:eq(0)');						
						if (prevLink.size() > 0) {
							$(event.target).trigger('mouseout');
							prevLink.trigger('mouseover');
						};						
					}
					else { container.find('a:eq(0)').trigger('mouseover'); }
					return false;
					break;	
				case 39: // right arrow 
					if ($(event.target).is('.ui-menu-indicator')) {						
						if (menuType == 'flyout') {
							$(event.target).next().find('a:eq(0)').trigger('mouseover');
						}
						else if (menuType == 'ipod') {
							$(event.target).trigger('click');						
							setTimeout(function(){
								$(event.target).next().find('a:eq(0)').trigger('mouseover');
							}, options.crossSpeed);
						};				
					}; 
					return false;
					break;
				case 40: // down arrow 
					if ($(event.target).is('.' + options.linkHover)) {
						var nextLink = $(event.target).parent().next().find('a:eq(0)');						
						if (nextLink.size() > 0) {							
							$(event.target).trigger('mouseout');
							nextLink.trigger('mouseover');
						};				
					}
					else { container.find('a:eq(0)').trigger('mouseover'); }		
					return false;						
					break;
				case 27: // escape
					killAllMenus();
					break;
				case 13: // enter
					if ($(event.target).is('.ui-menu-indicator') && menuType == 'ipod') {							
						$(event.target).trigger('click');						
						setTimeout(function(){
							$(event.target).next().find('a:eq(0)').trigger('mouseover');
						}, options.crossSpeed);					
					}; 
					break;
			};			
		});
	};
	this.create = function(){	
		container.css({ width: options.width }).appendTo('body').find('ul:first').not('.ui-menu-breadcrumb').addClass('ui-menu');
		container.find('ul, li a').addClass('ui-corner-all');
		// aria roles & attributes
		container.find('ul').attr('role', 'menu').eq(0).attr('aria-activedescendant','active-menuitem').attr('aria-labelledby', caller.attr('id'));
		container.find('li').attr('role', 'menuitem');
		container.find('li:has(ul)').attr('aria-haspopup', 'true').find('ul').attr('aria-expanded', 'false');
		container.find('a').attr('tabindex', '-1');
		// when there are multiple levels of hierarchy, create flyout or drilldown menu
		if (container.find('ul').size() > 1) {
			if (options.flyOut) { menu.flyout(container, options); }
			else { menu.drilldown(container, options); }	
		}
		else {
			container.find('a').click(function(){
				menu.chooseItem(this);
				return false;
			});
		};
		if (options.linkHover) {
			var allLinks = container.find('.ui-menu li a');
			allLinks.hover(
				function(){
					var menuitem = $(this);
					$('.'+options.linkHover).removeClass(options.linkHover).blur().parent().removeAttr('id');
					$(this).addClass(options.linkHover).focus().parent().attr('id','active-menuitem');
				},
				function(){
					$(this).removeClass(options.linkHover).blur().parent().removeAttr('id');
				}
			);
		};
		if (options.linkHoverSecondary) {
			container.find('.ui-menu li').hover(
				function(){
					$(this).siblings('li').removeClass(options.linkHoverSecondary);
					if (options.flyOutOnState) { $(this).siblings('li').find('a').removeClass(options.flyOutOnState); }
					$(this).addClass(options.linkHoverSecondary);
				},
				function(){ $(this).removeClass(options.linkHoverSecondary); }
			);
		};
		menu.setPosition(container, caller, options);
		menu.menuExists = true;
	};
	this.chooseItem = function(item){
		menu.kill();
		// edit this for your own custom function/callback:
		$('#menuSelection').text($(item).text());	
		location.href = $(item).attr('href');
	};
};
Menu.prototype.flyout = function(container, options) {
	var menu = this;
	this.resetFlyoutMenu = function(){
		var allLists = container.find('ul ul');
		allLists.removeClass('ui-widget-content').hide();	
	};
	container.addClass('ui-menu-flyout').find('li:has(ul)').each(function(){
		var linkWidth = container.width();
		var showTimer, hideTimer;
		var allSubLists = $(this).find('ul');		
		allSubLists.css({ left: linkWidth, width: linkWidth }).hide();
		$(this).find('a:eq(0)').addClass('ui-menu-indicator').html('<span>' + $(this).find('a:eq(0)').text() + '</span><span class="ui-icon '+options.nextMenuLink+' right"></span>').hover(
			function(){
				clearTimeout(hideTimer);
				var subList = $(this).next();
				if (!fitVertical(subList, $(this).offset().top)) { subList.css({ top: 'auto', bottom: 0 }); };
				if (!fitHorizontal(subList, $(this).offset().left + 100)) { subList.css({ left: 'auto', right: linkWidth, 'z-index': 999 }); };
				showTimer = setTimeout(function(){
					subList.addClass('ui-widget-content').show(options.showSpeed).attr('aria-expanded', 'true');	
				}, 300);	
			},
			function(){
				clearTimeout(showTimer);
				var subList = $(this).next();
				hideTimer = setTimeout(function(){
					subList.removeClass('ui-widget-content').hide(options.showSpeed).attr('aria-expanded', 'false');
				}, 400);	
			}
		);
		$(this).find('ul a').hover(
			function(){
				clearTimeout(hideTimer);
				if ($(this).parents('ul').prev().is('a.ui-menu-indicator')) {
					$(this).parents('ul').prev().addClass(options.flyOutOnState);
				}
			},
			function(){
				hideTimer = setTimeout(function(){
					allSubLists.hide(options.showSpeed);
					container.find(options.flyOutOnState).removeClass(options.flyOutOnState);
				}, 500);	
			}
		);	
	});
	container.find('a').click(function(){
		menu.chooseItem(this);
		return false;
	});
};
Menu.prototype.drilldown = function(container, options) {
	var menu = this;	
	var topList = container.find('.ui-menu');	
	var breadcrumb = $('<ul class="ui-menu-breadcrumb ui-widget-header ui-corner-all ui-helper-clearfix"></ul>');
	var crumbDefaultHeader = $('<li class="ui-menu-breadcrumb-text">'+options.crumbDefaultText+'</li>');
	var firstCrumbText = (options.backLink) ? options.backLinkText : options.topLinkText;
	var firstCrumbClass = (options.backLink) ? 'ui-menu-prev-list' : 'ui-menu-all-lists';
	var firstCrumbLinkClass = (options.backLink) ? 'ui-state-default ui-corner-all' : '';
	var firstCrumbIcon = (options.backLink) ? '<span class="ui-icon ui-icon-circle-triangle-w"></span>' : '';
	var firstCrumb = $('<li class="'+firstCrumbClass+'"><a href="#" class="'+firstCrumbLinkClass+'">'+firstCrumbIcon+firstCrumbText+'</a></li>');
	container.addClass('ui-menu-ipod');
	if (options.backLink) { breadcrumb.addClass('ui-menu-footer').appendTo(container).hide(); }
	else { breadcrumb.addClass('ui-menu-header').prependTo(container); };
	breadcrumb.append(crumbDefaultHeader);
	var checkMenuHeight = function(el){
		if (el.height() > options.maxHeight) { el.addClass('ui-menu-scroll') };	
		el.css({ height: options.maxHeight });
	};
	var resetChildMenu = function(el){ el.removeClass('ui-menu-scroll').removeClass('ui-menu-current').height('auto'); };
	this.resetDrilldownMenu = function(){
		$('.ui-menu-current').removeClass('ui-menu-current');
		topList.animate({ left: 0 }, options.crossSpeed, function(){
			$(this).find('ul').each(function(){
				$(this).hide();
				resetChildMenu($(this));				
			});
			topList.addClass('ui-menu-current');			
		});		
		$('.ui-menu-all-lists').find('span').remove();	
		breadcrumb.empty().append(crumbDefaultHeader);		
		$('.ui-menu-footer').empty().hide();	
		checkMenuHeight(topList);		
	};
	topList
		.addClass('ui-menu-content ui-menu-current ui-widget-content ui-helper-clearfix')
		.css({ width: container.width() })
		.find('ul')
			.css({ width: container.width(), left: container.width() })
			.addClass('ui-widget-content')
			.hide();		
	checkMenuHeight(topList);	
	topList.find('a').each(function(){
		if ($(this).next().is('ul')) {// if the link opens a child menu:
			$(this)
				.addClass('ui-menu-indicator')
				.each(function(){ $(this).html('<span>' + $(this).text() + '</span><span class="ui-icon '+options.nextMenuLink+'"></span>'); })
				.click(function(){ // ----- show the next menu			
					var nextList = $(this).next();
		    		var parentUl = $(this).parents('ul:eq(0)');   		
		    		var parentLeft = (parentUl.is('.ui-menu-content')) ? 0 : parseFloat(topList.css('left'));    		
		    		var nextLeftVal = Math.round(parentLeft - parseFloat(container.width()));
		    		var footer = $('.ui-menu-footer'); 		
		    		resetChildMenu(parentUl);// show next menu
		    		checkMenuHeight(nextList);
					topList.animate({ left: nextLeftVal }, options.crossSpeed);						
		    		nextList.show().addClass('ui-menu-current').attr('aria-expanded', 'true');    	
		    		var setPrevMenu = function(backlink){
		    			var b = backlink;
		    			var c = $('.ui-menu-current');
			    		var prevList = c.parents('ul:eq(0)');
			    		c.hide().attr('aria-expanded', 'false');
		    			resetChildMenu(c);
		    			checkMenuHeight(prevList);
			    		prevList.addClass('ui-menu-current').attr('aria-expanded', 'true');
			    		if (prevList.hasClass('ui-menu-content')) { b.remove(); footer.hide(); };
		    		};
					if (options.backLink) {// initialize "back" link
						if (footer.find('a').size() == 0) {
							footer.show();
							$('<a href="#"><span class="ui-icon ui-icon-circle-triangle-w"></span> <span>BACK</span></a>')
								.appendTo(footer)
								.click(function(){ // ----- show the previous menu
									var b = $(this);
						    		var prevLeftVal = parseFloat(topList.css('left')) + container.width();		    						    		
						    		topList.animate({ left: prevLeftVal },  options.crossSpeed, function(){
						    			setPrevMenu(b);
						    		});			
									return false;
								});
						}
					}
					else { // or initialize top breadcrumb
		    			if (breadcrumb.find('li').size() == 1){				
							breadcrumb.empty().append(firstCrumb);
							firstCrumb.find('a').click(function(){
								menu.resetDrilldownMenu();
								return false;
							});
						}
						$('.ui-menu-current-crumb').removeClass('ui-menu-current-crumb');
						var crumbText = $(this).find('span:eq(0)').text();
						var newCrumb = $('<li class="ui-menu-current-crumb"><a href="javascript://" class="ui-menu-crumb">'+crumbText+'</a></li>');	
						newCrumb
							.appendTo(breadcrumb)
							.find('a').click(function(){
								if ($(this).parent().is('.ui-menu-current-crumb')){
									menu.chooseItem(this);
								}
								else {
									var newLeftVal = - ($('.ui-menu-current').parents('ul').size() - 1) * 180;
									topList.animate({ left: newLeftVal }, options.crossSpeed, function(){
										setPrevMenu();
									});
									// make this the current crumb, delete all breadcrumbs after this one, and navigate to the relevant menu
									$(this).parent().addClass('ui-menu-current-crumb').find('span').remove();
									$(this).parent().nextAll().remove();									
								};
								return false;
							});
						newCrumb.prev().append(' <span class="ui-icon '+options.nextCrumbLink+'"></span>');
		    		};			
		    		return false;    		
    			});
		}
		else {// if the link is a leaf node (doesn't open a child menu)
			$(this).click(function(){
				menu.chooseItem(this);
				return false;
			});
		};
	});
};

/* Menu.prototype.setPosition parameters (defaults noted with *):
	referrer = the link (or other element) used to show the overlaid object 
	settings = can override the defaults:
		- posX/Y: where the top left corner of the object should be positioned in relation to its referrer.
				X: left*, center, right
				Y: top, center, bottom*
		- offsetX/Y: the number of pixels to be offset from the x or y position.  Can be a positive or negative number.
		- directionH/V: where the entire menu should appear in relation to its referrer.
				Horizontal: left*, right
				Vertical: up, down*
		- detectH/V: detect the viewport horizontally / vertically
		- linkToFront: copy the menu link and place it on top of the menu (visual effect to make it look like it overlaps the object) */

Menu.prototype.setPosition = function(widget, caller, options) { 
	var el = widget;
	var referrer = caller;
	var dims = { refX: referrer.offset().left, refY: referrer.offset().top, refW: referrer.getTotalWidth(), refH: referrer.getTotalHeight()};	
	var options = options;
	var xVal, yVal;
	var helper = $('<div class="positionHelper"></div>');
	helper.css({ position: 'absolute', left: dims.refX, top: dims.refY, width: dims.refW, height: dims.refH });
	el.wrap(helper);
	switch(options.positionOpts.posX) {// get X pos
		case 'left': 	xVal = 0; 
			break;				
		case 'center': xVal = dims.refW / 2;
			break;				
		case 'right': xVal = dims.refW;
			break;
	};
	switch(options.positionOpts.posY) {// get Y pos
		case 'top': 	yVal = 0;
			break;				
		case 'center': yVal = dims.refH / 2;
			break;				
		case 'bottom': yVal = dims.refH;
			break;
	};
	// add offsets (0 by default)
	xVal += options.positionOpts.offsetX;
	yVal += options.positionOpts.offsetY;
	// position vertically
	if (options.positionOpts.directionV == 'up') {
		el.css({ top: 'auto', bottom: yVal });
		if (options.positionOpts.detectV && !fitVertical(el)) {
			el.css({ bottom: 'auto', top: yVal });
		}
	} 
	else {
		el.css({ bottom: 'auto', top: yVal });
		if (options.positionOpts.detectV && !fitVertical(el)) {
			el.css({ top: 'auto', bottom: yVal });
		}
	};
	// & horizontally
	if (options.positionOpts.directionH == 'left') {
		el.css({ left: 'auto', right: xVal });
		if (options.positionOpts.detectH && !fitHorizontal(el)) {
			el.css({ right: 'auto', left: xVal });
		}
	} 
	else {
		el.css({ right: 'auto', left: xVal });
		if (options.positionOpts.detectH && !fitHorizontal(el)) {
			el.css({ left: 'auto', right: xVal });
		}
	};
	// if specified, clone the referring element and position it so that it appears on top of the menu
	if (options.positionOpts.linkToFront) {
		referrer.clone().addClass('linkClone').css({
			position: 'absolute', 
			top: 0, 
			right: 'auto', 
			bottom: 'auto', 
			left: 0, 
			width: referrer.width(), 
			height: referrer.height()
		}).insertAfter(el);
	};
};

/* Utilities to sort & find viewport dimensions */
function sortBigToSmall(a, b) { return b - a; };
jQuery.fn.getTotalWidth = function(){ return $(this).width() + parseInt($(this).css('paddingRight')) + parseInt($(this).css('paddingLeft')) + parseInt($(this).css('borderRightWidth')) + parseInt($(this).css('borderLeftWidth'));};
jQuery.fn.getTotalHeight = function(){ return $(this).height() + parseInt($(this).css('paddingTop')) + parseInt($(this).css('paddingBottom')) + parseInt($(this).css('borderTopWidth')) + parseInt($(this).css('borderBottomWidth'));};
function getScrollTop(){ return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;};
function getScrollLeft(){ return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;};
function getWindowHeight(){
	var de = document.documentElement;
	return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
};
function getWindowWidth(){
	var de = document.documentElement;
	return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
};

/* Utilities to test whether an element will fit in the viewport
	Parameters:
	el = element to position, required
	leftOffset / topOffset = optional parameter if the offset cannot be calculated (i.e., if the object is in the DOM but is set to display: 'none') */
function fitHorizontal(el, leftOffset){
	var leftVal = parseInt(leftOffset) || $(el).offset().left;
	return (leftVal + $(el).width() <= getWindowWidth() + getScrollLeft() && leftVal - getScrollLeft() >= 0);
};
function fitVertical(el, topOffset){
	var topVal = parseInt(topOffset) || $(el).offset().top;
	return (topVal + $(el).height() <= getWindowHeight() + getScrollTop() && topVal - getScrollTop() >= 0);
};

/*-------------------------------------------------------------------- 
 * Javascript Method: "pxToEm"
 * by: Scott Jehl (scott@filamentgroup.com) & Maggie Wachs (maggie@filamentgroup.com)
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) & GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/				
 * Options:  	 								
 		scope: string or jQuery selector for font-size scoping
 		reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library						  
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 * Version: 2.0, 08.01.2008 
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({ scope: 'body', reverse: false }, settings);
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};	
	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
		to get an accurate em value. */		
	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };	
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};

/* jQuery UI Selectmenu
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt) & GPL (GPL-LICENSE.txt) licenses.
 * http://docs.jquery.com/UI	*/

$.widget("ui.selectmenu", {
	_init: function() {
		var self = this, o = this.options;
		var num = Math.round(Math.random() * 1000);
		this.ids = [this.element.attr('id') + '_' + 'button' + '_' + num, this.element.attr('id') + '_' + 'menu' + '_' + num];
		this._safemouseup = true;
		this.newelement = $('<a class="'+ this.widgetBaseClass +' ui-widget ui-state-default ui-corner-all" id="'+this.ids[0]+'" role="button" href="#" aria-haspopup="true" aria-owns="'+this.ids[1]+'" aria-expanded="false"></a>')
			.insertAfter(this.element);
		var tabindex = this.element.attr('tabindex') || '0'; 
		this.newelement.attr('tabindex', tabindex);
		this.newelement.data('selectelement', this.element);
		this.selectmenuIcon = $('<span class="'+ this.widgetBaseClass +'-icon ui-icon"></span>')
			.prependTo(this.newelement)
			.addClass( (o.style == "popup")? 'ui-icon-triangle-2-n-s' : 'ui-icon-triangle-1-s' );	
		$('label[for='+this.element.attr('id')+']')
			.attr('for', this.ids[0])
			.bind('click', function(){
				self.newelement.focus();
				return false;
			});	
		this.newelement
			.bind('mousedown', function(event){
				self._toggle(event);
				if(o.style == "popup"){
					self._safemouseup = false;
					setTimeout(function(){self._safemouseup = true;}, 300);
				}	
				return false;
			})
			.bind('click',function(){ return false;})
			.keydown(function(event){
				var ret = true;
				switch (event.keyCode) {
					case $.ui.keyCode.ENTER:
						ret = true;
						break;
					case $.ui.keyCode.SPACE:
						ret = false;
						self._toggle(event);	
						break;
					case $.ui.keyCode.UP:
					case $.ui.keyCode.LEFT:
						ret = false;
						self._moveSelection(-1);
						break;
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.RIGHT:
						ret = false;
						self._moveSelection(1);
						break;	
					case $.ui.keyCode.TAB:
						ret = true;
						break;	
					default:
						ret = false;
						self._typeAhead(event.keyCode, 'mouseup');
						break;	
				}
				return ret;
			})
			.bind('mouseover focus', function(){ $(this).addClass(self.widgetBaseClass+'-focus ui-state-hover');})
			.bind('mouseout blur', function(){ $(this).removeClass(self.widgetBaseClass+'-focus ui-state-hover');});
		$(document).mousedown(function(event){ self.close(event);});
		this.element
			.click(function(){ this._refreshValue(); })
			.focus(function(){ this.newelement.focus(); });
		var cornerClass = (o.style == "dropdown")? " ui-corner-bottom" : " ui-corner-all"
		this.list = $('<ul class="' + self.widgetBaseClass + '-menu ui-widget ui-widget-content'+cornerClass+'" aria-hidden="true" role="listbox" aria-multiselectable="false" aria-labelledby="'+this.ids[0]+'" id="'+this.ids[1]+'"></ul>').appendTo('body');				
		var selectOptionData = [];
		this.element
			.find('option')
			.each(function(){
				selectOptionData.push({
					value: $(this).attr('value'),
					text: self._formatText(jQuery(this).text()),
					selected: $(this).attr('selected'),
					classes: $(this).attr('class'),
					parentOptGroup: $(this).parent('optgroup').attr('label')
				});
			});		
		var activeClass = (self.options.style == "popup") ? " ui-state-active" : "";
		for(var i in selectOptionData){
			var thisLi = $('<li><a href="#" tabindex="-1" role="option" aria-selected="false">'+ selectOptionData[i].text +'</a></li>')
				.data('index',i)
				.addClass(selectOptionData[i].classes)
				.data('optionClasses', selectOptionData[i].classes)
				.mouseup(function(event){
						if(self._safemouseup){
							var changed = $(this).data('index') != self._selectedIndex();
							self.value($(this).data('index'));
							self.select(event);
							if(changed){ self.change(event); }
							self.close(event,true);
						}
					return false;
				})
				.click(function(){ return false;})
				.bind('mouseover focus', function(){ 
					self._selectedOptionLi().addClass(activeClass); 
					self._focusedOptionLi().removeClass(self.widgetBaseClass+'-item-focus ui-state-hover'); 
					$(this).removeClass('ui-state-active').addClass(self.widgetBaseClass + '-item-focus ui-state-hover'); 
				})
				.bind('mouseout blur', function(){ 
					if($(this).is( self._selectedOptionLi() )){ $(this).addClass(activeClass); }
					$(this).removeClass(self.widgetBaseClass + '-item-focus ui-state-hover'); 
				});
			if(selectOptionData[i].parentOptGroup){
				var optGroupName = self.widgetBaseClass + '-group-' + selectOptionData[i].parentOptGroup;
				if(this.list.find('li.' + optGroupName).size()){
					this.list.find('li.' + optGroupName + ':last ul').append(thisLi);
				} else {
					$('<li class="'+self.widgetBaseClass+'-group '+optGroupName+'"><span class="'+self.widgetBaseClass+'-group-label">'+selectOptionData[i].parentOptGroup+'</span><ul></ul></li>')
						.appendTo(this.list)
						.find('ul')
						.append(thisLi);
				}
			} else { thisLi.appendTo(this.list);}
			this.list.bind('mousedown mouseup', function(){return false;});
			if(o.icons){
				for(var j in o.icons){
					if(thisLi.is(o.icons[j].find)){
						thisLi
							.data('optionClasses', selectOptionData[i].classes + ' ' + self.widgetBaseClass + '-hasIcon')
							.addClass(self.widgetBaseClass + '-hasIcon');
						var iconClass = o.icons[j].icon || "";	
						thisLi
							.find('a:eq(0)')
							.prepend('<span class="'+self.widgetBaseClass+'-item-icon ui-icon '+iconClass + '"></span>');
					}
				}
			}
		}
		this.list.find('li:last').addClass("ui-corner-bottom");
		if(o.style == 'popup'){ this.list.find('li:first').addClass("ui-corner-top"); }
		if(o.transferClasses){
			var transferClasses = this.element.attr('class') || ''; 
			this.newelement.add(this.list).addClass(transferClasses);
		}
		var selectWidth = this.element.width();
		this.newelement.width( (o.width) ? o.width : selectWidth);
		if(o.style == 'dropdown'){ this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width : selectWidth)); }
		else { this.list.width( (o.menuWidth) ? o.menuWidth : ((o.width) ? o.width - o.handleWidth : selectWidth - o.handleWidth)); }	
		if(o.maxHeight && o.maxHeight < this.list.height()){ this.list.height(o.maxHeight); }	
		this._optionLis = this.list.find('li:not(.'+ self.widgetBaseClass +'-group)');
		this.list
			.keydown(function(event){
				var ret = true;
				switch (event.keyCode) {
					case $.ui.keyCode.UP:
					case $.ui.keyCode.LEFT:
						ret = false;
						self._moveFocus(-1);
						break;
					case $.ui.keyCode.DOWN:
					case $.ui.keyCode.RIGHT:
						ret = false;
						self._moveFocus(1);
						break;	
					case $.ui.keyCode.HOME:
						ret = false;
						self._moveFocus(':first');
						break;	
					case $.ui.keyCode.PAGE_UP:
						ret = false;
						self._scrollPage('up');
						break;	
					case $.ui.keyCode.PAGE_DOWN:
						ret = false;
						self._scrollPage('down');
						break;
					case $.ui.keyCode.END:
						ret = false;
						self._moveFocus(':last');
						break;			
					case $.ui.keyCode.ENTER:
					case $.ui.keyCode.SPACE:
						ret = false;
						self.close(event,true);
						$(event.target).parents('li:eq(0)').trigger('mouseup');
						break;		
					case $.ui.keyCode.TAB:
						ret = true;
						self.close(event);
						break;	
					case $.ui.keyCode.ESCAPE:
						ret = false;
						self.close(event,true);
						break;	
					default:
						ret = false;
						self._typeAhead(event.keyCode,'focus');
						break;		
				}
				return ret;
			});
		if(o.style == 'dropdown'){
			this.newelement.addClass(self.widgetBaseClass+"-dropdown");
			this.list.addClass(self.widgetBaseClass+"-menu-dropdown");	
		} else {
			this.newelement.addClass(self.widgetBaseClass+"-popup");
			this.list.addClass(self.widgetBaseClass+"-menu-popup");	
		}
		this.newelement.prepend('<span class="'+self.widgetBaseClass+'-status">'+ selectOptionData[this._selectedIndex()].text +'</span>');
		this.element.hide();
		if(this.element.attr('disabled') == true){ this.disable(); }
		this.value(this._selectedIndex());
	},
	destroy: function() {
		this.element.removeData(this.widgetName)
			.removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled')
			.removeAttr('aria-disabled');
		$('label[for='+this.newelement.attr('id')+']')
			.attr('for',this.element.attr('id'))
			.unbind('click');
		this.newelement.remove();
		this.list.remove();
		this.element.show();	
	},
	_typeAhead: function(code, eventType){
		var self = this;
		if(!self._prevChar){ self._prevChar = ['',0]; }
		var C = String.fromCharCode(code);
		c = C.toLowerCase();
		var focusFound = false;
		function focusOpt(elem, ind){
			focusFound = true;
			$(elem).trigger(eventType);
			self._prevChar[1] = ind;
		};
		this.list.find('li a').each(function(i){	
			if(!focusFound){
				var thisText = $(this).text();
				if( thisText.indexOf(C) == 0 || thisText.indexOf(c) == 0){
						if(self._prevChar[0] == C){
							if(self._prevChar[1] < i){ focusOpt(this,i); }	
						} else { focusOpt(this,i); }	
				}
			}
		});
		this._prevChar[0] = C;
	},
	_uiHash: function(){ return { value: this.value()};},
	open: function(event){
		var self = this;
		this._refreshPosition();
		this._closeOthers(event);
		this.newelement
			.attr('aria-expanded', true)
			.addClass('ui-state-active');
		this.list
			.appendTo('body')
			.addClass(self.widgetBaseClass + '-open')
			.attr('aria-hidden', false)
			.find('li:not(.'+ self.widgetBaseClass +'-group):eq('+ this._selectedIndex() +') a').focus();	
		if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-all').addClass('ui-corner-top'); }	
		this._refreshPosition();
		this._trigger("open", event, this._uiHash());
	},
	close: function(event, retainFocus){
		if(this.newelement.is('.ui-state-active')){
			this.newelement
				.attr('aria-expanded', false)
				.removeClass('ui-state-active');
			this.list
				.attr('aria-hidden', true)
				.removeClass(this.widgetBaseClass+'-open');
			if(this.options.style == "dropdown"){ this.newelement.removeClass('ui-corner-top').addClass('ui-corner-all'); }
			if(retainFocus){this.newelement.focus();}	
			this._trigger("close", event, this._uiHash());
		}
	},
	change: function(event) {
		this.element.trigger('change');
		this._trigger("change", event, this._uiHash());
	},
	select: function(event) { this._trigger("select", event, this._uiHash());},
	_closeOthers: function(event){
		$('.'+ this.widgetBaseClass +'.ui-state-active').not(this.newelement).each(function(){
			$(this).data('selectelement').selectmenu('close',event);
		});
		$('.'+ this.widgetBaseClass +'.ui-state-hover').trigger('mouseout');
	},
	_toggle: function(event,retainFocus){
		if(this.list.is('.'+ this.widgetBaseClass +'-open')){ this.close(event,retainFocus); }
		else { this.open(event); }
	},
	_formatText: function(text){ return this.options.format ? this.options.format(text) : text;},
	_selectedIndex: function(){ return this.element[0].selectedIndex;},
	_selectedOptionLi: function(){ return this._optionLis.eq(this._selectedIndex());},
	_focusedOptionLi: function(){ return this.list.find('.'+ this.widgetBaseClass +'-item-focus');},
	_moveSelection: function(amt){
		var currIndex = parseInt(this._selectedOptionLi().data('index'), 10);
		var newIndex = currIndex + amt;
		return this._optionLis.eq(newIndex).trigger('mouseup');
	},
	_moveFocus: function(amt){
		if(!isNaN(amt)){
			var currIndex = parseInt(this._focusedOptionLi().data('index'), 10);
			var newIndex = currIndex + amt;
		} else { var newIndex = parseInt(this._optionLis.filter(amt).data('index'), 10); }
		if(newIndex < 0){ newIndex = 0; }
		if(newIndex > this._optionLis.size()-1){ newIndex =  this._optionLis.size()-1;}
		this._focusedOptionLi().find('a:eq(0)').blur();
		this._optionLis.eq(newIndex).find('a:eq(0)').focus();
	},
	_scrollPage: function(direction){
		var numPerPage = Math.floor(this.list.outerHeight() / this.list.find('li:first').outerHeight());
		numPerPage = (direction == 'up') ? -numPerPage : numPerPage;
		this._moveFocus(numPerPage);
	},
	_setData: function(key, value) {
		this.options[key] = value;
		if (key == 'disabled') {
			this.element
				.add(this.newelement)
				.add(this.list)
					[value ? 'addClass' : 'removeClass'](
						this.widgetBaseClass + '-disabled' + ' ' +
						this.namespace + '-state-disabled')
					.attr("aria-disabled", value);
		}
	},
	value: function(newValue) {
		if (arguments.length) {
			this.element[0].selectedIndex = newValue;
			this._refreshValue();
			this._refreshPosition();
		}
		return this.element[0].selectedIndex;
	},
	_refreshValue: function() {
		var activeClass = (this.options.style == "popup") ? " ui-state-active" : "";
		this.list
			.find('.'+ this.widgetBaseClass +'-item-selected')
			.removeClass(this.widgetBaseClass + "-item-selected" + activeClass)
			.find('a')
			.attr('aria-selected', 'false');
		this._selectedOptionLi()
			.addClass(this.widgetBaseClass + "-item-selected"+activeClass)
			.find('a')
			.attr('aria-selected', 'true');
		var currentOptionClasses = this.newelement.data('optionClasses') ? this.newelement.data('optionClasses') : "";
		var newOptionClasses = this._selectedOptionLi().data('optionClasses') ? this._selectedOptionLi().data('optionClasses') : "";
		this.newelement
			.removeClass(currentOptionClasses)
			.data('optionClasses', newOptionClasses)
			.addClass( newOptionClasses )
			.find('.'+this.widgetBaseClass+'-status')
			.html( 
				this._selectedOptionLi()
					.find('a:eq(0)')
					.html() 
			);
	},
	_refreshPosition: function(){	
		this.list.css('left', this.newelement.offset().left);
		var menuTop = this.newelement.offset().top;
		var scrolledAmt = this.list[0].scrollTop;
		this.list.find('li:lt('+this._selectedIndex()+')').each(function(){
			scrolledAmt -= $(this).outerHeight();
		});
		if(this.newelement.is('.'+this.widgetBaseClass+'-popup')){
			menuTop+=scrolledAmt; 
			this.list.css('top', menuTop); 
		} else { 
			menuTop += this.newelement.height();
			this.list.css('top', menuTop); 
		}
	}
});

$.extend($.ui.selectmenu, {
	getter: "value",
	version: "@VERSION",
	eventPrefix: "selectmenu",
	defaults: { transferClasses: true, style: 'popup', width: null, menuWidth: null, handleWidth: 26, maxHeight: null, icons: null, format: null}
});
	
/* jQuery UI: Init Handlers States */
$(document).ready(function(){

	$(".ui-state-default")
	.hover(function(){
			$(this).addClass("ui-state-hover")
		}, function(){
			$(this).removeClass("ui-state-hover")
		})
	.mousedown(function(){
			$(this).parents('.ui-buttonset-single:first').find(".ui-button.ui-state-active").removeClass("ui-state-active");
			if( $(this).is('.ui-state-active.ui-button-toggleable, .ui-buttonset-multi .ui-state-active') ){
				$(this).removeClass("ui-state-active");
			} else {
				$(this).addClass("ui-state-active");
			}
		})
	.mouseup(function(){
			if(! $(this).is('.ui-button-toggleable, .ui-buttonset-single .ui-button, .ui-buttonset-multi .ui-button') ){
				$(this).removeClass("ui-state-active");
			}
		});
	
/* Copyright (c) 2009, Keith Parent - transParent UI: Class Extensions */
// Image Feedback Classes 
	// .over img src swap :hover
		$("a.over img")
			.hover(function() {	$(this).attr('src', $(this).attr('src').split('.').join('_o.'));
			}, function() {	$(this).attr('src', $(this).attr('src').split('_o.').join('.'));	});
		
		$(".hit img")
			.mousedown(function() { $(this).attr("src", $(this).attr("src").split("_o.").join("_a."));})
			.mouseup(function() { $(this).attr("src",$(this).attr("src").split("_a.").join("_o."));	});
			
	// .fade img:hover
		$(".fade img")
			.hover(function() {	$(this).stop().animate({opacity: .5}, 1200);
			}, function() {	$(this).stop().animate({opacity: 1}, 300);	});
			
	// disjointed img rollover
		$(".thumb a").click(function(e) {
			e.preventDefault();
			$("#detail").attr("src", $(this).attr("rel"));
		});
	
	// Selectmenu
		var addressFormatting = function(text) {// custom format option callback
			var newText = text;
			var findreps = [ // array of regex find/replaces
				{find:/^([^\-]+) \- /g, rep:'<span class="ui-selectmenu-item-header">$1</span>'},
				{find:/([^\|><]+) \| /g, rep:'<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/([^\|><\(\)]+) (\()/g, rep:'<span class="ui-selectmenu-item-content">$1</span>$2'},
				{find:/([^\|><\(\)]+)$/g, rep:'<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/(\([^\|><]+\))$/g, rep:'<span class="ui-selectmenu-item-footer">$1</span>'}
			];
			for(var i in findreps) { newText = newText.replace(findreps[i].find, findreps[i].rep);}
			return newText;
		}
		
		$("select").selectmenu({
			/*maxHeight: 150,*/width: 200,style:/*'dropdown'*/'popup',menuWidth: 175,format: addressFormatting,
			icons: [{find: '.script', icon: 'ui-icon-script'},{find: '.image', icon: 'ui-icon-image'},{find: '.font', icon: 'ui-icon-document-b'},{find: '.customicons'}]
		});
		
		// Accordion
		$("#accordion").accordion({
			header:'h4', collapsible: true,
			icons: {header: 'ui-icon-plusthick',headerSelected: 'ui-icon-minusthick'},
			fillSpace: false,event: 'click',autoHeight: true,navigation: false,
			header:'> div > h4'}).sortable({axis:'y',handle:'h4'
		});
		
		// Tabs
		$("#tabs").tabs();
		
		// Datepickers
		var dates = $("#datefrom,#dateto").datepicker({
			defaultDate: "+0d",
			changeMonth: false,
			numberOfMonths: 6,
			onSelect: function(selectedDate) {
				var option = this.id == "datefrom" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				dates.not(this).datepicker("option", option, date);
			}
		});
		$("#datefrom,#dateto").datepicker({
			inline: true,
			altField: '#alternate', altFormat: 'DD, d MM, yy',
			numberOfMonths: 3,
			showButtonPanel: true,
			showOtherMonths: true,
			selectOtherMonths: true,
			changeMonth: false,
			changeYear: false,
			showOn: 'button',
			buttonImage: 'images/icons/fugue/calendar-month.png',
			buttonImageOnly: true,
			minDate: -20, maxDate: '+12M +1D',
			showWeek: true,
			firstDay: 1
		});
		$("#dateformat").change(function() { $("#datefrom, #dateto").datepicker("option", {dateFormat: $(this).val()});});
		$("#slider").slider({ range: true, values: [13, 69] });// Slider
		$("#progressbar").progressbar({ value: 42 });// Progressbar
		
		// Zebra Stripe table.data tr
		$("table.data tr:even").addClass("alt");
		
		// Dialog Function
		function showDialog(str,strtitle) {
			if(!strtitle) strtitle='Message';
			
			$('#dialog').dialog('destroy');
			$('#dialog').show();
			if(str) $('#dialog').html(str);
			
			$("#dialog").dialog({
				resizable: true,
				modal: true,
				overlay: {
					backgroundColor: '#fff',
					opacity: 0.8
				},
				title:strtitle,
				buttons: {
					'OK': function() {
						window.location.href = '';
					},
					'Cancel': function() {
						$(this).dialog("close");
					} 
				}
			});
		}

	// Init 'a#top' scrollTo hot link 
		$("body").prepend('<a class="ui-helper-hidden-accessible" name="top"></a>');
		
	// Build '#copyright'
		var copyTxt = '<a href="#">Copyright</a>';
		var copySym = '&copy;';
		var thisYear = (new Date).getFullYear();
		var companyName = 'Proximity Effect';
		var nbsp = '&nbsp;';
		var copyright = copyTxt + nbsp + copySym + nbsp + thisYear + nbsp + companyName;
		$('#copyright').html(copyright +',<br />All Rights Reserved');
		$('body').append('<div id="rights" class="ui-dialog-content ui-widget-content sml"><h3>'+companyName+'</h3><em><p><strong>'+companyName+'</strong> is the copyright owner or licensee of the content and/or information in this website, unless otherwise indicated.</p><p><strong>'+companyName+'</strong> does not grant to you a license to any content, features or materials on or contained in this website.</p><p><strong>You may not</strong> distribute, download, or save a copy of any of the content or screens for any purpose except as otherwise provided.</p></em></div>');
		$('#rights').dialog({
			autoOpen: false,
			resizable: true,
			modal: true,
			overlay: {
				backgroundColor: '#fff',
				opacity: 0.95
			},
			title: copyTxt + nbsp + copySym + nbsp + thisYear,
			buttons: {
				'Close': function() {
					$(this).dialog("close");
				} ,
				'U.S. Copyright Office': function() {
					window.location.href = 'http://www.copyright.gov/';
				}
			}
		});
		$('#copyright a').click(function() {
			$('#rights').dialog('open');
			return false;
		});
		
	// SWF Object
		var swfSrc = 'swf/main.swf';
		var swfWidth = '960';
		var swfHeight = '620';
		var flashvars = {};
		flashvars.xml = "xml/config.xml";
		var attributes = {};
		attributes.wmode = "transparent";
		attributes.id = "swjObj";
		swfobject.embedSWF(swfSrc, "swfObj", swfWidth, swfHeight, "9", "expressInstall.swf", flashvars, attributes);
/*})();
EOF*/});
