var nextAd = new Array();
var availSearchWidth = 0;
$(function() {
	$('#category a, #city a').livequery('click', function(evt) {
		// set a timeout to ensure the other method fires off to update the title
		setTimeout(tryRefresh, 50);
	});

	$('#catOptions li').livequery('click', function(evt) {
		evt.preventDefault();
		evt.stopPropagation();
		if ($(this).hasClass('checked')) {
			if ($(this).children('ul').size() > 0) {
				// need to uncheck all of the children as well
				$(this).children('ul').children('li').removeClass('checked');
			}
			$(this).removeClass('checked');
			// check for this being a sub category
			var liParent = $(this).parents('li');
			if (liParent.size() > 0) {
				// roll through the other siblings and set the state of parent accordingly
				var anyChecked = false;
				$(this).siblings().each(function() {
					if ($(this).hasClass('checked')) {
						anyChecked = true;
					}
				});
				if (anyChecked) {
					liParent.removeClass('checked').addClass('partial');
				} else {
					liParent.removeClass('partial');
				}
			}
		} else if ($(this).hasClass('partial')) {
			// check everything now
			$(this).children('ul').children('li').addClass('checked');
			$(this).addClass('checked').removeClass('partial');
		} else {
			$(this).addClass('checked');
			var liParent = $(this).parents('li');
			if (liParent.size() > 0) {
				// roll through the other siblings and set state of parent accordingly
				var allChecked = true;
				$(this).siblings().each(function() {
					if (!$(this).hasClass('checked')) {
						allChecked = false;
					}
				});
				if (allChecked) {
					liParent.removeClass('partial').addClass('checked');
				} else {
					liParent.removeClass('checked').addClass('partial');
				}
			}
			if ($(this).children('ul').size() > 0) {
				// need to uncheck all of the children as well
				$(this).children('ul').children('li').addClass('checked');
			}
		}
		var selected = new Array();
		$('#catOptions li').each(function() {
			if ($(this).hasClass('checked') && !$(this).hasClass('parent')) {
				selected.push($(this).attr('_id'));
			}
		});
		if (selected.length > 0) {
			var validCos = 0;
			$('#companyList div.company').each(function() {
				var subcats = $(this).attr('_ids').split(',');
				var match = false;
				for (var x=0; x < selected.length; x++) {
					match = true;
					if ($.inArray(selected[x], subcats) == -1) {
						match = false;
						break;
					}
				}
				if (match) {
					$(this).slideDown(300);
					validCos++;
				} else {
					$(this).slideUp(300);
				}
			});
			if (validCos > 0) {
				$('#noResults').hide();
			}
			setTimeout(function() {
				$('#scrollWrap').jScrollPane({showArrows: true, osxStyleArrows: true, scrollbarWidth: 11, arrowSize: 17, trackTopPadding: 4});
				if (validCos == 0) {
					$('#noResults').show();
				}
			}, 300);
		} else {
			$('#noResults').hide();
			$('#companyList div.company').slideDown(300, function() {
				$('#scrollWrap').jScrollPane({showArrows: true, osxStyleArrows: true, scrollbarWidth: 11, arrowSize: 17, trackTopPadding: 4});
			});
		}
	});

	if (typeof cityId=='string' && $.trim(cityId) != '') {
		$('#city a[_id=' + cityId + ']').each(function() {
			$('#city div.title').html($(this).html()).attr('_title', $(this).html());
			$('#city').attr('_id', $(this).attr('_id')).addClass('filled');
		})
	}
	if (typeof catId=='string' && $.trim(catId) != '') {
		$('#category a[_id=' + catId + ']').each(function() {
			$('#category div.title').html($(this).html()).attr('_title', $(this).html());
			$('#category').attr('_id', $(this).attr('_id')).addClass('filled');
		})
	}
	if (typeof regionId=='string' && $.trim(regionId) != '') {
		$('#region a[_id=' + regionId + ']').each(function() {
			$('#region div.title').html($(this).html()).attr('_title', $(this).html());
			$('#region').attr('_id', $(this).attr('_id')).addClass('filled');
		});
	}
	if (typeof stateId=='string' && $.trim(stateId) != '') {
		$('#state a[_id=' + stateId + ']').each(function() {
			$('#state div.title').html($(this).html()).attr('_title', $(this).html());
			$('#state').attr('_id', $(this).attr('_id')).addClass('filled');
		});
	}
	checkSearchBoxWidths();
	checkIndicator();

	connectVendorInfoLinks();
	$('#vendorClose').click(function(evt) {
		$('#vendor').fadeOut(300);
		if ($.support.opacity) {
			$('#shade').fadeOut(300);
		} else {
			$('#shade').css('display', 'none');
		}
		return false;
	});
	if (typeof catId=='string' && $.trim(catId) != '') {
		updateAd();
	}

	$('#sort1').click(function() {
		var companies = $('#companyList div.company').remove();
		for (var x=0; x < order1.length; x++) {
			$('#companyList').append(companies.filter('#ven' + order1[x]));
		}
		connectVendorInfoLinks();
		return false;
	});
	$('#sort2').click(function() {
		var companies = $('#companyList div.company').remove();
		for (var x=0; x < order2.length; x++) {
			$('#companyList').append(companies.filter('#ven' + order2[x]));
		}
		connectVendorInfoLinks();
		return false;
	});

	$('#adLink').click(function() {
		if ($(this).attr('href') != '#') {
			getVendorInfo($(this).attr('_venid'), $(this).attr('href'));
			pageTracker._trackPageview('/ad/' + stateId + '/' + cityId + '/' + catId +  '/' + $(this).attr('_venid') + '.html');
		}
		return false;
	});
	$('#main.vendor #scrollWrap').jScrollPane({showArrows: true, osxStyleArrows: true, scrollbarWidth: 11, arrowSize: 17, trackTopPadding: 4});
	updateCategories();

});

function updateAd() {
//	if ($.trim(catId) != '') {
		var d = new Date();
		$.get(baseUrl + 'vendor/ad/' + stateId + '/' + regionId + '/' + cityId + '/' + catId + '.html?t=' + d.getTime(), function(data) {
			eval(data);
			if ($.trim(nextAd['ven_id']) != '' && nextAd['ven_id'] != '0') {
				$('#adLink').attr('_venid', nextAd['ven_id']);
				$('#adLink').attr('_adid', nextAd['ad_id']);
				$('#adLink').attr('href', baseUrl + 'vendor/' + nextAd['ven_id']);
				$('#adLink img').attr('src', baseUrl + 'images/ads/' + nextAd['image']);
				setTimeout(updateAd, 10000);
			} else {
				$('#adLink').attr('_venid', 0);
				$('#adLink').attr('_adid', 0);
				$('#adLink img').attr('src', baseUrl + 'images/default_ad.gif');
			}
		});
//	}
}

function connectVendorInfoLinks() {
	$('a.vendorInfo').click(function() {
		var id = $(this).parents('div.company').attr('id').substr(3);
		getVendorInfo(id, $(this).attr('href'));
		return false;
	});
}

function getVendorInfo(id, url) {
	$('#vendorPrint').attr('href', baseUrl + 'vendor/print_vend/' + id);
	//$('#vendorContent').load(baseUrl + 'search/js_vendor/_/_/' + id, function() {
	$('#vendorContent').load(url + '?js=true', function() {
		var width = $('#vendor').width() / 2;
		var height = $('#vendor').height() /2;
		if ($(window).height() < $('#vendor').height()) {
			height = $(window).height() / 2;
		}

		$('#vendor').css({marginLeft: -width, marginTop: $(window).scrollTop() - height});
		$('#vendor').fadeIn(300);
		if ($('#vendorDetails').height() + 10 < $('#vendorDesc').height()) {
			$('#vendorDetails').height($('#vendorDesc').height() - 10);
		}
		if ($(document).height() > $('body').height()) {
			$('#shade').width($(document).width()).height($(document).height());
		} else {
			$('#shade').css({'width': $('body').width(), height: $('body').height() + 10});
		}
		if ($.support.opacity) {
			$('#shade').fadeIn(300);
		} else {
			$('#shade').css('display', 'block');
		}
		pageTracker._setCustomVar(1, 'popup', 'true');
		pageTracker._trackPageview('/vendor/' + id + '.html');
	});
}

function tryRefresh() {
	if ($('#state').attr('_id') && $('#category').attr('_id') && $('#city').attr('_id')) {
		var regionId = '_';
		if ($('#region').attr('_id')) {
			regionId = $('#region').attr('_id');
		}
		document.location = baseUrl + 'search/' + $('#state').attr('_id') + '/' + regionId + '/'
			+ $('#city').attr('_id') + '/' + $('#category').attr('_id') + '.html';
	}
}

var reagRegionsCA = ['San-Diego-County', 'San-Francisco', 'San-FranciscoEast-Bay', 'San-FranciscoNorth-Bay', 'San-FranciscoPeninsula', 'SFSilicon-ValleySouth-Bay', 'Greater-Sacramento-Area'];
function updateCategories() {
	var $state = $('#state');
	var stateId = $state.attr('_id');
	var $region = $('#region');
	var regionId = $region.attr('_id');
	var $category = $('#category');
	if (stateId == 'Idaho' || (stateId == 'Washington' && regionId == 'CentralEastern') ||
		(stateId == 'California' && $.inArray(regionId, reagRegionsCA) > -1)) {
		$('#category a[_id=Commercial-Real-Estate-Agents]').parent().css('display', 'list-item');
	} else {
		$('#category a[_id=Commercial-Real-Estate-Agents]').parent().css('display', 'none');
		if ($category.attr('_id') == 'Commercial-Real-Estate-Agents') {
			$category.removeAttr('_id').removeClass('filled');
			$category.children('div.title').html('Select a Category').removeAttr('_title');
		}
	}
	if ((stateId == 'Idaho' && regionId == 'Southwestern') || (stateId == 'California' && regionId == 'San-Diego-County')) {
		$('#category a[_id=Attorneys]').parent().css('display', 'list-item');
	} else {
		$('#category a[_id=Attorneys]').parent().css('display', 'none');
		if ($category.attr('_id') == 'Attorneys') {
			$category.removeAttr('_id').removeClass('filled');
			$category.children('div.title').html('Select a Category').removeAttr('_title');
		}
	}
}
function checkIndicator() {
	if (!$('#state').hasClass('filled')) {
		$('#state').addClass('nextStep');
		$('#region, #city, #category').removeClass('nextStep');
	} else {
		if (!$('#region').hasClass('filled')) {
			$('#region').addClass('nextStep');
			$('#state, #city, #category').removeClass('nextStep');
		} else {
			if (!$('#city').hasClass('filled')) {
				$('#city').addClass('nextStep');
				$('#state, #region, #category').removeClass('nextStep');
			} else {
				if (!$('#category').hasClass('filled')) {
					$('#category').addClass('nextStep');
					$('#state, #region, #city').removeClass('nextStep');
				} else {
					$('#state, #region, #city, #category').removeClass('nextStep');
				}
			}
		}
	}
}