var b_first_resize = true;
//in case resizing and fliping at the same time
var nw;
var nh;
var testmessage = function(m) { $('#b_ground').css({height:'1.2em'}); $('#b_ground_2').html(m).css({'text-align':'right',color:'white'}); }
var b_overview_items;

$(document).ready(function(){
	if (page_type == 'feature') {
		var feature_gallery = {}; 
		make_feature_gallery();
	} else if (page_type == 'overview') {
		make_scroll_area($('#b_overview_up_button'), $('#b_overview_down_button'), $('#b_middle_1') );
	} else if (page_type == 'gallery') {
		make_scroll_area($('#b_gallery_up_button'), $('#b_gallery_down_button'), $('#b_gallery_left') );
		initiateGallery();
	} else if (page_type == 'blog') {

		/*
		if (document.getElementById('fake_scroll')) {
			$('#b_right_col').css({overflowY:'scroll',right:-25, paddingRight:25});
		}
		*/


		if (document.getElementById('b_right_col_in')) {

			//fix houzz links
			$('.blog_post_container>div').each( function(i,e) {
				if ($(e).attr('id').substring(0, 6) == 'hzroot') {
					var hzid = $(e).attr('id').substring(6)
					//alert('houzz_fix test '+$(e).attr('id'));
					$(e).css({'text-align':'left'});
					$(e).children('div').css({'font-size':'medium'});
					$(e).find('div#hzexpand'+hzid).hide();
					$(e).find('div#hzfooter'+hzid).hide();
					var hzgallery = $(e).find('iframe');
					hzgallery.css( {width:'100%'} )
				};
			});
			
			$('#b_right_col_in').css( {paddingBottom:25, width:$('#b_right_col').width(), overflow:'hidden'} );
			$('#b_right_col').hover(
				function() {
					$(this).css({overflowY:'scroll',right:-25, paddingRight:25});
					$('#b_middle_1').css({overflow:'visible'});
				},
				function() {
					$(this).css({overflowY:'hidden',right:0, paddingRight:0});
				}
			)
		}


		make_scroll_area($('#b_overview_up_button'), $('#b_overview_down_button'), $('#b_right_col') );
		$('#b_right_col img').each( function(i,image){
			//if ( $(image).width() > 100 ) $(image).css({width:'100%',height:'auto',marginLeft:'auto',marginRight:'auto'});
		})
	} else if (page_type == 'regular') {
		make_scroll_area($('#b_overview_up_button'), $('#b_overview_down_button'), $('#b_right_col') );
	} else if (page_type == 'contact') {
		make_scroll_area($('#b_overview_up_button'), $('#b_overview_down_button'), $('#b_right_col') );
	}
	$(window).resize();
})

function fixGalleryImageSize() {
//	return false;
	pw = $('#b_gallery_selected').width();
	ph = $('#b_gallery_selected').height();
	w = $('#b_gallery_right img').width(); //original gallery image width
	h = $('#b_gallery_right img').height(); //original gallery image width
	if ( w>h && (pw/ph)-(w/h)>0 && (pw/ph)-(w/h) < .175 ) {
		$('#b_gallery_right img').css( {width:'100%', height:'auto'} );
		h = $('#b_gallery_right img').height();
		if (h>ph) {
			$('#b_gallery_right img').css( {marginTop:(ph-h)} );
		}
	} else {
//		alert('height 100%. h='+h+' ph='+ph);
		$('#b_gallery_right img').css( {width:'auto', height:'100%', marginTop:0} );
	}
}
function initiateGallery() {
	$('#b_gallery_thumbs').children().each(function(i,e){
		$(e).click(function(){
//			if ($('#b_gallery_right > img:nth-child('+(i+1)+')').hasClass('selected')) return;
			$('#b_gallery_thumbs').children().removeClass('selected');
			$(this).addClass('selected');
			$('#b_gallery_last').empty().append($('#b_gallery_selected').children());
			$('#b_gallery_selected').empty().hide().append($('#b_gallery_images_container > img:nth-child('+(i+1)+')').clone()).fadeIn();
			$('#b_gallery_current_imnum').text( (i+1)<10 ? '0'+(i+1) : i+1);
			//$('#b_gallery_right > img').css('z-index',50);
			//$('#b_gallery_right > img.selected').css('z-index',99).removeClass('selected');
			//$('#b_gallery_right > img:nth-child('+(i+1)+')').css('z-index',100).hide().fadeIn().addClass('selected');			
			fixGalleryImageSize();
		});
	});
	$('#b_gallery_prev_pic').click(function(){ $('#b_gallery_thumbs > img.selected').prev().click(); });
	$('#b_gallery_next_pic').click(function(){ $('#b_gallery_thumbs > img.selected').next().click(); });
	$(document).keydown(function(e){
		// see http://ejohn.org/blog/keypress-in-safari-31/ on why keypress is bad
		c = e.which;
		//188 is the comma and the less than sign. 37 is the left arrow.
		//190 is the period and the gt sign. 39 is the right arrow.
		if (c == 188 || c == 37) { $('#b_gallery_prev_pic').click(); }
		if (c == 190 || c == 39) { $('#b_gallery_next_pic').click(); }
	});
//	this breaks FF on back/forward buttons
//	$('#b_gallery_images_container :first-child').bind("load", function (){ $('#b_gallery_thumbs img:first-child').click(); });
//	replaced with this, which is not as pretty on first load.. but works!
	$('#b_gallery_thumbs img:first-child').click();
	$('#b_gallery_images_container :first-child').bind("load", function (){
		fixGalleryImageSize();
	})
	
}
function make_scroll_area(ub, db, sa) { //up button, down button, scroll area - all jquery objects
	b_scroll_area = {
		ub:ub, //up button
		db:db, //down button
		sa:sa, //scroll area
		d:5, //speed distance can change to increase speed
		max_delta_detected:1,
		si:{}, //scroll interval
		checkButtonVisibility:function(){
			var totalHeight = 0;
			sa.children().each(function(){totalHeight += $(this).outerHeight()});
//			alert( totalHeight + ' ? ' +sa.height() );
			if ( totalHeight <= sa.height() ){
				this.ub.hide();
				this.db.hide();
			} else {
				this.ub.show();
				this.db.show();
			}
		},
		stopscrolling:function() { this.sa.stop(); clearInterval(this.si) },
		startscrolling:function(direction) {
			me = this;
			me.stopscrolling();
			me.si = setInterval( function() { me.sa.stop().animate({ scrollTop : me.sa.scrollTop() + direction*me.d }, 200, 'linear'); }, 200);
		},
		init:function() {
			var me = this;
			me.ub
				.hover( function() { me.d = 50; me.startscrolling(-1) }, function() { me.stopscrolling(); } )
				.mousedown( function() { me.d = 150; } )
				.mouseup( function() { me.d = 50; } )
			me.db
				.hover( function() { me.d = 50; me.startscrolling(1) }, function() { me.stopscrolling(); } )
				.mousedown( function() { me.d = 150; } )
				.mouseup( function() { me.d = 50; } )
			me.sa.mousewheel(function(event, delta) {
				var dir = delta > 0 ? 'Up' : 'Down';
				
				if ( Math.abs(delta) > 15 || me.max_delta_detected > 15) { 
					if ( Math.abs(delta) < 15) {
						me.sa.scrollTop( me.sa.scrollTop() - delta*5 );
					} else {
						me.sa.scrollTop( me.sa.scrollTop() - delta );
					}
					me.max_delta_detected = (Math.abs(delta)>me.max_delta_detected?Math.abs(delta):me.max_delta_detected);
				} else {
					me.sa.scrollTop( me.sa.scrollTop() - delta*15 );
				}
				
				/*
				me.si = setInterval( function() { me.sa.stop().animate({ scrollTop : me.sa.scrollTop() + direction*me.d }, 200, 'linear'); }, 200);
				if (delta > 0) me.startscrolling(1);
				else me.startscrolling(-1);
				vel = Math.abs(delta*10); //can this line be removed? - DFC 10/4/2010
				*/
				
				return false;
			});
		}
	}
	b_scroll_area.init();
}

function make_feature_gallery() {

	var only_one_image = true;
	if ($('#b_feature_images img').size() > 1) {
		var only_one_image = false;
		$(document).keydown(function(e){
			// see http://ejohn.org/blog/keypress-in-safari-31/ on why keypress is bad
			c = e.which;
			//188 is the comma and the less than sign. 37 is the left arrow.
			//190 is the period and the gt sign. 39 is the right arrow.
			if (c == 188 || c == 37) $('#b_feature_left_button').mouseenter().click().mouseleave();
			if (c == 190 || c == 39) $('#b_feature_right_button').mouseenter().click().mouseleave();
		});
	}

	var only_two_images = false;
	if ( $('#b_feature_images img').size() == 2 ) {
		only_two_images = true;
		$('#b_feature_images').append( $('#b_feature_images').html() );
	}
	
	feature_gallery = {
		transitioning:false,
		current_image_number:0,
		number_of_images:$('#b_feature_images img').size(),
		prev_button:$('#b_feature_left_button'),
		next_button:$('#b_feature_right_button'),
		all_images:$('#b_feature_images img'),
		get_prev_image_number: function() { return (this.current_image_number==0?this.number_of_images-1:this.current_image_number-1) },
		get_next_image_number: function() { return ( this.current_image_number+1)%this.number_of_images },
		get_current_image: function() { return this.all_images.eq(this.current_image_number) },
		get_prev_image: function() { return this.all_images.eq(this.get_prev_image_number() ) },
		get_next_image: function() { return this.all_images.eq(this.get_next_image_number() ) },
		ww: function() { return $(window).width() },
//		wh: function() { return $(window).height() },
		aa_interval:{},
		update_numbers:function() {
			if (only_one_image) {
				$('#feature_control').hide();
			} else if (only_two_images) {
				$('#b_feature_current').html( this.current_image_number%2+1 );
				$('#b_feature_total').html(2);
			} else {
				$('#b_feature_current').html( this.current_image_number+1 );
				$('#b_feature_total').html( this.number_of_images );
			}
		},
		hide_all_images: function() {
			this.all_images.hide();
		},
		show_image: function(direction) {
			fg = this;
			if (this.transitioning == true) return false;
			this.transitioning = true;
			
			//update current image number based on direction
			if (direction == -1) this.current_image_number = this.get_prev_image_number();
			else if (direction == 1) this.current_image_number = this.get_next_image_number();
			else if (direction == 0) this.transitioning = false;
			this.update_numbers(); //on the ui

			var ww = this.ww();
			var ci = this.get_current_image();
			var pi = this.get_prev_image();
			var ni = this.get_next_image();
			var side_image_offset = ( ww<1000 ? 0 : 15);

			this.all_images.each( function(i,image){
				if ( i != fg.current_image_number && i != fg.get_prev_image_number() && i != fg.get_next_image_number() ) {
					$(image).hide();
				}
				//in case resizing and fliping at the same time!
				if (nh) { $(image).css({height:nh}) }
				if (nw) { $(image).css({width:nw}) }
			})

			if (direction == -1) pi.css({left:-( ww-ci.width()>0?ww-ci.width():0 )/2-ci.width(), 'opacity':0.20});
			if (direction == 1) ni.css({left:(ww-ci.width())/2+ci.width(), 'opacity':0.20});
			//alert('pause for testing');

			if ( this.number_of_images>1 ) {
				$('#b_feature_caption').fadeOut();
				
				ci.show().stop().css({zIndex:'2'}).animate({left:0, 'opacity':0.85}, 1900, 'swing', function() {
					ci.show().stop().animate({'opacity':1}, 800);
					fg.loadCaption(fg.current_image_number);
					fg.transitioning = false;
				});
				pi.show().stop().css({zIndex:'1'}).animate({left:-( ww-ci.width()>0?ww-ci.width():0 )/2-ci.width()+side_image_offset, 'opacity':0.20}, 1900);
				ni.show().stop().css({zIndex:'1'}).animate({left:(ww-ci.width())/2+ci.width()-side_image_offset, 'opacity':0.20}, 1900);

				ci.unbind('click mouseenter mouseleave');
				this.get_prev_image().css({cursor:'pointer'}).unbind('click').click( function() { fg.prev_button.click(); return false; } );
				this.get_next_image().css({cursor:'pointer'}).unbind('click').click( function() { fg.next_button.click(); return false; } );
				this.get_prev_image().css({cursor:'pointer'}).unbind('mouseenter').mouseenter( function() { fg.prev_button.mouseenter() });
				this.get_prev_image().css({cursor:'pointer'}).unbind('mouseleave').mouseleave( function() { fg.prev_button.mouseleave() });
				this.get_next_image().css({cursor:'pointer'}).unbind('mouseenter').mouseenter( function() { fg.next_button.mouseenter() });
				this.get_next_image().css({cursor:'pointer'}).unbind('mouseleave').mouseleave( function() { fg.next_button.mouseleave() });
			}
		},
		loadCaption:function(i) {
			fg = this;
			$('#b_feature_caption').fadeIn().text(feature_captions[i]);
			if (feature_links[i] != '') {
				$('#b_feature_caption').css('cursor','pointer').click(function(){ window.location = feature_links[i] });
				fg.get_current_image().css('cursor','pointer').click(function(){ window.location = feature_links[i] });
			} else {
				$('#b_feature_caption').css('cursor','default').click(function(){});
				fg.get_current_image().css('cursor','default').click(function(){});
			}
		},
		restartAutoAdvance:function() {
			clearInterval(this.aa_interval);
			this.startAutoAdvance();
		},
		startAutoAdvance:function() {
			fg = this;
			this.aa_interval = setInterval( function() { fg.next_button.click()}, 6000 );
		},
		init: function() {
			fg = this;
			this.all_images.css({position:'absolute'}); //'z-index':100
			this.update_numbers();
			this.next_button.css({cursor:'pointer'});
			this.prev_button.css({cursor:'pointer'});
			this.show_image(0);
			this.loadCaption(0);
			
			this.prev_button.click( function(){ fg.restartAutoAdvance(); fg.show_image(-1); })
			this.next_button.click( function(){ fg.restartAutoAdvance(); fg.show_image(1); })

			this.prev_button.hover(
				function () { if (fg.transitioning == true) return; fg.get_prev_image().css({opacity:0.35}); fg.prev_button.stop().css({opacity:1.0}) },
				function () { fg.get_prev_image().css({opacity:0.20}); fg.prev_button.stop().animate({opacity:0.35}) }
			);
			this.next_button.hover(
				function () { if (fg.transitioning == true) return; fg.get_next_image().css({opacity:0.35}); fg.next_button.stop().css({opacity:1.0}) },
				function () { fg.get_next_image().css({opacity:0.20}); fg.next_button.stop().animate({opacity:0.35}) }
			);
			this.startAutoAdvance();
		}
	}
	feature_gallery.init();
}

$(window).resize(function() {

	//remove verticle scrollbars for resize calculations
	$('body').css( {'overflow-x':'hidden','overflow-y':'hidden'} );

	var ww = $(window).width();		//window width
	var wh = $(window).height();	//window height
	var w_inc = 130; //should grow in additions of 130px as needed

	//calculate
	var pw = ww - (100+100); //potential image area width, should not be less than 900 + 100 for extra padding when enlarging
	var ph = wh - (300+100); //potential image area height, should not be less than 400 + 100 for extra padding when enlarging
	var pa = (pw/ph); //potential aspect ratio
	var ia = (900/400);
	var mt = 25; //margin top
	var d = 200; if (b_first_resize) { d = 0; b_first_resize = false; }

	if ( ph>(400) && pw>(900) ) {
		if (pa>ia) {
			nh = ph;
			nw = nh*ia;
		} else {
			nw = pw;
			nh = nw/ia;
		}

		//snap to nearest 130px extention after 900px
		nw = nw - ( (nw-900)%w_inc )
		nh = nw/ia;

	} else {
		nw = 900;
		nh = 400;
	}
	var mt = (wh-(nh+230))/2; if (mt<25) mt = 25;

	//update
	$('#b_top').css( { marginTop:mt} );
	$('#b_top, #b_middle_2, #b_bottom').stop().animate( {width:nw}, d, function() {
		if (page_type == 'regular' || page_type == 'blog') {
			$('#b_bottom').css({'overflow':'visible'});
		}																		
	});
	$('#b_ground_1').css( {width:nw} );
	$('#b_middle_1').stop().animate( {width:nw, height:nh}, d, function() {
		if (page_type == 'feature') {
			$('#b_middle_1').css( {overflow:'visible'} )
		}
		if (page_type == 'gallery') {
			fixGalleryImageSize();
			setTimeout('fixGalleryImageSize()',50);
			setTimeout('fixGalleryImageSize()',500);
		}
	});

	//FOR FEATURE
	if (page_type == 'feature') {
		var side_image_offset = ( ww<1000 ? 0 : 15);
		feature_gallery.get_current_image().stop().animate( {width:nw, height:nh, left:0, 'opacity':1}, d );
		if ( feature_gallery.number_of_images>1 ) {
			feature_gallery.get_prev_image().stop().animate( {width:nw, height:nh, left: -(ww-nw>0?ww-nw:0)/2-nw+side_image_offset, 'opacity':0.20 }, d );
			feature_gallery.get_next_image().stop().animate( {width:nw, height:nh, left: (ww-nw)/2+nw-side_image_offset, 'opacity':0.20 }, d );
		}
		//$('#b_feature_images img:not(:visible)').css( {width:nw, height:nh} ); // may not needed b/c height also updated when images are switched.
		feature_gallery.transitioning = false;
	}

	//FOR REGULAR PAGE AND OVERVIEW PAGE
	if (page_type == 'regular' | page_type == 'overview' | page_type == 'blog' ) {
		$('#b_right_col').css( {width:nw-390, height:nh} );
		
		

		if (document.getElementById('b_right_col_in')) {
			//fix houzz gallery resize
			$('.blog_post_container>div').each( function(i,e) {
				if ($(e).attr('id').substring(0, 6) == 'hzroot') {
					var hzid = $(e).attr('id').substring(6)
					var hzgallery = $(e).find('iframe');
					var hzsrc = hzgallery.attr('src');
					var iframe_css_width = nw-390;
					//only allowed values for iframe are 620x490,480x385,380x310,300x275,240x205,200x175,160x145,120x115
					var iframe_width = 120;
					var iframe_height = 115;
					if (iframe_css_width >= 160) {iframe_width=160; iframe_height=145; }
					if (iframe_css_width >= 200) {iframe_width=200; iframe_height=175; } 
					if (iframe_css_width >= 240) {iframe_width=240; iframe_height=205; } 
					if (iframe_css_width >= 300) {iframe_width=300; iframe_height=275; } 
					if (iframe_css_width >= 380) {iframe_width=380; iframe_height=310; } 
					if (iframe_css_width >= 480) {iframe_width=480; iframe_height=385; } 
					if (iframe_css_width >= 620) {iframe_width=620; iframe_height=490; }
					hzgallery.css( {width:iframe_css_width, height:iframe_height,overflow:'hidden'} );
					//var hz_new_src = hzsrc.replace(/\bwidth=[0-9]+\b/, 'width='+iframe_width.toString() );
					var hz_new_src = hzsrc.replace(/\bwidth=[0-9]+\b/, 'width='+iframe_width );
					hzgallery.attr('src',hz_new_src);
				};
			});
		}
		
		
		
		
		if (document.getElementById('b_right_col_in')) {
			$('#b_right_col_in').css( {width:nw-390} );
			$('#b_middle_1').css({overflow:'visible'});
			/*
				$('#b_right_col').css({overflowY:'scroll',right:-25, paddingRight:25});
			*/
		}
		
		b_scroll_area.checkButtonVisibility();		
	}

	//FOR OVERVIEW
	if (page_type == 'overview') {
		$('#b_middle_1').css( {backgroundColor:'#F0F0F0'} );
		var oi_w; //overview image width
		var oi_m = 10; //overview image margin
		var oi_n_per_line = 7; //default
		var oi_n = 1; //the number of images in the largest set
		//find the length of the largest set
		
		$('.b_overview_set').each( function(i,thisSet){
			if ($(thisSet).children('a').size() > oi_n) { oi_n = $(thisSet).children('a').size(); }
		})
		
		
		//determine width of images based on the largest set
		
		/* OLD FORMULA THAT SHOWS NICE LARGE IMAGES
		if (oi_n<=2) {
			oi_w = Math.floor(nh-80); //80px for caption and header
			oi_n_per_line = Math.floor(oi_n);
		} else if (oi_n<7) {
			oi_w = ( nw-(oi_n-1)*10 )/oi_n;
			oi_n_per_line = Math.floor( (nw+10)/oi_w );
		} else {
			oi_w = 120;
			oi_n_per_line = (nw+10)/130;
		} */
		
		$('.b_overview_set').each( function(i,thisSet){
			if ($(thisSet).children('a').size() > oi_n) { oi_n = $(thisSet).children('a').size(); }
			oi_n = $(thisSet).children('a').size();
					
			//NEW FORMULA
			if (oi_n<7) {
				if (oi_n<=4) { oi_n2 = 4; } else { oi_n2 = oi_n; }
				oi_w = ( nw-(oi_n2-1)*10 )/oi_n2;
				oi_n_per_line = Math.floor( (nw+10)/oi_w );
			} else {
				oi_w = 120;
				oi_n_per_line = (nw+10)/130;
			}
			
			$('#b_middle_1').css({overflow:'hidden'})
			$(thisSet).children('a').css({marginRight:10, width:oi_w, height:oi_w+40});
			$(thisSet).children('a').children('img').css({width:oi_w, height:oi_w});
			$(thisSet).children('a:nth-child('+oi_n_per_line+'n)').css({marginRight:0}); //,opacity:.5
		});
/*		
		//for each set
		$('.b_overview_set').each( function(i,thisSet){
			$('#b_middle_1').css({overflow:'hidden'})
			$(thisSet).children('a').css({marginRight:10, width:oi_w, height:oi_w+40});
			$(thisSet).children('a').children('img').css({width:oi_w, height:oi_w});
			$(thisSet).children('a:nth-child('+oi_n_per_line+'n)').css({marginRight:0}); //,opacity:.5
		})
		
*/
		
		
	}

	//FOR GALLERY
	$('#b_gallery_right').stop().animate({width:nw-300, height:nh});
//	$('#b_gallery_right img').stop().animate({width:nh*(3/2), height:nh}); //reall old way
//	$('#b_gallery_right img').stop().animate({width:nw-300, height:(nw-300)*2/3, marginTop:nh-(nw-300)*2/3 }); // old way
//	new way
	if (page_type == 'gallery') {
		//fixGalleryImageSize();
		/*
		ogiw = $('#b_gallery_right img').width(); //original gallery image width
		ogih = $('#b_gallery_right img').height(); //original gallery image width
		*/
		/*
		if ( ogiw == 860 && ogih == 515 ) {
			alert('test 01');
			$('#b_gallery_right img').stop().animate({width:nw-300, height:(nw-300)*2/3, marginTop:nh-(nw-300)*2/3 });
		} else {
			alert('test 02');
			$('#b_gallery_right img').stop().animate({width:'auto', height:'100%'});
		}
		*/
	}





	$('#b_gallery_left').stop().animate({height:nh});

	//no longer first resize, duration can be > 0.
	b_first_resize = false;

	//put body scroll bars back as needed
	$('body').css( {'overflow-x':'hidden','overflow-y':'auto'} );


});





function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

