$(document).ready(function() {
	/* Header */
	// Empty Search Field
	$('#header form input[name="term"]').each(function() {
		searchText = $(this).val();
		searchColor = $(this).css('color');
		
		$(this).focus(function() {
			if($(this).val()==searchText) {
				$(this).val('');
				$(this).css('color', '#555');
			}
		});
		
		$(this).blur(function() {
			if(empty($(this).val())) {
				$(this).css('color', searchColor);
				$(this).val(searchText);
			}
		});
	});
	
	/* Navigation */
	$('.left-nav').each(function() {
		// Adds dropdowns for nested lists (For Horses)
		$(this).find('ul:has("ul")').each(function() {
			$(this).find('ul').hide();
			
			$(this).children('li').addClass('dropdown').click(function(event) {
				 if (!$(event.target).is('a')) {
					$(this).find('ul').slideToggle();
					
					if(strpos($(this).css('background-image'), 'expand')) {
						$(this).css('background-image', 'url("/media/images/buttons/collapse.gif")');
					} else {
						$(this).css('background-image', 'url("/media/images/buttons/expand.gif")');
					}
				 }
			});
		});
	
		// Explodes other left-nav lists
		$(this).find('> li > ul').each(function() {
			if(!$(this).children('li').children('ul').size()) {
				$(this).children('li:lt(5)')
					.wrapAll(document.createElement("ul")).parent()
					.wrapAll(document.createElement("li"));
				
				$(this).children('li:gt(0)')
					.wrapAll(document.createElement("ul")).parent()
					.wrapAll(document.createElement("li")).parent()
						.addClass('more');
				
				if($(this).siblings('h2:contains("Shop by brand")').size()) {
					type = 'brands';
				} else {
					type = 'products';
				}
				
				$(this).children('.more')
					.after('<li><a href="#" class="toggle">More ' + type + '</a></li>')
					.hide();
			}
		});
		
		// Toggle link functionality
		$(this).find('.toggle').click(function() {
			$(this).parent().each(function() {
				$(this).siblings('.more').slideToggle();
				if($(this).parent().siblings('h2:contains("Shop by brand")').size()) {
					more = 'More brands'; less = 'Less brands';
				} else {
					more = 'More products'; less = 'Less products';
				}
			});
			switch($(this).html()) {
				case more : $(this).html(less); break;
				case less : $(this).html(more);
			}
			return false;
		});
	});
});

function empty(str) {
	if (str === "" || str === 0 || str === "0" || str === null || str === false || typeof str === 'undefined') {
		return true;
	}
	if (typeof str == 'object') {
		var key;
		for (key in str) {
			return false;
		}
		return true;
	}
	return false;
}

function strpos(haystack, needle, offset) {
	var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}