﻿var photoSetOffset = 0;
var setSize = 10;
var currentImage = 0;
var isSlideshow = false;
var slideTimeoutID = null;
var slideCount = 0;
var isImageLoading = false;

function isLoaded() {
	if (typeof (images) == 'undefined') return false;	
	if (typeof (thumbnails) == 'undefined') return false;	
	if (typeof (captions) == 'undefined') return false;	
	if (typeof (alphaListingID) == 'undefined') return false;	
	return true;
}

function updateCaption() {
	if (!isLoaded()) return 0;
	var photoCaption = getElement('photoCaption');
	if (photoCaption == undefined) return 0;

}

function showSprite() {
	var sprite = getElement('mainphotoSprite');
	if (sprite != undefined) {
		sprite.style.display = 'inline-block';
	}
}

function hideSprite() {
	var sprite = getElement('mainphotoSprite');
	if (sprite != undefined) {
		sprite.style.display = 'none';
	}
}

function updatePhoto(thumbnailAnchor) {
	if (!isLoaded()) return 0;

	var mainPhoto = getElement('mainPhoto');
	if (mainPhoto == undefined) return 0;

	var photoCaption = getElement('photoCaption');
	if (photoCaption == undefined) return 0;

	var spriteTimer = null;
	if (!isSlideshow) spriteTimer = setTimeout('showSprite()', 600);  // set timer to show after downloading for 600ms 

	// set the global value to show that the image is currently opening
	isImageLoading = true;

	var newImage = new Image();

	// setup the event to handle the d/l of the new image src; this will cause all these actions to fire on the download rather than the click
	newImage.onload = function() {
		mainPhoto.src = this.src;
		thumbnailAnchor.className = thumbnailAnchor.className + ' selected';
		photoCaption.innerHTML = captions[currentImage];
		mainPhoto.alt = captions[currentImage];
		mainPhoto.title = captions[currentImage];
		if (spriteTimer != null) clearTimeout(spriteTimer);
		hideSprite();  // just in case
	}

	// now ask for the download	
	newImage.src = images[currentImage];

	// tracking pixel
	var trackingPixel = new Image();
//	var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
//	var hostname = window.location.hostname;
	var tpixelsrc = '';
//	if (hostname != 'localhost') { 
//		tpixelsrc = protocol + hostname;
//	}	
	tpixelsrc = tpixelsrc + '/Handlers/ImageTracker.ashx?alid=' + alphaListingID + '&ii=' + currentImage;
	if (typeof (customerID) != 'undefined') {
		tpixelsrc = tpixelsrc + '&custid=' + customerID;
	}	
	trackingPixel.src = tpixelsrc;

	isImageLoading = false;

	preLoad();
}


function selectThumbnail(index) {
	//escape cases
	if (!isLoaded()) return 0;	
	var thumbnail = getElement('thumbnail' + String(index));
	if (thumbnail == undefined) return 0;
	if (thumbnail.className.indexOf('selected') >= 0) return 0;
	if (thumbnail.style.visibility == 'hidden') return 0;

	var thumbnailBox = getElement('thumbnailBox');
	if (thumbnailBox == undefined) return 0;

	
	// reset the current selected thumbnail
	for (var i = 0; i < thumbnailBox.children.length; i++) {
		if (thumbnailBox.children.item(i).tagName.toUpperCase() == 'A') {
			thumbnailBox.children.item(i).hideFocus = true;
			thumbnailBox.children.item(i).className = thumbnailBox.children.item(i).className.replace(' selected', '');
		}
	}

	// update the page with the selected thumbnail
	currentImage = index + photoSetOffset;
	updatePhoto(thumbnail);
}

function selectPhotoSet(index, thumbnailIndex) {
	//escape cases
	if (!isLoaded()) return 0;

	var photoSet = getElement('photoSet' + String(index));
	if (photoSet == undefined) return 0;
	if (photoSet.className.indexOf('selected') >= 0) return 0;

	var thumbnailBox = getElement('thumbnailBox');
	if (thumbnailBox == undefined) return 0;

	var photoSetBox = getElement('photoSetBox');
	if (photoSetBox == undefined) return 0;

	photoSetOffset = index * setSize;

	if ((thumbnailIndex == undefined) || (thumbnailIndex == null)) thumbnailIndex = 0;

	// reset the current photo set selection
	for (var i = 0; i < photoSetBox.children.length; i++) {
		if (photoSetBox.children.item(i).tagName.toUpperCase() == 'A') {
			photoSetBox.children.item(i).className = photoSetBox.children.item(i).className.replace(' selected', '');
		}
	}

	// now update the thumbnails and selections
	var count = 0;
	var thumbnail;
	var anchor;
	var selectedIndex = 0;

	for (var i = 0; i < thumbnailBox.children.length; i++) {
		if (thumbnailBox.children.item(i).tagName.toUpperCase() == 'A') {
			anchor = thumbnailBox.children.item(i);
			if ((anchor.children.length > 0) && (anchor.children.item(0).tagName.toUpperCase() == 'IMG')) {
				thumbnail = thumbnailBox.children.item(i).children.item(0);  // ref to the image
				anchor.className = anchor.className.replace(' selected', ''); // unselect the anchor tag (default)

				if (count + photoSetOffset < images.length) { // make sure we have more photos, otherwise hide the links
					anchor.style.visibility = 'visible'; // ensure visibility
					thumbnail.src = thumbnails[photoSetOffset + count];
					if (count <= thumbnailIndex) { // selected thumbnail?
						selectedIndex = count;
					}
					count++;
				}
				else {
					anchor.style.visibility = 'hidden';  // we're past image count, hide the anchor and image
				}
			}
		}
	}

	selectThumbnail(selectedIndex);
	photoSet.className = photoSet.className + ' selected';
}

function selectNextPhoto() {	
	if (!isLoaded()) return 0;
	if ((currentImage % setSize == 9) || (currentImage == images.length - 1)) {
		// last photo of set, so move to next set if there is a next set
		if (setSize >= images.length) {
			selectThumbnail(0);
		} else {
			var setCount = Math.floor(images.length / setSize) + (images.length % setSize == 0 ? 0 : 1);
			var currentSet = Math.floor(currentImage / setSize);
			if (currentSet < setCount - 1) {
				selectPhotoSet(currentSet + 1);
			}
			else {
				selectPhotoSet(0);
			}
		}
	}
	else {
		var thumbnailIndex = currentImage % setSize;
		selectThumbnail(thumbnailIndex + 1);
	}
}

function selectPreviousPhoto() {
	if (!isLoaded()) return 0;
	if (currentImage % setSize == 0) {
		// first photo of set, so move to previous set if there is a previous set
		if (setSize >= images.length) {
			selectThumbnail(images.length - 1);
		} else {
			var currentSet = Math.floor(currentImage / setSize);
			if (currentSet > 0) {
				selectPhotoSet(currentSet - 1, setSize - 1);
			}
			else {
				var setCount = Math.floor(images.length / setSize) + (images.length % setSize == 0 ? 0 : 1);
				selectPhotoSet(setCount - 1, setSize - 1);
			}
		}
	}
	else {
		var thumbnailIndex = currentImage % setSize;
		selectThumbnail(thumbnailIndex - 1);
	}
}

function playSlideshow() {
	var slideshowAnchor = getElement('slideshow');
	if (slideshowAnchor != undefined) slideshowAnchor.innerHTML = 'Stop Slideshow';
	isSlideshow = true;
	playSlide();
}

function playSlide() {	
	if (isSlideshow) {
		if (!isImageLoading) {
			selectNextPhoto();
			slideCount++;
			if (slideCount < images.length) {
				slideTimeoutID = setTimeout('playSlide()', 2000);
			}
			else {
				slideTimeoutID = null;
				stopSlideshow();
			}
		}
		else {
			slideTimeoutID = setTimeout('playSlide()', 2000);
		}
	}
}

function stopSlideshow() {
	var slideshowAnchor = getElement('slideshow');
	if (slideshowAnchor != undefined) slideshowAnchor.innerHTML = 'View Slideshow';
	if (slideTimeoutID != null) clearTimeout(slideTimeoutID);
	isSlideshow = false;
	slideCount = 0;
	slideTimeoutID = null;
}

function slideShowClick(anchor) {
	if (!isLoaded()) return 0;
	if (anchor.innerHTML == 'View Slideshow') {
		slideCount = 0;
		playSlideshow();
	}
	else {
		stopSlideshow();
	}
}

function preLoad() {
	// loads the next and previous images into the browser cache to increase performance
	if (!isLoaded()) return 0;
	var prevIndex = currentImage == 0 ? images.length - 1 : currentImage - 1;
	var nextIndex = currentImage == images.length - 1 ? 0 : currentImage + 1;

	var prevImage = new Image();
	var nextImage = new Image();

	nextImage.src = images[nextIndex];
	prevImage.src = images[prevIndex];
}

function preFetchThumbnails() {
	// we could have done this recursively, but IE is lame with a stack depth max of 12
	if (isLoaded()) {
		for (var i = 0; i < thumbnails.length; i++) {
			var prethumb = new Image();
			prethumb.src = thumbnails[i];
		}
	}
}

var thumbTimer = null;
function loadEvent() {
	thumbTimer = setTimeout('preFetchThumbnails()', 5000); // 5-second delay before caching all the thumbnails
	preLoad();
}

function unloadEvent() {
	if (thumbTimer != null) clearTimeout(thumbTimer);
}

function contactSellerClickShow(e, pos, hoffset, voffset) {
	positionElement(e, pos, hoffset, voffset);
	showElement(e);
}

attachEventHandler(window, 'load', loadEvent);
attachEventHandler(window, 'unload', unloadEvent);


function validateEmailFriend(){
	$("#EmailFriend_YourNameRequired").hide();
	$("#EmailFriend_YourEmailRequired").hide();
	$("#EmailFriend_FriendEmailRequired").hide();
	$("#EmailFriend_MessageRequired").hide();

	var valid = true;	
	if ($("#TextBoxEmailFriendYourName").val() == "")
	{
		$("#EmailFriend_YourNameRequired").show();
		valid = false;
	}
	if ($("#TextBoxEmailFriendYourEmail").val() == "")
	{
		$("#EmailFriend_YourEmailRequired").text("Required");
		$("#EmailFriend_YourEmailRequired").show();
		valid = false;
	}
	else
	{
		var emailtext = $("#TextBoxEmailFriendYourEmail").val();		
		if (emailtext.match(new RegExp("^[\s]*(([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))[\s]*$")) == null) {
			$("#EmailFriend_YourEmailRequired").text("Invalid");
			$("#EmailFriend_YourEmailRequired").show();
			valid = false;
		}	
	}
	if ($("#TextBoxEmailFriendEmail").val() == "") {
		$("#EmailFriend_FriendEmailRequired").show();
		valid = false;
	}
	else {
		var emailtext = $("#TextBoxEmailFriendEmail").val();
		if (emailtext.match(new RegExp("^[\s]*(([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))[\s]*$")) == null) {
			$("#EmailFriend_FriendEmailRequired").text("Invalid");
			$("#EmailFriend_FriendEmailRequired").show();
			valid = false;
		}
	}
	if ($("#TextBoxEmailFriendMessage").val() == "")
	{				
		$("#EmailFriend_MessageRequired").show();
		valid = false;
	}									
	return valid;
}

function validateContactSeller(){

	$("#ContactSeller_YourName").hide();
	$("#ContactSeller_YourEmail").hide();
	$("#ContactSeller_Message").hide();
	var valid = true;	
	if ($("#TextBoxName").val() == "")
	{
		$("#ContactSeller_YourName").show();
		valid = false;
	}
	if ($("#TextBoxEmail").val() == "")
	{
		$("#ContactSeller_YourEmail").text("Required");
		$("#ContactSeller_YourEmail").show();
		valid = false;
	}
	else
	{
		var emailtext = $("#TextBoxEmail").val();
		if (emailtext.match(new RegExp("^[\s]*(([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))[\s]*$")) == null) {
			$("#ContactSeller_YourEmail").text("Invalid");
			$("#ContactSeller_YourEmail").show();
			valid = false;
		}
	}	
	if ($("#TextBoxMessage").val() == "")
	{				
		$("#ContactSeller_Message").show();
		valid = false;
	}									
	return valid;
}
function getPhones() {
	var dataToSend = "{'alphaListingId':'" + $("#HiddenAlphaListingID").val() + "'}";
	$("#DivContactSellerCaptcha").hide();
	$("#DivContactSellerDetails").show();
	$.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: "/search/listing-rewrite.aspx/getphonenumbers",
		data: dataToSend,
		dataType: "json",
		success: function (data) {
			if (data.d != '') {
				$.each(data.d, function (i, item) {
					$("#PhoneList").append("<li>" + item.phoneType + "<br/><b>" + item.phoneNumber + "</b></li>")
				});
				$("#NoPhone").hide();
				$("#Phone").show();
			}
		},
		error: function () {
		},
		complete: function () {
		},
		async: true,
		timeout: 3000
	});
}


$(document).ready(function () {

	$("#AnchorPropertyTypeContactSeller").click(function (e) {
		e.preventDefault();
		ntptEventTag('ev=showlisting_viewcontactinfo');
		resetContactSeller();
		$("#" + calloutContactSellerID).find(".notch").css("left", 0);
		$("#" + calloutContactSellerID).find(".notch").css("top", 20);
		$("#" + calloutContactSellerID).attr('class', 'callout callout-large-sidenotch callout-left-notch');
		$("#" + calloutContactSellerID).show();
		$("#" + calloutContactSellerID).position({
			my: "left top",
			at: "right center",
			of: "#AnchorPropertyTypeContactSeller",
			offset: "0 -38",
			collision: "none none"
		});
	});

	$("#AnchorContactSellerFromDescription").click(function (e) {
		e.preventDefault();
		ntptEventTag('ev=showlisting_viewcontactinfo');
		resetContactSeller();
		var top = $("#AnchorContactSellerFromDescription").position().top;
		$("#" + calloutContactSellerID).find(".notch").css("left", 80);
		$("#" + calloutContactSellerID).find(".notch").css("top", 0);
		$("#" + calloutContactSellerID).attr('class', 'callout callout-large-nosidenotch callout-top-notch');
		$("#" + calloutContactSellerID).show();
		$("#" + calloutContactSellerID).position({
			my: "center top",
			at: "right bottom",
			of: "#AnchorContactSellerFromDescription",
			offset: "115 0",
			collision: "none none"
		});
	});

	$("#link_contact, #link_message").click(function (e) {
		e.preventDefault();
		ntptEventTag('ev=showlisting_viewcontactinfo');
		resetContactSeller();
		$("#" + calloutContactSellerID).find(".notch").css("left", 504);
		$("#" + calloutContactSellerID).find(".notch").css("top", 20);
		$("#" + calloutContactSellerID).attr('class', 'callout callout-large-sidenotch callout-right-notch');
		$("#" + calloutContactSellerID).show();
		$("#" + calloutContactSellerID).position({
			my: "right top",
			at: "left top",
			of: "#h3ContactSeller",
			offset: "0 -28",
			collision: "none none"
		});

	});

	$("#AnchorClose").click(function () {
		$("#" + calloutContactSellerID).hide();
	});

  $("#recaptcha_response_field").keypress(function (e) {
		if (e.keyCode == 13) {
			$("#AnchorVerify").trigger('click');
		}
	});

	$("#ActionButtonCloseEmailFriend").click(function () {
		$("#" + calloutEmailFriendID).hide();
	});

	$("#ActionButtonEmailFriend").click(function (e) {
		e.preventDefault();
		if (validateEmailFriend()) {
			var dataToSend = "{'alphaListingId':'" + $("#HiddenAlphaListingID").val() + "'";
			dataToSend += ",'yourName':'" + $("#TextBoxEmailFriendYourName").val() + "'";
			dataToSend += ",'yourEmail':'" + $("#TextBoxEmailFriendYourEmail").val() + "'";
			dataToSend += ",'friendsEmail':'" + $("#TextBoxEmailFriendEmail").val() + "'";
			dataToSend += ",'message':'" + $("#TextBoxEmailFriendMessage").val() + "'}";

			$.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: "/search/listing-rewrite.aspx/emailtofriend",
				data: dataToSend,
				dataType: "json",
				success: function () {
				},
				error: function () {
				},
				complete: function () {
				},
				async: true,
				timeout: 3000
			});
			$("#TextBoxEmailFriendEmail").val("")
			$("#TextBoxEmailFriendMessage").val("")
			$("#DivEmailFriend").hide();
			$("#DivEmailFriendConfirm").show();
		}
	});

	$("#TextBoxMessage, #TextBoxEmailFriendMessage").keypress(function (e) {		
		if ($(this).val().length >= 200) {
			if (e.which == 13 || (e.which >= 32 && e.which <= 126)) {
				e.preventDefault();
			}
		}
	});

	$("#TextBoxMessage").keyup(function () {
		$("#CharsRemaining").text(200 - $(this).val().length + " Remaining");
	});

	
	$("#TextBoxMessage").bind('paste', function (e) {
		e.preventDefault();
	});

	$("#AnchorVerify").click(function (event) {
		event.preventDefault();
		$("#InvalidCaptcha").hide();
		$("#PhoneList").each(function (n, item) { $(item).empty(); });
		var alphaListingId = $("#HiddenAlphaListingID").val();

		var dataToSend = "{'challenge':'" + $("#recaptcha_challenge_field").val() + "'";
		dataToSend += ",'response':'" + $("#recaptcha_response_field").val() + "'";
		dataToSend += ",'alphaListingId':'" + alphaListingId + "'}";
		$.ajax({
			type: "POST",
			contentType: "application/json; charset=utf-8",
			url: "/search/listing-rewrite.aspx/verifycaptcha",
			data: dataToSend,
			dataType: "json",
			success: function (data) {
				$("#DivContactSellerCaptcha").hide();
				$("#DivContactSellerDetails").show();
				if (data.d != '') {
					$.each(data.d, function (i, item) {
						$("#PhoneList").append("<li>" + item.phoneType + "<br/><b>" + item.phoneNumber + "</b></li>")
					});
					$("#NoPhone").hide();
					$("#Phone").show();
				}
				else {
					$("#NoPhone").show();
					$("#Phone").hide();
				}
			},
			error: function (xhr, status, error) {
			  $("#InvalidCaptcha").show();
			  showRecaptcha('DivContactSellerCaptcha');
			},
			complete: function () {
				$("#TextBoxVerify").val("");
			},
			async: true,
			timeout: 3000
		});
	});

	$("#AnchorSendMessage").click(function (event) {
		event.preventDefault();
		if (validateContactSeller()) {
			$("#ContactSellerConfirm").show();
			$("#ContactSellerForm").hide();
			$("#NoPhone").hide();

			var dataToSend = "{'alphaListingId':'" + $("#HiddenAlphaListingID").val() + "'";
			dataToSend += ",'yourName':'" + $("#TextBoxName").val() + "'";
			dataToSend += ",'yourEmail':'" + $("#TextBoxEmail").val() + "'";
			dataToSend += ",'message':'" + $("#TextBoxMessage").val() + "'}";

			$.ajax({
				type: "POST",
				contentType: "application/json; charset=utf-8",
				url: "/search/listing-rewrite.aspx/sendselleremail",
				data: dataToSend,
				dataType: "json",
				success: function () {
				},
				error: function (xhr, status, error) {
				},
				complete: function () {
					$("#TextBoxMessage").val("");
				},
				async: true,
				timeout: 3000
			});
		}
	});
});

function resetEmailFriend() {
	$("#" + calloutContactSellerID).hide();
	$("#DivEmailFriend").show();
	$("#DivEmailFriendConfirm").hide();
}

function resetContactSeller() {
	$("#CharsRemaining").text((200 - $("#TextBoxMessage").val().length) + " Remaining");
	$("#" + calloutEmailFriendID).hide();
	if ($("#" + calloutContactSellerID).is(':hidden')) {
	  $.ajax({
	    type: "POST",
	    contentType: "application/json; charset=utf-8",
	    url: "/search/listing-rewrite.aspx/iscaptchavalid",
	    dataType: "json",
	    success: function (data) {
	      if (data.d) {
	        $("#DivContactSellerCaptcha").hide();
	        $("#DivContactSellerDetails").show();
	        $("#ContactSellerConfirm").hide();
	        $("#ContactSellerForm").show();
	      } else {
	        if (isCaptchaCreated == true) {
	          $("#DivContactSellerCaptcha").show();
	        } else {
	          showRecaptcha('DivContactSellerCaptcha');
	        }
	        $("#DivContactSellerDetails").hide();
	      }
	    },
	    error: function (xhr, status, error) {
	    },
	    complete: function () {
	    },
	    async: true,
	    timeout: 3000
	  });
	}
}
