/*global jQuery $ window document swfobject currentState Track */
/*
	
SolarWorld Global Javascript Functions
By Christoph Saxe, Devin Olsen - ISITE Design

*/

var rotatorcontent = "";

// jquery no conflict. use $j or jQuery outside of ready function
var $j = jQuery.noConflict();

// incrementor used by swfobject call to ensure unique ids for multiple flash objects
var flashcount = 0;

// incrementor used by swfobject call to ensure unique ids for multiple flash video objects
var videocount = 0;

// utility for checking for and pulling apart url query
// returns false if no query or else an object with query keys/vals 
String.prototype.parseQuery = function (clear) {
	var queryobject = false,
		queryarray = [],
		temp = [];
	if (/\?{1}/.test(this)) {
		if(clear) {
			return this.slice(0,this.indexOf('?'));
		}
		queryobject = {};
		queryarray = this.split('?')[1].split('&');
		for(var i=0;i<queryarray.length;i++) {
			temp = queryarray[i].split('=');
			queryobject[temp[0]] = temp[1];
		}
	}
	return queryobject;
};


// jQuery document ready
$j(function($) {

	// JS enabled
	$('html').addClass('js');

	// Few setups for IE6
	if (document.all) {
		//add class to drop downs and buttons 
		$('#nav li, button').hover(
			function() {
				$(this).addClass('over');
			},
			function() {
				$(this).removeClass('over');
			}
	    );
	} // if document.all


	/*****************************************************************
	these functions fire on every page
	*/

	// sitewide utilities: search and language selector
	$('#site-utilities').addClass('IX_utilities');
	$('#nav-language').selectedLanguage();




	/*****************************************************************
	these functions only fire on some pages
	*/

	// add input setter to specified inputs
	$('.inputsetter').inputSetter();

	// helper class for left hand nav display
	$('#nav-sub li.on:last-child').addClass('laston');

	//activate tabbed sections
	$('.tabs').IX_tabs();

	// tooltip for the Need Some Inspiration? on the contest landing page
	$('.tooltip-target').toolTip();

	// simple accordian is for content buckets on product landing pages
	$('.simple-accordian>ul').simpleAccordian();

	// video page lightbox
	if ($('.feature-item .hero a').length || $('.feature-item .image-list a').length) {
		$('.feature-item .hero a, .feature-item .image-list a').lightweightbox({
			video: true,
			vote: true
		});
	}
	// complex accordian (as on contact page)
	$('.accordian dl').IX_faq();

	//replace tags with a class of state-name with the name of the user's state
	if (typeof (currentState) !== 'undefined' && typeof (currentState) !== null) {
		$("span.state-name").replaceWith(currentState);
	}

	// jqModal, implemented for change location links on events listing.
	if ($('#change-location').length) {
		$("#change-location")
		.addClass('jqmWindow')
		.find('fieldset').append('<button id="CancelButton" class="left jqmClose">Cancel</button>').end()
		.jqm({ modal: true, trigger: '#change-location-link', overlay: 70, toTop: 'true' });
	}


	/*****************************************************************
	these functions fire in forms
	*/

	//Form's that have password change ability extends here
	$('a.change-password, a.cancle-password').passwordChange();

	// help text, generates a special help button as well.
	$('.help-text').inlineHelp();

	// fancy up file uploaders in forms
	$.IX_fileUpload();

	// create a select in a form that operates like a tab interface, revealing and hiding different sub-options
	$j('.select-tabs').IX_selectTabs();

	// focus on an "other" field when checkbox label gets click
	$j('.choice-other').each(function() {
		var $this = $j(this),
			$radio = $this.prev('.checkbox');
		if ($radio.length) {
			$radio.click(function() {
				$this.focus();
			});
		}
	});

	//edit installer notes
	$('.installer-notes').each(function() {
		var edit = $(this).find('a.edit');
		var cancel = $(this).find('a.cancel');
		var editor = $(this).find('.edit-note');
		var content = $(this).find('.note p');

		edit.click(function(e) {
			e.preventDefault();
			content.hide(); editor.removeClass('accessibility');
		});

		cancel.click(function(e) {
			e.preventDefault();
			content.show(); editor.addClass('accessibility');
		});

	});

	// show/hide function in forms using boolean radio buttons
	// use this format:
	/* 
	<fieldset><ol><li class="toggle"><fieldset>
	... 
	<input type="radio" value="true" />
	... 
	<input type="radio" value="false" />
	... 
	</fieldset></li></ol></fieldset>
	*/
	$('fieldset li.toggle').each(function() {
		var $hidden = $('fieldset', this),
	        buttons = $('input[type=radio]', this);
		if (buttons.length > 2) {
			return false;
		}
		$hidden.hide();
		$(buttons[0]).click(function() {
			var $this = $(this);
			if ($hidden.hasClass('visible')) {
				return true;
			}
			$hidden.slideDown('fast').addClass('visible');
			return true;
		});
		$(buttons[1]).click(function() {
			var $this = $(this);
			if ($hidden.hasClass('visible')) {
				$hidden.slideUp('fast').removeClass('visible');
			}
			return true;
		});
	});

	$('.installer-steps .phone').mask('(999)-999-9999');
	$('.installer-steps .zip').mask('99999');

	/*****************************************************************
	specials, one-offs etc.
	*/

	// primary landing rotator
	try {
		if (rotatorcontent !== undefined) {
			$('.page-landing.with-rotator #lead .inner-wrap').IX_rotator(rotatorcontent);
		}
	}
	catch (e) {
		var s = e.message;
	}

	// LA locator map widget
	$('.locations .content').locatorMap({track: true});

	$('.ssh-campaign .locator').locatorMap({ addmap: true, tooltip: true, track: true });

	// fixes #secondary to prevent offscreen scroll.
	if ($('body').is('.ssh-campaign') && $('body').not('.facebook')) {
		fixSidebar();
	}

	// LA short contact form lightbox
	$('.panel .button').quickBox();

	// add slide down behavior to specific sections in calculator
	$('#system-information, #financing-information').formBlind('h2');

	// tree-style sitemap list
	$("ul.sitemap").enableTree();

	// gallery pages
	$('#viewer').galleryViewer('/Layouts/Data/ImageGalleryDriver.ashx?id=');

	//simple gallery lightbox
	if ($('.simple-gallery ul').length) {
		$('.simple-gallery ul a').colorbox({
			current: "Image {current} of {total}",
			speed: 400
		});
	}

	$('.simple-gallery a').eq(0).click(function(e) {
		e.preventDefault();
		$('.simple-gallery ul a[href="' + $(this).attr('href') + '"]').trigger('click');
	});

	$('.simple-gallery .thumbnails a').mouseover(function() {
		var $previewurl = ($('img', this).attr('src').replace(/\?(.*)/g, '')) + ('?thn=0&amp;w=400');
		var $linkurl = $(this).attr('href');
		$('.simple-gallery img').eq(0).attr('src', $previewurl).parent('a').attr('href', $linkurl);
	});

	// Embed flash objects 
	// Uses tags of the form <a class="flash [height] [width]" href="[path to swf]" /> to embed the indicated swf.
	$("a.flash").each(function(i) {
		var $this = $(this);
		if (this.id === "") {
			this.id = "inline-flash" + (flashcount++);
		}
		var inlineParams = $this.attr("class").split(" "),
			height = inlineParams[1],
			width = inlineParams[2],
			flashvars = {},
			params = {},
			attributes = {};
		params.wMode = 'transparent';
		swfobject.embedSWF($this.attr("href"), this.id, width, height, "8", false, flashvars, params, attributes);
	});

	// Embed videoes 
	// Uses tags of the form <a class="video [height] [width]" href="[path to video file]" /> to embed the indicated swf.
	$("a.video").each(function(i) {
		var $this = $(this);
		if (this.id === "") {
			this.id = "inline-video" + (videocount++);
		}
		var inlineParams = $this.attr("class").split(" "),
		    height = inlineParams[1],
		    width = inlineParams[2],
		    flashvars = {},
		params = {},
		attributes = {};
		params.wMode = 'transparent';
		flashvars.file = "/" + $this.attr("href");
		swfobject.embedSWF("/_resources/flash/player-licensed.swf", this.id, width, height, "8", false, flashvars, params, attributes);
	});

	//Phone number toggle (same as above, or new)
	$('.installers input[name="same-old-phone"]').change(function() {
		if ($('.new-phone').is(':checked')) {
			$('li.phone:gt(2) input').removeAttr('disabled');
		} else {
			$('li.phone:gt(2) input').attr('disabled', 'disabled');
		}
	});

	//Callout and Mini Callout Inputsetter
	$('.callout .zip-code,.small-callout .zip-code').inputSetter();

	$('.section.media a.video').lightweightbox({
		video: true,
		setScroll: true
	});
	$('input.zipcode').focus(function() {
		if ($(this).val().length === 0) {
			$('input.zipcode').mask("99999");
		}
	}).blur(function() {
		setTimeout(function() {
			if ($('input.zipcode').val().length === 0) {
				$('input.zipcode').inputSetter();
			}
		}, 1);
	});

	//Deciaml Masking
	$('.decimal').dmask("#,###.00", "number");


	//Clear checkboxes
	$('a.clear-checkboxes').click(function(e) {
		if ($(this).text() == 'Select All') {
			$(this).text('Deselect All');
			$('.installer-steps #tab3 input[type="checkbox"]').attr('checked', 'checked');
		} else {
			$(this).text('Select All');
			$('.installer-steps #tab3 input[type="checkbox"]').attr('checked', false);
		}
		e.preventDefault();
	});

	//Manage installer date and sales edit toggle
	$('.edit-install-total,.edit-sales-date').live('click', function(e) {
		//varrrrrrs
		var $trigger = $(this),
		$input = $(this).prev('span').find('input'),
		$parent = $input.parent('span');

		//condition
		if ($(this).prev('span').find('input').is('.accessibility')) {
			$trigger.text('done');
			$input.val($parent.text()).removeClass('accessibility');

			$parent.text('').html($input);
			$trigger.trigger('mouseover');
			$trigger.trigger('mouseout');
		} else {
			$trigger.text('edit');
			$input.addClass('accessibility');
			$parent.text($input.val()).append($input);
		}
		e.preventDefault();
	});

	//Open and close inputs upon password change request
	$('input.password-change').click(function(e) {
		var $targets = $('ol.password-change input');
		if ($(this).is(':checked')) {
			$targets.removeAttr('disabled').removeClass('disabled');
		} else {
			$targets.attr('disabled', 'disabled').addClass('disabled');
		}
	});


	//Profile install details
	$('.edit-sales-date,.edit-install-total').click(function(e) {
		$(this).parent();
		e.preventDefault();
	});


	//Installer Registartion
	//Custom share math and prevent non-numerical values
	$('.installer-steps .customer-share input[type="text"]').blur(function() {
		var totals = 0;
		$('.customer-share input[type="text"]').each(function() {
			if ($(this).val().length) {
				totals = (parseInt(totals)) + (parseInt($(this).val()));
			}
		});
		$('.customer-share .total').text('= Total: ' + totals + '%');
	}).keydown(function(event) {
		// Allow only backspace and delete
		if (event.keyCode == 46 || event.keyCode == 8) {
			// let it happen, don't do anything
		}
		else {
			// Ensure that it is a number and stop the keypress
			if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
				event.preventDefault();
			}
		}
	});

	//Store Customer Param Link Appending
	if ($('.store-url-params').length) {
		$('a.store-url').each(function() {

			var params = $('.store-url-params').val();
			$(this).attr('href', params);
		});
	}
});    // document ready
 

/*****************************************************************
jQuery Plugins
*/
jQuery.fn.dmask = function(dmask, datatype) {
	var dmask = new Mask(dmask, datatype);
	this.each( function () {
		dmask.attach(this);
	});
};

// inputsetter
jQuery.fn.inputSetter = function(lower) {	
	return this.each(function() {
		var $input = jQuery(this);
		var $label = jQuery("label[for='"+$input.attr("id")+"']");
		var labeltext = lower && lower==1 ? $label.text().toLowerCase() : $label.text();
		$label.hide();	
		$input.val(labeltext).addClass('settered');		
		$input.focus(function() { if (this.value == labeltext) { this.value = ""; }	})
			  .blur(function() { if (!this.value.length) { this.value = labeltext; } });		
	});
};

// update language selector text
jQuery.fn.selectedLanguage = function () {
	var $links = jQuery('a', this),
		$label = jQuery('span', this),
		bodyClass = document.getElementsByTagName('body')[0].className;
	$links.each(function () {
		var $t = jQuery(this),
			langName = $t.text(),
			str = '',
			href = $t.attr('href').match(/sc_lang=[a-zA-Z]*/);
		if (href) {
			href = href[0];
			if (bodyClass.match(new RegExp('\\s' + href.substr(-2) + '\\s'))) { 
				$label.text(langName);
				return true;
			}
		}
	});
};

// pull discrete content off page and set up as a lightbox
// assumes css contains .quickBox { position:absolute; top:50%; left:50%; }
jQuery.fn.quickBox = function () {
	
	if (!jQuery('#lwb-overlay').length && this.length) { 
		var $overlay = jQuery('<div id="lwb-overlay"></div>').css('display', 'none'),
			$show = jQuery('input#show');
		$overlay.height(jQuery(document).height()).width(jQuery(window).width());
		jQuery('form').append($overlay);
	}

	this.each(function () {
		var $this = jQuery(this),
			$target = jQuery($this.attr('href')),
			h = $target.height(),
			w = $target.width(),
			$close = jQuery('<div class="lwb-close-control close"></div>');
		// if the targeted content is not yet processed, do it now; add a class and negative margining to center it
		if (!$target.is('.quickBox')) { 
			$target.addClass('quickBox').append($close); 
			$target.css({'margin-left': -1 * (w / 2), 'margin-top': -1 * (h / 2), 'display': 'none'});
			$target.appendTo('form');
			
			$overlay.bind('click', function () {
				$target.hide();
				$overlay.hide();
			});
			
			$target.find('.close').click(function(){
				$target.hide();
				$overlay.hide();
			});
			
			if($target.length > 0){
				jQuery(document).keyup(function(e){
					if(e.keyCode == 27){
						$target.hide();
						$overlay.hide();
					}
				});
			}
		}

		$this.bind('click', function (e) {
			$overlay.show();
			$target.show();
			e.preventDefault();
		});

	});
	
	if ($show && $show.length) {
		$overlay.show();
		$show.parents('.quickBox').show();
	}
	
	return true;
	
};

// locator widget
jQuery.fn.locatorMap = function (options) { 
	this.each( function () {
		var $this = jQuery(this),
			$tabs = jQuery('.areas a', this),
			$widget = jQuery('<div class="locator-widget"></div>'),
			$on = jQuery('<div class="locator-map-current"></div>'),
			$hover = jQuery('<div class="locator-map-hover"></div>'),
			$footnotes = jQuery('.footnotes', this),
			panels = [],
			firstclick = true, // only used if settings.scroll is an integer
			
			settings = {
				addmap: false,
				scroll: false,
				tooltip: false,
				track: false
			};
			
			
		jQuery.extend(settings, options);
		
		$tabs.each(function () {
			var $o = jQuery(this),
				panel = $o.attr('href'),
				countryClass = panel.substr(1);
				
			if (/^on-/.test(countryClass)) { countryClass = countryClass.substr(3); }
			if (/^off-/.test(countryClass)) { countryClass = countryClass.substr(4); }
				
			if (panel.indexOf("#") !== 0) {
				return true;
			}
			panels.push(panel);
			
			if (settings.tooltip) {
				$o.wrapInner('<span class="tooltip"><span class="tip"></span><span class="pointer" /></span>');
			}
			if ($footnotes.length) {
				$footnotes.clone().appendTo(panel + ' .inner');
			}
			
			$o.hover(
				function () { 
					$hover.addClass(countryClass);
				},
				function () { 
					$hover.removeClass(countryClass);
				}
			);
			$o.click(function (e) {
				var $this = jQuery(this);
				e.preventDefault();
				
				$tabs.removeClass('on');
				jQuery('.locator-map-hover a', this).removeClass('on');
				
				$on[0].className = 'locator-map-current ' + countryClass;
				
				jQuery(panels.join(",")).css({ 'display': 'none' });
				jQuery(panel).css('display', 'block');
				
				$tabs.filter(countryClass).addClass('on');
				jQuery('.locator-map-hover ' + countryClass, this).addClass('on');
				$this.blur();
				
				if(settings.track && _gaq != undefined) {
					var local = $this.text().split(',');
					_gaq.push(['_trackEvent', 'Map Click', local[0], local[2]]);
				}
			});
			
			$o.addClass(countryClass).clone(true).appendTo($hover);
		});
		
		$this.wrap($widget).after($hover).after($on);
		if(settings.addmap) {
			$this.before('<div class="locator-map"></div>');
		}
		if($footnotes.length) {
			$footnotes.remove();
		}
	});
	
};

// expand/collapse ul tree. nice for sitemappy situations.
jQuery.fn.enableTree = function () {

    var obj = jQuery(this);

	// hide children and set up css
	obj.addClass("expander").find("li li ul").hide();

	// insert the button to open/close and attach click event
	jQuery("li li", obj).each(function () {
		if (jQuery("li", this).length > 0) {
			jQuery(this).prepend('<a class="btn" href="#">+</a>');
			jQuery("a.btn", this).click(function () {
				var textinsert = $j(this).text() === "+" ? "-" : "+";
				$j(this).text(textinsert).toggleClass("open").parent("li").find("ul:first").slideToggle("fast");
				return false;
			});
		}
	});
	
	return this;
};

// make file inputs pretty

//Edited on Sep 7, 2011 by Devin O. - uniqueSuffix was equal to 0, and lived outside of the plugin's return, thus was never unique. 
//Also $fileInput.change()'s function now travers from it's self (jQuery(this)), to the next '.fake-field' to find fake input.
jQuery.IX_fileUpload = function () {
	return jQuery('input[type=file]').each(function () {
		var uniqueSuffix = parseInt(Math.random()*50);
		var $fileInput = jQuery(this),
		currentID = 'IX_fileUpload' + uniqueSuffix,
		$wrapper = jQuery('#' + currentID);

		$fileInput.addClass('real-field').wrap('<div id="' + currentID + '" class="IX_fileUpload"></div>');
		$fileInput.after('<div class="fake-field"><input type="text" /><a class="button">Browse</a></div>');
		
		$wrapper.find('.fake-field input').focus(function (e) { 
			jQuery(this).blur();
		});
		$fileInput.change(function () {
			jQuery(this).next('.fake-field').find('input').val(this.value).blur();
		});
	});
};

// generic tab builder
jQuery.fn.IX_tabs = function (tab) {
	return this.each(function () {
		var $container = jQuery(this),
			$tabs = jQuery("a", this),
			sethash = jQuery(this).is('.hashed') ? true : false,
			actionupdate = jQuery(this).is('.action-update') ? true : false;
	 		panes = [],
			bgPosAdd = 0;

		// extending IX_tabs to set explicit background positions on lis to accomodate rounded corners
		$container.addClass('IX_tabs');
		jQuery("li", this).each(function () {
			var $this = jQuery(this),
				bgPos = parseInt($this.css('backgroundPosition') ? $this.css('backgroundPosition') : $this.css('backgroundPositionX')); // IE through 8 returns 'undefined' on 'backgroundPosition'
			//$this.css('backgroundPosition', bgPosAdd + bgPos + 'px 0');
			bgPosAdd -= $this.width();
			//$this.filter(':last-child').css('width', $this.width() - parseInt($this.css('padding-left')) - parseInt($this.css('padding-right')) + $this.parent('ul').width() + bgPosAdd + 'px');
		});

		$tabs.each(function () {
			var $this = jQuery(this),
 			// using the href to make the collection of panes	
				pane = $this.attr('href');
			
			if (pane.indexOf("#") !== 0) {
				return true;
			}
			panes.push(pane);

			$this.bind("click", function (e) {
				
				// kill the page jump
				e.preventDefault();
				
				//build the jq selector. cheap.
				jQuery(panes.join(",")).css({ 'position': 'absolute', 'left': '-9999em' });

				//do some class switching
				jQuery('ul.IX_tabs li').each(function () {
					jQuery(this).addClass('non-active');
					if ($this.parents('ul.IX_tabs').width() < 700) {
						if ($this.parent("li").is(':last-child')) {
							$this.parents("ul.IX_tabs").css({backgroundPosition: '0 0'});
						} else {
							$this.parents("ul.IX_tabs").css({backgroundPosition: '-2668px 0'});
						}						
					} else {
						if ($this.parents('.tabbed').is('.distributors')) {
							if ($this.parent("li").is(':last-child')) {
								$this.parents("ul.IX_tabs").css({backgroundPosition: '0 0'});
								$this.css({backgroundPosition: '-1930px 0;'});
							} else {
								$this.parents("ul.IX_tabs").css({backgroundPosition: '-1908px 1px'});
							}
						}
						else if ($this.parent("li").is(':last-child')) {
							$this.parents("ul.IX_tabs").css({backgroundPosition: '66px 0'});
						}  else {
							$this.parents("ul.IX_tabs").css({backgroundPosition: '-3302px 0'});
						}						
					}

				});
				$container.find('.active').removeClass('active');
				$this.parent("li").removeClass('non-active').addClass("active").removeAttr('style');

				jQuery(pane).css('position', 'static');
				
				if(sethash) { 
					window.location.hash = 'tab-' + pane.substr(1);
					if(actionupdate){
						var currentaction = jQuery('form#aspnetForm').attr('action').replace(/#(.*?)$/g,'');
						jQuery('form#aspnetForm').attr('action',currentaction+'#tab-'+pane.substr(1))
					}
				}// add an obfuscated hash (to prevent page jumping)

				// for analytics - call the tracking script when a tab is clicked + report id of clicked pane
				Track(EmbedInUrl(window.location.pathname, pane));
				
			
				//custom setup page event tracking on installer's profile tabs
				if(jQuery('.installer-steps.tabbed').length){
					var urlhash = window.location.hash.substr(5),
					tabmock = '';
					if(urlhash == 'tab0'){ tabmock = 'primary-locaiton-info/';	}
					if(urlhash == 'tab1'){ tabmock = 'additional-location/'; }
					if(urlhash == 'tab2'){ tabmock = 'contact-info/'; }
					if(urlhash == 'tab3'){ tabmock = 'service-area/'; }
					if(urlhash == 'tab4'){ tabmock = 'password/';	}

					var fullurl = window.location.href.replace(/.aspx+(.*$)/,'/'),
					customurl = fullurl+tabmock;
					_gaq.push(['_trackPageview', customurl]);		
				}//end custom page event tracking				
				
				return false;
			});
		});

		// set which tab to show

		// urltab = the hash in the url
		// show = if urltab isn't empty or a default link is checked, decide which of those two is true: if urltab, set it, otherwise set to a.default. If neither, set to tab or  0
		// this means the url hash is more important than the default class set in the html
		// 

		var urltab = window.location.hash.substr(5),
			show = urltab !== "" || jQuery('a.default', $container).length ? urltab !== "" ? $tabs.index(jQuery('a[href=' + '#' + urltab + ']')) : $tabs.index(jQuery('a.default')) : tab || 0;

		// this line is pretty gross, but cheap
		// make sure the tab we think we can show is actually there. if so, click it. else click the first tab
		$tabs.eq(show).length ? $tabs.eq(show).click() : $tabs.eq(0).click();
	});
};


// help text in forms
jQuery.fn.inlineHelp = function () {
	var $w = jQuery(window); // wrapping the window once here for edge test later.
	this.each(function () {
		var $this = jQuery(this),
			$helpButton = jQuery(($this.hasClass('plain')) ? $this.find('.help-label').get(0) : '<span class="help-button"></span>');
		//class tooltip, position offscreen, insert the button.
		$this.addClass('tooltip').css({ 'left': '-9999em', 'top': '0' }); // position:absolute and z-index set in CSS
		if ($helpButton.hasClass('help-label')) { 
			$this.prev('input').prev('label').css('float', 'left').after($helpButton);
		}
		else {
			$this.before($helpButton);
		}

		$helpButton.hover(function (e) {
				// make sure the tooltip doesn't extend off the bottom of the screen
				var collisionTest = (e.pageY + $this.outerHeight()) - ($w.height() + $w.scrollTop() - 10),
					top = e.pageY;
				if (collisionTest >= 0) { 
					top -= (collisionTest);
				}

				$this.css({ 'top': top + 'px', 'left': e.pageX + 26 + 'px' });
			},
			function () {
				$this.css({ 'top': '0', 'left': '-9999em' });
			}
		);
	});
};

jQuery.fn.toolTip = function () {
	var $w = jQuery(window); // wrapping the window once here for edge test later.
	this.each(function () {
		var $target = jQuery(this),
			$tooltip = jQuery('#' + $target.attr('id') + '-tooltip');
		$tooltip.appendTo(jQuery("body"));
		//class tooltip, position offscreen
		$tooltip.addClass('tooltip').css({ 'left': '-9999em', 'top': '0' }); // position:absolute and z-index set in CSS

		$target.hover(
			function (e) {
				// make sure the tooltip doesn't extend off the bottom of the screen
				var collisionTest = (e.pageY + $tooltip.outerHeight()) - ($w.height() + $w.scrollTop() - 10),
					top = e.pageY;
				if (collisionTest >= 0) { 
					top -= (collisionTest);
				}
				$tooltip.css({ 'top': top + 'px', 'left': e.pageX + 26 + 'px' });
			},
			function () {
				$tooltip.css({ 'top': '0', 'left': '-9999em' });
			});
	});
};

// simple accordian : very simple "blind" effect for product landing page content buckets. expects a ul.
jQuery.fn.simpleAccordian = function () {
	this.children('li').each(function () {
		var $this = jQuery(this),
			$blind = jQuery('<div class="sa_blind"></div>'),
			$toggle = jQuery('<span class="sa_toggle">Read More</span>');
		$this.append($blind).append($toggle);
		$blind.hide();
		$this.find('p').each(function () { // performing move individually for IE interoperability
			var $p = jQuery(this);
			if ($p.prev().get(0).tagName === "P") { 
				$p.remove().appendTo($blind);
			}
		});

		$toggle.click(function () {
			$blind.slideToggle('fast');
		});
	});
};

jQuery.fn.formBlind = function (title) {
	this.each(function () {
		var $this = jQuery(this),
			$blind = $this.find('.form_blind'),
			$heading = $blind.find(title);

		$this.addClass('form_blind_section').wrapInner('<div class="form_blind"></div>');
		$heading.remove().insertBefore($blind);
		$blind.hide();
		$heading.click(function () {
			jQuery(this).toggleClass('open');
			$blind.slideToggle();
		});
	});

};

jQuery.fn.passwordChange = function(){
	$obj = jQuery(this);
	$obj.click(function(){
		if(jQuery(this).hasClass('change-password')){
			jQuery(this).parents('.current-password').hide().next('.new-password').show();	
		}else{
			jQuery(this).parents('.new-password').hide().prev('.current-password').show();
		}
		return false;		
	});

};

// gallery viewer
jQuery.fn.galleryViewer = function (callbackURL, nav) {
	nav = (nav) ? nav : '.image-nav';

	this.after('<div id="browser"><a href="#" class="prev">Prev</a><a href="#" class="next">Next</a></div>');

	var $viewer = this,
		$next = jQuery('#browser .next'),
		$prev = jQuery('#browser .prev'),
		$thumbs = jQuery(nav + ' li');

	$viewer.cycle = function (uri) {
		$viewer.fadeOut('fast', function () { 
			$viewer.load(uri, function () { 
				$viewer.fadeIn('fast'); 
			});
		});
	};

	$thumbs.each(function () {
		var $link = jQuery(this).find('a'),
			linkurl = $link.attr('href');
		$link.data('hash', linkurl.substr(linkurl.indexOf('#') + 1));
		$link.click(function () {
			var $this = jQuery(this),
				hash = $this.data('hash');
			$viewer.cycle(callbackURL + hash);
			if (window.location.hash !== hash) { 
				window.location.hash = hash;
			}
			$thumbs.filter('.on').removeClass('on');
			$this.parent('li').addClass('on');
			return false;
		});
	});
	
	$next.click(function () {
		if ($thumbs.filter(':last').hasClass('on')) {
			$thumbs.filter(':first').find('a').click();
		}
		else {
			$thumbs.filter('.on').next().find('a').click();
		}
		return false;
	});
	$prev.click(function () {
		if ($thumbs.filter(':first').hasClass('on')) {
			$thumbs.filter(':last').find('a').click();
		}
		else {
			$thumbs.filter('.on').prev().find('a').click();
		}
		return false;
	});

	if (window.location.hash !== '') {
		var hash = window.location.hash.substr(1);
		$viewer.cycle(callbackURL + hash);
		$thumbs.filter(function () { 
			return jQuery(this).find('a').data('hash') === hash; 
		}).addClass('on');
	} else {
		$thumbs.filter(':first').find('a').click();
	}
};


// IX_rotator plugin
// wrap it up with jQuery passed in as $ for name collision safety
(function ($) {

	// plugin definition
	$.fn.IX_rotator = function (content, options) {

		// if the content didn't get created or isn't an object, bail now before errors get tossed
		if (content === undefined || typeof content !== "object") {
			return this;
		}

		// build main options before element iteration
		// extends exposed defaults property
		// options might include transition effects or speeds or ???
		var opts = $.extend({}, $.fn.IX_rotator.defaults, options);

		// vaaarrrrrs	
		var $this = $(this),			// the rotator container
			$ul = $('<ul />').addClass(opts.classname || "rotator"), // the new rotator container
			current = opts.show || 1, // current displayed rotatee
			total = content.length, // total number of rotatee
			displayed = []; // array to store index of previously displayed slides

		// loop over content object and build out each rotatee	
		for (var j = 0; j < total; j++) {
			var rotatee = $.fn.IX_rotator.tmpl.replace(/<%=image%>/g, content[j].image.replace(/\s/g, "%20"))
											.replace(/<%=title%>/g, content[j].title)
											.replace(/<%=content%>/g, content[j].content),
				links = "";

			// for items that could have more than one, loop to create
			// this example uses multiple links placed into the btn template
			$.each(content[j].links, function (i) {
				if (content[j].links[i].url !== null) {
					if (links !== "") {
						links += "<br />";
					}
					content[j].links[i].url += (content[j].links[i].url.parseQuery()) ? '&promoID=' + encodeURIComponent(content[j].title) : '?promoID=' + encodeURIComponent(content[j].title);
					
					links += $.fn.IX_rotator.btn.replace(/<%=url%>/g, content[j].links[i].url)
												.replace(/<%=text%>/g, content[j].links[i].text)
												.replace(/<%=target%>/g, content[j].links[i].targetBlank);
				}
			});
			var $links = $(links).data('identifier', content[j].title).click(function (e) { _gaq.push(['_trackEvent', 'Promotion', 'clicks', $(this).data('identifier')]); });
			$(rotatee).find('.nav-rotator').append($links).end().appendTo($ul);
		}
		// make the nav and counter
		var pagelist = "";
		for (var p = 1; p <= total; p++) { 
			pagelist += '<li class="pagemarker">Page ' + p + '</li>';
		}
		$ul.append($.fn.IX_rotator.nav.replace(/<%=pagelist%>/g, pagelist));

		// hide all but the default rotatee
		$('li.rotator-item:not(:eq(' + (current - 1) + '))', $ul).hide();

		// turn on the current page marker in the page list
		$('li.pagemarker', $ul).eq(current - 1).addClass('on');


		// dump in the new html structure
		$this.html($ul);
		
		// report display of current slide to analytics
		var reportImpression = function(index) { 
			if(content[index] === undefined) { console.log(index); console.dir(content); return false; }
			if(!displayed.match(index)) {
				trackEvent(['_trackEvent', 'Promotion', 'Impressions', content[index].title]);
				displayed.push(index);
			}
		};
		reportImpression(current - 1);		

		// the cycler
		var cycle = function (e) {
			// set current depending on what nav item was pressed			
			current = $(e.target).parents('.arrow-previous').length ? current += -1 : current += 1;
			reportImpression(current - 1);		
			// loop to beginning or end if previous setting resulted in non-existent rotatee
			current = current < 0 ? total - 1 : current === total ? 0 : current;
			$('li.rotator-item:visible', $this).fadeOut("slow", function () {
				$('li.rotator-item', $this).eq(current - 1).fadeIn("slow"); 
			});
			$('.pages li.on', $this).removeClass('on');
			$('.pages li.pagemarker').eq(current - 1).addClass('on');
		};
		

		// start the auto rotating
		if (opts.auto) {
			var speed = $.fn.IX_rotator.autospeed || 7000;
			$.fn.IX_rotator.rotate = setInterval(function () { 
				$this.trigger('rotate');
			}, speed);
		}

		// image preloading
		for (var i = 0, length = content.length; i < length; i++) {
			$('<img>').attr("src", content[i].image.replace(/\s/g, "%20"));
		}

		// return and iterate
		return this.each(function () {
			$('a.btn-arrow', this).live('click', function (e) {
				clearInterval($.fn.IX_rotator.rotate);
				cycle(e);
				e.preventDefault();
			});
			$(this).bind('rotate', function (e) {
				cycle(e);
				e.preventDefault();
			});
		});


	}; // end plugin definition

	// exposed functions

	// default options
	$.fn.IX_rotator.defaults = {
		transition: "fade",
		speed: 100,
		auto: true,
		autospeed: 7000,
		classname: ""
	};

	// base html templates
	// better to base of html?
	$.fn.IX_rotator.tmpl = '<li class="rotator-item" style="background-image:url(<%=image%>);"><div class="wrapper"><h1><%=title%></h1><div class="content"><p><%=content%></p></div><div class="nav-rotator"></div></div></li>';
	$.fn.IX_rotator.btn = '<a class="btn" href="<%=url%>" target="<%=target%>"><%=text%></a>';
	$.fn.IX_rotator.nav = '<div class="nav-rotate"><ul><li class="arrow-previous"><a class="btn-arrow ir" href="#">Previous</a></li><li class="pages"><ol><%=pagelist%></ol></li><li class="arrow-next"><a class="btn-arrow ir" href="#">Next</a></li></ul></div>';

})(jQuery);

// @faq
// 01.26.10 pdf
// receives a dl

jQuery.fn.IX_faq = function () {
    var auto = (this.parent('.accordian').hasClass('noauto')) ? false : true;
	this.addClass('IX_faq');
	this.each(function () {
		jQuery(this).find("dd").hide();
		jQuery(this).find("dt").prepend('<span class="state"></span> ').click(function () {
			jQuery(this).toggleClass("open").next("dd").slideToggle("fast").end();
			return false;
		});
	});
	jQuery('dt:last').addClass('last');
	if (auto) { 
		jQuery('dt:first-child', this).click();
	}
};




/**
 * @IX_selectTabs
 * build select from link list to reveal and hide different options in a form
**/
jQuery.fn.IX_selectTabs = function () {	
	return this.each(function () {
		var $selector = jQuery('<select class="IX_selectTabs"><option value="">Please select one:</option></select>'),
			$this = jQuery(this),
			panes = [];
		
		$this.children('li').each(function () {
			var $tab = jQuery('a', this);
			$selector.append('<option value="' + $tab.attr('href') + '">' + $tab.text() + '</option>');
		});
		$this.replaceWith($selector);

		$selector.children('option').each(function () {
			var $this = jQuery(this),
			// using the href to make the collection of panes			
				pane = $this.attr('value');
			if (pane.indexOf("#") !== 0) {
				return true;
			}
		 	panes.push(pane);
		});

		jQuery(panes.join(",")).hide();
		
		$selector.bind("change", function () {
			if (jQuery(panes.join(":visible,") + ':visible').length) {
				jQuery(panes.join(":visible,") + ':visible').slideUp(250, function () { 
					jQuery($selector.val()).slideDown(350); 
				}); 
			} else { 
				jQuery($selector.val()).slideDown(250); 
			}
			return false;
		});
		
	});
};

// end @IX_selectTabs

jQuery.fn.bnsp = function (options) {	
	// if array of characters, use it. else use default set.
	var c = options || ["@", "/"];	
	// set bnsp entity based on browser support
	var b = jQuery.browser.msie && jQuery.browser.version < 7 ? "<wbr>" : "&#8203;";	
	// loop and return
	return this.each(function () {		
		var $this = jQuery(this); // store $(this) for use inside another function		
		// loop through each item in character array
		jQuery.each(c, function () {
			var rx = new RegExp(this, 'g'); // create new regex object with current character
			$this.html($this.html().replace(rx, this + b)); // replace character with itself + nbsp entity
		}); // end array loop		
	});// end return
}; // end bnsp



// etc

// clean console.log
function cl() { if (window.console && window.console.firebug) { var args = [].splice.call(arguments, 0); console.log(args.join(" ")); } } //cl()
// example: cl("If you use cl() instead of console.log(), it won't break IE when you forget to take it out.");

// array value matching using regex.
Array.prototype.match = function (val, opts) { 
	opts = opts || 'igm';
	if(val != null) {
		if ((typeof val).toLowerCase() == "object") {
			for ( var i = 0; i < val.length; i++ ) {
				if (this.join('|').match(new RegExp(val[i], opts))) { return true; }
			}
		}
		if ((typeof val).toLowerCase() === "string" || (typeof val).toLowerCase() === "number") {
			if (this.join('|').match(new RegExp(val, opts))) { return true; }
		}
	}
	return false;
};


// Function takes a string a url and a string and will insert the string in the url preceeding any .aspx extensions.
function EmbedInUrl(url, str) {
	var ret = new String(url);
	if (ret.toLowerCase().search(".aspx") !== -1) {
		ret = ret.toLowerCase().replace(".aspx", str + ".aspx");
	} else {
		ret = ret + str;
	}
	return ret;
}

function fixSidebar() {
	var s = jQuery('#secondary'),
		p = jQuery('#primary'),
		w = jQuery(window),
		f = jQuery('#footer'),
		scrollinterval = 0,
		running = false,
		stop,
		setLeft = function () { s.css({left: p.offset().left + p.outerWidth(true) + 'px'}); },
		positionSidebar = function () {
			
			stop = f.offset().top - f.height() - s.height();
			scrollinterval++;
			
			if (s.offset().top - w.scrollTop() < 12) { s.css({position: 'fixed', top: '12px'}); }
			else if (286 - w.scrollTop() >= 0 && s.css('position') === 'fixed') { s.css({position: 'static'});  }
			
			if (w.scrollTop() >= stop) { s.css({position: 'absolute', top: stop + 'px'}); }
			else if (w.scrollTop() <= stop && s.css('position') === 'absolute') {
				s.css({position: 'fixed', top: '12px'});
			}
			
			if ( scrollinterval < 1200) {
				setTimeout(positionSidebar, 50);
				running = true;
			} else {
				running = false;
			}
		};
		
	w.scroll(function() { 
		scrollinterval = 0;
		if ( !running ) {
			positionSidebar();
		}
	});
		
	w.resize(function () {
		setLeft();
	});
	
	setLeft();
	
	setTimeout(positionSidebar, 50);
	
}




/*
	Masked Input plugin for jQuery
	Copyright (c) 2007-2011 Josh Bush (digitalbush.com)
	Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
	Version: 1.3
*/
(function(a){var b=(a.browser.msie?"paste":"input")+".mask",c=window.orientation!=undefined;a.mask={definitions:{9:"[0-9]",a:"[A-Za-z]","*":"[A-Za-z0-9]"},dataName:"rawMaskFn"},a.fn.extend({caret:function(a,b){if(this.length!=0){if(typeof a=="number"){b=typeof b=="number"?b:a;return this.each(function(){if(this.setSelectionRange)this.setSelectionRange(a,b);else if(this.createTextRange){var c=this.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",a),c.select()}})}if(this[0].setSelectionRange)a=this[0].selectionStart,b=this[0].selectionEnd;else if(document.selection&&document.selection.createRange){var c=document.selection.createRange();a=0-c.duplicate().moveStart("character",-1e5),b=a+c.text.length}return{begin:a,end:b}}},unmask:function(){return this.trigger("unmask")},mask:function(d,e){if(!d&&this.length>0){var f=a(this[0]);return f.data(a.mask.dataName)()}e=a.extend({placeholder:"_",completed:null},e);var g=a.mask.definitions,h=[],i=d.length,j=null,k=d.length;a.each(d.split(""),function(a,b){b=="?"?(k--,i=a):g[b]?(h.push(new RegExp(g[b])),j==null&&(j=h.length-1)):h.push(null)});return this.trigger("unmask").each(function(){function v(a){var b=f.val(),c=-1;for(var d=0,g=0;d<k;d++)if(h[d]){l[d]=e.placeholder;while(g++<b.length){var m=b.charAt(g-1);if(h[d].test(m)){l[d]=m,c=d;break}}if(g>b.length)break}else l[d]==b.charAt(g)&&d!=i&&(g++,c=d);if(!a&&c+1<i)f.val(""),t(0,k);else if(a||c+1>=i)u(),a||f.val(f.val().substring(0,c+1));return i?d:j}function u(){return f.val(l.join("")).val()}function t(a,b){for(var c=a;c<b&&c<k;c++)h[c]&&(l[c]=e.placeholder)}function s(a){var b=a.which,c=f.caret();if(a.ctrlKey||a.altKey||a.metaKey||b<32)return!0;if(b){c.end-c.begin!=0&&(t(c.begin,c.end),p(c.begin,c.end-1));var d=n(c.begin-1);if(d<k){var g=String.fromCharCode(b);if(h[d].test(g)){q(d),l[d]=g,u();var i=n(d);f.caret(i),e.completed&&i>=k&&e.completed.call(f)}}return!1}}function r(a){var b=a.which;if(b==8||b==46||c&&b==127){var d=f.caret(),e=d.begin,g=d.end;g-e==0&&(e=b!=46?o(e):g=n(e-1),g=b==46?n(g):g),t(e,g),p(e,g-1);return!1}if(b==27){f.val(m),f.caret(0,v());return!1}}function q(a){for(var b=a,c=e.placeholder;b<k;b++)if(h[b]){var d=n(b),f=l[b];l[b]=c;if(d<k&&h[d].test(f))c=f;else break}}function p(a,b){if(!(a<0)){for(var c=a,d=n(b);c<k;c++)if(h[c]){if(d<k&&h[c].test(l[d]))l[c]=l[d],l[d]=e.placeholder;else break;d=n(d)}u(),f.caret(Math.max(j,a))}}function o(a){while(--a>=0&&!h[a]);return a}function n(a){while(++a<=k&&!h[a]);return a}var f=a(this),l=a.map(d.split(""),function(a,b){if(a!="?")return g[a]?e.placeholder:a}),m=f.val();f.data(a.mask.dataName,function(){return a.map(l,function(a,b){return h[b]&&a!=e.placeholder?a:null}).join("")}),f.attr("readonly")||f.one("unmask",function(){f.unbind(".mask").removeData(a.mask.dataName)}).bind("focus.mask",function(){m=f.val();var b=v();u();var c=function(){b==d.length?f.caret(0,b):f.caret(b)};(a.browser.msie?c:function(){setTimeout(c,0)})()}).bind("blur.mask",function(){v(),f.val()!=m&&f.change()}).bind("keydown.mask",r).bind("keypress.mask",s).bind(b,function(){setTimeout(function(){f.caret(v(!0))},0)}),v()})}})})(jQuery)





/*Mask plugin for decimals*/
function $addEvent(a,b,c,d){var e=b.toLowerCase(),f=typeof d=="boolean"?d:true,g=a[e]?a[e].toString():"";g=g.substring(g.indexOf("{")+1,g.lastIndexOf("}"));g=(f?g+c:c+g)+"\n";return a[e]=!!window.Event?new Function("event",g):new Function(g)}function qEvent(a){if(window.Event){var b=a.type.substring(0,3)=="key";this.keyCode=b?parseInt(a.which,10):0;this.button=!b?parseInt(a.which,10):0;this.srcElement=a.target;this.type=a.type;this.x=a.pageX;this.y=a.pageY;this.screenX=a.screenX;this.screenY=a.screenY;if(document.layers){this.altKey=(a.modifiers&Event.ALT_MASK)>0;this.ctrlKey=(a.modifiers&Event.CONTROL_MASK)>0;this.shiftKey=(a.modifiers&Event.SHIFT_MASK)>0;this.keyCode=this.translateKeyCode(this.keyCode)}else{this.altKey=a.altKey;this.ctrlKey=a.ctrlKey;this.shiftKey=a.shiftKey}}else{a=window.event;this.keyCode=parseInt(a.keyCode,10);this.button=a.button;this.srcElement=a.srcElement;this.type=a.type;if(document.all){this.x=a.clientX+document.body.scrollLeft;this.y=a.clientY+document.body.scrollTop}else{this.x=a.clientX;this.y=a.clientY}this.screenX=a.screenX;this.screenY=a.screenY;this.altKey=a.altKey;this.ctrlKey=a.ctrlKey;this.shiftKey=a.shiftKey}if(this.button==0){this.setKeyPressed(this.keyCode);this.keyChar=String.fromCharCode(this.keyCode)}}function Mask(a,b){this.mask=a;this.type=typeof b=="string"?b:"string";this.error=[];this.errorCodes=[];this.value="";this.strippedValue="";this.allowPartial=false;this.id=MaskAPI.instances++;this.ref="MaskAPI.objects['"+this.id+"']";MaskAPI.objects[this.id]=this}function _MaskAPI(){this.version="0.4b";this.instances=0;this.objects={}}MaskAPI=new _MaskAPI;Mask.prototype.attach=function(a){$addEvent(a,"onkeydown","return "+this.ref+".isAllowKeyPress(event, this);",true);$addEvent(a,"onkeyup","return "+this.ref+".getKeyPress(event, this);",true);$addEvent(a,"onblur","this.value = "+this.ref+".format(this.value);",true)};Mask.prototype.isAllowKeyPress=function(a,b){if(this.type!="string")return true;var c=new qEvent(a);if(c.keyCode>47&&b.value.length>=this.mask.length&&!c.ctrlKey)return false;return true};Mask.prototype.getKeyPress=function(a,b,c){this.allowPartial=true;var d=new qEvent(a);if(d.keyCode>47||c==true||d.keyCode==8||d.keyCode==46){var e=b.value,f;if(d.keyCode==8||d.keyCode==46)f=true;else f=false;if(this.type=="number")this.value=this.setNumber(e,f);else if(this.type=="date")this.value=this.setDateKeyPress(e,f);else this.value=this.setGeneric(e,f);b.value=this.value}this.allowPartial=false;return true};Mask.prototype.format=function(a){if(this.type=="number")this.value=this.setNumber(a);else if(this.type=="date")this.value=this.setDate(a);else this.value=this.setGeneric(a);return this.value};Mask.prototype.throwError=function(a,b,c){this.error[this.error.length]=b;this.errorCodes[this.errorCodes.length]=a;if(typeof c=="string")return c;return true};Mask.prototype.setGeneric=function(a,b){var c=a,d=this.mask;var e="x#*",f=[],g="",h,i,j=[],k=0,l={x:"A-Za-z","#":"0-9","*":"A-Za-z0-9"};c=c.replace(new RegExp("[^"+l["*"]+"]","gi"),"");if(b==true&&c.length==this.strippedValue.length)c=c.substring(0,c.length-1);this.strippedValue=c;var m=[];for(var n=0;n<d.length;n++){i=d.charAt(n);h=e.indexOf(i)>-1;if(i=="!")i=d.charAt(n++);if(h&&!this.allowPartial||h&&this.allowPartial&&f.length<c.length)f[f.length]="["+l[i]+"]";j[j.length]={chr:i,mask:h}}var o=false;if(!this.allowPartial&&!(new RegExp(f.join(""))).test(c))return this.throwError(1,'The value "'+a+'" must be in the format '+this.mask+".",a);else if(this.allowPartial&&c.length>0||!this.allowPartial){for(n=0;n<j.length;n++){if(j[n].mask){while(c.length>0&&!(new RegExp(f[k])).test(c.charAt(k)))c=c.length==1?"":c.substring(1);if(c.length>0){g+=c.charAt(k);o=true}k++}else g+=j[n].chr;if(this.allowPartial&&k>c.length)break}}if(this.allowPartial&&!o)g="";if(this.allowPartial){if(g.length<j.length)this.nextValidChar=l[j[g.length].chr];else this.nextValidChar=null}return g};Mask.prototype.setNumber=function(a,b){var c=String(a).replace(/[^\d.-]*/gi,""),d=this.mask;c=c.replace(/\./,"d").replace(/\./g,"").replace(/d/,".");if(!/^[\$]?((\$?[\+-]?([0#]{1,3},)?[0#]*(\.[0#]*)?)|([\+-]?\([\+-]?([0#]{1,3},)?[0#]*(\.[0#]*)?\)))$/.test(d))return this.throwError(1,"An invalid mask was specified for the \nMask constructor.",a);if(b==true&&c.length==this.strippedValue.length)c=c.substring(0,c.length-1);if(this.allowPartial&&c.replace(/[^0-9]/,"").length==0)return c;this.strippedValue=c;if(c.length==0)c=NaN;var e=Number(c);if(isNaN(e))return this.throwError(2,"The value entered was not a number.",a);if(d.length==0)return c;var f=String(Math.abs(c.indexOf(".")>-1?c.split(".")[0]:c));var g=c.indexOf(".")>-1?c.split(".")[1]:"";var h=g;var i=e!=0&&Math.abs(e)*-1==e;var j={$:/^[\$]/.test(d),"(":i&&d.indexOf("(")>-1,"+":d.indexOf("+")!=-1&&!i};j["-"]=i&&(!j["("]||d.indexOf("-")!=-1);d=d.replace(/[^#0.,]*/gi,"");var k=d.indexOf(".")>-1?d.split(".")[1]:"";if(k.length==0){f=String(Math.round(Number(f)));g=""}else{var l=k.lastIndexOf("0")+1;if(g.length>k.length)g=String(Math.round(Number(g.substring(0,k.length+1))/10));else while(g.length<l)g+="0"}var m=d.indexOf(".")>-1?d.split(".")[0]:d;m=m.replace(/[^0#]+/gi,"");var n=m.indexOf("0")+1;if(n>0){n=m.length-n+1;while(f.length<n)f="0"+f}if(/[#0]+,[#0]{3}/.test(d)){var o=[],p=0,q=Number(f);while(q>999){o[p]="00"+String(q%1e3);o[p]=o[p].substring(o[p].length-3);q=Math.floor(q/1e3);p++}o[p]=String(q%1e3);f=o.reverse().join(",")}if(g.length>0&&!this.allowPartial||k.length>0&&this.allowPartial&&c.indexOf(".")>-1&&h.length>=g.length){c=f+"."+g}else if(k.length>0&&this.allowPartial&&c.indexOf(".")>-1&&h.length<g.length){c=f+"."+h}else{c=f}if(j["$"])c=this.mask.replace(/(^[\$])(.+)/gi,"$")+c;if(j["+"])c="+"+c;if(j["-"])c="-"+c;if(j["("])c="("+c+")";return c};Mask.prototype.setDate=function(a){var b=a,c=this.mask;var d,e,f,g,h,i,j;d=c.split(/[^mdy]+/);j=c.split(/[mdy]+/);e=b.split(/[^0-9]/);if(j[0].length==0)j.splice(0,1);for(var k=0;k<d.length;k++){i=d[k].charAt(0).toLowerCase();if(i=="m")f=parseInt(e[k],10)-1;else if(i=="d")g=parseInt(e[k],10);else if(i=="y")h=parseInt(e[k],10)}if(String(h).length<3){h=2e3+h;if((new Date).getFullYear()+5<h)h=h-100}var l=new Date(h,f,g);if(l.getDate()!=g)return this.throwError(1,"An invalid day was entered.",a);else if(l.getMonth()!=f)return this.throwError(2,"An invalid month was entered.",a);var m="";for(k=0;k<d.length;k++){i=d[k].charAt(0).toLowerCase();if(i=="m"){f++;if(d[k].length==2){f="0"+f;f=f.substring(f.length-2)}m+=f}else if(i=="d"){if(d[k].length==2){g="0"+g;g=g.substring(g.length-2)}m+=g}else if(i=="y"){if(d[k].length==2)m+=l.getYear();else m+=l.getFullYear()}if(k<d.length-1)m+=j[k]}return m};Mask.prototype.setDateKeyPress=function(a,b){var c=a,e=this.mask,f=c.charAt(c.length-1);var g,h,i,j,k,l="",m="",n="",o,p,q;if(b==true){while(/[^0-9]/gi.test(c.charAt(c.length-1)))c=c.substring(0,c.length-1);if(/[^0-9]/gi.test(this.strippedValue.charAt(this.strippedValue.length-1)))c=c.substring(0,c.length-1);if(c.length==0)return""}g=e.split(/[^mdy]/);s=e.split(/[mdy]+/);if(s[0].length==0)s.splice(0,1);h=c.split(/[^0-9]/);p=h.length>0?h.length-1:0;i=g[p].charAt(0);j=g[p].length;for(var r=0;r<h.length;r++){o=g[r].charAt(0).toLowerCase();if(o=="m")l=parseInt(h[r],10)-1;else if(o=="d")m=parseInt(h[r],10);else if(o=="y")n=parseInt(h[r],10)}var t="";var u=0;for(r=0;r<h.length;r++){o=g[r].charAt(0).toLowerCase();if(o=="m"){q=/[^0-9]/.test(f)&&i=="m";l++;if(h[r].length==2&&l<10||g[r].length==2&&i!="m"||l>1&&i=="m"||q&&g[r].length==2){l="0"+l;l=l.substring(l.length-2)}k=String(l).length;j=2;t+=l}else if(o=="d"){q=/[^0-9]/.test(f)&&i=="d";if(h[r].length==2&&m<10||g[r].length==2&&i!="d"||m>3&&i=="d"||q&&g[r].length==2){m="0"+m;m=m.substring(m.length-2)}k=String(m).length;j=2;t+=m}else if(o=="y"){q=/[^0-9]/.test(f)&&i=="y";if(i=="y")n=String(n);else{if(g[r].length==2)n=d.getYear();else n=d.getFullYear()}if(h[r].length==2&&n<10||g[r].length==2&&i!="y"||q&&g[r].length==2){n="0"+n;n=n.substring(n.length-2)}j=g[r].length;k=String(n).length;t+=n}if((j==k||q)&&o==i&&r<s.length||r<s.length&&o!=i)t+=s[r]}if(t.length>e.length)t=t.substring(0,e.length);this.strippedValue=t=="NaN"?"":t;return this.strippedValue};qEvent.prototype.translateKeyCode=function(a){var b={};if(!!document.layers){if(this.keyCode>96&&this.keyCode<123)return this.keyCode-32;b={96:192,126:192,33:49,64:50,35:51,36:52,37:53,94:54,38:55,42:56,40:57,41:48,92:220,124:220,125:221,93:221,91:219,123:219,39:222,34:222,47:191,63:191,46:190,62:190,44:188,60:188,45:189,95:189,43:187,61:187,59:186,58:186,"null":null}}return!!b[a]?b[a]:a};qEvent.prototype.setKP=function(a,b){this.keyPressedCode=a;this.keyNonChar=typeof b=="string";this.keyPressed=this.keyNonChar?b:String.fromCharCode(a);this.isNumeric=parseInt(this.keyPressed,10)==this.keyPressed;this.isAlpha=this.keyCode>64&&this.keyCode<91&&!this.altKey&&!this.ctrlKey;return true};qEvent.prototype.setKeyPressed=function(a){var b=this.shiftKey;if(!b&&a>64&&a<91)return this.setKP(a+32);if(a>95&&a<106)return this.setKP(a-48);switch(a){case 49:case 51:case 52:case 53:if(b)a=a-16;break;case 50:if(b)a=64;break;case 54:if(b)a=94;break;case 55:if(b)a=38;break;case 56:if(b)a=42;break;case 57:if(b)a=40;break;case 48:if(b)a=41;break;case 192:if(b)a=126;else a=96;break;case 189:if(b)a=95;else a=45;break;case 187:if(b)a=43;else a=61;break;case 220:if(b)a=124;else a=92;break;case 221:if(b)a=125;else a=93;break;case 219:if(b)a=123;else a=91;break;case 222:if(b)a=34;else a=39;break;case 186:if(b)a=58;else a=59;break;case 191:if(b)a=63;else a=47;break;case 190:if(b)a=62;else a=46;break;case 188:if(b)a=60;else a=44;break;case 106:case 57379:a=42;break;case 107:case 57380:a=43;break;case 109:case 57381:a=45;break;case 110:a=46;break;case 111:case 57378:a=47;break;case 8:return this.setKP(a,"[backspace]");case 9:return this.setKP(a,"[tab]");case 13:return this.setKP(a,"[enter]");case 16:case 57389:return this.setKP(a,"[shift]");case 17:case 57390:return this.setKP(a,"[ctrl]");case 18:case 57388:return this.setKP(a,"[alt]");case 19:case 57402:return this.setKP(a,"[break]");case 20:return this.setKP(a,"[capslock]");case 32:return this.setKP(a,"[space]");case 91:return this.setKP(a,"[windows]");case 93:return this.setKP(a,"[properties]");case 33:case 57371:return this.setKP(a*-1,"[pgup]");case 34:case 57372:return this.setKP(a*-1,"[pgdown]");case 35:case 57370:return this.setKP(a*-1,"[end]");case 36:case 57369:return this.setKP(a*-1,"[home]");case 37:case 57375:return this.setKP(a*-1,"[left]");case 38:case 57373:return this.setKP(a*-1,"[up]");case 39:case 57376:return this.setKP(a*-1,"[right]");case 40:case 57374:return this.setKP(a*-1,"[down]");case 45:case 57382:return this.setKP(a*-1,"[insert]");case 46:case 57383:return this.setKP(a*-1,"[delete]");case 144:case 57400:return this.setKP(a*-1,"[numlock]")}if(a>111&&a<124)return this.setKP(a*-1,"[f"+(a-111)+"]");return this.setKP(a)}


// IE6 fixes
// make sure IE has the abbr and acronym tag
if (document.all) {
	document.createElement("abbr");
	document.createElement("acronym");
}
// prevent IE6 flicker
try { document.execCommand('BackgroundImageCache', false, true); } catch (e) { }


// convenience method for GA. expects an Array of _gaq arrays. if Array is not sent as argument, function attempts to substitute a global called contentEvents.  if this also fails, function returns false.
function trackEvent(eventArray) {

	 var events = (eventArray != null) ? eventArray : ((typeof contentEvents).toLowerCase() === 'object') ? contentEvents : false,

		  success = false;

	 if (!events) { // if no events reported, check for promo_id in query string

		  var query = window.location.href.parseQuery();

		  if (query && query['promo_id'] && window.location.hash != '#') {

				events = ['_trackEvent', 'Promotion', 'clicks', query['promo_id']];

				window.location.hash = '';
		  }

	 }

	 if (events && (typeof events).toLowerCase() === "object") {

		  if ((typeof events[0]).toLowerCase() === "object") {

				jQuery.each(events, function(i) {

					 try {

						  _gaq.push(events[i]);

						  success = true;

					 } catch (error) {

						  document.write('<!-- GA tracking failed: ' + error + ' -->');

					 }

				});

		  }

		  else {

				try {

					 _gaq.push(events);

					 success = true;

				} catch (error) {

					 document.write('<!-- GA tracking failed: ' + error + ' -->');

				}

		  }

	 }

	 return success;

}
