function Bind(sel, ev, func) {$(sel).live(ev, func);}
function FullQuery(q) {var r = {};if(!q) q = CurrentSearch();if(!q) return new Array(); q = q.replace(/^\?/,'').replace(/\&$/,'');$.each(q.split('&'), function(){r[this.split('=')[0]] = this.split('=')[1];});return r;};
function CurrentSearch() {var s = GetMetaData($('.searchquery'), location.search);if(!s || s == undefined)return false;return s;}
function GetMetaData(el, fallback) {el = $(el);if(typeof fallback == 'undefined')fallback = false;if(el.length == 0)return fallback;var h = $.trim(el.html());if(h.slice(0, 4) == '<!--')h = h.slice(4);if(h.slice(-3) == '-->')h = h.slice(0, -3);return $.trim(h);}
function FindMetaArray(el) {var tmp = el.find('.meta');if(tmp.length == 0) tmp = el; return FullQuery(GetMetaData(tmp));}
function setCookie(name,value, expires) {
	if(!expires) expires = 'Wed, 1 Jan 2020 00:00:00 UTC';
	if(location.host.indexOf('.') == -1 || location.host.indexOf('www.') == 0)
		document.cookie = name+'='+value+'; expires='+expires+'; path=/';
	else
		document.cookie = name+'='+value+'; expires='+expires+'; domain='+location.host+'; path=/';
}
function getCookie(name) {
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function deleteCookie(name) {
	setCookie(name,'','Sat, 1 Jan 2000 00:00:00 UTC');
}

jQuery.extend( jQuery.easing, {easeout: function (x, t, b, c, d) {return -c *(t/=d)*(t-2) + b;} });
var IE = $.browser.msie;
var IE6 = IE && /MSIE 6/.test(navigator.userAgent);
var IE8 = IE && /MSIE 8/.test(navigator.userAgent);
var DomReady = false;

$(document).ready(function () {	
	DomReady = true;
	var q = FullQuery();
	
	$('#nav li').hover(
				function(){$(this).addClass('hover');},
				function(){$(this).removeClass('hover');}
	);
		
		$('#refinements .refinable .hidden dd').hide();
		$('#refinements .refinable dt').click(function() { 
			var me = $(this);
			if(me.parent('dl').hasClass('hidden')) {
				$(this).nextUntil('dt').each(function() {
					if (this.className == 'collapsed') return false;
					else $(this).slideDown(250);
				});
			}
			else {				
				$(this).nextUntil('dt').each(function() {
					if (this.className == 'collapsed') return false;
					else $(this).slideUp(250);				
				});
			}
			var _this = $(this);
			setTimeout(function() { 
				$(_this).parent('dl').toggleClass('hidden'); 
			},150);
		});

		$('#refinements .show-all').click(function() {
			var me = $(this);
			me.parent('dd').next('dd').slideDown().removeClass('collapsed');
			me.remove();				
		});
		
		$('#search .textbox, .large-search .textbox').bind({
				focus: function() {
						if ($(this).val() == this.title) {$(this).val('')}
				},
				blur: function() {
						if ($(this).val() == '') {$(this).val(this.title)}
				}						
		});
																							
		$('#search .button').click(function() {
			var searchbox = $(this).prev('input');
			if (searchbox.val() == 'Search keyword/Plan ID') searchbox.val('');
		});

		if (document.getElementById('featured-slider')) {
				var previous = $('#featured-slider .previous');
				var next = $('#featured-slider .next');
				var itemCount = $('#featured-slider li').length-3;
				var animating = false;
				var distance = 180;
				var limit = (itemCount)*distance*-1;
				
				$('#featured-slider .next').click(function() {
						if (animating) return false;
						animating = true;
					var leftpos = parseInt($('#featured-slider li').css('left'))
						if ( leftpos < limit+distance ) {
								if (IE && !IE8) next.hide();
								else next.fadeOut();
						}
						if (IE && !IE8) previous.show();
						else previous.fadeIn();
						$('#featured-slider li').animate({left:'-=' + distance},400);
						setTimeout(function() {animating = false},400);
						return false;
				});
		
				$('#featured-slider .previous').click(function() {
						if (animating) return false;
						animating = true;
						var leftpos = parseInt($('#featured-slider li').css('left'))
						if ( leftpos == distance*-1 ) {
								if (IE && !IE8) previous.hide();
								else previous.fadeOut();						
						}
						if (IE && !IE8) next.show();
						else next.fadeIn();
						$('#featured-slider li').animate({left:'+=' + distance},400);
						setTimeout(function() {animating = false},750);
						return false;
				});
		}
						
		$('.reverselink').click(function() {
				$('.detail-thumbs IMG, .main-photo img, #house-plans-images IMG').toggleClass('flipx');
				if($.browser.mozilla && $('.detail-thumbs IMG').css('-moz-transform').length == 0 || $.browser.safari && $('.summary .image IMG').css('-webkit-transform').length == 0) {
						if(!window.flippedImages) {
								window.flippedImages = new Array();
							$('.summary .image IMG, .summary .thumbs IMG, .floorplans .image IMG, .floorplans .thumbs IMG, #sb-player').each(function() {
										var i = $(this), j=i[0] ,c = $('<canvas></canvas>'), x = c[0].getContext('2d');
										c[0].width = j.width;
										c[0].height = j.height;
										i.hide().after(c);
										x.scale(-1,1);
										x.drawImage(j, -1 * j.width, 0, j.width, j.height);
										window.flippedImages.push(i);
								});
						} else {
								jQuery.each(window.flippedImages, function(i,n) {
										n.show().next().remove();
								});
								window.flippedImages = false;
						}
				}
				return false;
		});		

		var printWindow = false;
		Bind('.printpage', 'click', function() {
				if(printWindow) return false;
				var a = new Array(
						'<div class="printtitle">'+$('#plan-nav h3').html()+': '+$('#col1 H1').html()+'</div>',
						'<div class="image firstimage"><img src="'+$('#col1 .main-photo img').attr('src').replace(/-MD\./, '-LG.')+'"/></div>',
						'<div class="summary">'+$('#quick-facts').html()+$('.pricing').html()+$('.summary').html()+'</div>',
						'<div class="image">');
				if($('#house-plans-images li').length == 0)
						a.push('<img src="'+$('#house-plans-images .col2 IMG').attr('src').replace(/-MD\./, '-LG.')+'"/>');
				else $('#house-plans-images .thumbs li IMG').each(function() {
						a.push('<img src="'+$(this).attr('src').replace(/-SM\./, '-LG.')+'"/>');
						});
				a.push('</div><div class="fullspecs">'+$('.complete-info').html().replace(/<br>/ig, '<hr/>')+'</div>');
				a.push('<div class="printfooter">'+$('.support p').html()+'</div>');
		
			PrintContent(a.join(''), {css:['/style.css?frn=local&debug=nocache,frommaster', '/print.css?frn=local&debug=nocache,frommaster'], print:true, preprocess:function(host) {
								host.attr("id","detailspage"); 
								host.find('*:hidden, .summary .actions, .summary .thumbs, .summary .links, .summary .buttons, .summary .button, .fullspecs .right, H1, .fullspecs .bottom .price:last').remove();
								host.find('HR').after('<br/>').remove();
						}
				});
				return false;
		});
		Bind('.printone', 'click', function() {
				PrintContent('<img src="'+$('#house-plans-images .col2 IMG').attr('src').replace(/-MD\./, '-LG.')+'"/>', {print:true});
				return false;
		});
		Bind('.printall', 'click', function() {
				var a = new Array();
				a.push('<style>@media print {IMG {page-break-after:always} }</style>');
				jQuery.map($('#house-plans-images IMG'), function(n,i) {
						a.push('<img src="'+$(n).attr('src').replace(/-SM\./, '-LG.').replace(/-MD\./, '-LG.')+'"/>');
				});
				PrintContent(a.join(''), {print:true});
				return false;
		});
		var PrintContent = function(what, options) {
				printWindow = window.open('','printerFriendly','toolbar=0,location=0,directories=1,menubar=1,scrollbars=1,resizable=1'); 
				var host = location.host;
				
				setTimeout(function() {
						var doc = printWindow.document;
						doc.open('text/html');
						doc.write('<html><head><title>BuilderHousePlans.com</title></head><body></body></html>');
						var b = $("body", doc);
						if(options && options.css) $.each(options.css, function(i, n) {
								var f = doc.createElement("link");
								f.setAttribute("rel", "stylesheet");
								f.setAttribute("type", "text/css");
								if(!n.match(/^http/i))
										n = 'http://'+host+'/'+n;
								f.setAttribute("href", n);
								doc.getElementsByTagName('head')[0].appendChild(f);
						});
						b.append(what); 
						if(options && options.preprocess) options.preprocess(b);
						printWindow.document.close(); 
						printWindow.focus();
						if(options && options.print) 
										try {
												setTimeout(function() {printWindow.print(); 
														printWindow.close(); 
														printWindow = false;}, 2000);
										} catch(e) {log(e);}
				}, 500);
		}
 
				Bind('A[href$=#estimate], #details #col2 a.estimate', 'click', function() {
				var update = function() {
						var v = popup.find('#estimatorStateSelect').val();
						var q = popup.find('#estimatorQualitySelect').val();
						setSession('estimatorStateSelect', popup.find('#estimatorStateSelect option:selected').text());
						setSession('estimatorQualitySelect', q);
						var cost = estimatorCosts[parseInt(v) - 1][parseInt(q) - 1];
						var m = FindMetaArray($('#estimator-meta'));
						cost = Math.floor((cost * parseInt(m['size'])) / 1000);
						UpdateCount($('#estimatorCount'), cost, 1000);
				};
		
				var popup = $('#estimatorpopup');
				if (!popup.data('bound')) {
						var states = popup.find('#estimatorStateSelect');
						var html = new Array();
						var v = getSession('estimatorStateSelect');
						var q = getSession('estimatorQualitySelect');
						for (var x in estimatorStates)
								html.push('<option value="' + estimatorStates[x] + '" '+(v==x?'selected':'')+'>' + x + '</option>');
						states.html(html.join(''));
						popup.data('bound', true);
						popup.find('SELECT').change(function() {
								update();
						});
						popup.find('.close').click(function() {
								popup.hide();
								RemoveOverlay();
						});
						if(q) popup.find('#estimatorQualitySelect').val(q);
				}
		
				popup.css({ position: 'absolute', top: -100, left: -500, zIndex: 200 }).show();
		
				var ww = $(window).width();
				var wh = $(window).height();
				var dl = $(document).scrollLeft();
				var dt = $(document).scrollTop();
				var ew = popup.width();
				var eh = popup.height();
				var left = (ww - ew) / 2 + dl;
				var top = (wh - eh) / 2 + dt;
				AddOverlay();
				popup.css({ top: top, left: left });
				if(IE6) $('SELECT', popup).css({visibility:'visible'});
				update();
				return false;
		});
		
		if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
				try {
						document.execCommand("BackgroundImageCache", false, true);
				} catch(err) {}
		}		
		
		var AddOverlay = function() {
				var mask = $('#overlaymask');
				if (mask.is(':visible'))
						return;
				if (mask.length == 0)
						mask = $('<div id="overlaymask" style="display:none"></div>').appendTo($('body'));
				var w = $(window).width();
				var h = $(window).height();
				var dw = $(document).width();
				var dh = $(document).height();
				if (dh > h) h = dh;
				if (dw > w) w = dw;
				if (IE6 || IE8) w -= 22;
				if (IE6) $('SELECT').css({ visibility: 'hidden' });
				$('object, embed').css({ visibility: 'hidden' });
				mask.css({ position: 'absolute', opacity: .0, backgroundColor: '#333', top: 0, left: 0, width: w, height: h, display: 'block', zIndex: 100 }).animate({ opacity: .3 }, 500);
				return this;
		}
		var RemoveOverlay = function() {
				$('#overlaymask').animate({opacity:.0}, 300, function() {$(this).hide();$('object, embed, SELECT').css({visibility:'visible'});});
				return this;
		}
			
		$('#sortby').change(function() {
				var me = $(this);
				trackEvent('Sort', me.find(':selected').text());
				q['sort'] = me.val();
				var u = '/default.aspx?';
				for(x in q)
						if(x && q[x] && q[x].length > 0)
								u += x+'='+q[x]+'&';
				u = u.substring(0, u.length-1);
				document.location.href = u;
		});
		
		$('#paging').change(function() {
				var me = $(this);
				trackEvent('Results Per Page', me.find(':selected').text());
				q['pz'] = me.val();
				if(q['pz'] == '16') q['pz'] = '';
				var u = '/default.aspx?';
				for(x in q)
						if(x && q[x] && q[x].length > 0)
								u += x+'='+q[x]+'&';
				u = u.substring(0, u.length-1);
				document.location.href = u;
		});			

		var UpdateCount = function(target, count, duration) {
				if(!duration) duration = 1000;
				var c = count;
				if(typeof count == 'string') {
						c = parseInt(count.replace(',', ''));
				}
				else if(count >= 1000) {
						count = count+'';
						count = count.substring(0, count.length - 3) + ',' + count.substring(count.length - 3);
				}
				var start = target.text();
				if(start.length > 0)
						start = parseInt(start.replace(',', ''));
				else 
						start = 0;
				
				jQuery({inc:start}).animate({inc:c}, {
						duration: duration,
						step: function() {
								var i = Math.round(this.inc);
								if(i<1000)
										target.text(i);
								else {
										i = i+'';
										target.text(i.substring(0, i.length-3)+','+i.substring(i.length-3));
								}
						},
						complete:function() {
								target.text(count);
						},
						easing:'easeout'
				});
		}		

		function setSession(name, value) {
				if(!window.name) window.name = '';
				var q = FullQuery(window.name);
				q[name] = encodeURIComponent(value);
				var tmp = new Array();
				for(var i in q)
						tmp.push(i+'='+q[i]);
				window.name = tmp.join('&');
		}

		function getSession(name) {
				if(!window.name)
						return null;
				return decodeURIComponent(FullQuery(window.name)[name]);
		}
												
		if($('.quicksearch').length > 0)
			setTimeout(function() {
					GetMatchCount($('.quicksearch'));
					if(IE) {
							var qs = $('.quicksearch FORM');
							qs.bind('click', function() { setTimeout(function() {GetMatchCount(qs);}, 200); });
							qs.find('INPUT').bind('keypress', function() { setTimeout(function() {GetMatchCount(qs);}, 200); });
							$('.quicksearch FORM').bind('submit', function() {SubmitQuickSearch($('.quicksearch FORM'));return false;});
					}
		}, 200);
		
		var FormToQuery = function(form, getFriendly) {
				var q = new Array();
				var me = $(form);
				var friendly = false;
				
				var pt = me.find('#ptype').val();
				var s = pt.split('|');
				if(s.length > 1) {
						pt = s[0];
						if(getFriendly) friendly = '/'+s[1];
				}
				
				var ps = me.find('#astyle').val();
				var s = ps.split('|');
				if(s.length > 1) {
						ps = s[0];
						if(getFriendly && !pt) friendly = '/'+s[1];
						else friendly = false;
				}
				
				var bed = '';
				me.find('.bedrooms input:checked').each(function() {
						bed += $(this).val()+';';
				});
				var bath = '';
				me.find('.bathrooms input:checked').each(function() {
						bath += $(this).val()+';';
				});
				
				if((pt+ps+bed+bath+'').length > 0) {
						var t = '';
						if(pt && pt.length > 0) t += pt+';';
						if(ps && ps.length > 0) t += ps+';';
						if(bed && bed.length > 0) {t+= '('+bed.substring(0, bed.length-1)+');';friendly = false;}
						if(bath && bath.length > 0) {t+= '('+bath.substring(0, bath.length-1)+');';friendly = false;}
						q['type'] = t.substring(0, t.length-1);
				}
				
				var fw = me.find('#fromwidth').val();
				var tw = me.find('#towidth').val();
				var fd = me.find('#fromdepth').val();
				var td = me.find('#todepth').val();
				var fs = me.find('#fromsqft').val();
				var ts = me.find('#tosqft').val();
				
				if((fw+tw).length > 0)
						q['r.EPWID'] = fw+','+tw;
				if((fd+td).length > 0)
						q['r.EPDEP'] = fd+','+td;
				if((fs+ts).length > 0)
						q['r.FSQF'] = fs+','+ts;
				if(q.length > 1) friendly = false;
				
				var u = new Array();
				for(x in q)
						if(x && q[x] && q[x].length > 0)
								u.push(x+'='+q[x]);
		
				return friendly?friendly:u.join('&');
		}
		var UpdateCount = function(target, count, duration) {
				if(!duration) duration = 1000;
				var c = count;
				if(typeof count == 'string') {
						c = parseInt(count.replace(',', ''));
				}
				else if(count >= 1000) {
						count = count+'';
						count = count.substring(0, count.length - 3) + ',' + count.substring(count.length - 3);
				}
				var start = target.text();
				if(start.length > 0)
						start = parseInt(start.replace(',', ''));
				else 
						start = 0;
				
				jQuery({inc:start}).animate({inc:c}, {
						duration: duration,
						step: function() {
								var i = Math.round(this.inc);
								if(i<1000)
										target.text(i);
								else {
										i = i+'';
										target.text(i.substring(0, i.length-3)+','+i.substring(i.length-3));
								}
						},
						complete:function() {
								target.text(count);
						},
						easing:'easeout'
				});
		}
		var cache = new Array();		
		var GetMatchCount = function(form) {
				var key = FormToQuery(form);
				if(key && key.length > 0) key = '&'+key;
				if(typeof cache['count'+key] != 'undefined') {
						UpdateCount(form.find('#matchcount'), cache['count'+key], 500);
						return;
				}
				$.ajax({
						url:'/cms/ws.aspx?action=count'+key,
						cache:true, dataType:'json', 
						success: function(data) { 
								if(data && data.count && data.count != '') {
										cache['count'+key] = data.count;
										UpdateCount(form.find('#matchcount'), data.count, 1000);
								}
								else 
										form.find('#matchcount').text('');
						}
				});
		}
		
		Bind('.quicksearch FORM INPUT, .quicksearch FORM SELECT', 'change', function() {
				var target = $(this).parents('form');
				if(target.length > 0)
						GetMatchCount(target);
		});
		
		var SubmitQuickSearch = function(form) {
				var q = FormToQuery(form, true);
				if(q && q.match(/^\//i))
						document.location.href = q;
				else {
						if(!q || q.length == 0)
								q = 'q=';
						document.location.href = '/default.aspx?ct=r&'+q;
				}
		}
		
		Bind('.quicksearch FORM', 'submit', function() {
				SubmitQuickSearch($(this));
				return false;
		});
				 
			
		function trackEvent(cat, type, data) {
				if(typeof dsTracker != 'object') {
						if(!DomReady)
								$(function(){ trackEvent(cat, type, data); });
						else
								log('trackEvent failed: no tracker', cat, type, data);
						return;
				}
				if(typeof cat != 'string') cat = false;
				if(typeof type != 'string') type = false;
				if(typeof data != 'string') data = false;
				
				if(cat && type && data) dsTracker._trackEvent(cat, type, data);
				else if(cat && type) dsTracker._trackEvent(cat, type);
				else if(cat) dsTracker._trackEvent(cat, "true");
		}			

		Bind('#plan-results A[href*=/pid/], #plan-results A[href*=/plan-detail/]', 'click', function() {
			 var p = $(this).parents('li');
			 var meta = FindMetaArray(p);
			 var id = $.trim(meta['id']);
			 var s = CurrentSearch();
			 if(s && id)
					setCookie('pnDetails', encodeURIComponent(s) + '|' + id + '|0');
		});
		Bind('#plan-nav A[href*=/pid/], #plan-nav A[href*=/plan-detail/]', 'click', function() {
			 var p = $(this).parents('#plan-nav');
			 var meta = FindMetaArray(p);
			 var id = $.trim(meta['id']);
			 var s = $.trim(meta['pnd']);
			 if(s.length < 1 || id.length < 1) return;
			 s = decodeURIComponent(s);
			 s = s.split('|')[0];
			 setCookie('pnDetails', s + '|' + id + '|0');
		});

		if($('div#featured-plan').length > 0) {
				var el = $('div#featured-plan div#imglist').find('.meta');
				if(el && el != null && el.length > 0) {
						var data = GetMetaData(el);
						var imageInfo = data.split(';');
						if(imageInfo && imageInfo != null && imageInfo.length > 0) {
							 var idx = Math.floor(Math.random() * imageInfo.length);
							 var parts = imageInfo[idx].split(',');
							 if(parts.length > 0) $('div#featured-plan div#featured-img').html('<img alt="featured plan" src="' + $.trim(parts[0]) + '" />');
							 if(parts.length > 1) $('div#featured-plan span#featured-span').html($.trim(parts[1]));
							 if(parts.length > 2) $('div#featured-plan a#featured-link').attr('href', $.trim(parts[2]));
						}
				}
		}
});

shadowboxOpen = function() {
	var sbcontainer = $('#sb-container');
	if ($('#col1 .main-photo img').hasClass('flipx')) sbcontainer.addClass('flipx');
	else sbcontainer.removeClass('flipx')
}

function CheckAd(adfunc)
{
		var strTemp=adfunc.toString().toUpperCase();
		if ((strTemp.indexOf('BLANK AD') == -1) && (strTemp.indexOf('GOOGLE') == -1) && (strTemp.indexOf('ENGINE.GIF') == -1) && (strTemp.indexOf('BLANKHTML') == -1))
		{
				return 'ad';
		}
		else if (strTemp.indexOf('GOOGLE') > -1)
		{
				return 'google';
		}
		else
		{
				return 'blank';
		}
}
function InsertAd(adfunc,cssclass,id)
{
		switch(CheckAd(adfunc))
		{
				case 'ad':
						document.writeln('<div class="ad">');
						document.writeln('<div class="' + cssclass + '" id="' + id + '">');
						adfunc();
						break;
				case 'google':
						document.writeln('<div class="google_' + cssclass + '" id="' + id + '">');
						adfunc();
						break;
				default:
						document.writeln('<'+'!-'+'- Blank Ad Suppressed Start-'+'-'+'>');
		}		

}
function InsertAdEnd(adfunc,cssclass,id)
{
		var strTemp=adfunc.toString().toUpperCase();
		switch(CheckAd(adfunc))
		{
				case 'ad':
						document.writeln('</div></div>');
						break;
				case 'google':
						document.writeln('</div>');
						break;
				default:
						document.writeln('');
		}
}

function log(msg) {
	if (typeof console == 'undefined') return;
	else console.log(msg);
}