$(function(){

	// ==================================================
	// general functions
	// ==================================================
	
		function submitAjaxForm(formID,formErrorID,formErrorAutohide,formAction,formData,formRedirect,formPopupClose) {
		
			if(formErrorID == "") { 
				formErrorID = "errorWrap"
			};
		
			$.ajax({
				type: "POST",
				url: formAction,
				data: formData,
				dataType: "xml",
				error: function() {
					// an internal error has occurred
					console.log("internal error - please try again later");
				},
				success: function(xml) {

					// get status response
					var statusMsg = $(xml).find("status").text();

					// set response status message
					if (statusMsg == "success") { 
						// check for an override redirect from the php script
						if($(xml).find("redirect").text() != ""){
							formRedirect = $(xml).find("redirect").text();
						};
						var successBox = '<div class="ajaxSuccess"><ul>'
						$(xml).find("message").each(function(){
							successBox = successBox + $(this).text()
						});

						// all completed successfully, display the success messages
						if ($(".ajaxErrors").length > 0) {
							$("#"+formErrorID).slideUp(500, function(){
								$(".ajaxErrors").remove();
								if (formRedirect != "") {
									window.location = (formRedirect);
								} else {
									$("#"+formErrorID).prepend(successBox).animate({opacity: 1}, 300, function(){
										$("#"+formErrorID).slideDown(500,function(){
											if(formPopupClose == 1) {
												$("#"+formErrorID).wait(4000).slideUp(500,function(){
													$(".ajaxSuccess").remove();
												});
											};
										});
									});
								};
							});
						} else { 
							if (formRedirect != "") {
								window.location = (formRedirect);
							} else {
								$("#"+formErrorID).prepend(successBox).animate({opacity: 1}, 300, function(){
									$("#"+formErrorID).slideDown(500,function(){
										if(formPopupClose == 1) {
											$("#"+formErrorID).wait(4000).slideUp(500,function(){
												$(".ajaxSuccess").remove();
											});
										};
									});
								});
							};
						};
					} else if (statusMsg == "error") { 
						// an error has occurred, display the error messages
						var errorBox = '<div class="ajaxErrors"><ul>'
						$(xml).find("message").each(function(){
							errorBox = errorBox + $(this).text()
						});
						errorBox = errorBox + '</ul></div>'
						// $(".fieldError").removeClass("fieldError");
						// $(xml).find("error").find("field").each(function(){
						// 	var fieldName = $(this).text();
						// 	$("#" + fieldName).siblings("label").each(function(){
						// 		$(this).addClass("fieldError");
						// 	});
						// });
						
						if ($(".ajaxErrors").length > 0) {
							$("#"+formErrorID).slideUp(500, function(){
								$(".ajaxErrors").remove();
								$("#"+formErrorID).prepend(errorBox).animate({opacity: 1}, 300, function(){
									$("#"+formErrorID).slideDown(500,function(){
										if(formErrorAutohide == 1) {
											$("#"+formErrorID).wait(2000).slideUp(500);
										};
									});
								});
							});
						} else {
							$("#"+formErrorID).prepend(errorBox).animate({opacity: 1}, 300, function(){
								$("#"+formErrorID).slideDown(500,function(){
									if(formErrorAutohide == 1) {
										$("#"+formErrorID).wait(2000).slideUp(500);
									};
								});
							});
						};
					};
				}
			});
	
		};




	// ==================================================
	// general page effects
	// ==================================================
		

		// ----------------------------------------------
		// show/hide subnav
		// ----------------------------------------------
		
			// if($("#homeWrap").length == 0){
			// 	if($("#listingsWrap").length == 0) {
			// 		$("#subNav").hide();
			// 	};
			// 	$("#showCategories").hover(function(){
			// 		$("#subNav").slideDown();
			// 	});
			// 	$("#primaryWrap").hover(function(){
			// 		$("#subNav").slideUp();
			// 	});
			// };


	
		// ----------------------------------------------
		// featured scroller
		// ----------------------------------------------

			var featLock = 0;
			var featRotate = 1;
			var featRotateCount = 0;

			if($("#featured").length > 0) {
		
				function rotateFeatured(){
					
					if (featRotate == 1 && featRotateCount < 10){
						
						featRotateCount++;
						//var currentTab = parseInt($("#featured li.on").attr("rel"));
						var currentTab = $("#featured li.on").attr("id");
						currentTab = parseInt(currentTab.replace("featured-item-", ""));
						//console.log(currentTab);
						
						if(currentTab == 5) { 
							nextTab = 1;
						} else {
							nextTab = currentTab + 1;
						};
						$("#featured").animate({ opacity: 1 },5000,function(){
							if (featRotate == 1){
								changeTab(nextTab);
								rotateFeatured();
							};
						})
												
					};
					
				};
				
				function changeTab(tabNo){
					
					$("#featured").children().removeClass("on");
					$("#featured li:nth-child("+ tabNo +")").addClass("on");
					$(".featPic").hide();
					$(".featPicDesc").hide();
					$("#featured li:nth-child("+ tabNo +")").find(".featPicDesc").wait(500).slideDown(350);
					$("#featured li:nth-child("+ tabNo +")").find(".featPic").fadeIn(850, function(){
						featLock = 0;
					});
					
				};
				
				// watch for clicks of new tab
				$("#featured li a.list").click(function(){
				
					if (featLock == 0){
					
						featLock = 1;
						featRotate = 0;
						
						changeTab($(this).attr("rel"));
						
					};
				
					return false;
				
				});
				
				// initiate rotateFeatured
				rotateFeatured();
				
			};



		// ----------------------------------------------
		// search box options
		// ----------------------------------------------
			
			$(".searchBox .searchCategory").change(function(){

				var newCategory = $(this).val();

				if (newCategory == "residential-and-new-homes") {
						var typeOptions = {
							"all" : "All",
							"apartment" : "Apartment",
							"bungalow" : "Bungalow",
							"detached" : "Detached",
							"semi-detached" : "Semi-Detached",
							"townhouse" : "Townhouse"
						};
						var priceOptions = {
							"all" : "All",
							"less200k" : "< 200,000",
							"200k-400k" : "200,000 - 400,000",
							"more400k" : "> 400,000"
						};
				} else if (newCategory == "farm-and-country-homes") {
						var typeOptions = {
							"all" : "All"
						};
						var priceOptions = {
							"all" : "All",
							"less200k" : "< 200,000",
							"200k-400k" : "200,000 - 400,000",
							"more400k" : "> 400,000"
						};
				} else if (newCategory == "sites") {
						var typeOptions = {
							"all" : "All"
						};
						var priceOptions = {
							"all" : "All"
						};
				} else if (newCategory == "homes-to-let") {
						var typeOptions = {
							"all" : "All"
						};
						var priceOptions = {
							"all" : "All"
						};
				} else if (newCategory == "commercial") {
						var typeOptions = {
							"all" : "All"
						};
						var priceOptions = {
							"all" : "All"
						};
				};
				
				$(this).parent().parent().find(".searchType").empty().addOption(typeOptions, false);
				$(this).parent().parent().find(".searchPrice").empty().addOption(priceOptions, false);
				
			});
		
		
		
		
		// ----------------------------------------------
		// search box options
		// ----------------------------------------------

			$(".searchOpen").click(function(){
				$('#searchPopup').lightbox_me({
					centered: true,
					appearEffect: "slideDown",
					disappearEffect: "slideUp",
					closeSelector: ".popupClose"
				});
				return false;
			});




		// ----------------------------------------------
		// latest news scroller
		// ----------------------------------------------

			var lnewsLock = 0;

			if($("#latestNews").length > 0) {
		
				$("#latestNews li a.showTab").click(function(){
				
					if (lnewsLock == 0){
					
						lnewsLock = 1;

						$(this).parent().siblings().removeClass("on");
						$(this).parent().addClass("on");
						$(".lnewsContent").hide();
						$(this).parent().find(".lnewsContent").fadeIn(650, function(){
							lnewsLock = 0;
						});
					
					}
				
					return false;
				
				});
			
			};



		// ----------------------------------------------
		// mortgage calculator
		// ----------------------------------------------
			
			if($("#mortCalc").length > 0) {

				$("#mortgageCalc").click(function(){
					var mcPrice,mcPayment,mcTerm,mcRate,mcDown;
					mcPrice = parseInt($("#mcPrice").val());
					mcTerm = parseInt($("#mcTerm").val()) * 12;
					mcRate = parseFloat($("#mcRate").val())/1200;
					//mcDown = 1 - parseFloat($("#mcDown").val())/100;
					//mcPrice = mcPrice * mcDown;
					mcPayment = (mcPrice*(mcRate*Math.pow(1+mcRate,mcTerm)))/(Math.pow(1+mcRate,mcTerm)-1);
					
					$("#mcAnswer").slideUp(function(){
						if(!isNaN(mcPayment)) {
							$("#mcPayment").val(""+mcPayment.toFixed(2));
						} else {
							$("#mcPayment").val('error');
						};
						$("#mcAnswer").wait(500).slideDown();
					});
					return false;
				});
				
			};





		// ----------------------------------------------
		// listings rollover and properies per page
		// ----------------------------------------------

			if($("#listingsWrap").length > 0) {

				$('#lstList .lstOne').supersleight();

				// properties per page
				// ----------------------------------------------

					$("#perPageSelected").hover(function(){
						if ($("#perPageSelected").attr("class") != "on") {
							$(this).addClass("over");
						};
					},function(){
						$(this).removeClass("over");
					});
					$("#perPageThisNumber").click(function(){
						if ($("#perPageSelected").attr("class") == "on") {
							$("#perPageOptions").stop(true,true).slideUp(function(){
								$("#perPageSelected").removeClass("on");
							});
						} else {
							$("#perPageSelected").removeClass("over");
							$("#perPageSelected").addClass("on");
							$("#perPageOptions").stop(true,true).slideDown();
						}
					});



				// individual listing hover
				// ----------------------------------------------

					$(".lstOne").hoverIntent(function(){
						$(this).find(".lstLoc").stop(true, true).slideUp(400);
						$(this).find(".lstBadge").stop(true, true).fadeOut(400); //animate({ opacity: 0 }, 400);
					},function(){
						$(this).find(".lstLoc").stop(true, true).slideDown(400);
						$(this).find(".lstBadge").stop(true, true).fadeIn(400); //animate({ opacity: 1 }, 400);
					});



				// listings navigation
				// ----------------------------------------------
					
					var lstLock = 0;
					
					function loadImage(thisImage,thisAddress,lstCount2){
						var img = new Image();
						$(img).load(function(){
							//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
							$(this).hide();
							$("#lstPanel"+ lstCount2 +" .lstPic .lstImg").removeClass("preload").append(this);
							$(this).fadeIn();
							//lstCount2++;
				        }).error(function(){
				            // notify the user that the image could not be loaded
				        }).attr('src', 'http://images.propertycms.net/_images/raymondpotterton.com/tn/'+thisImage).attr("alt",thisAddress).attr("width","174").attr("height","130");
					};
					
					// function to load listings via ajax
					function loadListings(pageNumber){
						lstLock = 1;
						$("#lstNav li").removeClass("on");
						pageNumberList = pageNumber + 1
						if(pageNumber <= totalPages){
							$("#lstNav li:nth-child("+ pageNumberList +")").addClass("on");
						};

						$("#lstListWrap").fadeOut(500,function(){
							
							$("#lstList").addClass("preload2");
							
							var thisCategory = $("#lstHeading h1").attr("id");
							var searchCat = $("#searchCat").text();
							var searchType = $("#searchType").text();
							var searchPrice = $("#searchPrice").text();
							var perPage = $("#perPageThisNumber").attr("rel");
							var lstCount = 1
							var lstCount2 = 1

							$.ajax({
								type: "GET",
								url: "/_pages/ajax/getlistings.asp?cat=" + thisCategory + "&sCat=" + searchCat + "&sType=" + searchType + "&sPrice=" + searchPrice + "&page=" + pageNumber + "&perpage=" + perPage,
								dataType: "xml",
								error: function() {
									// an internal error has occurred
									// console.log("internal error - please try again later");
								},
								success: function(xml) {
									
									//$("title").html("Residential &amp; New Homes Meath (Page "+ pageNumber +") - Raymond Potterton Auctioneers, Navan, Meath");
									//document.title = "Residential &amp; New Homes Meath (Page "+ pageNumber +") - Raymond Potterton Auctioneers, Navan, Meath";
									$(document).attr("title", "Residential & New Homes Meath (Page "+ pageNumber +") - Raymond Potterton Auctioneers, Navan, Meath");
									
									$(xml).find("listing").each(function(){
									
										$("#lstPanel"+lstCount+"").show();
										//$("#lstPanel"+lstCount+" .lstLoc").html(pageNumber + " " + $(this).find("location").text());
										$("#lstPanel"+lstCount+" .lstLoc").html($(this).find("location").text());
										$("#lstPanel"+lstCount+" .lstStrap").html($(this).find("strap").text());
										$("#lstPanel"+lstCount+" .lstPrice").html($(this).find("price").text());
										$("#lstPanel"+lstCount+" .lstOverlay a").attr("href",$(this).find("link").text());
										$("#lstPanel"+lstCount+" .lstPic .lstImg").addClass("preload");
										$("#lstPanel"+lstCount+" .lstPic .lstImg img").remove();
										$("#lstPanel"+lstCount+" .lstPic .lstBadge").html('<img src="/_images/design/badge-'+ $(this).find("badge").text() +'.png" alt="badge" width="90" height="49" />');
										var thisAddress = $(this).find("address").text();
										$("#lstPanel"+lstCount+" .lstOverlay img").attr("alt",thisAddress);
									
										var thisImage = $(this).find("img").text();
										
										loadImage(thisImage,thisAddress,lstCount);
										
										lstCount++;

									});
								
								},
								complete: function(){

									hideOverflow = lstCount-2; // -2 because we are 1 above the total shown and 0 index for GT
									if(hideOverflow == -1) { 
										hideOverflowSelector = "#lstListWrap .lstOne";
									} else {
										hideOverflowSelector = "#lstListWrap .lstOne:gt("+ hideOverflow +")";
									};
									$(hideOverflowSelector).hide();
									$("#lstList").removeClass("preload2");
									$("#lstListWrap").fadeIn(500,function(){
										
										// check we're on the right page
										highlightedPage = parseInt($("#lstNav li.on a").attr("rel"));
										if(highlightedPage != pageNumber) {
											if(pageNumber <= totalPages){
												loadListings(highlightedPage);
											} else {
												lstLock = 0;
											};
										} else {
											lstLock = 0;
										};
										$('#lstList .lstOne').supersleight();

									});
								
								}
							});
						
						});
					
					};
			
					var totalPages = $("#lstNav a.page").length;
					var firstLoad = "yes";
					
					// on page click, change hash
					$("#lstNav a.page").click(function(){
						if(lstLock == 0) {
							var ajaxPage = $(this).attr("rel");
							$.bbq.pushState({ page: ajaxPage });
						};
						return false;
					});

					// on next click, change hash
					$("#lstNav a.next").click(function(){
						if(lstLock == 0) {
							currentPage = parseInt($("#lstNav li.on a").attr("rel"));				
							if (currentPage < totalPages) { 
								var ajaxPage = currentPage+1;
								$.bbq.pushState({ page: ajaxPage });
							};
						};
						return false;
					});

					// on prev click, change hash
					$("#lstNav a.prev").click(function(){
						if(lstLock == 0) {
							currentPage = parseInt($("#lstNav li.on a").attr("rel"));				
							if (currentPage > 1) { 
								var ajaxPage = currentPage-1;
								$.bbq.pushState({ page: ajaxPage });
							};
						};
						return false;
					});

					// watch for hash changes and then execute ajax load
					$(window).bind("hashchange", function(e) {

						var urlPage = e.getState("page");
						if (urlPage == undefined) { urlPage = "1" };

					    $("#lstNav a.page").each(function(){
					      var ajaxThisPage = $(this).attr("rel");

					      if (ajaxThisPage === urlPage) {
					        $(this).parent().addClass("on");
					      } else {
					        $(this).parent().removeClass("on");
					      }
					    });
					
						if (firstLoad == "yes") {
							firstLoad = "no";

							// check we're on the right page
							highlightedPage = parseInt($("#lstNav li.on a").attr("rel"));
							if(highlightedPage != 1) {
								if(parseInt(urlPage) <= totalPages){
									loadListings(highlightedPage);
								};
							};

						} else {
							if(lstLock == 0) {
						    	loadListings(parseInt(urlPage));
							};
						};
					});
					
					// required to load properly
					$(window).trigger("hashchange");
			
			};




		// ----------------------------------------------
		// detail page photo control, map, etc.
		// ----------------------------------------------

			if($("#detailWrap").length > 0) {
				
				$('#lstList .lstOne').supersleight();

				// ----------------------------------------------
				// popup boxes
				// ----------------------------------------------

					$(".popupLink").click(function(){
						var thisPopup = $(this).attr("id")
						$("#popup" + thisPopup).lightbox_me({
							centered: true,
							appearEffect: "slideDown",
							disappearEffect: "slideUp",
							closeSelector: ".popupClose",
							onLoad: function() { 
								$("#popup" + thisPopup).find("input:first").focus()
							}
						});
						return false;
					});
					
					$(".popupBox form").submit(function(){
						
						formAction = $(this).attr("action");

						formID = $(this).attr("id");
						formErrorID = $(this).find(".errorBox").attr("id");
						formErrorAutohide = 0;
						formPopupClose = 1;
						formData = "";
						formRedirect = "";

						formData = $(this).serialize();
						
						// alert(formID)
						// alert(formErrorID)
						// alert(formErrorAutohide)
						// alert(formData)
						// alert(formRedirect)
						
						submitAjaxForm(formID,formErrorID,formErrorAutohide,formAction,formData,formRedirect,formPopupClose);
						
						return false;
					});



				// individual listing hover
				// ----------------------------------------------

					$(".lstOne").hoverIntent(function(){
						$(this).find(".lstLoc").stop(true, true).slideUp(400);
						$(this).find(".lstBadge img").stop(true, true).animate({ opacity: 0 }, 400);
					},function(){
						$(this).find(".lstLoc").stop(true, true).slideDown(400);
						$(this).find(".lstBadge img").stop(true, true).animate({ opacity: 1 }, 400);
					});
			

				
				// cycle through thumbs
				// ----------------------------------------------

					$("#dtlPhotoThumbsInner").cycle({ 
					    fx: 'scrollHorz',
						timeout: 0,
						pause: 0,
						prev: '#dtlPhotoLeft a',
						next: '#dtlPhotoRight a'
					});


				
				// add opacity to unselected thumbs
				// ----------------------------------------------

					$("#dtlPhotoThumbsInner li a:not(.on)").animate({
						opacity: 0.5
					},0);


				
				// medium opacity effect on hover and full opacity when clicked
				// ----------------------------------------------

					$("#dtlPhotoThumbsInner li a").hover(function(){
						if($(this).hasClass("on")){
							// nothing
						} else {
							$(this).animate({
								opacity: 0.8
							},0);
						}
					},function(){
						if($(this).hasClass("on")){
							// nothing
						} else {
							$(this).animate({
								opacity: 0.5
							},0);
						}
					}).click(function(){
						var thisID = $(this).attr("rel");
						$("#dtlPhotoThumbsInner li a.on").removeClass("on").animate({
							opacity: 0.5
						},0);
					
						$(this).animate({
							opacity: 1
						},0).addClass("on");
					
						$("#dtlPhotoLarge li").fadeOut();
						$("#largePhoto"+thisID).fadeIn();
						
					});
				


				// cycle through large photos (preloading basicall)
				// ----------------------------------------------

					$("#dtlPhotoLarge ul").cycle({ 
					    fx: 'scrollHorz',
						timeout: 0,
						pause: 0
					});

				
			};





});
