/* *************************************************************************
Title : Behavior Javascript File
Author : Designkitchen, Inc.
Description : Sets up js for entire site, includes global onload events
Created : 12.10.2007 
Modified : 
************************************************************************* 

JS TOC
=Global VARS
=CENTER BACKGROUND IMAGE
=CENTER CONTAINER ELEMENT
=CHECK LOGIN
=INITIALIZE Control.Window
....
=Accordion.js v0.3
=GOOGLE AUTOFILL COLOR CORRECT
=BACKGROUND IMAGE FUNCTIONS
=INITIALIZE TOOL TIPS
************************************************************************* */




/* *************************************************************************
=CENTER BACKGROUND IMAGE
Adjusts for rounding errors on centered background
images in Internet Explorer and Safari
************************************************************************* */

function centerFeature() {
	target = $$('div.feature')[0];
	targetWidth = 1200;
	if (target && target.length != 0) {
		if ((document.viewport.getWidth()<targetWidth) && (document.viewport.getWidth()%2===1)) {
			if (Prototype.Browser.IE) target.setStyle( { marginLeft: '1px' } )
			if (Prototype.Browser.WebKit) target.setStyle( { marginRight: '1px' } )
		}
		else target.setStyle( { marginRight: 0, marginLeft: 0 } );
	}
}
if (Prototype.Browser.IE || Prototype.Browser.WebKit) {
	document.observe('dom:loaded', centerFeature);
	Event.observe(window, 'resize', centerFeature);
}

/* *************************************************************************
=CENTER CONTAINER ELEMENT
Adjusts for rounding errors on centered elements
in Internet Explorer and Firefox 3
************************************************************************* */

function centerContainer() {
	target = $$('div.nav','div.container');
	targetWidth = 1200;
	if (target && target.length != 0) {
		if (Prototype.Browser.IE) {
			if (($('feature-flash-container').getStyle('display') != 'block') && (document.viewport.getWidth()>targetWidth) && (document.viewport.getWidth()%2===1)) target.invoke('setStyle', { left: '1px' } );
			else if (($('feature-flash-container').getStyle('display') != 'block') && (document.viewport.getWidth()<targetWidth) && (document.viewport.getWidth()%2===1)) target[0].setStyle( { left: '1px' } );
			else target.invoke('setStyle', { left: 0 } );
		}
		else if (Prototype.Browser.Gecko) {
			if (document.viewport.getWidth()%2===1) target.invoke('setStyle', { left: '-1px' } );
			else target.invoke('setStyle', { left: 0 } );
		}
	}
}
if (Prototype.Browser.IE || (Prototype.Browser.Gecko && navigator.userAgent.indexOf('Firefox/3') > -1)) {
	document.observe('dom:loaded', centerContainer);
	Event.observe(window, 'resize', centerContainer);
}

/* *************************************************************************
=CHECK LOGIN
AJAX call checks whether the user is logged in
hides/shows the correct login display
shows the total number of project lists
************************************************************************* */

//AJAX Reponse
var handleLoginResponse = function(t) {
	var loginVal = t.responseText;	
	checkLogin(loginVal);
}

//AJAX Request
Event.observe(window, 'load', function() { 
    var url;
    url = "/Handlers/IsUserLoggedIn.ashx?r=" + Math.random();
    new Ajax.Request(url,{
		method: 'get',
        onSuccess: handleLoginResponse
    });
});

//Sets display for login panel and project list number
function checkLogin(loginVal){
    
   /* var testdiv = document.createElement('div');
    $$(".account")[0].appendChild(testdiv);
    testdiv.innerHTML = loginVal;*/
    if(loginVal == "n"){
        $("loginInactive").style.display  = "block";
        $("loginActive").style.display = "none";         
    }else{
        $("loginInactive").style.display  = "none";
        $("loginActive").style.display  = "block";
        $$(".projectNum")[0].innerHTML = "Project Lists ("+loginVal+")";
    };
}

// Used to validate login forms
function validate_login(login_form){
    var valid = true;
    var email_el = login_form.down('#txtEmail');
    var pass_el = login_form.down('#txtPass');
    var email_error = login_form.down('#txtEmailError');
    var pass_error = login_form.down('#txtPassError');
    if(email_el.value == ""){
        valid = false;
        //email_error.innerHTML = '*';
        email_error.show();
    }else{
        //email_error.innerHTML = '';
        email_error.hide();
    };
    if(pass_el.value == ""){
        valid = false;
        //pass_error.innerHTML = '*';
        pass_error.show();
    }else{
        //pass_error.innerHTML = '';
        pass_error.hide();
    };
    return valid;
};

/* *************************************************************************
=INITIALIZE Control.Window
************************************************************************* */
var add_to_project_list;
var duplicate_list;
var delete_list;
var login_panel;

function addToProjectList(productID) {
	$('add_to_project_list').down('iframe').src = '/AddToWishlist.aspx?urlReferrer=' + escape(location.href) + '&productId=' + productID + '&r=' + Math.random();
	add_to_project_list.open();
	return false;
}
function resetProjectListFrame() {
    $('add_to_project_list').down('iframe').src = "";
}

Event.observe(window, 'load', function() {
	if ($('add_to_project_list')) {
		$$('form')[0].insert( { bottom: $('add_to_project_list').remove() } );
		add_to_project_list = new Control.Window($(document.body).down('[href=#add_to_project_list]'),{
			className: 'popup',
			width: 331,
			height: 427
		});
	}
});
Event.observe(window, 'load', function() {
	if ($(document.body).down('[href=#duplicate_list]')) {
		$$('form')[0].insert( { bottom: $('duplicate_list').remove() } );
		duplicate_list = new Control.Window($(document.body).down('[href=#duplicate_list]'),{
			className: 'popup',
			beforeOpen: function() {
				delete_list.close();
			},
			afterOpen: function() {
				_isDuplicateOpen = true;
			},
		    afterClose: function() {
		        _isDuplicateOpen  = false;
		    }
		});
	}
});
Event.observe(window, 'load', function() {
	if ($(document.body).down('[href=#delete_list]')) {
		$$('form')[0].insert( { bottom: $('delete_list').remove() } );
		delete_list = new Control.Window($(document.body).down('[href=#delete_list]'),{
			className: 'popup',
			beforeOpen: function() {
				duplicate_list.close();
			}
		});
	}
});
Event.observe(window, 'load', function() {
	if ($(document.body).down('[href=#login_panel]')) {
		login_panel = new Control.Window($(document.body).down('[href=#login_panel]'),{
			iframeshim: false,
			closeOnClick: 'overlay',
			position: 'relative',
			offsetTop: -6,
			offsetLeft: -16 ,
			afterOpen: function() {
			    $('txtEmail').focus();
			}
		});
	}
});

function setLink(myVar) {
	$('bg0').hide();
	$('bg1').hide();
	$('bg2').hide();
	$('bg3').hide();
	$('bg4').hide();
	$(myVar).show();
}

Event.observe(window, 'load', function() {
	$$('input.hover', 'img.hover')
	.invoke('observe', 'mouseover', function(e) {
		this.src = this.src.replace('.png','-on.png');
	})
	.invoke('observe', 'mouseout', function(e) {
		this.src = this.src.replace('-on.png','.png');
	})
});

// window print function
Event.observe(window, 'load', function() {
	var printLink = $$('a.printopen');
	if(printLink.length > 0){
		for(var i=0; i<printLink.length; i++){
			printLink[i].href= "javascript:void(0)";
			printLink[i].onclick = function(){
				window.print();
			}
		}		
	}
});


Event.observe(window, 'load', function() {
	$$('span.organization_type').each(function(span) {
	    handleOrganizationType(span);
		Event.observe(span, 'click', function() {
		    handleOrganizationType(span);	
		});
	});
});

function handleOrganizationType(span) { 
    span.select('input[type="radio"]').each(function(input) {
		var divID = 'div' + input.value;
		var div = $(divID);
		if (div && !input.checked) div.hide();
		else if (div && input.checked) div.show();
	});
}


Event.observe(window, 'load', function() {
// if($$('.get-a-quote-form .row fieldset table').length >0){
// 	if($$('.get-a-quote-form .row fieldset table')[0].id.indexOf("calendar") != -1){
	$$('.form .row fieldset table.organization_type','.form .row fieldset table.notify_me_by').each(function(tables) {
		var tbody = new Element('tbody');
		var tr = new Element('tr');
		tables.getElementsBySelector('tr').each(function(trs){
			trs.getElementsBySelector('td').each(function(tds){
				tds.remove();
				tr.insert( { bottom: tds } );
			});
			trs.remove();
		});
		tbody.insert( { bottom: tr } );
		tables.insert( { bottom: tbody } );
	});
// 	}
// }
});

Event.observe(window, 'load', function() {
	$$('dl.customer-faq dt').each(function(dt) {
		Event.observe(dt, 'click', function() {
			dt.next('dd').toggle();
		});
	});
});

Event.observe(window, 'load', function() {
	$$('table tr.features td').each(function(td) {
		var span = new Element('span', { 'class': 'toggle' }).observe('click', function(event){
			td.parentNode.select('td div p').each(function(p){
				p.parentNode.firstDescendant().toggleClassName('hide');
				if (p.parentNode.getHeight() === 48) {
					Effect.BlindDown(p.parentNode, { scaleFrom: 100, scaleTo: ((p.offsetHeight/p.parentNode.getHeight())*100), restoreAfterFinish: false });
				}
				else {
					Effect.BlindUp(p.parentNode, { scaleFrom: 100, scaleTo: ((48/p.offsetHeight)*100), restoreAfterFinish: false, afterFinishInternal: function(){} });
				}
			});
		});
		td.down('div').insert({ top: span });
	});
});
 
Event.observe(window, 'load', function() {
	$$('select.fancy_companysize','select.fancy_timeframe','select.fancy_projectbudget').each(function(e) {
		var currentClassname = 'current';
		var ol = new Element('ol', { 'class': 'fancy_select group', id: e.className });
		e.childElements().each(function(option, index){
			if (option.value){
				var selected = '';
				if (option.selected) selected = 'current';
				ol.appendChild(new Element('li', { id: e.className+'-'+index, 'class': selected }).update('<span class="fir">'+option.innerHTML+'</span>').observe('click', function(event){
					this.siblings().each(function(s){
						s.removeClassName(currentClassname);
					});
					if (this.hasClassName(currentClassname)){
						this.removeClassName(currentClassname);
						e.selectedIndex = 0;
					}
					else {
						this.addClassName(currentClassname);
						e.selectedIndex = index;
					}
				}));
			}
		});
		e.insert({ after: ol });
		e.hide();
	});
});

Event.observe(window, 'load', function() {
	$$('table.hover tr').each(function(e) {
		Event.observe(e, 'mouseover', function() {
			Element.addClassName(e, 'hover');
		});
		Event.observe(e, 'mouseout', function() {
			Element.removeClassName(e, 'hover');
		});
	});
});

Event.observe(window, 'load', function() {
	$$('input.default_value', 'textarea.default_value')
	.invoke('observe', 'focus', function(e) {
		if (this.hasClassName('default_value')) {
			this.value='';
			this.removeClassName('default_value');
		}
	})
	.invoke('observe', 'blur', function(e) {
		if (this.value=='') {
			this.addClassName('default_value');
			this.value=this.defaultValue;
		}
	})
});

//Event.observe(window, 'load', function() {
	
//	$$('div.nav li.products')
//	.invoke('observe', 'mouseover', function(e) {
		
//		$$('div.nav li.products')[0].insert({top: '<!--[if lt ie 7]><iframe id="ieFixCart" style="filter:mask(); position: absolute; top: 0; left: 169px; z-index: -1; height:330px; width: 650px;" src="javascript:\'<html></html>\';" frameborder="0" scrolling="no"></iframe><![endif]-->'});
//		$$('div.nav li.products').invoke('addClassName', 'hover');
//		$$('div.nav li.products ul.panel').invoke('show');
//	})
//	.invoke('observe', 'mouseout', function(e) {
//		if($('ieFixCart')){
//			$('ieFixCart').remove();
//		}
//		$$('div.nav li.products').invoke('removeClassName', 'hover');
//		$$('div.nav li.products ul.panel').invoke('hide');
//	})
//});

Event.observe(window, "load", function() {

		
	var currentSwitch = 0;
	
	if ($$('div.switcher').length > 0){
	
	$$('div.switcher div.eventItem')[0].style.display = "block";
	$$('div.switcher a.next')[0].href = "javascript:void(0);"
	$$('div.switcher a.previous')[0].href = "javascript:void(0);"
	
	$$('div.switcher a.next').invoke('observe','click', function(e) {

		$$('div.switcher div.eventItem')[currentSwitch].setStyle({
			display: 'none'
		});
		
		if (currentSwitch < ($$('div.switcher div.eventItem').length - 1)) {
			currentSwitch = currentSwitch + 1;
			$$('div.switcher div.eventItem')[currentSwitch].setStyle({
				display: 'block'
			});
		} else {
			$$('div.switcher div.eventItem')[0].setStyle({
				display: 'block'
			});
			currentSwitch = 0;
		};
		return false;
	});

	$$('div.switcher a.previous' ).invoke('observe','click', function(e) {
		$$('div.switcher div.eventItem')[currentSwitch].setStyle({
			display: 'none'
		});
		
		if (currentSwitch > 0) {
			currentSwitch = currentSwitch - 1;
			$$('div.switcher div.eventItem')[currentSwitch].setStyle({
				display: 'block'
			});
		} else {
			$$('div.switcher div.eventItem')[$$('div.switcher div.eventItem').length - 1].setStyle({
				display: 'block'
			});
			currentSwitch = $$('div.switcher div.eventItem').length - 1;
		};
		return false;
	});
   }


	
});

function djTabs(tabClass) {
	var tabParent = $$('div.' + tabClass + ' a')
	var currentTab = tabParent[0];

	tabParent.each( function(e) {
		if ($(e.readAttribute('href')) && !(e.hasClassName('note') || e.hasClassName('active'))) {

			$(e.readAttribute('href')).setStyle({
				display: 'none',
				overflow: 'visible',
				height: 'auto'
			});

		}

	});
	
	tabParent.invoke('observe', 'click', function(e) {
		Event.stop(e);

		if ((this.readAttribute('href') != null) && $(this.readAttribute('href'))) {
			if (currentTab) {
				currentTab.removeClassName('active');
				$(currentTab.readAttribute('href')).style.display = 'none';
			};
			$(this.readAttribute('href')).setStyle({
				display: 'block'
			});
			this.addClassName('active');
			currentTab = this;
		};

	});

};

function djSlider() {
	$$('.slideContent').each(function(node) {

		var slideHeight = node.childElements()[0].getHeight()+7;
		var collapseHeight = node.getHeight();

		node.siblings().each(function(e2) {
			if (e2.hasClassName('slideDown')) {
				var origText = e2.innerHTML;
				e2.onclick = function(e){
			
					if (this.hasClassName('active')) {
						this.removeClassName('active');
						this.innerHTML = origText;
						node.morph('height:' +  collapseHeight + 'px', {duration: .4});
					} else {
						node.morph('height:' + slideHeight + 'px', {duration: .4});

						if (origText.include('+')) {
							this.innerHTML = origText.gsub(/\+/, '-');
						} else {
							this.innerHTML = origText.gsub('More', 'Less')
						};
						
						this.addClassName('active');
					};
					return false;
				};
			};
		});
		
	});
};






function swatchLoad(nodeGUID) {

	$('allSwatches').setStyle({
		'display': 'block'
	});

	if($('allSwatches').hasClassName('loaded') == false){
		// First time clicking View All Swatches -- Do AJAX request and insert images
		var url = "/Handlers/GetProductAllSwatchesMarkup.ashx?guid="+ nodeGUID;
		// AJAX Call to get swatch content
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				$('divAllSwatchesContent').insert(transport.responseText);
			}
		});	

		$('allSwatches').addClassName('loaded');
	}; 
};

Event.observe(window, "load", function() {
	if($$('.random').length = 0){return false}
	$$('.random').each(function(node){
		
		var randoms = 0;
		var randomParent = $(node.parentNode);

		node.childElements().each(function(x) {
			if (x.hasClassName('randomItem')) {
				x.setStyle({ 'display':'none'})
				randoms++;
			};
		});

		node.childElements()[Math.floor(Math.random()*randoms)].setStyle({ 'display': 'block' });
	});
	
	$$('.market_segment-news .separator').each(function(node) {
		node.setStyle({
			'height': $$('.market_segment-news')[0].getHeight() - 50 + 'px'
		});
	});
	
	$$('.market_segment-news .ad span').each(function(node) {
		node.setStyle({
			'height': $$('.market_segment-news')[0].getHeight() + 'px'
		});
	});

	if ($$('div.features').length > 0) {

		var featureLinks = $$('div.features a');
		var featureFirstLink = $$('div.features a')[0];
		var flashvars = {};
		var params = {};
		
		for(var i = 0; i<featureLinks.length; i++){
		    featureLinks[i].removeAttribute('onclick');
		}
	
		params.allowscriptaccess = "always";
		params.quality = "high";
		params.salign = "t";
		params.bgcolor = "#FFFFFF";
		params.wmode = "transparent";
		
		$$('div.features div')[0].update('<div id="featuresSwap"><img src="/_images/chairFeatures/feature_spacer.gif" alt="" /></div>');

		if (featureLinks) {
			Event.observe($$('div.features img')[0], "load", function() {
				if (featureFirstLink.readAttribute('featuretype') == 'gif') {

					$$('div.features div')[0].update('<div id="featuresSwap"><img src="' + featureFirstLink.readAttribute('href') + '" alt="" /></div>');
			
				} else if (featureFirstLink.readAttribute('featuretype') == 'swf') {

					swfobject.embedSWF(featureFirstLink.readAttribute('href'), 'featuresSwap', "140", "140", "9.0.0", "/_flash/expressInstall.swf", flashvars, params );
				};
			})

			featureFirstLink.addClassName('active');
		};

		featureLinks.invoke('observe','click', function(e) {
			Event.stop(e);
			featureLinks.each(function(node){
				node.removeClassName('active');
			});

			this.addClassName('active');
			
			if (this.readAttribute('featuretype') == 'gif') {

				$$('div.features div')[0].update('<div id="featuresSwap"><img src="' + this.readAttribute('href') + '" alt="" /></div>')
				
				this.readAttribute('href').scan('feature_spacer.gif', function(match){
					$$('div#featuresSwap img')[0].src = '/_stylesheets/_images/not-available.gif';
					$$('div#featuresSwap img')[0].setStyle({ 'height': '140px' });
				});

			} else if (this.readAttribute('featuretype') == 'swf') {

				swfobject.embedSWF(this.readAttribute('href'), 'featuresSwap', "140", "140", "9.0.0", "/_flash/expressInstall.swf", flashvars, params );

			};

			return false;
		});
		
	};
	
	$$('a.changePassword').invoke('observe','click', function(e) {
		this.hide();
		Effect.BlindDown(this.next(), {duration:.5});
	});
});



/* *************************************************************************
 * Accordion.js v0.3 - Creates a Accordion UI element from a definition list
 *
 * AUTHOR: 	C. James Callaway <TehTreag@CyberGod.net>
 * WEBSITE:	http://www.CyberGod.net
 * DATE:   	Wed Sep 12 00:23:16 CDT 2007
 *
 * LICENSE:	This work is licensed under a Creative Commons
 *		Attribution 3.0 License
 *		http://creativecommons.org/licenses/by/3.0/
 *

 ************************************************************************ */

Accordion = Class.create();
Accordion.prototype = {
	initialize: function(elem) {
		this.options = Object.extend({
			activeElement: null,
			activeIndex: 1,
			effect: 'blind',
			duration: 0.2,
			activeClassName: 'active',
			onActivate: null
		}, arguments[1] || {});
		var children = $$('#' + elem + ' > dt');
		children.invoke('observe','click',
			this._activateByEvent.bindAsEventListener(this))
			.invoke('next')
			.invoke('hide');
		this.activePanel = (this.options.activeElement)
			? $(this.options.activeElement)
			: children[this.options.activeIndex - 1];
		this.activePanel.addClassName(this.options.activeClassName)
			.next().show().addClassName(this.options.activeClassName);
	},
	_activateByEvent: function(event) {
		this.activate(Event.element(event));
	},

	activate: function(elem) {
		var panel = $(elem);
		if(panel != this.activePanel) {
			if (this.options.onActivate && !this.options.onActivate(panel)) {
				return;
			}

			if (this.options.effect == 'blind') {
				new Effect.Parallel (
					[
						new Effect.BlindUp(this.activePanel.next()),
						new Effect.BlindDown(panel.next())
					], {duration: this.options.duration});
			} else if (this.options.effect == 'slide') {
				new Effect.Parallel (
					[
						new Effect.SlideUp(this.activePanel.next()),
						new Effect.SlideDown(panel.next())
					], {duration: this.options.duration});
			} else {
				this.activePanel.next().hide();
				panel.next().show();
			}

			panel.addClassName(this.options.activeClassName);
			this.activePanel.removeClassName(this.options.activeClassName)
				.next().removeClassName(this.options.activeClassName);
			this.activePanel = panel;
		}
	}
}

function registerDealerTooltip(){
   $$('.locatorTrigger').each(function(node){
		if (node.hasClassName('diamond')) {
			new Tooltip(node, $$('div.diamond')[0].innerHTML, 150);
		} else if (node.hasClassName('platinum')) {
			new Tooltip(node, $$('div.platinum')[0].innerHTML, 150);
		} else if (node.hasClassName('gold')) {
			new Tooltip(node, $$('div.gold')[0].innerHTML, 150);
		} else if (node.hasClassName('gsa')) {
			new Tooltip(node, $$('div.gsa')[0].innerHTML, 150);
		} else if (node.hasClassName('showcasetip')) {
			new Tooltip(node, $$('div.showcasetip')[0].innerHTML, 150);
		};
	});
}

var Tooltip = Class.create();
Tooltip.prototype = {

	initialize: function(element, tool_tip, tool_tip_width) {
		var options = Object.extend({
			default_css: false,
			margin: "0px",
			padding: "5px",
			backgroundColor: "#d6d6fc",
			min_distance_x: 5,
			min_distance_y: 5,
			delta_x: 0,
			delta_y: 0,
			zindex: 1000
		}, arguments[2] || {});

		this.element      = $(element);

		this.options      = options;

		// use the supplied tooltip element or create our own div
		if($(tool_tip)) {
			this.tool_tip = $(tool_tip);
		} else {
			this.tool_tip = $(document.createElement("div")); 
			document.body.appendChild(this.tool_tip);


			if (this.element.hasClassName('locatorTrigger')) {
				this.tool_tip.addClassName("locatorTip");
			} else {
				this.tool_tip.addClassName("tooltip");
			};
			
			this.tool_tip.setStyle({
				width: tool_tip_width + 'px'
			});
			
			this.tool_tip.insert(tool_tip);

			/*iframe = '<!--[if lt ie 7]><iframe style=\"filter:mask(); position: absolute; top: 0; left: 0; z-index: 999; width: 100%; height: ' + this.tool_tip.getHeight() + 'px;\" src=\"javascript:\'<html></html>\';\" frameborder=\"0\" scrolling=\"no\"></iframe><![endif]-->';
			
			this.tool_tip.insert({top:iframe});
            alert(this.tool_tip.innerHTML);*/
		}

	// hide the tool-tip by default
		this.tool_tip.hide();

		this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
		this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
		this.eventMouseMove  = this.moveTooltip.bindAsEventListener(this);

		this.registerEvents();
	},

	destroy: function() {
		Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
		Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
		Event.stopObserving(this.element, "mousemove", this.eventMouseMove);
	},

	registerEvents: function() {
		Event.observe(this.element, "mouseover", this.eventMouseOver);
		Event.observe(this.element, "mouseout", this.eventMouseOut);
		Event.observe(this.element, "mousemove", this.eventMouseMove);
	},

	moveTooltip: function(event){
		Event.stop(event);
		// get Mouse position
		var mouse_x = Event.pointerX(event);
		var mouse_y = Event.pointerY(event);

		// decide if wee need to switch sides for the tooltip
		var dimensions = Element.getDimensions( this.tool_tip );
		var element_width = dimensions.width;
		var element_height = dimensions.height;

		// if ( (element_width + mouse_x) >= ( this.getWindowWidth() - this.options.min_distance_x) ){ // too big for X
		// 		  mouse_x = mouse_x - element_width;
		// 		  // apply min_distance to make sure that the mouse is not on the tool-tip
		// 		  mouse_x = mouse_x - this.options.min_distance_x;
		// } else {
		// 		  mouse_x = mouse_x + this.options.min_distance_x;
		// }
		// 
		// if ( (element_height + mouse_y) >= ( this.getWindowHeight() - this.options.min_distance_y) ){ // too big for Y
		// 		  mouse_y = mouse_y - element_height;
		//   // apply min_distance to make sure that the mouse is not on the tool-tip
		// 		  mouse_y = mouse_y - this.options.min_distance_y;
		// } else {
		// 		  mouse_y = mouse_y + this.options.min_distance_y;
		// } 

		mouse_x = mouse_x + this.options.min_distance_x;
		mouse_y = mouse_y + this.options.min_distance_y;

		// now set the right styles
		this.setStyles(mouse_x, mouse_y);
	},


	showTooltip: function(event) {
		Event.stop(event);
		this.moveTooltip(event);
		iframe = '<!--[if lt ie 7]><iframe id=\"ttFrame\" style=\"filter:mask(); position: absolute; top: 0; left: 0; z-index: 999; width: 100%; height: ' + this.tool_tip.getHeight() + 'px;\" src=\"javascript:\'<html></html>\';\" frameborder=\"0\" scrolling=\"no\"></iframe><![endif]-->';
		this.tool_tip.insert({top:iframe});
		new Element.show(this.tool_tip);
		/*@cc_on
			@if (@_jscript_version <= 5.6)

				if ($$('.productDetail').length > 0) {

					this.tool_tip.select('span.stem')[0].setStyle({
						'width': this.tool_tip.getWidth() + 'px'
					});

				};

			@end
		@*/
	},

	setStyles: function(x, y){

		if (this.tool_tip.hasClassName('locatorTip')) {
			var tipOffset = 53;
		} else {
			var tipOffset = 36;
		};

		// set the right styles to position the tool tip
		Element.setStyle(this.tool_tip, {
			position:'absolute',
			top:y + this.options.delta_y - this.tool_tip.getHeight() - 24 + "px",
			left:x + this.options.delta_x - tipOffset + "px",
		    zindex:this.options.zindex
		});

		// apply default theme if wanted
		if (this.options.default_css){
			Element.setStyle(this.tool_tip, {
				margin:this.options.margin,
				padding:this.options.padding,
				backgroundColor:this.options.backgroundColor,
				zindex:this.options.zindex
			});	
		}	

		// $('djPosition').value = (x) + ' ' + (y);
	},

	hideTooltip: function(event){
	    if($('ttFrame')){
			$('ttFrame').remove();
		}
		new Element.hide(this.tool_tip);
	},

	getWindowHeight: function(){
		var innerHeight;
		if (navigator.appVersion.indexOf('MSIE')>0) {
			innerHeight = document.body.clientHeight;
		} else {
			innerHeight = window.innerHeight;
		}
		return innerHeight;	
	},

	getWindowWidth: function(){
		var innerWidth;
		if (navigator.appVersion.indexOf('MSIE')>0) {
			innerWidth = document.body.clientWidth;
		} else {
			innerWidth = window.innerWidth;
		}
		return innerWidth;	
	}
}




/* *************************************************************************
=GOOGLE AUTOFILL COLOR CORRECT 
Blocks the google autofill color 
************************************************************************* */
//if(window.attachEvent)
//	window.attachEvent("onload",setListeners);

function setListeners(){
	inputList = document.getElementsByTagName("INPUT");
	for(i=0;i<inputList.length;i++){
		if(inputList[i].type == "text"){
		    if(window.addEventListener){ // Mozilla, Netscape, Firefox
	            inputList[i].addEventListener('onDOMAttrModified', restoreStyles, false);
	            inputList[i].style.backgroundColor = "";
    	        
            } else { // IE
	            inputList[i].attachEvent("onpropertychange",restoreStyles);
			    inputList[i].style.backgroundColor = "";
            }
    			
		 } else if(inputList[i].type == "checkbox"){
			if(window.addEventListener){ // Mozilla, Netscape, Firefox
	            inputList[i].addEventListener('onDOMAttrModified', restoreStyles, false);
	            //inputList[i].style.backgroundColor = "";
    	        
            } else { // IE
	                inputList[i].attachEvent("onpropertychange",restoreStyles);
			        //inputList[i].style.backgroundColor = "";
            }
		 }
	}
	selectList = document.getElementsByTagName("SELECT");
		//selectList[i].attachEvent("onpropertychange",restoreStyles);
	for(i=0;i<selectList.length;i++){
		if(window.addEventListener){ // Mozilla, Netscape, Firefox
	            selectList[i].addEventListener('onDOMAttrModified', restoreStyles, false);
	            selectList[i].style.backgroundColor = "";
    	        
         } else { // IE
	            selectList[i].attachEvent("onpropertychange",restoreStyles);
			    selectList[i].style.backgroundColor = "";
         }
    			
		    
	}
}

function restoreStyles(e){
	if (!e) {var e = window.event;}
    if (e){
	
	if((e.srcElement.style.backgroundColor != "")||(e.srcElement.style.backgroundColor != "#fff"))
		e.srcElement.style.backgroundColor = "";
	}
}

Event.observe(window, 'load', setListeners);

/* *************************************************************************
=BACKGROUND IMAGE FUNCTIONS
Ajax request is writen inline on each page
Returns an XML response depending on the page path
Handler function:
    creates an array of the XML values
    Selects a random number 
    Sets background image and links
    Determines height/placement of links
************************************************************************* */

//AJAX Response
var handleXML = function(t) {
	var xmlData = t.responseXML;	
	initXML(xmlData);
}	

//Handler function

function initXML(xmlData){

	var allItems = xmlData.getElementsByTagName("item");
	var bkgItem =  new Array();
	var count = 0;
	
	//creates XML Array
	for(var i=0; i<allItems.length; i++){
		if((allItems[i].getAttribute("type") == "thumb")&&(allItems[i].getAttribute("bg") == "yes")){	

		var thisThumb = allItems[i].getAttribute("file");
		var thisURL = allItems[i].getAttribute("url");
		var thisTitle = allItems[i].getAttribute("title");
		var thisHeight = allItems[i].getAttribute("height");
		var thisArray = new Array();

		thisArray["thumb"] = thisThumb;
		thisArray["url"] = thisURL;
		thisArray["title"] = thisTitle;
		thisArray["height"] = thisHeight;
		bkgItem[count] = thisArray;

		count++;
	}
}

//sets random number
var n = Math.floor(Math.random()*bkgItem.length);

//sets background image path
var bkgPath =  'url(/_stylesheets/_images/random-backgrounds/' + bkgItem[n]["thumb"] + ')';

//preload the background image
var bkgImg = new Image();
bkgImg.src = '/_stylesheets/_images/random-backgrounds/' + bkgItem[n]["thumb"];

//once loaded, set the background style
Event.observe(window, 'load', function() {
	$$('div.feature')[0].setStyle({
		backgroundImage: bkgPath
	});
});

if(!bkgItem[n]["title"]){return false;}

//sets link properties
$$('div.feature-link a')[0].href = bkgItem[n]["url"];
$$('div.feature-link a')[0].update(bkgItem[n]["title"]);
$$('div.feature-link')[0].setStyle({
	display: 'block'
});

//sets link positioning 
if(($$('div.feature-link-height')[0])&&(Element.getHeight($$('div.feature-link-height')[0]) > parseInt(bkgItem[n]["height"]))){
       $$('div.feature-link')[0].setStyle({
	        top: "auto"
        });
}
else{
$$('div.feature-link')[0].setStyle({
	        top: bkgItem[n]["height"] + "px"
        });
}

}

/* *************************************************************************
=INITIALIZE TOOL TIPS
************************************************************************* */
Event.observe(window, 'load', function() {

	var tooltipWidth;
	
	$$('.tooltipTrigger').findAll(function(node){
		if (node.nextSiblings()[0].hasClassName('tooltipContent')) {
			return node.nextSiblings()[0].innerHTML;
		}
	}).each(function(node){
		tooltipWidth = node.nextSiblings()[0].getWidth();
		new Tooltip(node,node.nextSiblings()[0].innerHTML, tooltipWidth);
		node.nextSiblings()[0].remove();
	});



	// @else
	// 	document.write("OS is NOT 32-bit. Browser is IE.");
	
	
	djSlider();
	djTabs('tabs');
	djTabs('emp_faces');
	

});

function toggleFormElements(el, target) {
	if (el.checked == true) {
		$$('.' + target)[0].removeClassName('disabled');
		$$('.' + target + ' input').invoke('enable');
	}
	else {
		$$('.' + target)[0].addClassName('disabled');
		$$('.' + target + ' input').invoke('disable');
	}
}

