window.addEvents({
	'domready': function () {
		//make sure background image is as large as it needs to be
		var windowDims = $(window).getScrollSize();
		var windowHeight = windowDims.y;

		//something with the html construction of the search results page (table layout) is
		//causing the scrollsize to not be returned properly for certain browsers
		if ($(document.body).hasClass('productSearch') && (Browser.chrome || Browser.safari)) {
			windowHeight += 30;
		}

		$(document.body).setStyle('height', windowHeight);

		//landing page rotating promo initializer
		if ($('mainContent').getElements('.promo').length > 1) {
			var promoRotator = new PromoRotator('promo');
		}

		//search box initializer
		if ($(document.body).getElement('ul li.navSearch') && $('searchInputBox')) {
			var searchNavLink = $(document.body).getElement('ul li.navSearch a');

			$('searchInputBox').setStyles({
				'opacity': 0,
				'display': 'block'
			});
			searchNavLink.addEvent('click', function (e) {
				e.stop();
				$('searchInputBox').fade('show');
				var searchOverText = new OverText($('searchTextInput'));
				searchOverText.focus();
				searchOverText.destroy();
			});
			$('closeSearch').addEvent('click', function (e) {
				e.stop();
				$('searchTextInput').set('value', '');
				$('searchInputBox').fade('hide');
			});
		}

		//custom selects initializer
		if ($(document.body).getElement('.mooSelect')) {
			var customSelect = new CustomSelects({ className: 'mooSelect' });
		}

		//product quiz initializer
		if (document.id('quizQuestion')) {
			$(document.body).addClass('quizQuestion');
			var quiz = new ProductQuiz();
		}

		//Random function to swap out promotional images in the header of search results page.
		//all promo images must have the same naming convention of searchResultImg_1.jpg
		if ($(document.body).hasClass('productSearch')) {
			var currentImg = document.id('mainImage').getElement('img').get('src').split('_');
			var preImg = currentImg[0];
			var postImg = currentImg[1].substr(1, currentImg[1].length);
			var ranNum = Math.floor(Math.random() * 4) + 1;
			document.id('mainImage').getElement('img').set('src', preImg + '_' + ranNum + postImg);
		}

	},
	'resize': function () {
		//make sure background image is as large as it needs to be
		var windowDims = $(window).getScrollSize();
		$(document.body).setStyle('height', windowDims.y);
	}
});


/*
CustomSelects v.1
Based off SimpleSelectStyle written by author Ben Stilson
*/
var CustomSelects = new Class(
{
    Implements: Options,
    options :
    {   
        className : '',
        formId : ''
    },

    initialize: function(options)
    {
        this.setOptions(options);
        if ($chk(this.options.className))
        {          
            this.selects = $chk($(this.options.formId)) ? $(this.options.formId).getElements('select') : $$('select.'+this.options.className) ;
            this.selects.each(this.skinSelects.bind(this));
        }
    },
    skinSelects : function(select_el)
    {
        var select_el_width = select_el.getSize().x;
        var selectID = select_el.get('id');
        var value = select_el.getFirst().get('value');
        var text = select_el.getFirst().get('text');

        var selectContainer = new Element('div', {'class':this.options.className+'Container png_bg'}).setStyles({'width':select_el_width}).inject(select_el,'before');
        var selectText = new Element('div', {'class':this.options.className}).set('text',text).inject(selectContainer);
        var selectImage = new Element('div', {'class':this.options.className + 'ArrowImage png_bg'}).inject(selectContainer);
        var selectOptions = new Element('div', {'class':this.options.className + 'Options', 'rel': selectID}).setStyles({'width':select_el_width - 4}).inject(selectContainer);

        select_el.getElements('option').each(function(o, count){
			if(count > 0) {
				var spanOption = new Element('div', {
					'class': 'option',
					'html': o.get('text'),
					'rel': count
				}).addEvent('click', function(e){
					selectText.set('text',this.get('text'));
					$( this.getParent().get('rel') ).options[this.get('rel')].selected = true;
				}).inject(selectOptions);
        	}			
        });
        
        var selectOptionsFx = new Fx.Slide(selectOptions).hide();
        selectContainer.addEvent('click', function(e){
        		e.stop();
        		if(selectOptionsFx.open) {
        			selectOptionsFx.slideOut();
        		}else{
					$$('.mooSelectOptions').each(function(ele,counter){
						if(parseInt(ele.getStyle('margin')) == 0){
								ele.slide('out');
						}
					});
        			selectOptionsFx.slideIn();
        		}
        });

        selectOptions.getParent().setStyle('position','absolute');
        
        select_el.addClass(this.options.className).setProperty('size',1).setStyles({
			'opacity':.01,
			'left':'-9000px',
			'position':'absolute'			
		});
    }   
});



/*
	Class:    	ProductQuiz
	Author:   	John Keber
	Website:    http://www.tuftex.com
	Version:  	0.0.1
	Date:     	10/18/2010
	Built Using:  MooTools 1.3
*/

var ProductQuiz = new Class({
	
	//implements
	Implements: [Options, Events],

	//options
	options: {
		maxQuestions: 9
	},

	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		this.setQuestionsOpacity();
		this.setQuestionHovers();
		this.createToolTips();	

		this.questionsComplete = 0;
		this.activeQuestion = 1;
		this.nextQuestion = 2;
		this.updating = false;

		//delay the building of future question images to help with user flow
		//and speed up page load
		window.addEvent('load', function(){
			this.populateQuestionImages();
		}.bind(this));
		
	},
	
	//setting questions opacity to allow for smooth fade in transition
	setQuestionsOpacity: function(){
		$$('#contentCopy .show').set({
			'styles': {
				'opacity':'1',
				'display':'block'
			}
		}).removeClass('show');
		$$('#contentCopy .hide').set({
			'styles': {
				'opacity':'0',
				'display':'none'
			}
		}).removeClass('hide');
	},
	
	//function that populates questions 2-maxquestions on page load
	//name of images have specific pattern
	populateQuestionImages: function(){
		document.id('contentCopy').getElements('.question').each(function(question, counter){
			if(counter > 0){
				question.getElements('.questionImageContainer .questionImage').each(function(imgEle, imgCounter){
					if(imgEle.get('html') === ''){
						var image = new Element('img', {
							'src': '/TuftexMicrosite/images/quiz/lrg/q' + (counter + 1) + '_' + (imgCounter + 1) + '.jpg',
								'height':'156',
								'width':'187',
								'alt':''
						}).inject($(imgEle));
					}
				});
			}
		});
	},
	
	//function to create image hover effect
	//in this case we are creative a div overlay on mouseover
	//checks are in place to not keep creating elements that have already been created
	setQuestionHovers: function(){
		document.id('contentCopy').getElements('.questionImageContainer .questionImage').each(function(qImg){
				qImg.addEvents({
					'mouseenter': function(e){
						if(e) e.stop(); 
						if(qImg.getElement('.questionImageHover')){
							qImg.getElement('.questionImageHover').addClass('show').removeClass('hide');
						}else{
							var hoverDiv = new Element('div', {
								'class': 'questionImageHover show',
								'html': this.get('html')
							}).inject(this);
						}
					},
					'mouseleave': function(e){
						if(e) e.stop();
						if(qImg.getElement('.questionImageHover')){
							qImg.getElement('.questionImageHover').addClass('hide').removeClass('show');
						}
					},
					'click': function(e){
						if(e) e.stop();
						var currentQuestionNum = qImg.getParent().getParent().get('id').split('_');
						this.updatePagination(qImg, currentQuestionNum[1]);
					}.bind(this)
				});
				
		}.bind(this));
	},
	
	//this function will update the pagination bar when question image has been clicked
	updatePagination: function(qImg, questionNum){
		var imgSrc = qImg.getElement('img').get('src');
		$('a_'+questionNum).getElement('a').empty();
		var paginationImage = new Element('img', {
			'class': 'paginationImage',
			'src': imgSrc.replace('lrg','sml'),
			'alt': '',
			'height': '64',
			'width':'76',
			'styles': {
				'opacity':0,
				'display':'block'
			}
		}).inject($('a_'+questionNum).getElement('a')).fade(1);
		
		//get image name and set href to this so that we can use it later
		//to calculate the result
		var imgName = imgSrc.split('/');
		var questionAnswer = imgName.getLast().substring(imgName.indexOf('.'),4);
		$('a_'+questionNum).getElement('a').set('href', questionAnswer);
		
		if(this.updating){
			this.nextQuestion = this.activeQuestion;
			this.updating = false;
		}

		//attach click events to the images in the pagination
		this.addPaginationClickEvents();
		
		var nextQuestion = this.nextQuestion;
		if(nextQuestion <= this.options.maxQuestions){
			$('q_'+questionNum).fade(0).setStyle('display','none');
			$('q_'+nextQuestion).setStyle('display','block').fade(1);
			this.activeQuestionUpdate(nextQuestion);
		} else {
			$('q_'+questionNum).fade(0).setStyle('display','none');
			this.showReview();
		}

		
	},
	
	//if user wants to change question, this function handles the removal
	//of changing question and display the correct question for user to select
	goBackToQuestion: function(questionNum) {
		this.updating = true;
		if($(document.body).hasClass('quizReview')){
			
			$$('#reviewTop, #reviewBottom').setStyles({
					'display':'none'				
			});
			$(document.body).addClass('quizQuestion').removeClass('quizReview');

		}else{
			$('q_' + this.activeQuestion).fade(0).setStyle('display','none');
		}
		$('a_' + questionNum).getElement('a img').set('tween', {
			onComplete: function(){
				$('a_' + questionNum).getElement('a').empty();
			}	
		}).fade(0);
		
		//allow only one question to be changed at a time
		//add new click events on pagination image that will pop
		//an overlay message
		this.addPaginationOverlayClickEvents(questionNum);
		$('q_' + questionNum).setStyle('display','block').fade(1).addClass('update');
	},
	addPaginationClickEvents: function(questionNum){
		document.id('quizPagination').getElements('.pAnswer a').each(function(ele,counter){
			if(ele.getElement('img')) {
				ele.removeEvents('click');
				ele.addEvent('click', function(e){
					if(e) e.stop(); 
					this.goBackToQuestion(counter+1);
				}.bind(this));
			}
		}.bind(this));
	},
	addPaginationOverlayClickEvents: function(questionNum){
		document.id('quizPagination').getElements('.pAnswer a').each(function(ele, counter){
			if(ele.getElement('img')) {
				ele.removeEvents('click');
				ele.addEvent('click', function(e){
					if(e) e.stop(); 
					this.showMessageOverlay(questionNum);
				}.bind(this));
			}
		}.bind(this));		
	},
	showMessageOverlay: function(questionNum) {
			var overlayMask = new Mask(document.id('q_'+questionNum).getElement('.questionImageContainer'), {
				'style': {
					'opacity': .5,
					'background-color': '#fff'
				},
				'onClick': function(){
					overlayMask.destroy();
					overlayMessage.destroy();
					if(Browser.name == 'ie' && Browser.version <= 6) {
						if(document.id('q_'+questionNum).getElement('shape')){
							document.id('q_'+questionNum).getElements('shape').destroy();
						}
					}
				}					
			}).show();
			var overlayMessage = new Element('div',{
					'html': 'Please complete this question before continuing.',
					'class': 'overlaymessage png_bg'
				}).inject(document.id('q_'+questionNum).getElement('.mask'), 'after');
			overlayMessage.position({
				'relativeTo': document.id('q_'+questionNum).getElement('.questionImageContainer')
			});
			var overlayContinueBtn = new Element('a', {
					'class':'continueBtn',
					'href':'#',
					'text':'continue',
					'events': {
						'click': function(e){
							if(e) e.stop();
							overlayMask.destroy();
							overlayMessage.destroy();
							if(Browser.name == 'ie' && Browser.version <= 6) {
								if(document.id('q_'+questionNum).getElement('shape')){
									document.id('q_'+questionNum).getElements('shape').destroy();
								}
							}
						}.bind(this)
					}
			}).inject(overlayMessage);
	},
	quizProgressUpdate: function() {
		if(this.updating) {
			this.nextQuestion == this.activeQuestion;
		}else{
			this.nextQuestion++;
			this.questionsComplete++;
		}
	},
	activeQuestionUpdate: function(activeQuestionNum){
		this.activeQuestion = activeQuestionNum;
		this.quizProgressUpdate();
	},
	
	//function that creates the hover bubbles in the pagination
	createToolTips: function() {
		//get question title and make them the link titles for the pagination
		var questionTitles = document.id('contentCopy').getElements('.question .copy h1').get('html');
		var paginationLinks = document.id('quizPagination').getElements('a.toolTips');
		paginationLinks.each(function(link,counter){
			link.addEvent('click', function(e){
				e.stop();
			});
			link.store('tip:title',questionTitles[counter]);
			link.store('tip:text', '');
		})
		var paginationTips = new Tips('.toolTips',{
			'className': 'tip-wrap png_bg',
			'fixed':true,
			'offset': {
				'x':-65,
				'y':-60
			},
			'showDelay': 0,
			'hideDelay': 0
		});
		$$('.tip-wrap').addClass('png_bg');
		paginationTips.addEvents({
			'show':	function(tip, el){
				if( el.getParent().get('id') === 'a_2' || el.getParent().get('id') === 'a_3' || el.getParent().get('id') === 'a_5' || el.getParent().get('id') === 'a_7' || el.getParent().get('id') === 'a_8'){
					$$('.tip-wrap').setStyles({
						'padding':'10px 10px 0 10px',
						'height':'51px',
						'width':'176px'
					});
				}else{
					$$('.tip-wrap').setStyles({
						'padding':'20px 10px 0 10px',
						'height':'41px',
						'width':'176px'
					});
				}
				tip.setStyles({
					'display':'block',
					'opacity':1
				});
			},
			'hide': function(tip, el){
				tip.setStyles({
					'display':'none',
					'opacity':0
				});
			}
		});    	

	},
	
	//when all questions are completed then show the review state of the quiz
	showReview: function(){
		this.activeQuestion = 10;
		$('contentCopy').getElements('.question').setStyles({
				'opacity': 0,
				'display':'none'
		});
		$$('#reviewTop, #reviewBottom').setStyles({
				'opacity':0,
				'display':'block'				
		});
		$('quizPagination').fade('out');
		$(document.body).addClass('quizReview').removeClass('quizQuestion');
		$$('#reviewTop, #quizPagination, #reviewBottom').fade('in');
		
		this.calculateAnswer();
	},
	
	//from the review page, clicking get my result will trigger this calculate function
	//quiz answers are populated within the href of the pagination bar
	calculateAnswer: function(){
		var quizAnswers = document.id('quizPagination').getElements('.pAnswer a').get('href')
		
		//start building result answer
		var q1Answer = quizAnswers[0].split('_');
		var q2Answer = quizAnswers[1].split('_');
		var q3Answer = quizAnswers[2].split('_');
		var q4Answer = quizAnswers[3].split('_');
		var q5Answer = quizAnswers[4].split('_');
		var q6Answer = quizAnswers[5].split('_');
		var q7Answer = quizAnswers[6].split('_');
		var q8Answer = quizAnswers[7].split('_');
		var q9Answer = quizAnswers[8].split('_');
		
		var resultAnswer;
		if(q6Answer.getLast()==='1' || q6Answer.getLast()==='2' || q6Answer.getLast()==='5' || q6Answer.getLast()==='6' || q6Answer.getLast()==='7')
		{
			//onto question 5 check
			if(q5Answer.getLast()==='1' || q5Answer.getLast()==='4' || q5Answer.getLast()==='5' || q5Answer.getLast()==='6')
			{
				//onto question 8 check
				if(q8Answer.getLast()==='3' || q8Answer.getLast()==='4' || q8Answer.getLast()==='6' || q8Answer.getLast()==='7')
				{
					//Central Valley Cineyard
					resultAnswer = 'central-valley-vineyard';
				}else{
					//then user selected 1|2|5|8
					//Modern Coastal
					resultAnswer = 'modern-coastal';
				}				
			}else{
				//then user selected 2|3|7|8
				//onto question 1 check
				if(q1Answer.getLast()==='2' || q1Answer.getLast()==='4' || q1Answer.getLast()==='5' || q1Answer.getLast()==='6')
				{
					//Canyon Estate
					resultAnswer = 'canyon-estate';
				}else{
					//then user selected 1|3|7|8
					//Mesa Chalet
					resultAnswer = 'mesa-chalet';
				}
			}
		}else{
			//then user selected 3|4|8
			//onto question 4 check
			if(q4Answer.getLast()==='3' || q4Answer.getLast()==='4' || q4Answer.getLast()==='5' || q4Answer.getLast()==='6')
			{
				//onto question 2 check
				if(q2Answer.getLast()==='2' || q2Answer.getLast()==='3' || q2Answer.getLast()==='4' || q2Answer.getLast()==='6')
				{
					//Desert Oasis
					resultAnswer = 'desert-oasis';
				}else{
					//then user selected 1|5|7|8
					//Woodland Retreat
					resultAnswer = 'woodland-retreat';
				}
			}else{
				//then user selected 1|2|7|8
				//onto question 9 check
				if(q9Answer.getLast()==='1' || q9Answer.getLast()==='2' || q9Answer.getLast()==='5' || q9Answer.getLast()==='6')
				{
					//Lakeside Cabin
					resultAnswer = 'lakeside-cabin';
				}else{
					//then user selected 3|4|7|8
					//Riverhead Lodge
					resultAnswer = 'Riverhead-lodge';

				}
			}
		}
		
		//set Get My Style button URL with resulting page
		$('reviewBottom').getElement('a.getMyStyle').set('href', '/Tuftex/'+resultAnswer)
	}
	
});


/*
	Class:    	PromoRotator
	Author:   	John Keber
	Website:    http://www.tuftex.com
	Version:  	0.0.1
	Date:     	11/04/2010
	Built Using:  MooTools 1.3
*/

var PromoRotator = new Class({
	//implements
	Implements: [Options, Events],

	//options
	options: {
		defaultSelector : 'promo',
		rotatePromos : true,
		rotationDelay : 10000
	},

	//initialization
	initialize: function(options) {
		//set options
		this.setOptions(options);
		this.promos = $(document.body).getElements('.'+this.options.defaultSelector);
		this.numPromos = this.promos.length;
		this.activePromo = 0;
		this.previousPromo = 0;
		this.previousActivePromo = 1;
		this.setPromoOpacity();
	},

	setPromoOpacity: function(){
		this.promos.each(function(el, counter){
			if(counter == this.activePromo){
				el.getElements('.fadeThis').fade('show');
			}else{
				el.getElements('.fadeThis').fade('hide');
			}
			el.removeClass('hide').removeClass('show').addClass(this.options.defaultSelector + '_'+(counter+1));
		}.bind(this));
		this.setUpControls();
	},
	setUpControls: function(){
		//this is for future expansion of rotation if controls are to be added
		
		//after controls set up then start rotation
		this.activePromo = 1;
		this.rotatePromo();
	},
	rotatePromo: function(){
		if (this.options.rotatePromos) {
            this.periodical;
            promoToRotate = function() {
                this.showPromo();
            }.bind(this);
            this.periodical = promoToRotate.periodical(this.options.rotationDelay);
        } 
	},
	stopPromos: function(){
		//this is for future expansion of rotation if controls are to be added
	},
	playPromos: function(){
		//this is for future expansion of rotation if controls are to be added
	},
	showPromo: function(){
		//there could potentially be some race conditions here
		//so we have added a 1.25 second delay to fade out previous promo
		//and to then increment the numbers.
		this.promos[this.activePromo].getElements('.fadeThis').fade('in');
		(function(){
				this.promos[this.previousPromo].getElements('.fadeThis').fade('out');
				this.updateActivePromo();
		}.bind(this)).delay(1250);
	},
	updateActivePromo: function(){
		this.previousPromo = this.activePromo;
		this.activePromo++;
		if(this.activePromo >= this.promos.length) {
			this.activePromo = 0;
		}
	}
});

