$(function(){

// General
// ===========

	var templateURL = $("#templateURL").text()
	var baseDir = $("#baseDir").text()


	

// Home Page
// ===========

	// change tabs when clicked
	// --------------------------------------------------------------
	function changeTabHome(previousTab,thisTab,previousPerson,thisPerson) {
		$("#" + previousTab).stop().animate({ opacity: 0 }, 500, function() {
			$("#" + previousTab).hide();
			$("#" + thisTab).stop().css({ opacity: 0 }).show().animate({ opacity: 1 }, 500, function() {
				//$("#tabs a").attr("disabled", "");
			});
		});
		$("#" + previousPerson).stop().animate({ opacity: 0 }, 500, function() {
			$("#" + previousPerson).hide();
			$("#" + thisPerson).stop().css({ opacity: 0 }).show().animate({ opacity: 1 }, 500);
		});
	};
	
	
	if ($("#tabs.home").length > 0) {
		$("#tabs a:not(#manageLoggedIn)").click(function(){
			
			//$("#tabs a").attr("disabled", "disabled");

			var clickedTab = $(this).attr("rel");
			var lastTab = $("#tabs").find("li.on a").attr("rel");

			if ($(this).parent().attr("class") != "on") { 
				
				$(this).parent().siblings().removeClass("on");
				$(this).parent().addClass("on");
				
				if (clickedTab == "search") { 
					if (lastTab == "placead") {
						changeTabHome("tabPlaceAd","tabSearch","homePersonPlace","homePersonSearch");
					}
					else if (lastTab == "manageads") {
						changeTabHome("tabManageAds","tabSearch","homePersonManage","homePersonSearch");
					};
				}
				else if (clickedTab == "placead") {	
					if (lastTab == "search") {
						changeTabHome("tabSearch","tabPlaceAd","homePersonSearch","homePersonPlace");
					}
					else if (lastTab == "manageads") {
						changeTabHome("tabManageAds","tabPlaceAd","homePersonManage","homePersonPlace");
					};
				}
				else if (clickedTab == "manageads") {	
					if (lastTab == "placead") {
						changeTabHome("tabPlaceAd","tabManageAds","homePersonPlace","homePersonManage");
					}
					else if (lastTab == "search") {
						changeTabHome("tabSearch","tabManageAds","homePersonSearch","homePersonManage");
					};
				};
			};
			return false;
		});
		
	};

	// attach colorbox lightbox to show all categories link
	// --------------------------------------------------------------
	$("#browseList.homePage a#all").fancybox({
		overlayColor: "#000",
		overlayOpacity: ".75",
		frameWidth: 800,
		frameHeight: 430,
		hideOnContentClick: false
	});



	// add example text into login fields
	// --------------------------------------------------------------
	
	if ($("#loginForm").length > 0) {
		//set default search box (what/where) text
		var loginUserExample = 'your email, e.g. john@gmail.com';
		var loginPassExample = 'yourpass';
		var loginForgotExample = 'just enter your email';
		$('input#loginUser').example(loginUserExample);
		$('input#loginPass').example(loginPassExample);
		$('input#loginForgot').example(loginForgotExample);
	};



	// send forgotten password email
	// --------------------------------------------------------------
	
	if ($("#loginForgotForm").length > 0) { 
		
		// when user clicks to send reminder
		$("#forgotSubmit").click(function() { 
			
			// show the loading gif
			$("#forgotAjaxLoading").removeClass("hide");
			$("#forgotAjaxMsg").empty();
			if ($("#forgotAjaxMsg").attr("class") != "hide") { 
				$("#forgotAjaxMsg").addClass("hide");
			};
			
			//collect form variable
			var userEmail = $("#loginForgot").val();
			
			// initiate the ajax call
			$.ajax({
				type: "POST",
				url: baseDir + "user/forgotten_password",
				data: "email=" + userEmail,
				dataType: "xml",
				success: function(xml) {
					
					// get status response
					var statusMsg = $(xml).find("status").text();
					
					// set response status message
					if (statusMsg == "Success") { 
						$("#forgotAjaxMsg").empty().append("reminder sent");
					} else if (statusMsg == "Fail") { 
						$("#forgotAjaxMsg").empty().append("user not found");
					};
					
					// remove loading gif and show status message
					$("#forgotAjaxLoading").addClass("hide");
					$("#forgotAjaxMsg").removeClass("hide");
				}
			});
			return false;
		});
	};




// Search Page
// ============
	
	
	// set filter display on search page load
	// --------------------------------------------------------------
	if ($("#optWrap").length > 0) { 
		setFilterDisplay();
	};
	
	
	

	// move the detail panel as user scrolls
	// --------------------------------------------------------------
	if ($("#detailsWrap").length > 0) {
		function setScrollFollow(sfOffset) {
			$("#detailsWrap").scrollFollow({
				speed: 500,
				offset: sfOffset,
				delay: 100,
				easing: 'jswing'
			});
		};
		setScrollFollow(20);
	};


	
	// change save icon to saved
	// --------------------------------------------------------------
	
	if ($("#listingsWrap").length > 0) {
		$("#listingsWrap .adSave").livequery('click', function() {
			
			var saveID = $(this).parent().attr("id");
			
			// if statement only allows saving one at a time
			if ($("#listingsWrap .saveLoading").length == 0) {
				
				var currentAdCount = $("#savedAdsCount").text();
				var oldCount = currentAdCount;
				
				var saveLink = $(this);
				var saveLoading = '<div id="loading' + saveID + '" class="saveLoading"><img src="' + templateURL + 'images/design/ajax-loader-small-blue.gif" width="40" height="6" alt="loading" /></div>';
	
				if ((saveLink).attr("class") == "adSave adSaved") {
					saveURL = baseDir+"ajax/adsaves_minus"
					currentAdCount --;
					if (currentAdCount == 0) {
						$("p#savedAds").empty().append("You have <strong>0 saved ads</strong>. To save an ad, click the save button in the bottom right corner of the picture.")
					};
				}
				else if ((saveLink).attr("class") == "adSave") {
					saveURL = baseDir+"ajax/adsaves_plus"
					currentAdCount ++;
					if (currentAdCount == 1) {
						$("p#savedAds").empty().append('You have <strong><span id="savedAdsCount">1</span> saved <span id="savedAdsDesc1">ad</span></strong>&nbsp;&nbsp;|&nbsp;&nbsp;<a href="javascript:void(0)" id="loadSavedAds">Click here to load the <span id="savedAdsDesc2">ad</span></a>&nbsp;&nbsp;|&nbsp;&nbsp;<span id="clearSavedAdsWrap1"><a href="javascript:void(0)" id="clearSavedAds">Or, click here to clear all your saved ads</a>.</span><span id="clearSavedAdsWrap2" class="hide">Are you sure? <a href="javascript:void(0)" id="clearSavedAdsYes">Yes, do it!</a> or <a href="javascript:void(0)" id="clearSavedAdsNo">No, Cancel</a>.</span>')
						attachClearSavedAdsClicks();
						$("#savedAds a#loadSavedAds").click(function() {
							loadSavedAds();
							return false;
						});
					};
				}
				
				$(this).parent().prepend(saveLoading)
				
				$.ajax({
					type: "POST",
					url: saveURL,
					data: "id=" + saveID,
					success: function(response) {
						$(saveLink).toggleClass("adSaved");
						//alert(response);
						$("#loading" + saveID).remove();
						$("#savedAdsCount").empty().append(currentAdCount);
						if (currentAdCount > 1) {
							$("#savedAdsDesc1").empty().append("ads");
							$("#savedAdsDesc2").empty().append("ads");
						} else {
							$("#savedAdsDesc1").empty().append("ad");
							$("#savedAdsDesc2").empty().append("ad");
						};
					}
				});
			};
			return false;
		});
	};
		
	
	
	// change tabs when clicked
	// --------------------------------------------------------------
	
	if ($("#tabs.search").length > 0) {
		$("#tabs a").click(function(){
			
			if ($.browser.msie && $.browser.version.substr(0,1)<8) {
				// do nothing
			} else {
				
				//alert($.browser.version.substr(0,1));
				
				var clickedTab = $(this).attr("rel");
				var lastTab = $("#tabs").find("li.on a").attr("rel");

				if ($(this).parent().attr("class") != "on") { 

					$(this).parent().siblings().removeClass("on");
					$(this).parent().addClass("on");

					if (clickedTab == "search") { 
						if (lastTab == "browse") {
							$("#browseListWrap").fadeOut(500, function() {
								$("#middleBannerWrap").stop().animate({ height: "100px" }, 500, function() { 
									$("#searchFormWrap").fadeIn(500);
								});
								setScrollFollow(70);
							});
						}
						else if (lastTab == "saved") {
							$("#savedAdsWrap").fadeOut(500, function() { 
								$("#middleBannerWrap").stop().animate({ height: "100px" }, 500, function() { 
									$("#searchFormWrap").fadeIn(500);
								});
								setScrollFollow(-40);
							});
						};
					}
					else if (clickedTab == "browse") {	
						if (lastTab == "search") {
							$("#searchFormWrap").fadeOut(500, function() { 
								$("#middleBannerWrap").stop().animate({ height: "150px" }, 500, function() { 
									$("#browseListWrap").fadeIn(500);
								});
								setScrollFollow(-30);
							});
						}
						else if (lastTab == "saved") {
							$("#savedAdsWrap").fadeOut(500, function() { 
								$("#middleBannerWrap").stop().animate({ height: "150px" }, 500, function() { 
									$("#browseListWrap").fadeIn(500);
								});
								setScrollFollow(-90);
							});
						};
					}
					else if (clickedTab == "saved") {	
						if (lastTab == "search") {
							$("#searchFormWrap").fadeOut(500, function() { 
								$("#middleBannerWrap").stop().animate({ height: "40px" }, 500, function() { 
									$("#savedAdsWrap").fadeIn(500);
								});
								setScrollFollow(80);
							});
						}
						else if (lastTab == "browse") {
							$("#browseListWrap").fadeOut(500, function() { 
								$("#middleBannerWrap").stop().animate({ height: "40px" }, 500, function() { 
									$("#savedAdsWrap").fadeIn(500);
								});
								setScrollFollow(130);
							});
						};
					};
				};
				return false;				
			};

		});
	};




	// Functions to generate ad html for ajax listing results
	// --------------------------------------------------------------
	
	
		// ad html generator
		// ------------------------------ 
		function BuildAdHTML(adID,adPubID,adCount,adName,adURL,adOverlay,adMainPhoto,adAdded,adAge,adLocation,adPrice,adSaved,adSaleWanted,adFirst){
		
			// Build HTML string and return
			output = '<div id="' + adPubID + '" class="listAd' + adFirst + '">';
			if (adSaleWanted == "buy") { output += '<div class="adWantedBadge"><img src="' + templateURL + 'images/design/wanted-badge.png" alt="wanted ad" width="46" height="24"/></div>'; };
			output += '<div class="adSave' + adSaved +'"><a href="javascript:void(0)">&nbsp;</a></div>';
			output += '<div class="adTop">';
			output += '<span class="adCount">' + adCount + '</span>';
			output += '<span class="adAge">' + adAge + '</span>';
			output += '</div>';
			output += '<div class="adImage" style="background: transparent url(' + adMainPhoto + ') center top no-repeat;"><a href="' + baseDir + 'view/' + adURL + '#middleBanner" class="detailLink"><img src="' + adOverlay + '" alt="' + adName + '" width="142" height="104"/></a></div>';
			output += '<div class="adDetail">';
			output += '<p class="adName">' + adName + '</p>';
			output += '<p class="adLocation">' + adLocation + '</p>';
			output += '<p class="adPrice">' + adPrice + '</p>';
			output += '</div>';
			output += '</div>';
			return output;
		};


		// load more ads function
		// ------------------------------ 
		function loadMoreAds(autoLoadDetail, callback) {

			var countID = $("#adCurrentCount").text();
		
			var htmlOutput = '';
		
			var listOffset = countID;
			var listKeywords = $("#listKeywords").text();
			var listAddKeywords = $("#listAddKeywords").text();
			var listLocation = $("#listLocation").text();
			var listCategory = $("#listCategory").text();
			var listOrderBy = $("#listOrderBy").text();
			//var listOrderDirection = $("#listOrderDirection").text();
			var listType = $("#listType").text();
			var listSaleWanted = $("#listSaleWanted").text();
			var listDaysOld = $("#listDaysOld").text();
			var listPriceMin = $("#listPriceMin").text();
			var listPriceMax = $("#listPriceMax").text();
			var listSaved = $("#listSaved").text();
			var listUserID = $("#listUserID").text();
			if (listOffset == "0") {
				var listNumber = "30";
			}
			else {
				var listNumber = "30";			
			}

			$.ajax({
				type: "POST",
				url: baseDir + "ajax/listing",
				//data: "offset=" + listOffset + "&keywords=" + listKeywords + "&location=" + listLocation + "&category=" + listCategory + "&orderby=" + listOrderBy + "&saved=" + listSaved + "&userid=" + listUserID + "&number=" + listNumber + "",
				data: "offset=" + listOffset + "&keywords=" + listKeywords + " " + listAddKeywords + "&location=" + listLocation + 
						"&category=" + listCategory + "&orderby=" + listOrderBy + "&saved=" + listSaved + "&buysell=" + listSaleWanted + 
						"&userid=" + listUserID + "&number=" + listNumber + "&type=" + listType + "&days_old=" + listDaysOld +
						"&price_min=" + listPriceMin + "&price_max=" + listPriceMax + "",
				dataType: "xml",
				success: function(xml) {
					//loop through each ad and build the html output
					$(xml).find("ad").each(function() {
						countID ++
						var adID = $(this).find("id").text();
						var adPubID = $(this).find("pub_id").text();
						var adName = $(this).find("name").text();
						var adURL = $(this).find("url_name").text();
						var adPhotos = $(this).find("photos").text();
						var adOverlay = $(this).find("overlay").text();
						var adMainPhoto = $(this).find("mainphoto").text();
						var adSeller = $(this).find("seller").text();
						var adAdded = $(this).find("added").text();
						var adAge = $(this).find("age").text();
						var adLocation = $(this).find("location").text();
						var adViewed = $(this).find("viewed").text();
						var adDesc = $(this).find("desc").text();
						var adPrice = $(this).find("price").text();
						var adPriceDisplay = "";
						if (adPrice == "") { 
							adPriceDisplay = "--";
						} else {
							adPriceDisplay = "&euro;" + adPrice;
						};
						var adSaved = $(this).find("saved").text();
						var adSaleWanted = $(this).find("buysell").text();
						if (adSaved == "yes") { adSaved = " adSaved" } else { adSaved = "" };
						if (countID == 1) { adFirst = " first" } else { adFirst = "" };

						var thisAdHTML = BuildAdHTML(adID,adPubID,countID,adName,adURL,adOverlay,adMainPhoto,adAdded,adAge,adLocation,adPriceDisplay,adSaved,adSaleWanted,adFirst);
						htmlOutput = htmlOutput + thisAdHTML;
																				
						$("#adCurrentCount").empty().append(countID);
						$("#adLocked").empty().append("no");
					});
				
					//check if any results came back
					var adCount = $(xml).find("ads_count").text();
					if (adCount > 0) { 
					
						//hide message that no results returned
						$("#fullMessage").fadeOut(200, function() { 
							$("#fullMessage").addClass("hide");
							$("#fullMessage").text("<!-- -->");
						});

						//append the outputted html to the page
						$("#listingsWrap").append(htmlOutput);
						if (listOffset == "0") {
							$("#adListDetailWrap").fadeIn(500);
						};
					
						//reset the ad count
						$("#adsCountWrap").fadeOut(200, function() { 
							$("#adsCount").text(adCount)
							$("#adsCountWrap").fadeIn(200);
						});
	
						//auto load the first ad listed
						if (autoLoadDetail == "yes") { 
							var autoDetailID = $("#listingsWrap div.first").attr("id");
							loadDetailedAd(autoDetailID, callback);
						
							//reset load options
							if (adCount > countID) { 
								$("#btnLoadMore").removeClass("hide");
								$("#btnEndOfResults").addClass("hide");
							};
							$("#autoLoadCount").empty().append("0");
							setScrollFollow(20);
						
							//make sure load options are visible
							$("#btnListOptions").show();

							//hide load options if <= 21
							if (adCount < 22) { 
								$("#btnListOptions").hide();
							};
						};
					
						//check ad count versus served ads and remove "load more ads" option if necessary
						if (adCount == countID) { 
							$("#btnEndOfResults").removeClass("hide");
							$("#btnLoadMore").addClass("hide");
						};

					} else { 
					
						//lock the autoload feature
						$("#adLocked").empty().append("yes");
					
						//reset the ad count
						$("#adsCountWrap").fadeOut(200, function() { 
							$("#adsCount").text(adCount)
							$("#adsCountWrap").fadeIn(200);
						});
					
						//show message that no results returned
						$("#fullMessage").fadeOut(200, function() { 
							$("#fullMessage").removeClass("hide");
							$("#fullMessage").text("Sorry, there were no results for your chosen criteria.");
							$("#fullMessage").fadeIn(200, callback);
						});
					};				
				}
			});
			return false;
		};


		// auto load results on scroll btm
		// ------------------------------ 
		if ($("#listingsWrap").length > 0) { 
			$(window).scroll(function(){
				if  (($(window).scrollTop() > $(document).height() - $(window).height() - 500) && $("#adLocked").text() == "no" && ($("#autoLoadCount").text() < 3)) {
					$("#adLocked").empty().append("yes");
					loadMoreAds("no", "");
				
					//record how many autoloads there have been
					var autoLoadCount = $("#autoLoadCount").text()
					autoLoadCount ++ 
					$("#autoLoadCount").empty().append(autoLoadCount);
				}
			}); 
		};


		// load results when btn clicked
		// ------------------------------ 
		if ($("#btnListOptions").length > 0) { 
			$("a#btnLoadMore").click(function(){ 
				loadMoreAds("no", "");
				return false;
			});
			$("a#btnEndOfResults").click(function(){ 
				return false;
			});
		};


		// keyword/location based search
		// ------------------------------ 
		if ($("#searchFormWrap").length > 0) { 
			//set default search box (what/where) text
			var searchWhatExample = 'e.g. Audi, Labrador, or leave blank';
			//var searchWhereExample = 'e.g. Cork, Dundalk, or leave blank';
			$('input#searchWhat').example(searchWhatExample);
			//$('input#searchWhere').example(searchWhereExample);
		};

		if ($("#searchFormWrap.searchPage").length > 0) { 
			$("#searchFormWrap.searchPage #searchGo").click(function() {
			
				//remove browse by category highlight
				$("#browseList.searchPage a").removeAttr("class");
			
				//retrieve search inputs
				var searchWhat = $("input#searchWhat").val();
				var searchWhere = $("select#searchWhere").val();
			
				//check if equal to default, and blank if so
				if (searchWhat == searchWhatExample) { searchWhat = "" };
				//if (searchWhere == searchWhereExample) { searchWhere = "" };
			
				//set search options
				$("#adCurrentCount").empty().append("0");
				$("#listKeywords").empty().append(searchWhat);
				$("#listLocation").empty().append(searchWhere);
				$("#listCategory").empty().append("");
				$("#listOrderBy").empty().append("");
				$("#listSaved").empty().append("");
				$("#listUserID").empty().append("");

				$("#listAddKeywords").empty().append("");
				$("#listOrderBy").empty().append("");
				//$("#listOrderDirection").empty().append("");
				$("#listType").empty().append("");
				$("#listDaysOld").empty().append("");
				$("#listPriceMin").empty().append("0");
				$("#listPriceMax").empty().append("10000000");
			
				//fade out listings/detail, empty listing results, hide detail ad, load listing ads
				$("#adListDetailWrap").fadeOut(500, function() {
					$("#listingsWrap").empty();
					$("#detailAd").hide();
					loadMoreAds("yes", "");
					setFilterDisplay();
				});
				return false;
			});
		};


		// category based search
		// ------------------------------ 
		function runCategorySearch(clickedCategory,clickedCategoryLabel,callback) {

			//reset search box text
			$('input#searchWhat').attr("value", "").example(searchWhatExample);
			//$('input#searchWhere').attr("value", "").example(searchWhereExample);
		
			//remove other category highlights and add this clicked one
			$("#browseList.searchPage a").removeAttr("class");
			$(this).addClass("browseSelected");
		
			//set search options
			$("#adCurrentCount").empty().append("0");
			$("#listKeywords").empty().append("");
			$("#listLocation").empty().append("");
			$("#listCategory").empty().append(clickedCategory);
			$("#listCategoryLabel").empty().append(clickedCategoryLabel);
			$("#listOrderBy").empty().append("");
			$("#listSaved").empty().append("");
			$("#listUserID").empty().append("");

			$("#listAddKeywords").empty().append("");
			$("#listOrderBy").empty().append("");
			//$("#listOrderDirection").empty().append("");
			$("#listType").empty().append("");
			$("#listDaysOld").empty().append("");
			$("#listPriceMin").empty().append("0");
			$("#listPriceMax").empty().append("10000000");
		
			//fade out listings/detail, empty listing results, hide detail ad, load listing ads
			$("#adListDetailWrap").fadeOut(500, function() {
				$("#listingsWrap").empty();
				$("#detailAd").hide();
				loadMoreAds("yes", callback);
				setFilterDisplay();
			});
		};
	
		// watch for category clicks
		if ($("#browseList.searchPage").length > 0) { 
		
			// ie7 fix
			$("#categoryLocked").text("no");
		
			// watch in top 16, except last one
			$("#browseList.searchPage a:not('#all')").click(function(){
				if ($("#categoryLocked").text() == "no") { 
					$("#categoryLocked").text("yes");
					var clickedCategory = $(this).attr("id");
					var clickedCategoryLabel = $(this).attr("rel");
					runCategorySearch(clickedCategory,clickedCategoryLabel,function() { 
						$("#categoryLocked").text("no");
					});
				}
				return false;
			});
		
			$("#browseList.searchPage a#all").fancybox({
				overlayColor: "#000",
				overlayOpacity: ".75",
				frameWidth: 800,
				frameHeight: 430,
				hideOnOverlayClick: false,
				hideOnContentClick: false,
				callbackOnShow: function(){
					// watch for one of them to be clicked and load results
					$("#lbAllCats a").click(function(){ 
						var clickedCategory = $(this).attr("rel");
						var clickedCategoryLabel = $(this).text();
						//console.log(clickedCategoryLabel);
						runCategorySearch(clickedCategory,clickedCategoryLabel,"");
						$.fn.fancybox.close();
						return false;
					});				
				}
			});
		};		
		

		// show saved ads
		// ------------------------------ 
		function loadSavedAds(){
		
			// unbind the link
			$("#savedAds a#loadSavedAds").unbind();
		
			//reset search box text
			$('input#searchWhat').attr("value", "").example(searchWhatExample);
			//$('input#searchWhere').attr("value", "").example(searchWhereExample);

			//remove browse by category highlight
			$("#browseList.searchPage a").removeAttr("class");

			//set search options
			$("#adCurrentCount").empty().append("0");
			$("#listKeywords").empty().append("");
			$("#listLocation").empty().append("");
			$("#listCategory").empty().append("");
			$("#listOrderBy").empty().append("");
			$("#listSaved").empty().append("y");
			$("#listUserID").empty().append("");
		
			$("#listAddKeywords").empty().append("");
			$("#listOrderBy").empty().append("");
			//$("#listOrderDirection").empty().append("");
			$("#listType").empty().append("");
			$("#listDaysOld").empty().append("");
			$("#listPriceMin").empty().append("0");
			$("#listPriceMax").empty().append("10000000");
		
			//fade out listings/detail, empty listing results, hide detail ad, load listing ads
			$("#adListDetailWrap").fadeOut(500, function() {
				$("#listingsWrap").empty();
				$("#detailAd").hide();
				loadMoreAds("yes", function() { 
					$("#savedAds a#loadSavedAds").bind("click", function() {
						loadSavedAds();
						return false;
					});
				});
				setFilterDisplay();
			});
		};
	
		if ($("#savedAds.searchPage").length > 0) { 
			$("#savedAds a#loadSavedAds").click(function() {
				loadSavedAds();
				return false;
			});
		};


		// clear saved ads function
		// ------------------------------ 
		function clearSavedAds(){
		
			// unbind links
			$("#savedAds a#clearSavedAdsYes").unbind();
			$("#savedAds a#clearSavedAdsNo").unbind();
			$("#listSaved").empty().append("");
		
			// clear saved ads using ajax
			$.ajax({
				type: "POST",
				url: baseDir+"ajax/adsaves_destroy",
				data: "",
				success: function(response) {
					// reset count message
					$("p#savedAds").empty().append("You have <strong>0 saved ads</strong>. To save an ad, click the save button in the bottom right corner of the picture.")
				
					//set search options
					$("#adCurrentCount").empty().append("0");
					$("#listKeywords").empty().append("");
					$("#listLocation").empty().append("");
					$("#listCategory").empty().append("");
					$("#listOrderBy").empty().append("");
					$("#listSaved").empty().append("");
					$("#listUserID").empty().append("");

					$("#listAddKeywords").empty().append("");
					$("#listOrderBy").empty().append("");
					//$("#listOrderDirection").empty().append("");
					$("#listType").empty().append("");
					$("#listDaysOld").empty().append("");
					$("#listPriceMin").empty().append("0");
					$("#listPriceMax").empty().append("10000000");

					// load 0 ads - fade out listings/detail, empty listing results, hide detail ad, load listing ads
					$("#adListDetailWrap").fadeOut(500, function() {
						$("#listingsWrap").empty();
						$("#detailAd").hide();
						loadMoreAds("yes", "");
						setFilterDisplay();
					});
				}
			});
		};

	
		// function to show/hide "are you sure" message for clear saved ads
		function attachClearSavedAdsClicks(){
			$("#savedAds a#clearSavedAds").click(function() {
				$("#clearSavedAdsWrap1").addClass("hide")
				$("#clearSavedAdsWrap2").removeClass("hide")
				return false;
			});

			$("#savedAds a#clearSavedAdsNo").click(function() {
				$("#clearSavedAdsWrap2").addClass("hide")
				$("#clearSavedAdsWrap1").removeClass("hide")
				return false;
			});

			$("#savedAds a#clearSavedAdsYes").click(function() {
				clearSavedAds();
				return false;
			});
		};
	
		// attach function on pageload
		if ($("#savedAds a#clearSavedAds").length > 0) { 
			attachClearSavedAdsClicks();
		};


		/* This script and many more are available free online at
		The JavaScript Source!! http://javascript.internet.com
		Created by: Robert Nyman | http://robertnyman.com/ */
		function removeHTMLTags(oldString) {

		   var newString = "";
		   var inTag = false;
		   for(var i = 0; i < oldString.length; i++) {

		        if(oldString.charAt(i) == '<') inTag = true;
		        if(oldString.charAt(i) == '>') {
		              if(oldString.charAt(i+1)=="<")
		              {
		              		//dont do anything
			}
			else
			{
				inTag = false;
				i++;
			}
		        }

		        if(!inTag) newString += oldString.charAt(i);

		   }

		   return newString;
		}


	// display detail ad when clicked
	// --------------------------------------------------------------
	
		// get detailed ad function
		// ------------------------------ 
		function loadDetailedAd(getID,callback) {

			$("#detailAd").fadeOut(500, function() {
				var detailLoading = '<div id="loadingDetail"><img src="' + templateURL + 'images/design/loader-circle-large-blue.gif" width="64" height="64" alt="loading" /></div>';
				$("#detailsWrap").prepend(detailLoading)

				$.ajax({
					type: "POST",
					url: baseDir + "ajax/detail",
					data: "id=" + getID,
					dataType: "xml",
					success: function(xml) {
						$(xml).find("ad").each(function() {
							var detailID = $(this).find("id").text();
							var detailPubID = $(this).find("pub_id").text();
							var detailName = $(this).find("name").text();
							var detailPhotos = $(this).find("photos").text();
							var detailURLName = $(this).find("url_name").text();
							var detailPhotos2 = ' Photos';
						
							var detailMainPhoto = $(this).find("mainphoto").text();
							var detailMainPhotoLarge = $(this).find("mainphoto_large").text();
							var detailNewMainPhoto = "<a style='background: transparent url("+ detailMainPhoto +") center center no-repeat;' href='" + detailMainPhotoLarge + "'>&nbsp;</a>"
							var detailYoutube = $(this).find("youtube").text();
							var detailYoutube2 = ""
							var detailSeller = $(this).find("seller").text();
							var detailAdded = $(this).find("added").text();
							var detailAge = $(this).find("age").text();
							var detailLocation = $(this).find("location").text();
							var detailViewed = $(this).find("viewed").text();
							var detailDesc = $(this).find("desc").text();
							var detailPrice = $(this).find("price").text();
							var detailURL = $(this).find("url_name").text();
							var detailContact = baseDir + "contact/" + detailURL;
							var detailBump = baseDir + "myads/refresh/" + detailURL;
							var detailUpdate = baseDir + "myads/edit/" + detailURL;
							var detailReport = baseDir + "report/" + detailURL;
							var detailBuySell = $(this).find("buysell").text();
							var detailBuyerSeller = "";
							var detailSaleWanted = "";
							var detailType = $(this).find("type").text();
							var detailTradeName = $(this).find("trade_name").text();
							var detailTradeAddress = $(this).find("trade_address").text();

							var moreImageCount = 0;
							var detailMoreImages = '<ul>';
							$(this).find("img").each(function() {
								moreImageCount ++;
								detailMoreImages = detailMoreImages + '<li><a href="' + $(this).find("image").text() + '" rel="detailMorePics" title="' + detailName + '">' + moreImageCount + '</a></li>';
							});
							if (detailYoutube.length > 0) {
								detailYoutube2 = ' / 1 Video';
								detailMoreImages = detailMoreImages + '<li><a href="' + baseDir + 'ajax/youtube/' + detailPubID + '" rel="detailMorePics">youtube</a></li>';
							};
							detailMoreImages = detailMoreImages + '</ul>';
							if (detailPhotos < 2) {
								detailPhotos2 = ' Photo';
							};
							if (detailBuySell == "buy") { 
								detailBuyerSeller = "Buyer";
								detailSaleWanted = "Wanted";
							} else if (detailBuySell == "sell") { 
								detailBuyerSeller = "Seller";
								detailSaleWanted = "For Sale";
							};

							$("#detailID").empty().append("#" + detailPubID);
							$("#detailName").empty().append(detailName);
							$("#detailPhotos").empty().append(detailPhotos + detailPhotos2 + detailYoutube2);
							$("#detailImage").empty().append(detailNewMainPhoto);
							$("#detailWantedBadge").attr("class", "hide");
							if (detailBuySell == "buy") { $("#detailWantedBadge").attr("class", ""); };
							$("#detailOverlay a").attr("href", detailMainPhotoLarge)
							$("#detailOverlay img").attr("alt", detailName)
							$("#detailMoreImages").empty().append(detailMoreImages);
							$("#detailBuyerSeller").empty().append(detailBuyerSeller + ":");
							$("#detailBuyerSeller2").empty().append(detailBuyerSeller);
							$("#detailSeller").empty().append(detailSeller);
							$("#detailAdded").empty().append(detailAdded);
							$("#detailAge").empty().append(detailAge);
							$("#detailLocation").empty().append(detailLocation);
							$("#detailViewed").empty().append(detailViewed + " times");
							
							$("#detailDescText").empty().append(detailDesc);
							$("#detailSaleWanted").empty().append(detailSaleWanted);
							$("#detailType").empty().append(detailType + ' AD');
							
							var addthis_ui_config =
							{
								services_expanded: 'facebook, twitter, igoogle, favourites, delicious, digg, netvibes, bebo',
							    services_compact: 'facebook, twitter, igoogle, favorites'
							}
							var addthis_share_config = 
							{
							    url: 'http://www.fetch.ie/' + detailPubID,
							    title: detailName + ' - For Sale on Fetch.ie',
							    description: removeHTMLTags(detailDesc),
								swfurl: "http://www.youtube.com/v/P3kd-r7Fhi8",
								width: "560",
								height: "340",
							    screenshot: detailMainPhoto
							}
							addthis.button("#btn1", addthis_ui_config, addthis_share_config);						
							
							$("#detailDesc").empty().append(detailDesc);
							// $("#detailDesc").prepend('<span id="detailSaleWanted">' + detailSaleWanted + '</span> ');
							// $("#detailDesc").prepend('<span id="detailType">' + detailType + ' ad</span>');
							if (detailPrice == "") { 
								$("#detailPrice").empty().append("Price: n/a");
							} else {
								$("#detailPrice").empty().append("Price: &euro;" + detailPrice);
							};
							if (detailTradeName != "") {
								$("#detailDesc").append('<br /><span class="tradeDetails"><strong>Business Details:</strong> ' + detailTradeName + ' ' + detailTradeAddress + '</span>');
							};
							$("#detailContact a").attr("href", detailContact); 
							$("#option1 a").attr("href", detailBump);
							$("#option2 a").attr("href", detailUpdate);
							$("#reportAdLink a").attr("href", detailReport);
						});
					
						//remove the loader graphic
						$("#loadingDetail").remove();
					
						//animate is used to delay the fadeIn
						$("#detailAd").animate({opacity: 1}, 500).fadeIn(1000, callback);
					
						$("a[rel='detailMorePics']").fancybox({
							overlayColor: "#000",
							overlayOpacity: ".75",
							imageScale: true
						});
					}
				});
			});
		};
	
	
		// show detailed ad on click
		// ------------------------------ 
		if ($("#listingsWrap").length > 0) { 

			//ie7 fix
			$("#detailLocked").text("no");
			$("#categoryLocked").text("no");
			$("#listCategoryLabel").text("no filters");
			$("#listPriceMin").text("0");
			$("#listPriceMax").text("10000000");
			$("#adCurrentCount").text("30");
			$("#autoLoadCount").text("0");
			$("#adLocked").text("no");
			$("#adFirstLoad").text("yes");
		
			$(".listAd a.detailLink").livequery('click', function() {
				if ($("#detailLocked").text() == "no") { 
					$("#detailLocked").text("yes");
					var getID = $(this).parent().parent().attr("id");
					loadDetailedAd(getID,function() { 
						$("#detailLocked").text("no");
					});
				};
				return false;
			});
		};


		// attach colorbox to links
		// ------------------------------ 
		if ($("#detailAdWrap").length > 0) {
			$("a[rel='detailMorePics']").fancybox({
				overlayColor: "#000",
				overlayOpacity: ".75",
				imageScale: true
			});
		
			$("#detailContact a").fancybox({
				overlayColor: "#000",
				overlayOpacity: ".75",
				frameWidth: 800,
				frameHeight: 340,
				hideOnOverlayClick: false,
				hideOnContentClick: false,
				callbackOnShow: function(){
					// when user clicks to send message
					$("#contactSendMsg").click(function() { 

						// clear error classes
						$("#contactSellerName").removeClass("error");
						$("#contactSellerEmail").removeClass("error");
						$("#contactSellerPhone").removeClass("error");
						$("#contactSellerMessage").removeClass("error");

						// show the loading message
						$("#contactSendMsg").val("Sending...").attr("disabled", "disabled").animate({opacity: 1}, 2000, function() { 

							//collect form variable
							var ajaxPost = $("#formContactSeller").attr("action");
							var userName = $("#contactSellerName").val();
							var userEmail = $("#contactSellerEmail").val();
							var userPhone = $("#contactSellerPhone").val();
							var userMessage = $("#contactSellerMessage").val();

							// initiate the ajax call
							$.ajax({
								type: "POST",
								url: ajaxPost,
								data: "name=" + userName + "&email=" + userEmail + "&phone=" + userPhone + "&message=" + userMessage + "",
								dataType: "xml",
								success: function(xml) {

									// get status response
									var statusMsg = $(xml).find("status").text();

									// set response status message
									if (statusMsg == "Success") { 
										// show status message
										$("#contactSellerName").val("");
										$("#contactSellerEmail").val("");
										$("#contactSellerPhone").val("");
										$("#contactSellerMessage").val("");
										$("#contactSendMsg").val("Message Sent!").animate({opacity: 1}, 10000, function() { 
											$("#contactSendMsg").attr("disabled", "").val("Send Message");
										});
									} else if (statusMsg == "Failure") { 
										// show status message
										$("#contactSendMsg").val("Internal Error!").animate({opacity: 1}, 2000, function() { 
											$("#contactSendMsg").attr("disabled", "").val("Send Message");
										});
									} else if (statusMsg == "Errors") { 
										// add error classes
										$(xml).find("error").each(function() {
											var thisError = $(this).text();
											$("#contactSeller" + thisError).addClass("error");				
										});

										// show status message
										$("#contactSendMsg").val("Errors! Try Again!").animate({opacity: 1}, 2000, function() { 
											$("#contactSendMsg").attr("disabled", "").val("Send Message");
										});
									};
								}
							});
						});
						return false;
					});
				}
			});		
		};
	
		if ($("#optFilterBtn").length > 0) {
			$("#optFilterBtn a").fancybox({
				overlayColor: "#000",
				overlayOpacity: ".75",
				frameWidth: 800,
				frameHeight: 400,
				hideOnOverlayClick: false,
				hideOnContentClick: false,
				callbackOnShow: function(){
					loadFilterOptions();
				}
			});
		};
	


	// lightbox filter options
	// --------------------------------------------------------------
	
		// function to reset and set selected
		// ------------------------------ 
		function setOptionSelected(optionGroup,selectedValue,checkValue){
		
			if (selectedValue != checkValue) {
				$(optionGroup).removeAttr("selected").each(function(){
					if ($(this).attr("value") == selectedValue) { 
						$(this).attr("selected", "selected");
					};
				});
			};
		};
	

		// function to load categories
		// ------------------------------ 
		function setFilterDisplay(){
			var listKeywords = $("#listKeywords").text();
			var listLocation = $("#listLocation").text();
			var listCategory = $("#listCategory").text();
				if (listCategory == "top") { listCategory = ""; };
			var listCategoryLabel = $("#listCategoryLabel").text();
				if (listCategoryLabel == "top") { listCategoryLabel = ""; };
				if (listCategoryLabel == "[object Object]") { listCategoryLabel = listCategory; };
				//alert(listCategoryLabel)
			var listType = $("#listType").text();
			var listSaved = $("#listSaved").text();
			var listSaleWanted = $("#listSaleWanted").text();
			var listPriceMin = $("#listPriceMin").text();
			var listPriceMax = $("#listPriceMax").text();
			var listDaysOld = $("#listDaysOld").text();
			var listOrderByShow = "";
			var listOrderBy = $("#listOrderBy").text();
				//var listOrderDirection = $("#listOrderDirection").text();
			if (listOrderBy == "datedesc") { listOrderByShow = "Date Newest First"; };
			if (listOrderBy == "dateasc") { listOrderByShow = "Date Oldest First"; };
			if (listOrderBy == "priceasc") { listOrderByShow = "Price Cheapest First"; };
			if (listOrderBy == "pricedesc") { listOrderByShow = "Date Dearest First"; };
			if (listOrderBy == "nameasc") { listOrderByShow = "Name ABC First"; };
			if (listOrderBy == "namedesc") { listOrderByShow = "Name ZYX First"; };

			var filterDisplay = "";
			if (listKeywords != "") { 
				filterDisplay += "<li>'" + listKeywords + "'</li>"; 
				$("input#searchWhat").val(listKeywords);
			};
			if (listLocation != "") { 
				filterDisplay += "<li>'" + listLocation + "'</li>"; 
				$("select#searchWhere").val(listLocation);
			};
			if (listSaved != "") { filterDisplay += "<li class='capitalize' id='lbFilterSavedLabel'>Saved Ads</li>"; };
			if (listCategory != "") { filterDisplay += "<li class='capitalize' id='lbFilterCategoryLabel'>" + listCategoryLabel + "</li>"; };
			if (listType == "trade") { filterDisplay += "<li class='capitalize'>Trade Only</li>"; } else if (listType == "private") { filterDisplay += "<li>Private Only</li>"; };
			if (listSaleWanted == "sell") { filterDisplay += "<li class='capitalize'>For Sale Only</li>"; } else if (listType == "buy") { filterDisplay += "<li>Wanted Only</li>"; };
			if (listPriceMin != 0) { filterDisplay += "<li class='capitalize'>Min &euro;" + listPriceMin + "</li>"; };// else { filterDisplay += "<li>No Min</li>"; };
			if (listPriceMax != 10000000) { filterDisplay += "<li class='capitalize'>Max &euro;" + listPriceMax + "</li>"; };// else { filterDisplay += "<li>No Max</li>"; };
			if (listDaysOld != "") { filterDisplay += "<li class='capitalize'>&lt;" + listDaysOld + " days old</li>"; };
			if (listOrderBy != "") { filterDisplay += "<li class='capitalize'>Order by " + listOrderByShow + "</li>"; };
		
			if (filterDisplay != "") {
				$("#optCurrentFilters ul").empty().append(filterDisplay);
			} else {
				$("#optCurrentFilters ul").empty().append('<li id="filterNone">no filters</li>');
			};
		};
	
	
		// function to load categories
		// ------------------------------ 
		function loadParentChildCategories(thisCatID,thisCategory,thisCategoryLabel){
			if (thisCatID == "") { thisCatID = ""; };
			if (thisCategory == "") { thisCategory = "top"; };
			if (thisCategoryLabel == "") { thisCategoryLabel = "top"; };

			$.ajax({
				type: "POST",
				url: baseDir + "ajax/getSubcats",
				data: "category=" + thisCategory,
				dataType: "xml",
				success: function(xml) {
					var subCategories = '<option value="' + thisCatID + '" rel="' + thisCategory + '" title="' + thisCategoryLabel + '">All</option>';
					var parentCategories = '<li class="hide">hide</li>';
					var lastParent = "top";
					var subCount = 0;
				
					$(xml).find("parent").find("cat").each(function() {
						var catID = $(this).find("id").text();
						var catURL = $(this).find("url_name").text();
						var catName = $(this).find("name").text();
						var catDesc = $(this).find("description").text();
						var catSubCatOf = $(this).find("subcat_of").text();
					
						//parentCategories += '<li><a href="#" rel="' + catSubCatOf + '">' + catName + '</a></li>'
						parentCategories += '<li><a href="#" rel="' + lastParent + '">' + catName + '</a></li>';
					
						lastParent = catURL;
					});
					$(xml).find("child").find("cat").each(function() {
						var catID = $(this).find("id").text();
						var catURL = $(this).find("url_name").text();
						var catName = $(this).find("name").text();
						var catDesc = $(this).find("description").text();
						var catSubCatOf = $(this).find("subcat_of").text();
					
						subCategories += '<option value="' + catID + '" rel="' + catURL + '" title="' + catName + '">' + catName + '</option>'
						subCount ++;
					});
				
					parentCategoriesFinal = '<ul>' + parentCategories + '</ul>'
					$("#parentCategories").empty().append(parentCategoriesFinal);
					$("#parentCategories ul :last-child").addClass("last");
				
					subCategoriesFinal = '<select name="category" id="lbFilterCategory">' + subCategories + '</select>';
					$("#childCategories").empty().append(subCategoriesFinal);
				
					if (subCount == 0) { $("#lbFilterCategory").addClass("hide"); };
				
					checkReturnedAdsCount();
				
					$("#lbFilterCategory").change(function() { checkReturnedAdsCount(); loadParentChildCategories($("#lbFilterCategory").val(),$("#lbFilterCategory :selected").attr("rel"),$("#lbFilterCategory :selected").attr("title")); });
				
					$("#parentCategories a").click(function() {
						thisParentID = $(this).attr("rel");
						thisParentLabel = $(this).text();
						loadParentChildCategories("",thisParentID,thisParentLabel);
						return false;
					});
				}
			});
		}
	
		if ($("#lbFilterCategory").length > 0) { 
			if ($("#curr_cat_name").length > 0)	{ 
				var defaultCategoryName = $("#curr_cat_name").val();
			}  else { 
				var defaultCategoryName = ""; 
			};
			if ($("#curr_cat_id").length > 0) { 
				var defaultCategoryID = $("#curr_cat_id").val(); 
			} else { 
				var defaultCategoryID = ""; 
			};
			loadParentChildCategories(defaultCategoryID,defaultCategoryName,"");
		}


		// function to load filter options
		// ------------------------------ 
		function loadFilterOptions(){
			if ($("#lbFilter").length > 0) { 
				// get current values user has selected/entered
				var lbListKeywords = $("#listKeywords").text();
				var lbListLocation = $("#listLocation").text();
				var lbListCategory = $("#listCategory").text();
				var lbListCategoryLabel = $("#lbFilterCategoryLabel").text();
				var lbListOrderBy = $("#listOrderBy").text();
				//var lbListOrderDirection = $("#listOrderDirection").text();
				var lbListType = $("#listType").text();
				var lbListSaleWanted = $("#listSaleWanted").text();
				var lbListDaysOld = $("#listDaysOld").text();
				var lbListPriceMin = $("#listPriceMin").text();
				var lbListPriceMax = $("#listPriceMax").text();
			
				// show sub categories if there is a main category
				loadParentChildCategories("",lbListCategory,lbListCategoryLabel);

				// set trade or private 
				setOptionSelected("#lbFilterTradePrivate option",lbListType,"");
			
				// set for sale or wanted 
				setOptionSelected("#lbFilterSaleWanted option",lbListSaleWanted,"");
			
				// set keywords 
				if (lbListKeywords != "") { $("#lbFilterKeywords").attr("value", lbListKeywords); };

				// set location
				if (lbListLocation != "") { $("#lbFilterLocation").val(lbListLocation); };
			
				// set min/max price 
				setOptionSelected("#lbFilterMinPrice option",lbListPriceMin,"0");
				setOptionSelected("#lbFilterMaxPrice option",lbListPriceMax,"10000000");
			
				// set age of ad 
				setOptionSelected("#lbFilterAge option",lbListDaysOld,"");
			
				// set order by 
				setOptionSelected("#lbFilterOrder option",lbListOrderBy,"");

				// listen for changes to search filter options
				// ------------------------------
				$("#lbFilterTradePrivate").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterSaleWanted").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterKeywords").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterLocation").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterMinPrice").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterMaxPrice").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterAge").change(function() { checkReturnedAdsCount(); });
				$("#lbFilterOrder").change(function() { checkReturnedAdsCount(); });
				$("#formFilter").submit(function() { setFilterOptions(); return false; });
			
				// listen for click of apply filter
				// ------------------------------
				$("#lbButton a").click(function(){ 
					setFilterOptions();
					return false;
				});
			};
		};
	

		// function to set filter options
		// ------------------------------ 
		function setFilterOptions(){
		
			// get current values user has selected/entered
			var lbFilterKeywords = $("#lbFilterKeywords").val();
			var lbFilterLocation = $("#lbFilterLocation").val();
			var lbFilterCategory = $("#lbFilterCategory :selected").attr("rel");
				if (lbFilterCategory == "top") { lbFilterCategory = ""; };
			var lbFilterCategoryLabel = $("#lbFilterCategory :selected").attr("title");
				if (lbFilterCategoryLabel == "top") { lbFilterCategoryLabel = ""; };
			var lbFilterTradePrivate = $("#lbFilterTradePrivate").val();
			var lbFilterSaleWanted = $("#lbFilterSaleWanted").val();
			var lbFilterMinPrice = $("#lbFilterMinPrice").val();
			var lbFilterMaxPrice = $("#lbFilterMaxPrice").val();
			var lbFilterAge = $("#lbFilterAge").val();
			var lbFilterOrder = $("#lbFilterOrder").val();
		
			// set current values user has selected/entered
			$("#listKeywords").text(lbFilterKeywords);
			$("#listLocation").text(lbFilterLocation);
			$("#listCategory").text(lbFilterCategory);
			$("#listCategoryLabel").text(lbFilterCategoryLabel);
			$("#listType").text(lbFilterTradePrivate);
			$("#listSaleWanted").text(lbFilterSaleWanted);
			$("#listPriceMin").text(lbFilterMinPrice);
			$("#listPriceMax").text(lbFilterMaxPrice);
			$("#listDaysOld").text(lbFilterAge);
			$("#listOrderBy").text(lbFilterOrder);
			$("#adCurrentCount").empty().append("0");
		
			// set filter option display
			setFilterDisplay();

			// fade out listings/detail, empty listing results, hide detail ad, load listing ads
			$.fn.fancybox.close();
			$("#adListDetailWrap").fadeOut(500, function() {
				$("#listingsWrap").empty();
				$("#detailAd").hide();
				loadMoreAds("yes", "");
			});
		};
	
	
		// function to check the count of returned ads
		// ------------------------------ 
		function checkReturnedAdsCount(){
			if ($("#content.searchPage").length > 0) {
				var lbListKeywords = $("#lbFilterKeywords").val();
				var lbListLocation = $("#lbFilterLocation").val();
				var lbListCategory = $("#lbFilterCategory :selected").attr("rel");
					if (lbListCategory == "top") { lbListCategory = ""; };
				var lbListOrderBy = $("#lbFilterOrder").val();
				var lbListType = $("#lbFilterTradePrivate").val();
				var lbListSaleWanted = $("#lbFilterSaleWanted").val();
				var lbListDaysOld = $("#lbFilterAge").val();
				var lbListPriceMin = $("#lbFilterMinPrice").val();
				var lbListPriceMax = $("#lbFilterMaxPrice").val();
				var lbListSaved = $("#listSaved").text();
				var lbListUserID = $("#listUserID").text();
				var lbListOffset = "0";
				var lbListNumber = "30";
	
				$.ajax({
					type: "POST",
					url: baseDir + "ajax/listCount",
					data: "offset=" + lbListOffset + "&keywords=" + lbListKeywords + "&location=" + lbListLocation + 
							"&category=" + lbListCategory + "&orderby=" + lbListOrderBy + "&saved=" + lbListSaved + "&buysell=" + lbListSaleWanted + 
							"&userid=" + lbListUserID + "&number=" + lbListNumber + "&type=" + lbListType + "&days_old=" + lbListDaysOld +
							"&price_min=" + lbListPriceMin + "&price_max=" + lbListPriceMax + "",
					dataType: "xml",
					success: function(xml) {
						//check how many results came back
						var adCount = $(xml).find("ads_count").text();
						$("#lbReturnedAds").empty().append(adCount);
					}
				});
			};
		};


	

// Place Ad & My Account Sections
// ==================================

	// My Ads Table - chage row colour on hover
	// --------------------------------------------------------------
	if ($("#myaccAdsTable").length > 0) { 
		$("#myaccAdsTable tbody tr").hover(
		function(){
			$(this).addClass("hover");
		}, 
		function() {
			$(this).removeClass("hover");
		});
	};


	// add example text into youtube field
	// --------------------------------------------------------------
	if ($("#elementWrapYouTube").length > 0) { 
		//set example text for youtube link up
		var youtubeExample = 'e.g. http://www.youtube.com/watch?v=V4QLFVrZ-fw';
		$('#elementWrapYouTube input#youtube').example(youtubeExample);
	};


	// add loader icon and text while images are uploading
	// --------------------------------------------------------------
	if ($("#photosUploading").length > 0) { 
		// When user clicks to upload images, do this
		$("#uploadButton").click(function() { 
			// remove the 'hide' class on the uploading message
			$("#photosUploading").removeClass("hide");
			// disable the button to stop multiple clicks
			//$("#uploadButton").attr("disabled", "disabled");
		});
	};


	// show/hide business name/address if trade ad selected
	// --------------------------------------------------------------
	if ($("#elementWrapType").length > 0) { 
		var newType = $("#typeTradePrivate").val();
		if (newType == "private") {
			$("#tradeOptions").addClass("hide");
		};
		$("#typeTradePrivate").change(function(){
			newType = $("#typeTradePrivate").val();
			
			$("#tradeOptions").attr("class", "")
			if (newType == "private") {
				$("#tradeOptions").addClass("hide");
			};
		});
	};




// ADDED BY MICHAEL
// ===================

	// limit .valid-number input fields to numbers only (for price, etc.)
	// ------------------------------ 
	$('input.valid-number').bind('keypress', function(e) {
		return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
	})

    // Appearing and disapearing 'flash' messages - for errors and status
	// ------------------------------ 
    $.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };

	$("#flashMessage").fadeIn(500,
        function(){
            $("#flashMessage")
			.wait(2000)
			.fadeOut(1500);
        });
	$("#flashError").fadeIn(500,
        function(){
            $("#flashMessage")
			.wait(2000)
			.fadeOut(1500);
        });

});
