
//***** start sifr-config
/*
    =:project
    scalable Inman Flash Replacement (sIFR) version 3, revision 419

    =:file
    Copyright: 2006 Mark Wubben.
    Author: Mark Wubben, <http://novemberborn.net/>

    =:history
    * IFR: Shaun Inman
    * sIFR 1: Mike Davidson, Shaun Inman and Tomas Jogin
    * sIFR 2: Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben

    =:license
    This software is licensed and provided under the CC-GNU LGPL.
    See <http://creativecommons.org/licenses/LGPL/2.1/>    
*/

parseSelector.pseudoClasses = {
    'not': function(nodes, selector) {
        var result = [];
        each: for(var i = 0, node; i < nodes.length; i++) {
            node = nodes[i];
            var ignore = parseSelector(selector, node.parentNode);
            for(var j = 0; j < ignore.length; j++) {
                if(ignore[j] == node) continue each;
            }
            result.push(node);
        }
        return result;
    }
}

var swfPath = rootVirtual + '_flash/_sifr/';

var GilSansLite = {
    src: swfPath + 'GilSansLite.swf',
    ratios: [7, 1.32, 8, 1.31, 12, 1.27, 20, 1.22, 28, 1.19, 30, 1.17, 36, 1.18, 45, 1.17, 61, 1.16, 62, 1.15, 65, 1.16, 66, 1.15, 67, 1.16, 116, 1.15, 117, 1.14, 123, 1.15, 124, 1.14, 1.15]
};

sIFR.activate(GilSansLite);

function do_sIFR() {

    sIFR.replace(GilSansLite, {
        selector: 'div#explore h1',
        css: [
            '.sIFR-root { color: #721472; text-transform: uppercase; }',
            'strong { color: #000000; font-weight: normal; }',
            'em { color: #000000; font-style: normal; }',
            'a { text-decoration: none; }',
            'a:link { color: #721472; }',
            'a:hover { color: #ec008c; }'
        ],
        wmode: 'transparent'
    });

    sIFR.replace(GilSansLite, {
        selector: 'h1:not(.newstitle)',
        css: [
            '.sIFR-root { color: #cc1d00; text-transform: uppercase; }',
            'strong { color: #000000; font-weight: normal; }',
            'em { color: #000000; font-style: normal; }',
            'a { text-decoration: none; }',
            'a:link { color: #cc1d00; }',
            'a:hover { color: #e07118; }'
        ],
        wmode: 'transparent'
    });

    sIFR.replace(GilSansLite, {
        selector: 'div#homepagecallouts h2',
        css: [
            '.sIFR-root { color: #ffffff; letter-spacing: 3; }'
        ],
        wmode: 'transparent'
    });

}

document.observe('dom:loaded', do_sIFR);

Ajax.Responders.register({onComplete: do_sIFR});

//***** end sifr-config


//***** start date-chooser

/* 
Date Chooser from: http://www.scripteka.com/script/datechooser
this file includes: 
	EventDispatcher.js
	GridBase2.js
	GridBuild.js
	CalendarSelect.js
	GregorianCalendar.js
	DateSelect.js
*/
// JavaScript Document
/**
 * @author 		Matthew Foster
 * @date		June 6th 2007
 * @purpose		To have a base class to extend subclasses from to inherit event dispatching functionality.
 * @procedure	Use a hash of event "types" that will contain an array of functions to execute. The logic is if any function explicitally returns false the chain will halt execution.
 */
 var EventDispatcher = Class.create({});

	Object.extend(EventDispatcher.prototype,
					{

						buildListenerChain : function(){
							if(!this.listenerChain)
								this.listenerChain = {};							
						},
						addEventListener : function(type, listener){
							this.buildListenerChain();
							if(!this.listenerChain[type])					
								this.listenerChain[type] = [listener];
							else
								this.listenerChain[type].push(listener);
						},
						hasEventListener : function(type){
							return (typeof this.listenerChain[type] != "undefined");
						},
						removeEventListener : function(type, listener){
							if(!this.hasEventListener(type))
								return false;
								
							for(var i = 0; i < this.listenerChain[type].length; i++)
								if(this.listenerChain[type][i] == listener)
									this.listenerChain[type].splice(i, 1);
						},
						dispatchEvent : function(type, args){
							this.buildListenerChain();
							if(!this.hasEventListener(type))
								return false;
							this.listenerChain[type].any(function(f){ return (f(args) == false ? true : false); });						
						},
						on : function(type, listener){
							this.addEventListener(type, listener);
						},
						fire : function(type, args){
							this.dispatchEvent(type, args);
						}
					}
				);

/**
Copyright (c) 2007 Matthew E. Foster

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

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

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

var GridBase = function(){};
	
Object.extend(Object.extend(GridBase.prototype, EventDispatcher.prototype),
				{

					setTable : function(table){
						this.table = $(table);
					},
					getCell : function(row, cell){
						return this.table.down("tr", row).down("td", cell);
					},
					createListener : function(){
						this.createCellListener();
						this.createRowListener();
						this.createTableListener();
					},
					applyBehavior : function(){
						this.table.getElementsBySelector("td").each(this.attachCellListener.bind(this));
						this.table.getElementsBySelector("td").each(this.attachRowListener.bind(this));
						this.attachTableListener(this.table);
					},
					createCellListener : function(){
						this.cellOverHandle = this.handleCellOver.bindAsEventListener(this);
						this.cellOutHandle = this.handleCellOut.bindAsEventListener(this);
						this.cellClickHandle = this.handleCellClick.bindAsEventListener(this);
						this.cellDownHandle = this.handleCellDown.bindAsEventListener(this);
						this.cellUpHandle = this.handleCellUp.bindAsEventListener(this);
					},
					createRowListener : function(){
						this.rowOverHandle = this.handleRowOver.bindAsEventListener(this);
						this.rowOutHandle = this.handleRowOut.bindAsEventListener(this);
					},
					createTableListener : function(){
						this.tableOverHandle = this.handleTableOver.bindAsEventListener(this);
						this.tableOutHandle = this.handleTableOut.bindAsEventListener(this);
						this.tableDownHandle = this.handleTableDown.bindAsEventListener(this);
						this.tableUpHandle	= this.handleTableUp.bindAsEventListener(this);				
					},
					attachCellListener : function(cell){
						Event.observe(cell, "click", this.cellClickHandle);
						Event.observe(cell, "mouseover", this.cellOverHandle);
						Event.observe(cell, "mouseout", this.cellOutHandle);
					},
					attachRowListener : function(row){
						Event.observe(row, "mouseover", this.rowOverHandle);
						Event.observe(row, "mouseout", this.rowOutHandle);
					},
					attachTableListener : function(table){
						Event.observe(table, "mouseover", this.tableOverHandle);
						Event.observe(table, "mouseout", this.tableOutHandle);
						Event.observe(table, "mousedown", this.tableDownHandle);
						Event.observe(table, "mouseup", this.tableUpHandle);
					},
					handleCellOver : function(e){
						this.dispatchEvent("cellover", e);
						if(this.mouseDown == true)
							this.dispatchEvent("celldown", e);
					},
					handleCellOut : function(e){
						this.dispatchEvent("cellout", e);
					},
					handleCellUp : function(e){
						this.dispatchEvent("cellup", e);
					},
					handleCellDown : function(e){
						this.dispatchEvent("celldown", e);
					},
					handleCellClick : function(e){
						this.dispatchEvent("cellclick", e);
					},
					handleRowOver : function(e){
						this.dispatchEvent("rowover", e);
					},
					handleRowOut : function(e){
						this.dispatchEvent("rowout", e);
					},
					handleTableOver : function(e){
						this.dispatchEvent("tableover", e);
					},
					handleTableOut : function(e){
						this.dispatchEvent("tableout", e);
					},
					handleTableDown : function(e){
						this.mouseDown = true;
						this.dispatchEvent("tabledown", e);
					},
					handleTableUp : function(e){
						this.mouseDown = false;
						this.dispatchEvent("tableup", e);
					}
				}
			);

/**
Copyright (c) 2007 Matthew E. Foster
*/
//if(!$C)
	$C = function (name, options){
				return Element.extend(Object.extend(document.createElement(name || "div"), options || {})); 
			}

var GridBuild = function(){};

Object.extend(Object.extend(GridBuild.prototype, GridBase.prototype),
				{
					buildGrid : function(col, row){
						var table = $C("table");
						var tbody = $C("tbody");
						//a lexical flex
						row.times(function(itr){											
										var elerow = $C("tr");
										col.times(function(index){
													elerow.appendChild($C("td"));
												});
										tbody.appendChild(elerow);
									})
						table.appendChild(tbody);
						return table;
					},						
					loadJSON : function(dto){
						dto.each(this.iterateRow.bind(this));
					},
					loadXML : function(xml){
						$A(xml.getElementsByTagName("row")).each(this.iterateRowXML.bind(this))
					},
					iterateRowXML : function(row, itr){
						try{
							$A(row.getElementsByTagName("cell")).each(this.applyCellXML.bind(this, itr));
						}
						catch(e){
							console.log(e);
						}
					},
					iterateRow : function(rowArr, itr){
						rowArr.each(this.applyCellJSON.bind(this, itr));
					},
					applyCellXML : function(row, obj, cell){
						var cellNode = this.getCell(row, cell);
						if(cellNode)
							cellNode.innerHTML = obj.firstChild.nodeValue;
					},
					applyCellJSON : function(row, obj, cell){
						var cellNode = this.getCell(row, cell);
						if(cellNode)
							Object.extend(cellNode, obj || {});
					}
				}
			);

/**
 * @author Matthew FOster
 * @date   September 10th 2007
*/
var CalendarSelect = Class.create();

Object.extend(Object.extend(CalendarSelect.prototype, GridBuild.prototype),
					{

						initialize : function(container, options){
							this.options = Object.extend({ weekLength : 7, endWeek : 6, date : new Date()}, options || {});
							this.container = $(container);
							this.range = this.buildCalendarRange(this.options.date);
							this.monthDTO = this.buildCalendarDTO(this.range);
							this.createTable(this.monthDTO);
							this.createListener();
							this.applyBehavior();
							this.loadJSON(this.monthDTO);
						},
						getCell : function(row, cell){
								var ret = this.tbody.childNodes[row].childNodes[cell];
								if(ret)
									return ret;
								else
									return GridBuild.prototype.getCell.apply(this, arguments);
						},
						createListener : function(){ 
							GridBuild.prototype.createListener.apply(this, arguments);
							this.dayClickHandle = this.handleDayClick.bindAsEventListener(this);
						},							
						createTable : function(arr){
							var table = this.buildGrid(this.options.weekLength, arr.length);
							this.setTable(table);
							this.container.appendChild(this.table);
							this.tbody = table.getElementsByTagName("tbody").item(0);
						},
						buildCalendarRange : function(date, month){
							return new GregorianCalendar(date, month);
						},
						applyCellJSON : function(row, obj, cell){
							var cellNode = this.getCell(row, cell);
							if(!(cellNode && obj instanceof Date))
								return false;
							//if it passed test it must be a valid day, so apply a dateclick observer
							Event.observe(cellNode, "click", this.dayClickHandle);
							cellNode.innerHTML = obj.getDate();
							cellNode.date = obj;
						},
						buildCalendarDTO : function(range){
							var monthArr = [];
							var week = [];								
							//load offset with bogus data
							range.start.getDay().times(function(itr){ week.push(undefined) });
							var self = this;
							range.each(function(date){
											 week.push(date);
											 if(date.getDay() == self.options.endWeek){
												monthArr.push(week);
												week = [];
											}
										});
							if(week.length > 0)
								monthArr.push(week);
							return monthArr;
						},					
						handleDayClick : function(e){
							this.dispatchEvent("dayclick", Event.element(e).date);
						}
					}
				);

/**
 * @author Matthew FOster
 * @date   September 10th 2007
 */
Date.prototype.succ = function(){
		var ret = new Date(this.getTime());
		ret.setDate(this.getDate() + 1);
		return ret;
	}
Date.prototype.isLeapYear = function() {
	var year = this.getFullYear();
	return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
}

var GregorianCalendar = Class.create();

Object.extend(Object.extend(GregorianCalendar.prototype, ObjectRange.prototype),
				{	// !!!
					//MONTH_MAP : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
					MONTH_MAP : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
					//             J  F  M  A  M  J  J  A  S  O  N  D
					DAY_MAX_MAP : [31,00,31,30,31,30,31,31,30,31,30,31],
					initialize : function(year, month){
						this.date = this.buildDate(year, month);
						this.start = this.buildStart(this.date);
						this.end = this.buildEnd(this.date);
					},
					buildDate : function(year, month){
						var d = false;
						if(year instanceof Date){
							d = year;
						}
						else{
							d = new Date();
							d.setYear(year);
							d.setMonth(month);
							}
						d.setDate(1);
						d.setHours(0);
						d.setMinutes(0);
						d.setSeconds(0);
						d.setMilliseconds(0);
						return d;
					},
					buildStart : function(date){
						return new Date(date.getTime());
					},
					buildEnd : function(date){
						var month = date.getMonth();
						var maxDays = this.DAY_MAX_MAP[month];
						if(maxDays == 0)
							maxDays = this.getFebruaryMax();
						this.setMaxDays(maxDays);
						return new Date(date.getFullYear(),date.getMonth(),maxDays);
					},
					getFebruaryMax : function(){
						return (this.date.isLeapYear()) ? 29 : 28;
					},
					setMaxDays : function(num){
						this.maxDays = num;
					},
					getMaxDays : function(){
						return this.maxDays || 0;
					},
					getNextMonth : function(){
						return this.buildDate(this.date.getFullYear(), this.date.getMonth()+1);
					},
					getDate : function(){
						return this.date;
					},
					getPreviousMonth : function(){
						return this.buildDate(this.date.getFullYear(), this.date.getMonth()-1);
					},
					succ : function(){
						return new GregorianCalendar(this.getNextMonth());
					}
				}
			);

/**
 * @author Matthew FOster
 * @date   September 10th 2007
 */
var DateSelect = Class.create();

Object.extend(Object.extend(DateSelect.prototype, CalendarSelect.prototype),
					{
						DOW : ["S","M","T","W","T","F","S"],
						initialize : function(container, options){
								CalendarSelect.prototype.initialize.apply(this, arguments);
								this.createListener();
								this.controlBar = this.createControlBar();
								this.header = this.createHeader();
								this.injectTable(this.header);
								this.injectTable(this.controlBar);
								this.updateTitle();
						},
						createListener : function(){
							CalendarSelect.prototype.createListener.apply(this, arguments);
							this.nextHandle = this.handleNext.bindAsEventListener(this);
							this.prevHandle = this.handlePrev.bindAsEventListener(this);
						},
						updateTitle : function(){
							//this.controlBar.titleNode.innerHTML = this.range.date.getFullYear() + ", " + this.range.MONTH_MAP[this.range.date.getMonth()];
							//!!! 
							var strYear = new String(this.range.date.getFullYear());
							this.controlBar.titleNode.innerHTML = this.range.MONTH_MAP[this.range.date.getMonth()] + " '" + strYear.substr(2,2);
						},
						createControlBar : function(){
							var next = $C("td", { innerHTML : "&gt;", className : "next"});
							var prev = $C("td", { innerHTML : "&lt;", className : "prev"});
							next.observe("click", this.nextHandle);
							prev.observe("click", this.prevHandle);
							var main = $C("td", { className : "main" });
							main.setAttribute("colSpan", 5);
							var row = $C("tr", { className : "header"});
							row.titleNode = main;
							row.appendChild(prev);
							row.appendChild(main);
							row.appendChild(next);
							return row;
						},
						createHeader : function(){
							var row = $C("tr", { className : "dow"});
							this.DOW.each(function(itr){
											row.appendChild($C("td", { innerHTML : itr }));
										});
							return row;
						},
						rebuildTable : function(date){
							//remove from parents so the clear won't destroy the elements, hate you IE.
							this.header.parentNode.removeChild(this.header);
							this.controlBar.parentNode.removeChild(this.controlBar);
							this.container.innerHTML = "";
							this.range = this.buildCalendarRange(date);
							this.monthDTO = this.buildCalendarDTO(this.range);
							this.createTable(this.monthDTO);
							this.applyBehavior();
							this.loadJSON(this.monthDTO);
							this.injectTable(this.header);
							this.injectTable(this.controlBar);
							this.updateTitle();
						},
						handleNext : function(e){
							//push the new date a week into the next month
							var date = new Date(this.range.end.getTime());
							date.setDate(date.getDate() + 10);
							this.rebuildTable(date);
						},
						handlePrev : function(e){
							//push the new date a week into the next month
							var date = new Date(this.range.start.getTime());
							date.setDate(date.getDate() - 10);
							this.rebuildTable(date);
						},							
						injectTable : function(ele){
							try{
								var tbody = this.table.down("tbody");
								tbody.insertBefore(ele, tbody.firstChild)
							}
							catch(e){ 
								this.table.insertBefore(ele, this.table.firstChild);
							}
						}
					}
				);

//***** end date-chooser


//***** start utility-flyouts

/**
 * @classDescription Base class for handling the flyout widgets. Not for instatiating directly.
*/
var UtilFlyoutBase = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			serviceUrl: '/url_not_set.aspx', // must be set my subclasses.
			debugMode: false
		}, options || {});
		
		this.isOpen = false;

		// grab instance reference
		UtilFlyoutBase.instances.push(this);
		
		// body click for user clicking outside the flyout
		var boundBodyClick = this.__bodyClick.bindAsEventListener(this);
		$(document.body).observe('click', boundBodyClick);
		
	},
		
	__bodyClick: function(e){
		// note: e.relatedTarget is the node to which the pointer went, e.currentTarget is the node to which the event is attached
		var el = e.element();
		/*
		if(this.isOpen && Object.isElement(this.container) && !el.descendantOf(this.container)){
			this.close();
		}
		*/
		// loop through child classes and close them if they don't contain the target element.
		for(var i=0; i < UtilFlyoutBase.instances.length; i++){
			if(UtilFlyoutBase.instances[i].isOpen 
			&& Object.isElement(UtilFlyoutBase.instances[i].container) 
			&& !el.descendantOf(UtilFlyoutBase.instances[i].container)
			&& (el.id != 'lnk_adv_search') // exception for advanced search link in searchFlyout
			){
				UtilFlyoutBase.instances[i].close();
			}
		}		
	},

	close: function(){
		this.container.hide();
		this.container.fire('utilFlyout:close');
		this.isOpen = false;
	},

	open: function(){
		// Close all instances other than this instance.
		for(var i=0; i < UtilFlyoutBase.instances.length; i++){
			if(UtilFlyoutBase.instances[i] !== this && UtilFlyoutBase.instances[i].isOpen){
				UtilFlyoutBase.instances[i].close();
			}
		}
		
		this.container.show();
		this.container.fire('utilFlyout:open');
		this.isOpen = true;
	},

	createContainer: function(elParent, containerID, innerID, title){
		//console.log('creating');
		// create wrapper divs and controls for a child class
		//<div id="[containerID]" class="popover">
		//	<div class="head">
		//		<a class="lnk_close" href="#close">close <span>x</span></a>
		//		<h4>[title]</h4>
		//	</div>
		//	<div id="[innerID]" class="inner"><!--content goes here --></div>
		//	<div class="foot"></div>
		//</div>
		this.container = new Element('div', {id: containerID, 'class': 'popover'});
		var elLnkClose = new Element('a', {href: '#close', 'class': 'lnk_close'}).update('close <span>x</span>');
		var elHead =  new Element('div', {'class': 'head'});
		elHead.appendChild(elLnkClose);
		elHead.appendChild(new Element('h4').update(title));
		this.container.appendChild(elHead);
		
		// create and get ref to content area
		this.elContent = new Element('div', {id: innerID, 'class': 'inner'});
		this.container.appendChild(this.elContent);
		
		var elFoot = new Element('div', {'class':'foot'});
		this.container.appendChild(elFoot);
		
		// add container and it's children below parent element
		elParent.insert({top: this.container});
		
		// attach the close event handler
		elLnkClose.observe('click', this.__closeClick.bindAsEventListener(this));

		// create the spinner
		//display:none; filter:alpha(opacity=50); opacity:.50;" title="Loading..."
		this.spinner = new Element('div', {id: containerID + '_spinner', 'class': 'util_flyout_spinner', title: 'Loading...', style: 'opacity: .50'});
		
		elParent.insert({top: this.spinner});
		
		this.isContainerBuilt = true;

	},
	
	__closeClick: function(e){
		e.stop();
		this.close();
	},
	
	makeXhrRequest: function(url, method, params){

		Element.clonePosition(this.spinner, this.container);
		this.spinner.appear({to: 0.5, duration: 0.1});
		
		new Ajax.Request(url, {
				requestHeaders: {"X-Requested-With": "FlyoutXHR"},
				method: method,
				parameters: params,
				onSuccess: this.xhrSuccessCallback.bind(this),
				onFailure: this.xhrFailureCallback.bind(this)
			}
		);
	},
	
	xhrSuccessCallback: function(transport){
		 //console.log('xhrSuccessCallback fired');

		// figure out what mode we're in and respond accordingly
		var isJSResponse = /javascript/.test(transport.getResponseHeader('Content-Type') || '');
		if(!isJSResponse){
			var form = transport.responseXML.getElementsByTagName('form')[0];			
			for (var i=0; i<form.childNodes.length; i++) {
				var node = form.childNodes[i];
				if (node.nodeType == 4) { // find the CDATA section and insert contents
					this.elContent.update(node.nodeValue);
					this.container.fire('utilFlyout:update');
					break;
				}
			}
			
			var boundProcessContent = this.processContent.bind(this);
			boundProcessContent.defer();

			this.spinner.fade({from: 0.5, duration: 0.25});
		}
		else{
			this.spinner.hide();
		}
	},
	
	xhrFailureCallback: function(transport){
		console.log('something went wrong with the xhr request.\n"'+ transport.status+':'+transport.statusText+'"\ntransport:');
		console.log(transport);
		this.close();
		this.spinner.fade({from: 0.5, duration: 0.1});
		// go to failure url if defined
		if(!Object.isUndefined(this.options.failureUrl) && this.options.debugMode == false){
			window.location.href = this.options.failureUrl;
		}
	}
});
// static properties
UtilFlyoutBase.instances = [];	// for being able to close siblings.

/**
 * @classDescription Handle the flyout version of Sign in
*/
var SignInFlyout = Class.create(UtilFlyoutBase, {
	initialize: function($super, lnkSignIn, options) {
		// set options
		this.options = Object.extend({
			serviceUrl: '/account/signinFlyout.aspx', //if needed, rootSecure is an available global to force https.
			failureUrl:  '/account/signin.aspx',
			elParent: $('wrapper')
		}, options || {});
		
		$super(this.options);
		
		if(!lnkSignIn){return;}
		this.lnkSignin = lnkSignIn;
		this.isContainerBuilt = false;
		this.lnkSignin.observe('click', this.__signInClick.bindAsEventListener(this));
	},
	
	__signInClick: function(e){
		e.stop();

		if(!this.isContainerBuilt){
			this.createContainer();
			this.open();
			this.makeXhrRequest(this.options.serviceUrl, 'get', {});
		}
		else{
			this.open();
		}
	},
		
	__formButtonClick: function(e){
		e.stop();
		var params = $H();
		var btn = e.element();

        this.container.select('input[type=text],input[type=password]').each(function(txt){
	        params.set(txt.name, txt.value);
        });		
        
		// add the clicked button to the params
		params.set(btn.name, btn.value); 
		
		// post the form with params
		this.makeXhrRequest(this.options.serviceUrl, 'post', params.toQueryString());
		
		return false;
	},

	processContent: function(){
		//console.log('processContent fired');
		// hijack image buttons and attach our event handler
		var btnSignin = this.elContent.down('input.btn_signin');
		var btnForgot = this.elContent.down('input.btn_forgot');
		// hijack signin and forgot buttons and attach our event handler
		btnSignin.onclick = function(e){}; // replace inline onclick event
		btnSignin.observe('click', this.__formButtonClick.bindAsEventListener(this));
		btnForgot.onclick = function(e){}; // replace inline onclick event
		btnForgot.observe('click', this.__formButtonClick.bindAsEventListener(this));
	},
	
	createContainer: function($super){
		$super(this.options.elParent, 'signin_flyout', 'signin_content', 'Log In');
	}
	
});

/**
 * @classDescription Handle cart summary flyout
*/
var CartFlyout = Class.create(UtilFlyoutBase, {
	initialize: function($super, lnkCart, options) {
		// set options
		this.options = Object.extend({
			serviceUrl: '/basket/cartFlyout.aspx',
			failureUrl: '/basket/default.aspx',
			elParent: $('wrapper')
		}, options || {});
		$super(this.options);
		
		if(!lnkCart){return;}
		
		this.lnkCart = lnkCart;
		this.isContainerBuilt = false;

		this.lnkCart.observe('click', this.__lnkCartClick.bindAsEventListener(this));
	},
	
	__lnkCartClick: function(e){
		e.stop();
		if(!this.isContainerBuilt){
			this.createContainer();
			this.open();
			this.makeXhrRequest(this.options.serviceUrl, 'get', {});
		}
		else{
			this.makeXhrRequest(this.options.serviceUrl, 'get', {});// get fresh content for ticket timer.
			this.open();
		}
	},

	__removeItemClick: function(e){
		e.stop();
		var lnkRemove = e.element();
		// hijack remove link and make an xhr get--params are already in the href
		this.makeXhrRequest(lnkRemove.readAttribute('href'), 'get', {returnUrl: this.options.serviceUrl});
	},
	
	processContent: function(){
		// deal with remove links.
		//console.log('process content fired.');
		var aRemoveLinks = this.elContent.select('a.remove');
		for(var i=0, len = aRemoveLinks.size(); i < len; i++){
			aRemoveLinks[i].observe('click', this.__removeItemClick.bindAsEventListener(this));
		}
		
		// update the item count if it's included in the content: span.cartitemcount-update
		var elItemCountUpdate = this.elContent.down('span.cartitemcount-update');
		var elItemCount = this.lnkCart.next('span.cartitemcount');
		if(Object.isElement(elItemCountUpdate) && Object.isElement(elItemCount)){
			//console.log(updatedCount);
			var updatedCount = parseInt(elItemCountUpdate.firstChild.data);
			if(updatedCount == 0){
				elItemCount.hide();
			}
			else{
				elItemCount.update('(' + updatedCount + ')');
			}
		}
	},
	
	createContainer: function($super){
		$super(this.options.elParent, 'cart_flyout', 'cart_content', 'My Basket Summary');
	}

});

/**
 * @classDescription Handle advanced search flyout
*/
var AdvancedSearchFlyout = Class.create(UtilFlyoutBase, {
	initialize: function($super, eventSelector, txtSearch, options) {
		// set options
		this.options = Object.extend({
			serviceUrl: '/search/advancedSearchFlyout.aspx',
			failureUrl: '/search/default.aspx',
			searchUrl: '/search/default.aspx',
			elParent: $('wrapper')
		}, options || {});
		
		$super(this.options);
		
		var boundAdvSearchClick = this.__lnkAdvSearchClick.bindAsEventListener(this);
		
		Event.selector("a#lnk_adv_search", "click", boundAdvSearchClick);
		
		this.txtSearch = txtSearch;
		
		this.isContainerBuilt = false;
	},
	
	__lnkAdvSearchClick: function(e){
		e.stop();
		if(!this.isContainerBuilt){
			this.createContainer();
			this.open();
			this.makeXhrRequest(this.options.serviceUrl, 'get', {});
		}
		else{
			this.open();
		}
	},

	__btnSearchClick: function(e){
		// gather up selected options, add to querystring, and redirect
		e.stop();
		var params = $H();
		var btn = e.element();
		
        this.container.select('input').each(function(field){
			switch(field.type){
				case 'button', 'image':
					break;
				case 'checkbox':
					if(field.checked){
						params.set(field.name, $F(field));
					}
					break;
				case 'text':
					if(field.present()){
						params.set(field.name, $F(field));
					}
				default:
					params.set(field.name, $F(field));
					break;
			}
        });	
        // add the textbox
        params.set('term', this.txtSearch.value);
        // redirect
		window.location.href = this.options.searchUrl + '?' + params.toQueryString();
	},	

	processContent: function(){
		var boundSearchClick = this.__btnSearchClick.bindAsEventListener(this);
		this.container.down('input.btn_advsearch').observe('click', boundSearchClick);
	},
	
	createContainer: function($super){
		$super(this.options.elParent, 'adv_search_flyout', 'adv_search_content', 'Advanced Search');
		
		Element.clonePosition('adv_search_flyout', this.txtSearch, {
			setHeight: false,
			setWidth: false,
			offsetTop: this.txtSearch.getHeight()
		});
	}

});

// grab hooks into different flyout instances.
var UtilFlyouts = {
	signIn: false,
	cart: false,
	advsearch: false,
	searchPreview: false // to be implemented for hooking into search preview UI
};

document.observe('dom:loaded', function(){
	if($('lnk_cart')){
		UtilFlyouts.cart = new CartFlyout($('lnk_cart'),{});
	}
});

document.observe('dom:loaded', function(){
	var isHttps = /https/i.test(window.location.protocol);
	if(isHttps == true && $('lnk_signin')){
	    // only use flyout on https, otherwise it violates the browser's same origin policy for js
		
		// commented out to amend inconsistent behavior under HTTP(S)
		// UtilFlyouts.signIn = new SignInFlyout($('lnk_signin'),{});
	}
});

document.observe('dom:loaded', function(){
	var aTxtSearch = $$('input.txtSearch');
	if(aTxtSearch.size() > 0){
		UtilFlyouts.advSearch = new AdvancedSearchFlyout('a#lnk_adv_search', aTxtSearch.first(), {});	
	}
	
});

//***** end utility-flyouts


/* stub out console calls for ie
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i){
        window.console[names[i]] = function() {}
    }
}
*/


// Add a class name to the body as a global flag that the user has javascript.
document.observe('dom:loaded', function(){
	var elBody = $(document.body);
	if(elBody){
		elBody.addClassName('js-enabled');
	}
});


// Start RAHTracking
// Tracking for various tab switching and other content switching (singleton w/closure).
// Other specific tracking is done individually (syos, searchPreview).
var RAHTracking = (function(){
	// private method for calling urchinTracker 
	function _trackEvent(oArgs){
		var p_source = oArgs.source || document.location.pathname + document.location.search;
		var p_media = oArgs.media || '';
		var p_object = oArgs.object || '';
			p_object = p_object.replace(/_/gi,"+");
		var p_action = oArgs.action || '';
			p_action = p_action.replace(/_/gi,"+");
		var p_label = oArgs.label || '';
			p_label = p_label.replace(/_/gi,"+");
		var p_value = oArgs.value || '';
		var p_target = oArgs.target || '';

		//lowercase
		var p_action = p_action.toLowerCase();
		var p_label = p_label.toLowerCase();
		var p_object = p_object.toLowerCase();

		// Instantiate GA tracking call
		//var sReport = encodeURI('/_event/category='+_category+'/action='+_action+'/label='+_label);
		var sReport = encodeURI(p_source+'?utm_category='+p_object+'&utm_action='+p_action+'&utm_label='+p_label);
		try{
			urchinTracker(sReport);
			// Only uncomment during debugging
			//console.log("urchinTracker being called with: %s", sReport);
			//console.dir(oArgs);
		}
		catch(e){}
	}
	return {
		// track a tab switch (used by ContentSwitcher)
		TrackTab: function(trigger, tabId){
			// all will use click, all will have tab as object, only variance is tabID (hash);
			// trigger is most likely 'tab' or 'subnav'
			_trackEvent({"object": trigger, "action": 'click', "label": tabId});
		},
		// track a dropdown change (used by whatsonResponders.js)
		TrackDropDown: function(dropdownId, selectedValue){
			_trackEvent({"object": dropdownId, "action": 'change', "label": selectedValue});
		}	
	};
})();
// End RAHTracking

// start IframeBuster
var IframeBuster = Class.create ({
    initialize: function(link)
    {
        this.link = link;

        this.interval = setInterval(function()
        {
            this.doBustOut();
        }.bind(this), 1000); // wait 1 sec

    },
    doBustOut: function(e)
    {
        window.parent.location = this.link.href;
    }

});
// end IframeBuster


// start ToggleTextfield
var ToggleTextfield = Class.create ({
    initialize: function(input)
    {
        this.input = input;
        this.initvalue = $F(this.input);
        this.value = this.initvalue;
        
        Event.observe(this.input, 'focus', this.__Focus.bindAsEventListener(this));
        Event.observe(this.input, 'blur', this.__Blur.bindAsEventListener(this));
    },

    __Focus: function(e)
    {
		if (this.value == this.initvalue)
		{
		    this.input.value = '';
		}
    },

    __Blur: function(e)
    {
		this.value = $F(this.input);
		if (this.value == '')
		{
		    this.value = this.initvalue;
		    this.input.value = this.value;
		}
    }

});
// end ToggleTextfield


// start ProcessInterestsCheckboxes
var ProcessInterestsCheckboxes = Class.create ({
    initialize: function(container, link, inputs, emailcb)
    {
        this.container = container;
        this.link = link;
        this.inputs = inputs;
        this.emailcb = emailcb;
        this.length = this.inputs.size();
        this.checked = false;
        this.container.style.display = 'block';
        Event.observe(this.link, 'click', this.__ClickLink.bindAsEventListener(this));

        for (var i=0; i<this.length; i++)
        {
	        if (this.inputs[i].checked == true)
	        {
		        this.checkCB();
	        }
	        Event.observe(this.inputs[i], 'click', this.__ClickInputs.bindAsEventListener(this));
        }
    },

    __ClickLink: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        if (this.checked == false)
        {
            for (var i=0; i<this.length; i++)
            {
                this.inputs[i].checked = 'checked';
            }
            this.checked = true;
            this.link.update('Uncheck all');
            this.checkEmailCB();
        }
        else {
            for (var i=0; i<this.length; i++)
            {
                this.inputs[i].checked = '';
            }
            this.checked = false;
            this.link.update('Check all');
        }   
    },

    __ClickInputs: function(e)
    {
        var e = e || window.event;
        var element = Event.element(e);
        for (var i=0; i<this.length; i++)
        {
	        if (this.inputs[i] == element)
	        {
				if (this.inputs[i].checked == true)
				{
					this.checkEmailCB();
				}
	        }
        }
    },

    checkEmailCB: function()
    {
        this.emailcb.checked = true;
    }

});
// end ProcessInterestsCheckboxes


// start ToggleCartDetails
var ToggleCartDetails = Class.create ({
    initialize: function(links, items)
    {
        this.links = links;
        this.items = items;

		//this.elPopover  = new Element('div', {'class': 'popover'});
		this.elHead     = new Element('div', {'class': 'head'});
		this.elFoot     = new Element('div', {'class':'foot'});
		this.elLnkClose = new Element('a', {href: '#', 'class': 'lnk_close'}).update('close <span>x</span>');
		this.elTitleH4 = new Element('h4');
		this.elHead.appendChild(this.elLnkClose);
		this.elHead.appendChild(this.elTitleH4);
		
		Event.observe(this.elLnkClose, 'click', this.__ClickClose.bindAsEventListener(this));

		//this.elPopover.insert({top: this.elHead});
		//this.elPopover.insert({bottom: this.elFoot});

        // Loop through each and attach a click handler, toggle show/hide on elements
        for (var i=0; i<this.links.length; i++)
        {
	        this.links[i].style.display = 'block';
	        this.items[i].style.display = 'none';
	        Event.observe(this.links[i], 'click', this.__ClickOpen.bindAsEventListener(this));
        }
	},

    __ClickClose: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        if (this.elLnkClose == element)
        {
	        this.doToggle(-1);
        }
    },

    __ClickOpen: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
		        this.doToggle(i);
		        break;
	        }
        }
    },

    doToggle: function(iWhich)
    {
        for (var i=0; i<this.items.length; i++)
        {
	        if (i == iWhich)
	        {
	            this.items[i].style.display = 'block';
	            this.items[i].addClassName('popover');
	            this.items[i].insert({top: this.elHead});
	            this.items[i].insert({bottom: this.elFoot});
	            this.elTitleH4.update(this.links[i].innerHTML);
	        } else {
	            this.items[i].style.display = 'none';
	            this.items[i].removeClassName('popover');
	        }
        }
    }

});
// end ToggleCartDetails


// start PrintPage
var PrintPage = Class.create ({
    initialize: function(link)
    {
		if(!link){return;}//element check
        this.link = link;
        Event.observe(this.link, 'click', this.__Click.bindAsEventListener(this));
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        if (window.print){window.print();}
    }

});
// end PrintPage


// start GenericFlashEmbed
var GenericFlashEmbed = Class.create ({
    initialize: function(content, link)
    {
        this.content = content;
        this.link = link;
        this.swf = this.link.href;
        this.width = this.link.rel.split(',')[0];
        this.height = this.link.rel.split(',')[1];
        this.version = '9.0.0';
        this.writeSwf();
    },

    writeSwf: function()
    {
        swfobject.embedSWF(this.swf, this.content, this.width, this.height, this.version);
    }

});
// end GenericFlashEmbed


// start MainVideoEmbed
var MainVideoEmbed = Class.create ({
    initialize: function(content, flv)
    {
        this.content        = content;
        this.flv            = flv;
        this.width          = '568';
        this.height         = '320';
        this.flvWidth       = '568';
        this.flvHeight      = '320';
        this.version        = '9.0.0';
        this.bgcolor        = '#ffffff';
        this.swf            = '/_flash/_flv/rah_videoplayer_main.swf';
        this.writeSwf();
    },

    writeSwf: function()
    {
        this.flashvars = {
          flvPath: this.flv,
          flvWidth: this.flvWidth,
          flvHeight: this.flvHeight,
          autoPlayBool: false
        };
        this.params = {
          bgcolor: this.bgcolor,
          wmode: 'transparent'
        };
        this.attributes = {
          id: this.content,
          name: this.content
        };
        swfobject.embedSWF(this.swf, this.content, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end MainVideoEmbed


// start ProductionVideoEmbed
var ProductionVideoEmbed = Class.create ({
    initialize: function(content, flv)
    {
        this.content        = content;
        this.flv            = flv;
        this.width          = '385';
        this.height         = '245';
        this.flvWidth       = '384';
        this.flvHeight      = '216';
        this.version        = '9.0.0';
        this.bgcolor        = '#ffffff';
        this.swf            = '/_flash/_flv/rah_videoplayer.swf';
        this.writeSwf();
    },

    writeSwf: function()
    {
        this.flashvars = {
          flvPath: this.flv,
          flvWidth: this.flvWidth,
          flvHeight: this.flvHeight,
          autoPlayBool: false
        };
        this.params = {
          bgcolor: this.bgcolor,
          wmode: 'transparent'
        };
        this.attributes = {
          id: this.content,
          name: this.content
        };
        swfobject.embedSWF(this.swf, this.content, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end ProductionVideoEmbed

// start ContentSwitcher
var ContentSwitcher = Class.create ({
    initialize: function(links, items, rotate, showfirst)
    {
        this.links      = links;
        this.items      = items;
        this.rotate     = rotate || false;
        this.showfirst  = showfirst || false;
        this.top        = $('top');
        this.num        = 0;

        // custom: check the subnav for jump links
        this.sublinks = $$('div#subcolnavbox ul.subnav li a[href*=#]');

        // show different item every 8 seconds
        if (rotate)
        {
            this.interval = setInterval(function()
            {
                this.doRotate();
            }.bind(this), 5000);
        }

        // Loop through each and attach a click handler
        var handleClick = this.__Click.bindAsEventListener(this);
        for (var i=0; i<this.links.length; i++)
        {
	        Event.observe(this.links[i], 'click', handleClick);
        }

		// Show the first content item
        if (showfirst)
        {
            for (var i=0; i<this.items.length; i++)
            {
	            if (this.items[i].id == showfirst)
	            {
	                this.doShowHide(i);
	            }
            }
            this.top.scrollTo();
        }

        // custom: check the page for any other jump links
        this.anchors = $A($$('a[href*=#]'));
        var handleAllClick = this.__AllClick.bindAsEventListener(this);
        this.anchors.each(function(a)
        {
            if (!this.links.include(a))
            {
                if (this.links.include(a.href))
                {
                    $(a).observe('click', handleAllClick);
                }
            }
        }.bind(this));
    },

    __AllClick: function(e)
    {
        clearInterval(this.interval); // clear timer once link is clicked
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.anchors.length; i++)
        {
	        this.anchors[i].ahash = this.anchors[i].hash.replace('#','');
	        if (this.anchors[i] == element)
	        {
                for (var j=0; j<this.items.length; j++)
                {
                    if (this.items[j].id == this.anchors[i].ahash)
                    {
						if(typeof(RAHTracking) !== 'undefined'){
							RAHTracking.TrackTab('subnav', this.anchors[i].ahash);
						}
                        this.doShowHide(j);
                        break;
                    }
                }
	        } else {

	        }
        }
    },

    __Click: function(e)
    {
        clearInterval(this.interval); // clear timer once link is clicked
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
				if(typeof(RAHTracking) !== 'undefined'){
					RAHTracking.TrackTab('tab', this.items[i].id);
				}
		        this.doShowHide(i);
		        break;
	        }
        }
    },

    // Rotate thru items
    doRotate: function()
    {
        this.num++;
        if (this.num == this.links.length)
        {
            this.num = 0;
        }
        this.doShowHide(this.num);
    },

    // Show a specific item, hide the rest
    doShowHide: function(iWhich)
    {
        for (var i=0; i<this.items.length; i++)
        {
	        if (i == iWhich)
	        {
		        //this.items[i].show();
		        this.items[i].appear({ duration: 0.5 });
		        this.links[i].parentNode.className = 'in';
		        this.doSublinksShowHide(this.items[i].id);
		        
		        // this is needed to set the correct url for Send to Friend
		        if (typeof doSendUrlEmail != 'undefined')
		        {
		            doSendUrlEmail.SetUrlWithTab(this.items[i].id);
		        }
	        } else {
	            this.items[i].hide();
	            this.links[i].parentNode.className = '';
	        }
        }
    },

    // custom: show a specific subnav item, hide the rest
    doSublinksShowHide: function(iID)
    {
        if (this.sublinks != '')
        {
            for (var i=0; i<this.sublinks.length; i++)
            {
                this.sublinks[i].ahash = this.sublinks[i].hash.replace('#','');
	            if (this.sublinks[i].ahash == iID)
	            {
	                this.sublinks[i].parentNode.className = 'in';
	            } else {
	                this.sublinks[i].parentNode.className = '';
	            }
            }
        }
    }

});
// end ContentSwitcher


// start VideoSwitcher
// note: SWFObject embed params are hard-coded
var VideoSwitcher = Class.create ({
    initialize: function (player, links)
    {
        this.player         = player;
        this.links          = links;
        this.width          = '385';
        this.height         = '245';
        this.flvWidth       = '384';
        this.flvHeight      = '216';
        this.version        = '9.0.0';
        this.bgcolor        = '#ffffff';
        this.swf            = '/_flash/_flv/rah_videoplayer.swf';
        for (var i=0; i<this.links.length; i++)
        {
            Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }
        this.initWriteSwf(0);
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.findElement(e, 'a');
        for (var i=0; i<this.links.length; i++)
        {
            if (this.links[i] == element)
            {
                this.initWriteSwf(i);
                break;
            }
        }
    },

    initWriteSwf: function(iWhich)
    {
        for (var i=0; i<this.links.length; i++)
        {
            if (i == iWhich)
            {
                this.links[i].up().addClassName('in');
                this.writeSwf(i);
            } else {
                this.links[i].up().removeClassName('in');
            }
        }
    },

    writeSwf: function(i)
    {
        this.flashvars = {
          flvPath: this.links[i].href,
          flvWidth: this.flvWidth,
          flvHeight: this.flvHeight
        };
        this.params = {
          bgcolor: this.bgcolor,
          wmode: 'transparent'
        };
        this.attributes = {
          id: this.player,
          name: this.player
        };
        swfobject.embedSWF(this.swf, this.player, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end VideoSwitcher


// start AudioSwitcher
// note: SWFObject embed params are hard-coded
var AudioSwitcher = Class.create ({
    initialize: function (player, links)
    {
        this.player         = player;
        this.links          = links;
        this.width          = '385';
        this.height         = '35';
        this.version        = '9.0.0';
        this.bgcolor        = '#ffffff';
        this.swf            = '/_flash/_mp3/rah_audioplayer.swf';
        for (var i=0; i<this.links.length; i++)
        {
            Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }
        this.initWriteSwf(0);
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.findElement(e, 'a');
        for (var i=0; i<this.links.length; i++)
        {
            if (this.links[i] == element)
            {
                this.initWriteSwf(i);
                break;
            }
        }
    },

    initWriteSwf: function(iWhich)
    {
        for (var i=0; i<this.links.length; i++)
        {
            if (i == iWhich)
            {
                this.links[i].up().addClassName('in');
                this.writeSwf(i);
            } else {
                this.links[i].up().removeClassName('in');
            }
        }
    },

    writeSwf: function(i)
    {
        this.flashvars = {
          mp3Path: this.links[i].href
        };
        this.params = {
          bgcolor: this.bgcolor,
          wmode: 'transparent'
        };
        this.attributes = {
          id: this.player,
          name: this.player
        };
        swfobject.embedSWF(this.swf, this.player, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end AudioSwitcher


// start MediaVideoSwitcher
// note: SWFObject embed params are hard-coded
var MediaVideoSwitcher = Class.create ({
    initialize: function (player, links, items)
    {
        this.player     = player;
        this.links      = links;
        this.items      = items;
        this.width      = '385';
        this.height     = '245';
        this.flvWidth   = '384';
        this.flvHeight  = '216';
        this.version    = '9.0.0';
        this.bgcolor    = '#ffffff';
        this.swf        = '/_flash/_flv/rah_videoplayer.swf';
        for (var i=0; i<this.links.length; i++)
        {
            Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }
        this.initWriteSwf(0);
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.findElement(e, 'a');
        for (var i=0; i<this.links.length; i++)
        {
            if (this.links[i] == element)
            {
                $('mediaVideo').scrollTo();
                this.initWriteSwf(i);
                break;
            }
        }
    },

    initWriteSwf: function(iWhich)
    {
        for (var i=0; i<this.links.length; i++)
        {
            if (i == iWhich)
            {
                this.items[i].show();
                this.links[i].parentNode.className = 'in';
                this.writeSwf(i);
            } else {
                this.items[i].hide();
                this.links[i].parentNode.className = '';
            }
        }
    },

    writeSwf: function(i)
    {
        this.flashvars = {
          flvPath: this.links[i].href,
          flvWidth: this.flvWidth,
          flvHeight: this.flvHeight
        };
        this.params = {
          bgcolor: this.bgcolor,
          wmode: 'transparent'
        };
        this.attributes = {
          id: this.player,
          name: this.player
        };
        swfobject.embedSWF(this.swf, this.player, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end MediaVideoSwitcher


// start MediaAudioSwitcher
// note: SWFObject embed params are hard-coded
var MediaAudioSwitcher = Class.create ({
    initialize: function (player, links, items)
    {
        this.player     = player;
        this.links      = links;
        this.items      = items;
        this.width      = '385';
        this.height     = '35';
        this.version    = '9.0.0';
        this.bgcolor    = '#ffffff';
        this.swf        = '/_flash/_mp3/rah_audioplayer.swf';
        for (var i=0; i<this.links.length; i++)
        {
            Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }
        this.initWriteSwf(0);
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.findElement(e, 'a');
        for (var i=0; i<this.links.length; i++)
        {
            if (this.links[i] == element)
            {
                $('mediaAudio').scrollTo();
                this.initWriteSwf(i);
                break;
            }
        }
    },

    initWriteSwf: function(iWhich)
    {
        for (var i=0; i<this.links.length; i++)
        {
            if (i == iWhich)
            {
                this.items[i].show();
                this.links[i].parentNode.className = 'in';
                this.writeSwf(i);
            } else {
                this.items[i].hide();
                this.links[i].parentNode.className = '';
            }
        }
    },

    writeSwf: function(i)
    {
        this.flashvars = {
          mp3Path: this.links[i].href
        };
        this.params = {
          bgcolor: this.bgcolor,
          wmode: 'transparent'
        };
        this.attributes = {
          id: this.player,
          name: this.player
        };
        swfobject.embedSWF(this.swf, this.player, this.width, this.height, this.version, false, this.flashvars, this.params, this.attributes);
    }

});
// end MediaAudioSwitcher


// start SimpleContentSwitcher
var SimpleContentSwitcher = Class.create ({
    initialize: function(links, items)
    {
        this.links      = links;
        this.items      = items;
        this.showfirst  = true;

        // Loop through each and attach a click handler
        for (var i=0; i<this.links.length; i++)
        {
	        Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }

		// Show the first content item
        if (this.showfirst)
        {
            this.doShowHide(0);
        }
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
		        this.doShowHide(i);
		        break;
	        }
        }
    },

    // Show a specific item, hide the rest
    doShowHide: function(iWhich)
    {
        for (var i=0; i<this.items.length; i++)
        {
	        if (i == iWhich)
	        {
		        this.items[i].style.display = 'block';
		        this.links[i].parentNode.className = 'in';
	        } else {
	            this.items[i].style.display = 'none';
	            this.links[i].parentNode.className = '';
	        }
        }
    }

});
// end SimpleContentSwitcher


// start SimpleImageSwitcher
var SimpleImageSwitcher = Class.create ({
    initialize: function(links, image)
    {
        this.links = links;
        this.image = image;

        // Loop through each and attach a click handler
        for (var i=0; i<this.links.length; i++)
        {
	        Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }

        this.doImageSwap(0);

    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
		        //this.image.hide();
		        this.doImageSwap(i);
		        break;
	        }
        }
    },

    // Show a specific item, hide the rest
    doImageSwap: function(iWhich)
    {
        for (var i=0; i<this.links.length; i++)
        {
	        if (i == iWhich)
	        {
		        this.links[i].parentNode.className = 'in';
		        this.image.src = this.links[i].href;
		        this.image.alt = this.links[i].title;
		        //this.image.appear({ duration: 0.3 });
	        } else {
	            this.links[i].parentNode.className = '';
	        }
        }
    }

});
// end SimpleImageSwitcher


// start ImageSlideshow
var ImageSlideshow = Class.create ({
    initialize: function(prev, next, image, items, data)
    {
        this.prev       = prev;
        this.next       = next;
        this.image      = image;
        this.items      = items;
        this.data       = data;
        this.num        = 0;
        if(!image){return;}//element check

        this.doImgSwap(this.num);

        Event.observe(this.prev, 'click', this.__ClickPrev.bindAsEventListener(this));
        Event.observe(this.next, 'click', this.__ClickNext.bindAsEventListener(this));
    },

    __ClickPrev: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        if (this.num == 0)
        {
            this.num = this.data.length;
        }
        this.num--;
        this.image.hide();
        this.doImgSwap(this.num);
    },

    __ClickNext: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        this.num++;
        if (this.num == this.data.length)
        {
            this.num = 0;
        }
        this.image.hide();
        this.doImgSwap(this.num);
    },

    // Show a specific item, hide the rest
    doImgSwap: function(iWhich)
    {
        for (var i=0; i<this.items.length; i++)
        {
	        if (i == iWhich)
	        {
                this.image.src = this.data[i].imgSrc;
                this.image.alt = this.data[i].imgAlt;
                this.image.appear({ duration: 0.3 });
		        this.items[i].style.display = 'block';
	        } else {
	            this.items[i].style.display = 'none';
	        }
        }
        this.num = iWhich;
    }

});
// end ImageSlideshow


// start TextareaMaxlength
var TextareaMaxlength = Class.create ({
    initialize: function(textarea, maxlength)
    {
        this.textarea = textarea;
        this.maxlength = maxlength;
        // attach event handlers
        Event.observe(this.textarea, 'keyup', this.__Key.bindAsEventListener(this));
    },

    __Key: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        this.enforce();
    },

    // Enforce textarea maxlength
    enforce: function()
    {
        if ($F(this.textarea).length >= this.maxlength)
        {
            this.textarea.value = $F(this.textarea).substring(0, this.maxlength);
        }
    }

});
// end TextareaMaxlength


// start PopOver
var PopOver = Class.create ({
    initialize: function(trigger, popover, closer)
    {
        this.trigger = trigger;
        this.popover = popover;
        this.closer = closer;
        this.trigger.style.display = 'inline'; // 'block'

        // attach a click handler to trigger element
        Event.observe(this.trigger, 'click', this.__ClickTrigger.bindAsEventListener(this));

        // attach a click handler to close link
        Event.observe(this.closer, 'click', this.__ClickCloseX.bindAsEventListener(this));
    },

    __ClickTrigger: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        this.popover.style.display = 'block';
    },

    __ClickCloseX: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        this.popover.style.display = 'none';
    },
    
    ReregisterTrigger: function(trigger)
    {
        this.trigger = trigger;
        if (this.trigger)
        {
            Event.observe(this.trigger, 'click', this.__ClickTrigger.bindAsEventListener(this));
        }
    }        

});
// end PopOver


// start MultiPopOvers
var MultiPopOvers = Class.create ({
    initialize: function(aTriggers, aPopovers, aClosers)
    {
        this.links = aTriggers;
        this.items = aPopovers;
        this.closers = aClosers;

        // Loop through each and attach a click handler to trigger element
        for (var i=0; i<this.links.length; i++)
        {
	        Event.observe(this.links[i], 'click', this.__Click1.bindAsEventListener(this));
        }

        // Loop through each and attach a click handler to close link
        for (var i=0; i<this.closers.length; i++)
        {
	        Event.observe(this.closers[i], 'click', this.__Click2.bindAsEventListener(this));
        }
    },

    __Click1: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
		        this.doShowHide(i);
		        break;
	        }
        }
    },

    __Click2: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        this.doHide();
    },

    // Show a specific item, hide the rest
    doShowHide: function(iWhich)
    {
        for (var i=0; i<this.items.length; i++)
        {
	        if (i == iWhich)
	        {
		        this.items[i].style.display = 'block';
	        } else {
	            this.items[i].style.display = 'none';
	        }
        }
    },

    // Hide all items
    doHide: function()
    {
        for (var i=0; i<this.items.length; i++)
        {
	        this.items[i].style.display = 'none';
        }
    }

});
// end MultiPopOvers


// start TabSwitcher
var TabSwitcher = Class.create ({
    initialize: function(aLinks, aItems)
    {
        this.links = aLinks;
        this.items = aItems;
        this.timeout;

        // Loop through each and attach an event handler
        for (var i=0; i<this.links.length; i++)
        {
	        Event.observe(this.links[i], 'mouseover', this.__linkOver.bindAsEventListener(this));
	        Event.observe(this.links[i], 'mouseout', this.__linkOut.bindAsEventListener(this));
        }
        for (var i=0; i<this.items.length; i++)
        {
	        Event.observe(this.items[i], 'mouseover', this.__itemOver.bindAsEventListener(this));
	        Event.observe(this.items[i], 'mouseout', this.__itemOut.bindAsEventListener(this));
        }
    },

    // Deal with link mouseover
    __linkOver: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
		        this.doShowHide(i);
		        break;
	        }
        }
    },

    // Deal with link mouseout
    __linkOut: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
                this.timeout = setTimeout(function()
                {
                    this.items[i].style.display = 'none';
                }.bind(this), 1500);
		        break;
	        }
        }
    },

    // Deal with item mouseover
    __itemOver: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.items.length; i++)
        {
	        if (this.items[i] == element)
	        {
		        this.doShowHide(i);
		        break;
	        }
        }
    },

    // Deal with item mouseout
    __itemOut: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.items.length; i++)
        {
			  /*note: 
					e.relatedTarget is the node to which the pointer went
					e.currentTarget is the node to which the event is attached
			  */
	        if (this.items[i] == element && !(e.relatedTarget.descendantOf(element)))
	        {
                this.timeout = setTimeout(function()
                {
                    this.items[i].style.display = 'none';
                }.bind(this), 1500);
		        break;
	        }
        }
    },

    // Show a specific item, hide the rest
    doShowHide: function(iWhich)
    {
        for (var i=0; i<this.items.length; i++)
        {
	        if (i == iWhich)
	        {
		        clearTimeout(this.timeout);
		        this.items[i].style.display = 'block';
	        } else {
	            this.items[i].style.display = 'none';
	        }
        }
    }

});
// end TabSwitcher


// start PopupWindow
var PopupWindow = Class.create ({
    initialize: function(link, width, height, extras)
    {
        this.winName = 'popup';
        this.altWidth = 640;
        this.altHeight = 480;
        this.altExtras = 'location=yes,menubar=yes,statusbar=yes,toolbar=yes,scrollbars=yes,resizable=yes';
        this.link = link;
        this.url = link.getAttribute('href');
        this.w = width || this.altWidth;
        this.h = height || this.altHeight;
        this.x = extras || this.altExtras;
        this.features = 'width=' + this.w + ',height=' + this.h + ',' + this.x;
        Event.observe(this.link, 'click', this.__Click.bindAsEventListener(this));
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        var win = window.open(this.url, this.winName, this.features);
        win.focus();
    }

});
// end PopupWindow


// start MultiPopupWindows
var MultiPopupWindows = Class.create (
{
    initialize: function(links, width, height, extras)
    {
        this.winName = 'popup';
        this.altWidth = 640;
        this.altHeight = 480;
        this.altExtras = 'location=yes,menubar=yes,statusbar=yes,toolbar=yes,scrollbars=yes,resizable=yes';
        this.links = links;
        this.w = width || this.altWidth;
        this.h = height || this.altHeight;
        this.x = extras || this.altExtras;
        this.features = 'width=' + this.w + ',height=' + this.h + ',' + this.x;
        for(var i=0; i<this.links.length; i++)
        {
            Event.observe(this.links[i], 'click', this.__Click.bindAsEventListener(this));
        }
    },

    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        for (var i=0; i<this.links.length; i++)
        {
	        if (this.links[i] == element)
	        {
                var url = this.links[i].getAttribute('href');
                var win = window.open(url, this.winName, this.features);
                win.focus();
                break;
	        }
        }
    }

});
// end MultiPopupWindows


// start ClosePopup
var ClosePopup = Class.create ({
    initialize: function(link)
    {
        this.link = link;
        this.link.style.visibility = 'visible';
        Event.observe(this.link, 'click', this.__Click.bindAsEventListener(this));
    },
    __Click: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        window.close();
    }

});
// end ClosePopup


// start FlyoutNav
var FlyoutNav = Class.create ({
    initialize: function(nav)
    {
        this.nav = nav;
        this.navnodes = nav.childElements();
        // Loop through each and attach event handlers
        for(var i=0; i<this.navnodes.length; i++)
        {
            Event.observe(this.navnodes[i], 'mouseover', function()
            {
                this.addClassName('over');
            });
            Event.observe(this.navnodes[i], 'mouseout', function()
            {
                this.removeClassName('over');
            });
            //Event.observe(this.navnodes[i], 'mouseover', this.__Mouseover.bindAsEventListener(this));
            //Event.observe(this.navnodes[i], 'mouseout', this.__Mouseout.bindAsEventListener(this));
        }
    },
    __Mouseover: function(e)
    {
        var e = e || window.event;
        var element = Event.findElement(e, 'li');
        element.addClassName('over');
    },
    __Mouseout: function(e)
    {
        var e = e || window.event;
        var element = Event.findElement(e, 'li');
        element.removeClassName('over');
    }
});
// only needed for IE6, place in head inside IE6 conditional comment
/*
document.observe('dom:loaded', function()
{
    doSiteNavFlyout = new FlyoutNav( $('mainnav') );
});
*/
// end FlyoutNav


// start SendUrlEmailPopOver
var SendUrlEmailPopOver = Class.create ({
    initialize: function(trigger1, trigger2, popover, closer, formpanel, resultpanel, validationsummary, urlcontrol, urlhiddencontrol, useajax)
    {
        this.trigger1 = trigger1;
        this.trigger2 = trigger2;
        this.popover = popover;
        this.closer = closer;
        this.formpanel = formpanel;
        this.resultpanel = resultpanel;
        this.validationsummary = validationsummary;
        this.urlcontrol = urlcontrol;
        this.urlhiddencontrol = urlhiddencontrol;
        this.useajax = useajax;
        if (typeof this.urlhiddencontrol != 'undefined')
            this.url = this.urlhiddencontrol.value;
        else
            this.url = '';
        this.SetUrl(this.url);
        
        this.ShowHideForm(true);

        // attach a click handler to trigger element
        Event.observe(this.trigger1, 'click', this.__Click1.bindAsEventListener(this));
        if (this.trigger2)
            Event.observe(this.trigger2, 'click', this.__Click1.bindAsEventListener(this));

        // attach a click handler to close link
        Event.observe(this.closer, 'click', this.__Click2.bindAsEventListener(this));
    },

    // this is the event handler for trigger element
    __Click1: function(e)
    {
        var e = e || window.event;
        Event.stop(e);
        var element = Event.element(e);
        this.ShowHideForm(true);
        this.popover.style.display = 'block';
    },

    // this is the event handler for the close element
    __Click2: function(e)
    {
        //var e = e || window.event;
        //Event.stop(e);
        //var element = Event.element(e);
        this.CloseForm();
        this.ClearForm();
    },

    // this function is used to close the popover
    CloseForm: function()
    {
        this.popover.style.display = 'none';
        this.ShowHideForm(true);
    },
    
    // this function needs to be called when need to change the send to friend url
    SetUrl: function(url)
    {
        this.url = url;
        if (typeof this.urlcontrol != 'undefined')
        {
            if (document.all)
                this.urlcontrol.innerText = this.url;
            else
                this.urlcontrol.textContent = this.url;
        }
        
        if (typeof this.urlhiddencontrol != 'undefined')
        {
            this.urlhiddencontrol.value = this.url;
        }
    },
    
    // this function is used when using the javascript tabs
    SetUrlWithTab: function(tabName)
    {
        // Strip current URL's tab settings
        var myUrl = '';
        if (this.url.indexOf('#') > 0)
        {
            myUrl = this.url.substring(0, this.url.indexOf('#')+1) + tabName;
        }
        else
        {
            myUrl = this.url + '#' + tabName;
        }
        this.SetUrl(myUrl);
    },
    
    // this is used if the popover form is inside the ajax call like the send to friend form itself
    // in this case, the ajax call will replace the popover form element in the DOM, so this object
    // will lose the original element reference. Therefore, the references needs to be reset.
    ResetPanels: function(trigger2id, popoverid, formpanelid, resultpanelid, validationsummaryid, urlcontrolid, urlhiddencontrolid, showForm, closeForm)
    {
        this.trigger2 = $(trigger2id);
        if (this.trigger2)
            Event.observe(this.trigger2, 'click', this.__Click1.bindAsEventListener(this));
        this.popover = $(popoverid);
        this.formpanel = $(formpanelid);
        this.resultpanel = $(resultpanelid);
        this.validationsummary = $(validationsummaryid);
        this.urlcontrol = $(urlcontrolid);
        this.urlhiddencontrol = $(urlhiddencontrolid);
        this.ShowHideForm(showForm);
        if (closeForm)
            this.CloseForm();
    },
    
    // used to show or hide the form/result panel.
    ShowHideForm: function(doShow)
    {
        if (this.urlcontrol)
            this.urlcontrol.innerText = this.url;
        if (this.formpanel)
            this.formpanel.style.display = doShow ? 'block' : 'none';
        if (this.resultpanel)
            this.resultpanel.style.display = doShow ? 'none' : 'block';
    },
    
    // used to clear the form
    ClearForm: function()
    {
        var inputElements = this.formpanel.getElementsByTagName('input');
        for (var i=0; i<inputElements.length; i++)
        {
            if (inputElements[i].type == 'text')
                inputElements[i].value = '';
        }
        inputElements = this.formpanel.getElementsByTagName('textarea');
        if (inputElements.length > 0)
            inputElements[0].value = '';
        if (typeof this.validationsummary != 'undefined')
            ResetValidations(this.validationsummary.id, 'rfv,rev');
        /*if (this.repeateritempref != '' && this.repeatercountcontrolid != '')
            RemoveRepeaterItem(this.repeateritempref, this.repeatercountcontrolid, -1);*/
    },
    
    // this is used only for debugging purposes
    ShowProperties: function()
    {
        alert(this.trigger1.id);
        alert(this.trigger2.id);
        alert(this.popover.id);
        alert(this.closer.id);
        alert(this.formpanel.id);
        alert(this.resultpanel.id);
        alert(this.url);
        alert(this.urlcontrol.id);
    }
});
// end SendUrlEmailPopOver

// Utility to clear validations and validation summary
function ResetValidations(validationSummaryId, validationControlsPrefix)
{
    var spans;
    var divValSummary;
    var valPrefixArray = ("" + validationControlsPrefix).split(','); 

    if (document.all)
    {
        spans = document.all.tags('span');
        divValSummary = document.all(validationSummaryId);
    }
    else if (document.getElementsByTagName)
    {
        spans = document.getElementsByTagName('span');
        divValSummary = $(validationSummaryId);
    }

    if (typeof spans != 'undefined' && typeof valPrefixArray != 'undefined')
    {
        for (var i=0; i<spans.length; i++)
        {
            var currID = "" + spans[i].id;
            
            if (currID != '' && valPrefixArray[0] != '')
            {
                for (var j=0; j<valPrefixArray.length; j++)
                {
                    if (currID.indexOf('_' + valPrefixArray[j] + '_') > 0)
                        spans[i].style.visibility = 'hidden';
                }
            }
        }
    }
    
    if (typeof divValSummary != 'undefined')
        divValSummary.style.display='none';
}
// end ResetValidations

// Shows/hides a DOM element based on whether a checkbox is clicked.
var CheckboxShowHidePanel = Class.create ({
    // checkboxId: id of the checkbox input tag
    // panelId: id of the element to show/hide
    initialize: function(checkboxId, panelId)
    {
        this.checkbox = $(checkboxId);
        this.panel = $(panelId);
        
        this.__Click(null);
        
        Event.observe(this.checkbox, 'click', this.__Click.bindAsEventListener(this));
    },
    __Click: function(e)
    {
            this.panel.style.display = (this.checkbox.checked) ? 'block' : 'none';
    }
});

/*
 * EnterClick listens on a containing element for the enter/return key being pressed.
 * When the enter key is pressed within a child input element that will submit the form, 
 * it will prevent the default form submittal and fire the click event of a designated button.
 *  
 * Usage:
 * $('fieldset_forgot').onEnterClick($('btn_Forgot'));
 */
var EnterClick = Class.create({
	relevantTypes: $w('text password checkbox radio'),
	initialize: function(element, button){
		this.element = $(element).addClassName("enterclick");
		this.button = $(button);
		this.element.observe('keypress', this.__keyPress.bindAsEventListener(this));
	},
	__keyPress: function(e){
		var elSrc = e.element();
		if((e.keyCode == Event.KEY_RETURN) 
			&& (elSrc.nodeName == 'INPUT') 
			&& (this.relevantTypes.include(elSrc.type))) {
				// prevent default form submittal
				e.stop(); 
				// fire associated button's click event
				//console.log('firing ' + this.button.id);
				this.button.click();
		}
	}
});
// Extend Element with enterclick
Element.addMethods({
	onEnterClick: function(element, button) {
		new EnterClick(element, button);
		return element;
	}
});

// end EnterClick
// Start iFrameShim : fix for ie and elments positioned over select elements
var iFrameShim = Class.create({
	initialize: function(elParent, shimContainerId){
		this.IE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;
		this.elParent = $(elParent);
		this.containerId = shimContainerId;
		// IE6 and element check
		if (!this.IE6 || !this.elParent) { return; }
	},
	create: function(){
		// create shim and add attributes and styles
		var parentDim = this.elParent.getDimensions();

		this.shim = new Element('iframe', { 
			className: "ie6_shim"
		}).setStyle({
			position: 'absolute',
  			zIndex: '-2',
  			left: '0px',
  			top: '0px',
  			border: '0',
			width: parentDim.width+"px", 
			height: parentDim.height+"px"  			
		});
		
		// create buffer div so that you can never click through to the iframe
		this.bufferDiv = new Element('div', { 
			className: "buffer_div" 
		}).setStyle({
			position: 'absolute',
  			zIndex: '-1',
  			left: '0px',
  			top: '0px',
  			width: parentDim.width+'px',
  			height: parentDim.height+'px'
		});

		// create container div to hold shim and buffer div
		this.containerDiv = new Element('div', { id: this.containerId || "iframe_shim_container"});
		
		// insert buffer div and shim into container and container into parent
		this.containerDiv.insert({bottom: this.bufferDiv});
		this.containerDiv.insert({bottom: this.shim});
		this.elParent.insert({bottom: this.containerDiv});

		// change opacity after insertion
		this.shim.setOpacity(0);
	},
	resize: function(){
		// IE6 and element check
		if(!this.IE6 || !$(this.containerId)){ 
		    this.create();
		} else {
		    // get new dimensions
		    var newDimensions = this.elParent.getDimensions();
    		
		    // resize shim
		    $(this.containerId).down("iframe").setStyle({
			    width: newDimensions.width+"px",
			    height: newDimensions.height+"px"
		    });
    		
		    // resize buffer div
		    $(this.containerId).down("div").setStyle({
			    width: newDimensions.width+"px",
			    height: newDimensions.height+"px"		
		    });
		}
	},
	destroy: function(){
		// IE6 and element check
		if(!$(this.containerId) || !this.IE6){ return }
		
		this.containerDiv.remove();
		this.containerDiv = null;
	}
});
// apply ie6 iframe shim to search preview and util flyouts.
var isIE6 = false /*@cc_on || @_jscript_version <= 5.7 @*/;
if(isIE6){
    
    var searchResultsIframe;
    var flyoutIframe;
    
	document.observe('searchresults:show', function(ce){
        searchResultsIframe = new iFrameShim(ce.target, 'search_preview_shim');
        searchResultsIframe.create();
	});
	document.observe('searchresults:update', function(ce){
        searchResultsIframe.resize();
	});
	document.observe('searchresults:hide', function(ce){
		searchResultsIframe.destroy();
	});
	
	document.observe('utilFlyout:open', function(ce){
	    flyoutIframe = new iFrameShim(ce.target, ce.target.identify() + '_shim');
	    flyoutIframe.create();
	});
	document.observe('utilFlyout:update', function(ce){
		flyoutIframe.resize();
	});
	document.observe('utilFlyout:close', function(e){
		flyoutIframe.destroy();
	});

}
// End iFrameShim

// Utility to remove repeater item
/*function RemoveRepeaterItem(repeaterItemPref, repeaterCountControlId, removeIndex)
{
    var i = 1;  // never removes the first one (index=0)
    var myDiv = $(repeaterItemPref + '_' + ((i<10) ? "0" + i : "" + i));
    var myCount = $(repeaterCountControlId);
    var undefined;

    while(typeof myDiv != 'undefined')
    {
        try
        {
            if (removeIndex == -1 || removeIndex == i)
            {
                myDiv.style.display = 'none';
                while(myDiv.hasChildNodes())
                {
                    myDiv.removeChild(myDiv.lastChild);
                }
                myDiv.parentNode.removeChild(myDiv);

                if (typeof myCount != 'undefined' && (removeIndex != -1 || i == 1))
                    myCount.value = i;
            }
            
            i++;
            myDiv = $(repeaterItemPref + '_' + ((i<10) ? "0" + i : "" + i));
        }
        catch(err)
        {
            myDiv = undefined;
        }
    }
}*/

/**
* LabelInput uses the title attribute of a label element to show 
* guiding or default text into a text input through the label's title attribute.
* e.g. <label id="lblDOB" for="txtDOB" title="mm/dd/yyyy"/>
* Usage examples:
* $('lblDOB').labelInput();
* $('lblDOB').labelInput({inputText: 'first, last', defaultClassName: 'myclass'});
* $$('label').invoke('labelInput');
* 
**/
var LabelInput = Class.create({
    forms: [], // references to containing forms
    initialize: function(elLabel, options) {
        var elTxtInput = $(elLabel.readAttribute('for'));
        if (!Object.isElement(elTxtInput)) { return; }
        this.options = Object.extend({
            defaultClassName: 'hint', 				// class to apply to input when it's using the text set.
            inputText: elLabel.readAttribute('title')	// get the text from the options, or the label's title attribute
        }, options || {});

        // add the text to text input as a property.
        elTxtInput._labelText = this.options.inputText;

        elTxtInput.observe('focus', this.__txtInputFocus.bindAsEventListener(this));
        elTxtInput.observe('blur', this.__txtInputBlur.bindAsEventListener(this));

        //set the initial default text
        if (elTxtInput.value == '') {
            elTxtInput.value = elTxtInput._labelText;
            elTxtInput.addClassName(this.options.defaultClassName);
        }

        // clear out label text on form submit
        var elForm = elLabel.up('form');
        if (elForm && !this.forms.member(elForm)) {
            elForm.observe('submit', this.__frmSubmit.bindAsEventListener(this));
            this.forms.push(elForm);
        }
    },

    // sets the label text
    __txtInputBlur: function(e) {
        var elTxtInput = e.element();
        if (elTxtInput.value == '' && elTxtInput._labelText) {
            // add label text
            elTxtInput.value = elTxtInput._labelText;
            elTxtInput.addClassName(this.options.defaultClassName);
        }
        else {
            elTxtInput.removeClassName(this.options.defaultClassName);
        }
    },

    // removes the label text
    __txtInputFocus: function(e) {
        var elTxtInput = e.element();
        if (elTxtInput.value == elTxtInput._labelText) {
            elTxtInput.value = '';
            elTxtInput.removeClassName(this.options.defaultClassName);
        }
    },

    // makes sure text input values are not set to the label text upon form submission
    __frmSubmit: function(e) {
        //e.element().getInputs('text, textarea').each(function(txtInput){
        e.element().getElements().each(function(txtInput) {
            if (txtInput._labelText && (txtInput.value == txtInput._labelText)) {
                txtInput.clear();
            }
        });
    }
});

// Extend the Label tag with InputText
Element.addMethods('LABEL', {
    labelInput: function(element, options) {
        new LabelInput(element, options);
        return element;
    }
});

