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

	$('#catOptions li').livequery('click', function() {
		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});
			});
		}
		return false;
	});

	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() {
		if ($.support.opacity) {
			$('#vendor').fadeOut(300);
		} else {
			$('#vendor').hide();
		}
		hideShade();
		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() {
		var $this = $(this);
		if ($this.attr('href') != '#') {
			getVendorInfo($this.attr('_venid'), $this.attr('href'), $this.attr('_type'));
			if (typeof pageTracker != 'undefined') {
				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();

	$('#joinAdClose').click(function() {
		$('#joinAd').slideUp(300, function() {
			$(this).remove();
		});
		$('#searchCol').animate({'padding-top': 0}, 300);
		$('#catOptions').animate({'padding-bottom': 0}, 300);
		createCookie('hide_join_ad', 'true', 30);
		return false;
	});
	setTimeout(function() {
		$('#homeSrchMsg').find('h1').animate({top: -38}, 250);
	}, 5000);

	setTimeout(bumpSearchArrow, 10000);
});

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'],
					'_adid': nextAd['ad_id'],
					'href': baseUrl + 'vendor/' + nextAd['ven_id'] + '.html',
					'_type': nextAd['type']
				});
				$('#adLink img').attr('src', baseUrl + 'images/ads/' + nextAd['image']);
				setTimeout(updateAd, 10000);
			} else {
				$('#adLink').attr({'_venid': 0, '_adid': 0});
				$('#adLink img').attr('src', baseUrl + 'images/default_ad.gif');
			}
		});
//	}
}

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

function getVendorInfo(id, url, viewType) {
	$('#vendorPrint').attr('href', baseUrl + 'vendor/print_vend/' + id);
	//$('#vendorContent').load(baseUrl + 'search/js_vendor/_/_/' + id, function() {
//	var data = {js: true, }
	$('#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);
		}
		showShade();
		if (typeof pageTracker != 'undefined') {
			pageTracker._setCustomVar(1, 'popup', 'true');
			pageTracker._setCustomVar(2, 'viewType', viewType);
			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 (!$('#category').hasClass('filled')) {
		$('#category').addClass('nextStep');
		$('#state, #region, #city').removeClass('nextStep');
	} else 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');
				}
			}
		}
	}
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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 bumpSearchArrow() {
	if ($('#state div.title').text() == 'Select a State' && $('#category div.title').text() == 'Select a Category') {
		$('#homeSrchMsg').find('h1:last').animate({left: 4}, 150)
			.animate({left: -3}, 150)
			.animate({left: 1}, 120)
			.animate({left: 0}, 100, function() {
				setTimeout(bumpSearchArrow, 10000);
			});
	}
}
