$(function() {
	if (navigator.appVersion.indexOf("Win")!=-1) {
		$('body').css('font-family', 'tahoma, arial');
	}
	if (navigator.userAgent.toLowerCase().indexOf('safari') != -1) {
		$('#search').css({'top': '-12px', 'padding-bottom': '3px'});
	}
	$('#vendor, #shade').hide();

	$('#slider').attr('_showing', 'false');

	$('#searchBtn').click(function() {
		if ($('#search').val() != 'Site Search - Keyword...') {
			$('#googleCse').submit();
		} else {
			alert('Please enter something to search for.');
			$('#search').focus();
		}
		return false;
	});
	$('#search').focus(function() {
		if ($(this).val() == 'Site Search - Keyword...') {
			$(this).val('');
		}
	}).blur(function() {
		if ($.trim($(this).val()) == '') {
			$(this).val('Site Search - Keyword...');
		}
	});

	$('#nav a').mouseover(function() {
		$('#slider').stop().animate({'opacity': 1,
			'left': $(this).width() + $(this).parent().position()['left'] - 19}, 300);
	}).mouseout(function() {
		$('#slider').stop().animate({'opacity': 0, 'left': -7}, 300);
	});

	$('div.dropBox').click(function() {
		hideOtherDropBoxes(this.id);
		var $this = $(this);
		if ($this.attr('_scrollclick') == 'true') {
			$this.attr('_scrollclick', 'false');
			return false;
		}
		clearTimeout($this.attr('_hider'));
		var id = '#' + this.id;
		if ($this.attr('_showing') == 'true') {
			$this.attr({'_showing': 'false', '_overCount': 0});
			$(id + ' div.dropList div.dropListBody').animate({'height': 0}, 250);
			$(id + ' div.dropList').animate({'top': 19, 'height': 0}, 250);
		} else {
			var height = $(id + ' ul').height();
			if (height > 296) height = 296;
			$this.attr('_showing', 'true');
			$(id + ' div.dropListBody').css('height', 0).animate({'height': height}, 250);
			$(id + ' div.dropList').animate({'top': -((height) / 2), 'height': height + 43}, 250, checkScrolling);
		}
		return false;
	}).mouseover(function() {
		clearTimeout($(this).attr('_hider'));
		$(this).attr('_overCount', parseInt($(this).attr('_overCount')) + 1);
	}).mouseout(function() {
		clearTimeout($(this).attr('_hider'));
		$(this).attr('_overCount', parseInt($(this).attr('_overCount')) - 1);
		if (parseInt($(this).attr('_overCount')) <= 0) { 
			if ($(this).attr('_showing') == 'true') {
				$(this).attr('_overCount', 0);
				$(this).attr('_hider', setTimeout('hideDropBox("' + this.id + '")', 1000));
			}
		}
	}).attr({'_showing': 'false', '_overCount': 0, '_sliding': 'false'});

	$('div.dropBox div.dropListBody a').livequery('click', function() {
		var $this = $(this);
		var dropBox = $this.parents('div.dropBox');
		dropBox.attr('_id', $this.attr('_id')).addClass('filled').children('div.title').text($this.text());
		dropBox.children('div.title').attr('_title', $this.text());
		hideDropBox(dropBox.attr('id'), true);
		checkSearchBoxWidths();
		if (dropBox.attr('id') == 'state') {
			var id = $this.attr('_id');
			$('#city, #region').removeAttr('_id').removeClass('filled');
			$('#city div.title').text('Select a City/Territory');
			$('#region div.title').text('Select a Region');
			$('#region ul, #city ul').html('<li><span class="coming">Loading...</span></li>');
			$.get(baseUrl + 'search/regions_cities/' + id, function(data) {
				hideOtherDropBoxes(dropBox.attr('id'));
				var results = $(data);
				$('#citiesOfRegions').html(results.children('#citiesOfRegions').html());
				$('#city ul').html(results.children('#allCities').html()).css('top', 0);
				$('#region ul').html(results.children('#stateRegions').html()).css('top', 0);
				$('#city a.scrollUp, #region a.scrollUp').css('display', 'none');
				$('#city a.scrollDown, #region a.scrollDown').css('display', 'block');
				setTimeout(function() {
					var ul = $('#region ul');
					if (ul.children('li').size() == 1) {
						ul.children('li:first').children('a').trigger('click');
					}
				}, 50);
			});
			$('#stateTextFilter').val('Search States');
			setTimeout(function() {
				dropBox.find('li').show();
			}, 300);
			updateCategories();
		} else if (dropBox.attr('id') == 'region') {
			var id = $this.attr('_id');
			$('#city').removeAttr('_id').removeClass('filled');
			$('#city div.title').text('Select a City/Territory').removeAttr('_title');
			$('#city ul').html('<li><span class="coming">Loading...</span></li>')
				.load(baseUrl + 'search/cities/' + $('#state').attr('_id') + '/' + id, function() {
					hideOtherDropBoxes(dropBox.attr('id'));
					var ul = $(this);
					setTimeout(function() {
						if (ul.children('li').size() == 1) {
							// set the city to this one
							ul.children('li:first').children('a').trigger('click');
						}
					}, 50);
				}).css('top', 0);
			$('#city a.scrollUp').css('display', 'none');
			$('#city a.scrollDown').css('display', 'block');
			$this.trigger('mouseout');
			updateCategories();

		} else if (dropBox.attr('id') == 'linkStates') {
			document.location = baseUrl + 'links/' + dropBox.attr('_id') + '.html';
		} else if (dropBox.attr('id') == 'category') {
			// do nothing, just allow default behavior
		} else {
			// default behavior, just update related hidden form value if found
			var $input = $('#' + dropBox.attr('id').substr(0, dropBox.attr('id').length - 3));
			if ($input.size() > 0) {
				$input.val($this.attr('_id'));
			}
			dropBox.trigger('change');
			return false;
		}
		checkIndicator();
		dropBox.trigger('change');
		return false;
	});
	$('#stateTextFilter').click(function() {
		var $this = $(this);
		if ($.trim($this.val()) == 'Search States') {
			$this.val('');
		}
		$this.select();
		var state = $('#state');
		state.attr('_overcount', parseInt(state.attr('_overcount')) + 1);
		return false;
	}).blur(function() {
		var $this = $(this);
		if ($.trim($this.val()) == '') {
			$this.val('Search States');
		}
		setTimeout(function() {
			$('#state').attr({'_overcount': 0, '_showing': true}).trigger('mouseout');
		}, 200);
	}).keyup(stateKeyPress)
	.keypress(function(event) {
		if (event.keyCode == '13') { 
			return false; 
		}
	});
	$('#citiesOfRegions a').livequery('click', function() {
		var popup = $(this).parents('div.cityPopup');
		popup.trigger('mouseout');
		$('#region div.dropListBody a[_id=' + popup.attr('id').substring(3) + ']').trigger('click');
		$('#city div.title').attr('_title', $(this).text()).html($(this).text()).parent().addClass('filled').attr('_id', $(this).attr('_id'));
		checkSearchBoxWidths();
		checkIndicator();
		tryRefresh();
		return false;
	});
	$('div.dropBox a.scrollUp').livequery(function() {
		var btn = $(this);
		btn.attr({'_scroller': 'stopped', '_accelerate': 'false'});
		btn.hover(function() {
			if (btn.attr('_scroller') == 'stopped') {
				btn.attr('_scroller', setInterval(function() {
					scrollUp(btn);
				}, 25));
			}
		}, function() {
			var btn = $(this);
			if (btn.attr('_scroller') != 'stopped') {
				clearInterval(btn.attr('_scroller'));
				btn.attr('_scroller', 'stopped');
			}
		}).mousedown(function() {
			btn.attr('_accelerate', 'true');
			btn.parent().parent().attr('_scrollclick', 'true');
			return false;
		}).mouseup(function() {
			btn.attr('_accelerate', 'false');
			return false;
		});
	}, function() {
		$(this).unbind('mouseover').unbind('mouseout');
	});
	$('div.dropBox a.scrollDown').livequery(function() {
		var btn = $(this);
		btn.attr({'_scroller': 'stopped', '_accelerate': 'false'});
		btn.hover(function() {
			if (btn.attr('_scroller') == 'stopped') {
				btn.attr('_scroller', setInterval(function() {
					scrollDown(btn);
				}, 25));
			}
		}, function() {
			var btn = $(this);
			if (btn.attr('_scroller') != 'stopped') {
				clearInterval(btn.attr('_scroller'));
				btn.attr('_scroller', 'stopped');
			}
		}).mousedown(function() {
			btn.attr('_accelerate', 'true');
			btn.parent().parent().attr('_scrollclick', 'true');
			return false;
		}).mouseup(function() {
			btn.attr('_accelerate', 'false');
			return false;
		});
	}, function() {
		$(this).unbind('mouseover').unbind('mouseout');
	});

	$('#privacyLink, a.privacyLink').click(function() {
		var width = $('#privacy').width() / 2;
		var height = $('#privacy').height() /2;
		$('#privacy').css({marginLeft: -width, marginTop: $(window).scrollTop() - height});
		showShade();
		if ($.support.opacity) {
			$('#privacy').fadeIn(300);
		} else {
			$('#privacy').css('background-color', '#dddddd').fadeIn(300, function() {
				$(this).css('background-color', 'transparent');
			});
		}
		return false;
	});
	$('#privacyClose').click(function() {
		if ($.support.opacity) {
			$('#privacy').fadeOut(300);
		} else {
			$('#privacy').css('background-color', '#dddddd').fadeOut(300);
		}
		hideShade();
		return false;
	});
	// this looks a bit awkward but IE complains if I don't do the check for nav
	$('#nav').each(function() {
		$('#pointerTray').width($('#nav').width());
	});
	$('#region div.dropList a').livequery(function() {
		var link = $(this);
		link.mouseover(function() {
			link.attr('_count', parseInt(link.attr('_count')) + 1);
			if (link.attr('_cities') == 'false') {
				// need to show cities
				var cities = $('#citiesOfRegions div#cor' + link.attr('_id'));
				var listOffset = $('#region div.dropList').position()['top'];
				var scrollOffset = link.parent().parent().position()['top'];
				var topOffset = cities.height() / 2 - 32 - listOffset - link.position()['top'] - scrollOffset;
				// check to see if it is off the screen and adjust accordingly
				if (-topOffset < listOffset) {
					var shaveOff = Math.abs(listOffset + topOffset);
					cities.children('div.popArrow').css('margin-top', -(12 + shaveOff));
					topOffset -= shaveOff;
				} else if ($('#region div.dropList').position()['top'] + 60 + (cities.height() / 2) - $('#main').height() > 0) {
					var addOn = $('#region div.dropList').position()['top'] + 60 + (cities.height() / 2) - $('#main').height();
					cities.children('div.popArrow').css('margin-top', addOn - 12);
					topOffset += addOn;
				}
				var leftOffset = $('#region').position()['left'] + 172;
				cities.css({'top': -topOffset, 'left': leftOffset});
				link.attr('_cities', 'true');
			}
		}).mouseout(function() {
			var newCount = parseInt(link.attr('_count')) - 1;
			link.attr('_count', newCount);
			if (newCount <= 0) {
				link.attr('_count', 0);
				if (link.attr('_cities') == 'true') {
					clearTimeout(link.attr('_timer'));
					link.attr('_timer', setTimeout(function() {
						checkCitiesShowing(link);
					}, 100));
				}
			}
		}).attr({'_count': 0, '_cities': 'false'});
	});
	$('#citiesOfRegions div.cityPopup').livequery(function() {
		var popup = $(this);
		popup.mouseover(function() {
			var region = $('#region div.dropList a[_id=' + $(this).attr('id').substring(3) + ']');
			region.attr('_count', parseInt(region.attr('_count')) + 1).trigger('mouseover');
		}).mouseout(function() {
			var region = $('#region div.dropList a[_id=' + $(this).attr('id').substring(3) + ']');
			region.attr('_count', parseInt(region.attr('_count')) - 1);
			clearTimeout(region.attr('_timer'));
			region.attr('_timer', setTimeout(function() {
				checkCitiesShowing(region);
			}, 100)).trigger('mouseout');
		});
	});

	var searchOpts = $('#searchOptions');
	availSearchWidth = searchOpts.width() - (searchOpts.children('h1').width() + 248);
	$('.showVideo').click(showVideo);
	$.preloadCssImages();
	$(window).resize(sizeShade);
	if (location.hash == '#v') showVideo();

	$('#homeQuotes div.quote:not(.current)').hide();
	setTimeout(swapQuotes, 15000);
	if (isMobile()) { 
		$('body').addClass('mobile'); 
		currCities = $('#allCities_m');
	}

	$('#category_m, #state_m, #region_m, #city_m').change(mobileDropChange);
});
function hideDropBox(id, forceClose) {
	var item = $('#' + id);
	if ((forceClose || parseInt(item.attr('_overCount')) == 0) && item.attr('_showing') == 'true') {
		$('#' + id + ' div.dropListBody').animate({'height': 0}, 250);
		item.attr({'_showing': 'false', '_sliding': 'false', '_overCount': 0}).children('div.dropList').animate({'top': 19, 'height': 0}, 250);
		$('#' + id + ' a.scrollDown, #' + id + ' a.scrollUp').each(function() {
			if ($(this).attr('_scroller') != 'stopped') {
				clearInterval($(this).attr('_scroller'));
				$(this).attr('_scroller', 'stopped');
			}
		});
		$('#' + id).attr('_scrollclick', 'false');
	}
}
function hideOtherDropBoxes(id) {
	$('div.dropBox').each(function() {
		if (this.id != id) {
			hideDropBox(this.id, true);
		}
	});
}
function checkScrolling() {
	var $this = $(this);
	var ul = $this.children('div.dropListBody').children('ul');
	maxHeight = 296;
	if (ul.height() > maxHeight) {
		if ($this.children('a.scrollUp').size() == 0) {
			$this.append('<a href="#" class="scrollUp"></a><a class="scrollDown"></a>');
			ul.mousewheel(function(evt, delta) {
				delta = delta * 10;
				var list = $(this);
				var top = parseInt(list.css('top'));
				var height = list.parent().height() - list.height();
				if (delta < 0) {
					if (height < top) {
						if (delta + top < height) delta = height - top;
						list.css('top', top + delta);
						list.parent().parent().children('a.scrollDown, a.scrollUp').css('display', 'block');
					} else {
						list.parent().parent().children('a.scrollDown').css('display', 'none');
					}
				} else {
					if (0 > top) {
						if (delta + top > 0) delta = -top;
						list.css('top', top + delta);
						list.parent().parent().children('a.scrollUp, a.scrollDown').css('display', 'block');
					} else {
						list.parent().parent().children('a.scrollUp').css('display', 'none');
					}
				}
				return false;
			});
		}
	} else {
		if ($this.find('a.scrollUp, a.scrollDown').length > 0) {
			$this.find('a.scrollUp, a.scrollDown').remove();
		}
	}
}
function scrollUp(btn) {
	var ul = btn.parent().children('div.dropListBody').children('ul');
	var top = parseInt(ul.css('top'));
	if (btn.attr('_accelerate') == 'true') {
		top = top + 10;
	} else {
		top = top + 2;
	}
	if (top >= 0) {
		top = 0;
		btn.css('display', 'none');
		clearInterval(btn.attr('_scroller'));
		btn.attr({'_scroller': 'stopped', '_accelerate': 'false'});
	}
	ul.css('top', top);
	$(btn).parent().children('a.scrollDown').css('display', 'block');
}
function scrollDown(btn) {
	var container = btn.parent().children('div.dropListBody');
	var containerHeight = container.height();
	var ul = container.children('ul');
	var top = parseInt(ul.css('top'));
	var ulHeight = ul.height();
	if (btn.attr('_accelerate') == 'true') {
		top = top - 10;
	} else {
		top = top - 2;
	}
	if (top <= (containerHeight - ulHeight)) {
		top = containerHeight - ulHeight;
		btn.css('display', 'none');
		clearInterval($(btn).attr('_scroller'));
		btn.attr({'_scroller': 'stopped', '_accelerate': 'false'});
	}
	ul.css('top', top);
	btn.parent().children('a.scrollUp').css('display', 'block');
}

function checkCitiesShowing(region) {
	if (parseInt(region.attr('_count')) <= 0) {
		region.attr('_count', 0);
		if (region.attr('_cities') == 'true') {
			$('#cor' + region.attr('_id')).css('top', -2000);
			region.attr('_cities', 'false');
		}
	}
}
function checkSearchBoxWidths() {
	var currWidth = 0;
	var widths = {};
	var titles = $('#searchOptions div.dropBox div.title');
	titles.each(function() {
		if ($(this).attr('_title')) {
			$(this).html($(this).attr('_title'));
		}
		currWidth += $(this).width();
		widths[$(this).parent().attr('id')] = $(this).width();
	});
	if (currWidth > availSearchWidth) {
		// find the largest one and shrink it down
		var largest = 'state';
		var maxWidth = widths.state;
		if (widths.region > maxWidth) {
			largest = 'region';
			maxWidth = widths.region;
		}
		if (widths.city > maxWidth) {
			largest = 'city';
			maxWidth = widths.city;
		}
		if (widths.category > maxWidth) {
			largest = 'category';
			maxWidth = widths.category;
		}
		// grab the appropriate title and shave off some characters
		var title = $('#' + largest + ' div.title');
		maxWidth = maxWidth - (currWidth - availSearchWidth);
		var text = title.text();
		var i = 1;
		title.html('');
		while (title.width() < maxWidth && i < text.length) {
			title.html(text.substr(0, i) + '&#8230;');
			i++;
		}
	}
}
function showShade(dontFade) {
	sizeShade();
	var fadeTime = 300;
	if (dontFade) fadeTime = 0;
	if ($.support.opacity) {
		$('#shade').fadeIn(fadeTime);
	} else {
		$('#shade').css('display', 'block');
	}
}
function sizeShade() {
	if ($(document).height() > $('body').height()) {
		$('#shade').width($(document).width()).height($(document).height());
	} else {
		$('#shade').css({'width': $('body').width(), height: $('body').height() + 10});
	}
}
function hideShade(dontFade) {
	var fadeTime = 300;
	if (dontFade) fadeTime = 0;
	if ($.support.opacity) {
		$('#shade').fadeOut(fadeTime);
	} else {
		$('#shade').css('display', 'none');
	}
}
function showVideo() {
	showShade();
	if ($.support.opacity) {
		$('#video').fadeIn(300);
	} else {
		$('#video').show();
	}
	$('#video').append('<iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/_8o9rHidnlw" frameborder="0"></iframe> <p><button id="closeVideo">Close</button></p>');
	$('#closeVideo').click(function() {
		var completed = function() {
			$('#video').html('<div id="videoBody"></div>');
			hideShade();
		}
		if ($.support.opacity) {
			$('#video').fadeOut(300, completed);
		} else {
			$('#video').hide(completed);
		}
		return false;
	});
	if (typeof pageTracker != 'undefined') {
		pageTracker._setCustomVar(1, 'popup', 'true');
		pageTracker._trackPageview('/video.html');
	}
}
var mailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
function swapQuotes() {
	var curr = $('#homeQuotes div.current');
	if (curr.length > 0) {
		var next = parseInt(curr.attr('id').substr(5)) + 1;
		if (next > 5) next = 1;
		$('#quote' + next).fadeIn(1000).addClass('current');
		curr.fadeOut(1000).removeClass('current');
		setTimeout(swapQuotes, 14000);
	}
}
function stateKeyPress(event) {
	if (event.keyCode == 13) {
		var sel = $('#state li:not(.hiding)');
		if (sel.length > 0) {
			$(this).blur();
			sel.filter(':first').find('a').click();
		}
		return;
	}
	setTimeout(function() {
		var stf = $('#stateTextFilter');
		if (stf.val() == 'Search States') {
			$('#state li.hiding').removeClass('hiding');
			return;
		}
		var val = stf.val();
		val = val.replace('Search States', '');
		stf.val(val);
		var pattern = '\\b' + val;
		var regex = new RegExp(pattern, 'i');
		$('#state').find('li').each(function() {
			var $this = $(this);
			if (regex.test($this.text())) {
				$this.removeClass('hiding').show();
			} else {
				$this.addClass('hiding').hide();
			}
		});
		var height = $('#state ul').height();
		if (height > 296) height = 296;
		stf.attr('_showing', 'true');
		$('#state div.dropListBody').css('height', 0).animate({'height': height}, 150);
		$('#state div.dropList').animate({'top': -((height) / 2), 'height': height + 43}, 150, checkScrolling);
	}, 0);
}

function isMobile() {
	return (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))||(navigator.userAgent.match(/Android/i));
}

var currCities = null;

function mobileDropChange() {
	var $this = $(this);
	if (this.id == 'state_m') {
		// load up regions and cities
		var regm = $('#region_m').val('_');
		var citm = $('#city_m').val('_');
		var id = $this.val();
		if (id != '_') {
			regm.find(':selected').text('Loading...');
			citm.find(':selected').text('Loading...');
			$.get(baseUrl + 'search/regions_cities/' + id, function(data) {
				var html = $(data);
				currCities = html.find('#allCities_m');
				regm.html(html.find('#stateRegions_m').html());
				citm.html(currCities.html());
				regm.val('_');
				citm.val('_');
			});
		} else {
			return;
		}
	} else if (this.id == 'region_m') {
		// filter cities
		var regionId = $(this).val();
		var cits = $('#city_m').val('_');
		if (regionId != '_') {
			cits.html('');
			currCities.find('option').each(function() {
				var val = $(this).attr('value');
				if (val == '_' || val == 'All-Cities' || $(this).attr('data-region') == regionId) {
					cits.append($(this).clone());
				}
			});
		} else {
			currCities.find('option').each(function() {
				var val = $(this).attr('value');
				if (val != 'All-Cities') {
					cits.append($(this).clone());
				}
			});
		}
	}
	var catm = $('#category_m').val();
	var statem = $('#state_m').val();
	var citym = $('#city_m').val();
	if (catm != '_' && statem != '_' && citym != '_') {
		// got enough info to update search, go ahead and refresh
		document.location = baseUrl + 'search/' + statem + '/' + $('#region_m').val() + '/' + citym +  '/' + catm + '.html';
	}
}
