//var timer;

$(document).ready(
	function(){

		if ($('#container').get(0).offsetWidth!=780) return; //go nee further if CSS is disabled
		
		//jQuery.fx.off = true; //use this to disable animation effects
		messageFadeIn();
		setOneLinersInMenu();
		setBanner();
		addBannerControls();
		setHeaderLogo();
		setTabs();
		tabContent();
		setBackgroundHeight();
		
		$('.firstfocus').focus();

		fixSelectWidthsForIE();
		setContactFormBehavior();

		return; //still in dev
		
		setSectionMenu();
		setSpacing();
		flashErrorMsg();
		
		
	}
);

function setOneLinersInMenu() {
// Finds tabs in the main menu that are only one line of text and adds a special class to vertically center them.
// The default style is set up for tabs with two lines.

	$('#menu').children('ul').children('li').children('a').each(function()  {
			if ($(this).text().length < 15) $(this).addClass('oneliner');
		});
}

function setBanner() {
// Manhandles the DOM and launches the banner animation

	$('#banner').empty()
		.append('<div id="banner-shadow"></div>')
		.append('<div id="banner-loading"></div>')
		.append('<div id="bannercycle"></div>');
	$.preload( ['705','302','962-963','5111','411','372f','346','5221'], {
		base:'images/banners/',
		ext:'.jpg',
		onFinish:function(){
			// Uncomment the following line (and its closing bracket below) to test this on a delay
			//$('body').animate({opacity: 1.0},3000,function() {
				$('#banner-loading').fadeOut(400, function(){$(this).remove();});
				$('#bannercycle')
					.append('<div id="bannerphoto01" data-caption="The 705 style recliner"></div>')
					.append('<div id="bannerphoto02" data-caption="The 381 style group"></div>')
					.append('<div id="bannerphoto03" data-caption="The 963 style chair and 962 style swivel chair"></div>')
					.append('<div id="bannerphoto04" data-caption="The 5111 style sectional (from the 5000 series)"></div>')
					.append('<div id="bannerphoto05" data-caption="The 411 reclining sofa"></div>')
					.append('<div id="bannerphoto06" data-caption="The 372 style group"></div>')
					.append('<div id="bannerphoto07" data-caption="The 346 style group"></div>')
					.append('<div id="bannerphoto08" data-caption="The 5221 style group (from the 5000 series)"></div>')
					.innerfade({
						animationtype: 'fade',
						speed: 3000,
						timeout: 5000,
						type: 'random',
						animatefirst: true,
						firstanimation: 'fade',
						firstspeed: 1000,
						showcontrolbox: 'semihover',
						showcaptions: true,
						captionalignment: 'right'
					});
			//	});
			}
	});
}

function addBannerControls() {
// Adds three buttons beneath the banner, to set the state of the banner: hidden, small, or large

	if ($('body').hasClass('homepage')) return;
	// The above line isn't necessary for the script to work; it's just a design decision to leave these controls off the home page.
	// You can comment it out if you want: everything is set up to work properly either way.
	
	// create the control buttons
	$('#mainarea').append('<div id="bannercontrols"></div>');
	var bc = $('#bannercontrols');
	bc.append('<span id="bannercontrol-label">Banner photo: </span>')
	  .append('<a href="" id="banner-no">Hidden</a>');
	if ($('body').hasClass('homepage'))
		bc.append('<a href="" id="banner-sm">Small</a>')
		  .append('<a href="" id="banner-lg" class="active">Large</a>')
	else
		bc.append('<a href="" id="banner-sm" class="active">Small</a>')
		  .append('<a href="" id="banner-lg">Large</a>')
	bc.append('<span id="bannercontrol-tip"></span>');
	
	// set a hover event on the buttons to write a tooltip to a separate span on the page
	$('#bannercontrols a').hover(function() {
			$('#bannercontrol-tip').text($(this).text());
		},function() {
			$('#bannercontrol-tip').text('');
		});
	
	// the button functions
	$('#banner-no').click(function(){
			if ($(this).hasClass('active')) return false;
			
			//perform animations
			$('#banner').slideUp();
			$('#mainarea').animate({'top':'121px'});
			
			//calculate what the total height WILL be when animations finish, and set the background to animate to that
			//taking off 30 here because mainarea and menu overlap: menu is 150px tall but mainarea is set at 120px from top
			var newHeight = $('#mainarea').outerHeight(true) + $('#menu').outerHeight(true) - 30;
			$('#background').animate({'height':newHeight+'px'});
			
			$(this).addClass('active');
			$('#banner-sm, #banner-lg').removeClass('active');
			
			return false;
		});

	$('#banner-sm').click(function(){
			if ($(this).hasClass('active')) return false;
			
			//perform animations
			$('#bannercycle div').css({'background-position':'0 -70px'});
			$('#banner').animate({'height':'135px'});
			$('.innerfade-captions').animate({'top':'145px'});
			$('.innerfade-control').animate({'top':'110px'});
			$('#mainarea').animate({'top':'285px'});

			//calculate what the total height WILL be when animations finish, and set the background to animate to that
			var newHeight = $('#mainarea').outerHeight(true) + $('#menu').outerHeight(true) + 135;
			$('#background').animate({'height':newHeight+'px'});

			$('#banner-no, #banner-lg').removeClass('active');
			$(this).addClass('active');
			
			return false;
		});

	$('#banner-lg').click(function(){
			if ($(this).hasClass('active')) return false;
			
			$('#bannercycle div').css({'background-position':'0 0'});
			$('#banner').animate({'height':'300px'});
			$('.innerfade-captions').animate({'top':'310px'});
			$('.innerfade-control').animate({'top':'275px'});
			$('#mainarea').animate({'top':'450px'});
			
			var newHeight = $('#mainarea').outerHeight(true) + $('#menu').outerHeight(true) + 300;
			$('#background').animate({'height':newHeight+'px'});
			//$('#banner').queue(function(){setBackgroundHeight();$(this).dequeue();});

			$('#banner-no, #banner-sm').removeClass('active');
			$(this).addClass('active');
			
			return false;
		});

}

function setHeaderLogo() {
// Applies a hover effect to the main logo in the header

	$('#menu h1 a').css({'background-position':'0 0'}).hover(function() {
			$(this).append('<div></div>');
			$('#menu h1 a').children('div').hide().fadeIn(300);
		}, function() {
			$('#menu h1 a').children('div').fadeOut(400, function() {$(this).remove();});
	});
}

function setTabs() {
// Applies hover effects to the main tab, both for the tabs themselves as well as the dropdown menus

	
	//The following approach applies the hover effect to the main menu links, and KEEPS the effect on the main link
	//while the user hovers over the submenu menu.
	//This also uses a fadeIn effect, which in turn requires a step to neutralize any CSS-based effects on the anchor.
	//To remove the fadeIn, knock out anything to do with the unhoverState variable, including the jQuery call to set
	//the css of the anchor before appending the div. It will take out about 10-12 lines as well as a few jQuery chain links
	//from the code below.
	
	$('#menu').children('ul').children('li').each(function()  {
		
		
		var unhoverstate;
		if ($(this).hasClass('activetab')) unhoverstate = '-260px 0'; else unhoverstate = '0 0';
		
		$(this).hover(function() {
				var inlineStyle = new String();
				$(this).children('a')
					.css('background-position',unhoverstate)
					.append('<div'+inlineStyle+'>'+$(this).children('a').html()+'</div>')
					.children('div')
					.hide()
					.fadeIn(600);
		   }, function() {
				$(this).children('a')
					.css('background-position','') //does not work in ie
					.removeAttr('style') //takes care of ie
					.children('div')
					.fadeOut(200, function() {$(this).remove();});
		   });
	});
	
	
	// expand the dropdown submenus
	$('#menu').children('ul').children('li').each(function() {
		$(this).hover(function() {
				$(this).children('ul').hide().fadeIn(300);//.stop().css({'width':'0','display':'block'}).animate({'width':'180px'},300);
		   }, function() {
				$(this).children('ul').fadeOut(400);//.animate({'width':'0'},500, function(){$(this).css({'display':'none','width':'0'});});
		   });
	});

}

function setQuoteMarks() {
	var n=0;
	$('#content blockquote p').each(function() {
			n++;
			var s = new String();
			s = $(this).html();
			if (s===null) return;
			if (s.substr(0,1)=='"') s = s.substr(1,s.length);
			if (n==1) {
				sPrepend = '<span class="quotemark-open"><span>"</span></span>';
			}
			else sPrepend = '<span class="quotemark-blank"><span>"</span></span>';
			
			if (n == $('#content blockquote p').length && s.substr(s.length-1,1)=='"') {
				sAppend = '<span class="quotemark-close"><span>"</span></span>';
				s = s.substr(0,s.length-1);
			}
			else sAppend = '';
			
			$(this).html(s)
				.prepend(sPrepend)
				.append(sAppend)
				.addClass('quotemarks');
		});
}

function setSectionMenu() {
	if ($('#sectionmenu').length==0) return;
	$('#sectionmenu').hover(function() {
			var n = $(this).children('ul').children().length;
			var h = ((n+1)*1.2)+1.5;
			$(this).stop().animate({'height':h+'em'}, 500);
		},function() {
			$(this).stop().css({'overflow':'hidden','height':'auto'}).animate({'height':'1.2em'}, 500);
		});
}

function setSpacing() {

	//	1. Get rid of all the "cruft" and ensure that the page height is dictated by either the main area or the menu, but
	//	   not by unnecessary elements.
	// 	2. Make sure the footer is positioned at the bottom of the viewport.
	//  3. If moving the footer down created some space, add back the sidebar cruft.
	
	function s(){return $('#sidebar').outerHeight();}
	function m(){return $('#mainarea').outerHeight();}
	
	// restore to defaults (only needed in case of resizing a loading page)
	$('#filler').css('min-height','150px');
	$('#graboid1').show();
	$('#graboid2').show();
	$('#graboids').css('border-bottom','1px solid white');
	
	// remove sidebar cruft if the mainarea isn't long enough
	if (s() > m()) $('#filler').css('min-height','0');
	if (s() - 120 > m()) $('#graboid2').hide();
	if (s() > m()) $('#graboid1').hide();
	if ($('#graboid1').css('display')=='none' && $('#graboid2').css('display')=='none') $('#graboids').css('border-bottom','none');
	if (m() > s()) $('#filler').css('min-height',m()-s());
	
	// add spacing to mainarea to set the footer at the bottom of the page
	var spacerHeight = 0;
	if ($('#spacer').length!=0) {$('#spacer').remove();}
	if ($('#background').height() < $(window).height()) {
		$('#hrule').before('<div id="spacer" style="clear:both"></div>');
		spacerHeight = $(window).height() - $('#container').outerHeight() - $('#footerbar').outerHeight();
		if ($('#container').outerHeight() - $('#mainarea').outerHeight() > 0) spacerHeight += $('#container').outerHeight() - $('#mainarea').outerHeight();
		$('#spacer').height(spacerHeight);
	}
	if (spacerHeight>0) $('#filler').css('min-height',0);
	
	// restore cruft if adding the spacer created enough room
	if ($('#graboid1').css('display')=='none' && m()-121 > s()) $('#graboid1').show();
	if ($('#graboid2').css('display')=='none' && m()-120 > s()) $('#graboid2').show();
	if ($('#graboid1').css('display')!='none' || $('#graboid2').css('display')!='none') $('#graboids').css('border-bottom','1px solid white');
	if (m() > s()) $('#filler').css('min-height',m()-s());
	
	$(window).bind('resize', setSpacing);

}

function flashErrorMsg() {
//	$('div.form-error').fadeTo(400, .5, function(){$(this).fadeTo(400, 1, function(){$(this).fadeTo(400, .5, function(){$(this).fadeTo(600, 1, function(){});});});});
	$('div.form-error').fadeTo(400, .5, function(){$(this).fadeTo(1000, 1);});
}

function tabContent() {
	if ($('#tabcontent').length==0) return;
	
	$('#tabnav ul li').each(function() {
		$(this).click(function() {
			$('#tabnav ul li').removeClass('curr');
			$(this).addClass('curr');
			var sTab = $(this).children('a').attr('href').substr(1);
			if (sTab=='') sTab='top';
			if (animate) {
				//$('#tabcontent').children().slideUp(400);
				//$('#tabcontent-'+sTab).slideDown(400);
				$('#tabcontent').children('div:visible').slideUp(200, function(){$('#tabcontent-'+sTab).slideDown(200);});
			}
			else {
				$('#tabcontent').children().hide();
				$('#tabcontent-'+sTab).show();
			}
		});
	});
	
	//do something similar to above but this time scan the body of the page itself for any
	//local targets and reroute them as well
	$('#tabcontent a').each(function() {
			if ($(this).attr('href') && $(this).attr('href').indexOf('#')==0) {
				$(this).click(function() {
						sTab = $(this).attr('href').substr(1);
						$('#tabnav ul li').removeClass('current');
						//$('#tabcontent').children().slideUp(400);
						//$('#tabcontent-'+sTab).slideDown(400);
						$('#tabcontent').children('div:visible').slideUp(200, function(){$('#tabcontent-'+sTab).slideDown(200);});
						$('#tabnav ul li').children('a[href="#'+sTab+'"]').parent().addClass('current');
					});
			}
		});
	
	$('a.anchor').remove().hide().prependTo('body');
	
	var myFile = document.location.toString();
	var animate = false;
	if (myFile.match('#')) {
		var myAnchor = '#' + myFile.split('#')[1];
		$('#tabnav ul li a[href="' + myAnchor + '"]').parent().click();
	}
	else {
		$('#tabnav ul li:first').click();
	}
	animate = true;
}

function setBackgroundHeight() {
	var h = $('#mainarea').outerHeight(true) + $('#menu').outerHeight(true) + $('#banner').outerHeight(true);
	if ($('#banner:hidden').length==1) h-=$('#banner').outerHeight(true);
	$('#background').css('height',h);
	$(window).bind('resize', setBackgroundHeight);
}

function messageFadeIn() {
// any user messages from forms get faded in for emphasis
	
	$('div.form-error, div.form-success').hide().fadeIn(2000);
	
}

function fixSelectWidthsForIE() {

	if ($.browser.msie) {
		$('#reason1, #reason2')
			.each(function(){
				$(this).parent().css('position','relative');
				$(this)
					.data('origWidth', $(this).css('width'))
					.data('origX', $(this).position().left)
					.data('origY', $(this).position().top);
			})
			.focus(function(){
				$(this)
					.css({
						'width':'auto',
						'position':'absolute',
						'left': $(this).data('origX'),
						'top': $(this).data('origY')
						});
					
			}).blur(function(){
				$(this)
					.css({
						'width':$(this).data('origWidth'),
						'position':'relative',
						'left': 'auto',
						'top': 'auto'
						});
			});
	}
}

function setContactFormBehavior() {

	if ($('#reason1').length==0) return;
	
	$('#reason2, label[for="reason2"]').hide();
	$('#reason1').change(function() {
			if ($('#reason1 option[name=\'another\']:selected').length > 0) {
				$('#reason2, label[for="reason2"]').slideDown().focus();
			}
			else {
				$('#reason2, label[for="reason2"]').slideUp();
			}
		});
	$('#reason1').change();
	
}
