﻿/* google analytics */
$(function() {
	if (!window.asyncGaqLoaded) {
		window.asyncGaqLoaded = true;
		(function() {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		})();
	}
});
window._gaq = window._gaq || [];
window.gaGroup = window.gaGroup || [];
(function() {
	var oldGaGroup = window.gaGroup;
	window.gaGroup = {
		length: 0,
		accounts: [],
		push: function(arr) {
			if (arr[0].indexOf('.') != -1) {
				var acc = arr[0].split('.')[0];
				var accExists = false;
				for (var i = 0; i < this.accounts.length; i++)
					if (this.accounts[i] == acc) {
					accExists = true;
					break;
				}
				if (!accExists) this.accounts.push(acc);
				return _gaq.push(arr);
			}
			var ret = null;
			for (var i = 0; i < this.accounts.length; i++) {
				var clone = arr.slice(0);
				clone[0] = this.accounts[i] + '.' + clone[0];
				ret = _gaq.push(clone);
			}
			return ret;
		}
	};

	var val = null;
	for (var i = 0; i < oldGaGroup.length; i++)
		gaGroup.push(oldGaGroup[i]);
})();

/*
* Global Vars
*
*/
var tributeWallTipTimeout = false;
var ajaxRequest = false;
var ajaxRequestPager = false;
var ajaxAnnotate = false;
var currentTab = "#TributeWall";
var mediaVideoUploader;
var mediaPhotoUploader;
var setEditFieldsLoading = false;
var callbackLogin = false;
var callbackLogout = false;
var filesKeys = false;
var mediaFiles = [];
var currentUrl;
var currentAlbum;
var currenMediatFile;

/*
* Guestbook Entry
*
* Description:
*   Manage Guestbook Entries
*   Add Photos & Videos - Candles - Gifts
*
*/

var GuestbookEntry = {

	settings: {
		currentTab: ""
	},

	initialize: function() {
		if (!$("#guestbookEntry").get(0)) return false;
		this.upload.parent = this;
		this.upload.initialize();
		this.events();
		this.upload.events();
		//this.expressLogin = new ExpressLogin("#memorialExpressLogin", { container: "#guestbookEntry" });
		return this;
	},

	hide: function(clear) {
		$("#shareTabs").removeClass("controls-active");
		$("#shareTabs ul li").removeClass("active");
		$("#shareContent").hide();
		$("#shareContent div.line").hide();
		this.settings.currentTab = "";
		this.checkReady();
		this.showComment();
		//this.expressLogin.unlock();
		//if ($("#txtShare").val() == "") this.expressLogin.hide();
		$("#formShareControls").show();
		$("div.record-screen, div.media-link").hide();
		$("div.media-screen, ul.media-options").hide();
		$("#candleList, #giftList").html(""); // prevent bug ie7
		if (clear) {
			$("#txtShare").val("").blur();
			$("#txtShare").css({ 'height': '27px', 'min-height': '27px' });
		}
	},

	showComment: function() {
		$("#formShareComment:hidden").show();
	},

	submit: function() {

		var $this = this;

		if (LifeTributes.readOnly) {
			$('#ReadonlyAlert').click();
		} else {
			if ($("#lnkShare").attr("disabled") == "disabled") return;

			if (this.settings.currentTab && typeof (GuestbookEntry[GuestbookEntry.settings.currentTab].submit) != "undefined") {
				return this[this.settings.currentTab].submit.apply(this);
			} else {
				this.createGuestbookEntry();
			}

		}
	},

	createGuestbookEntry: function() {

		var $this = this;
		$("#output").fadeOut(300);

		var isMediaEmpty = ($("div.media-preview ul li.photo").length == 0);
		var isTextEmpty = ($.trim($("#txtShare").val()) == "");
		var isLinkingVideo = ($("div.media-screen div.media-link:visible").length > 0);

		if (isMediaEmpty && isTextEmpty) {
			$("#lnkShare").removeAttr("disabled");
			if (isLinkingVideo) {
				this.upload.linkVideo(function() {
					$("div.media-preview").hide();
					$this.createGuestbookEntry();
				});
			} else {
				$("#output").html("Please enter a comment.");
				$("#output").fadeIn(300);
				$("#txtShare").focus();
			}
			$("span.button-loading", "#lnkShare").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
			$("#lnkShare").removeAttr("disabled");
			return;
		}

		var comment = {
			"Text": ($("#txtShare").val()),
			"ItemId": LifeTributes.tributeId,
			"Medias": []
		};

		var loginData = Login.getData();
		if (loginData.source == Login.LoginSources.guest) {
			$.extend(comment, loginData);
		} else if (!LifeTributes.User.isAuth) {
			Login.open({
				onLogin: function(data) {
					GuestbookEntry.createGuestbookEntry();
				}
			});
			return;
		}

		var medias = $("li.photo", $("div.media-preview"));
		medias.each(function(i) {
			if (this.media) {
				var title = $(this).find("textarea").val();
				comment.Medias[i] = this.media.item;
				comment.Medias[i].Title = title || "";
			}
		});

		if (ajaxRequest) {
			ajaxRequest.abort();
			ajaxRequest = false;
		}

		var url = LifeTributes.tributeURL;
		url += LifeTributes.isExpired ? "/CreateExpiredGuestbookEntry" : "/CreateGuestbookEntry";

		ajaxRequest = $.ajax({
			url: url,
			type: "POST",
			dataType: "json",
			data: $.toJSON(comment),
			contentType: "application/json; charset=utf-8",
			beforeSend: function() {
				$("#lnkShare").prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
				$("span.button-loading", "#lnkShare").width($("#lnkShare").parent().width());
				$("#lnkShare").attr("disabled", "disabled");
			},

			success: function(responseText) {
				switch (responseText.status) {
					case GeneralLifeTributeStatus.Success:
						if ($("#wallPager").is(':visible')) {
							$("#TributesComments > li:last").remove();
						}
						$("#TributesComments").prepend(responseText.added);

						$("#output").fadeOut(300);
						$("div.block-share").removeClass("block-share-focus");

						$("div.media-preview div.media-items ul li").remove();

						$this.hide(true);
						$("li.no-items-found").remove();

						$("#txtShare").removeClass('block-share-focus');

						TributeWall.setEditFields();

						$("#shareTabs ul li").removeClass("active");
						$("#shareContent").hide();

						$("div.media-preview ul").remove();
						$("div.media-preview").hide();

						TributeWall.events();

						storeAds.show();

						break;

					case GeneralLifeTributeStatus.Error:
						$("#output").html("We couldn't process your request. Please try again.");
						$("#output").fadeIn(300);
						break;

					case GeneralLifeTributeStatus.ReadonlyTribute:
						$("#ReadonlyAlert").click();
						break;

					case GeneralLifeTributeStatus.RegisterExists:
						//$this.expressLogin.registerExists();
						break;

					case GeneralLifeTributeStatus.UserNotFound:
						//$this.expressLogin.userNotFound();
						break;

					case GeneralLifeTributeStatus.RequiredFieldsEmpty:
						//$this.expressLogin.error();
						break;
				}
			},

			error: function() {
				$("#output").html("We couldn't process your request. Please try again.");
				$("#output").fadeIn(300);
			},

			complete: function() {
				ajaxRequest = false;
				$("span.button-loading", "#lnkShare").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				$("#lnkShare").removeAttr("disabled");
			}
		});

	},

	events: function() {
		var $this = this;
		// Share text block events
		$("#txtShare").growfield({});
		$("#txtShare").val("").css({ 'height': '27px', 'min-height': '27px' });
		$("#txtShare").watermark();
		$("#txtShare").click(function(e) {
			if (LifeTributes.readOnly) $('#ReadonlyAlert').click();
		}).focus(function() {
			$('div.block-share').addClass('block-share-focus');
			$("#txtShare").css('min-height', '70px');
			$this.checkReady();
		}).blur(function(e) {
			$('div.block-share').removeClass('block-share-focus');
			$this.checkReady();
			$this.adjustWatermark(this);
		}).keydown(function() {
			$this.checkReady();
		});
		this.adjustWatermark("#txtShare");

		$("#shareTabs ul li:eq(0)").addClass("item-first");
		$("#shareTabs ul li:last").addClass("item-last");

		// Add History Exceptions
		$.History.bindException("\^/GiftStore");

		$(document).bind("click.share", function(e) {
			var target = e.target || e.originalTarget;
			var form = $("#guestbookEntry").get(0);
			var isEmpty = ($("#txtShare").val() == "");
			var isOutside = !($.inArray(form, $(target).parents()) != -1);
			if (isOutside && isEmpty) {
				$this.adjustWatermark("#txtShare");
				$("#output").fadeOut(300);
			}
		});

		// Close button event
		$("#shareContent a.close-button").click(function(e) {
			e.stopPropagation();
			$this.hide();
		});

		// Submit button event
		$("#lnkShare").click(function(e) {
			e.preventDefault();
			if ($(this).attr("disabled")) return false;
			$this.submit();
		});

		// Tabs events
		$("#shareTabs ul li a").click(function(e) {
			e.stopPropagation();

			if (LifeTributes.readOnly) {
				$('#ReadonlyAlert').click();
				return;
			}

			var ul = $("#shareTabs ul"), li = $(this).parents("li:first");
			var index = $("#shareTabs ul li").index(li);
			var tab = $(this).attr("class").match(/icon\-([a-z]+)/i)[1] || "";

			if (index == ($("#shareTabs ul li").length - 1) && $("#shareTabs ul li").length >= 4) {
				$("#shareContent a.close-button").addClass("close-button-last");
			} else {
				$("#shareContent a.close-button").removeClass("close-button-last");
			}

			if (!li.hasClass("active")) {
				$("#shareTabs").addClass("controls-active");
				// Show active tab
				ul.children("li.active").removeClass("active");
				li.addClass("active");
				// Show share content
				$("#shareContent div.line").hide().css("visibility", "hidden");
				$("#shareContent div.line-" + tab).show().css("visibility", "visible");
				$("#output").fadeOut(300);
				$("#shareContent, #formShareControls").show();
				$this.settings.currentTab = tab;
				$this.checkReady();
				$this.showComment();
				// Call share tab function
				if ($this[tab].show) $this[tab].show.apply($this);
			} else {
				$this.hide();
			}
		});

		$("#shareTabs a.icon-gift").click(function(e) {
			if(GuestbookEntry.gift.tmpReferrerICN != "") {
				GuestbookEntry.gift.referrerICN = GuestbookEntry.gift.tmpReferrerICN;
				GuestbookEntry.gift.tmpReferrerICN = "";
			} else {
				GuestbookEntry.gift.referrerICN = "memorial_page_walltab";
			}
		});
	},

	checkReady: function() {
		if (this.settings.currentTab == "") {
			$('div.block-share')[$("#txtShare").val() != "" ? "addClass" : "removeClass"]("block-share-ready");
		} else {
			$('div.block-share').addClass("block-share-ready");
		}
	},

	adjustWatermark: function(textarea) {
		textarea = $(textarea);
		if (textarea.val() == "") {
			textarea.stop(true, true);
			setTimeout(function() {
				textarea.stop(true, true);
				var watermark = textarea.closest("div.input-textarea").find("span.watermark");
				var minHeight = watermark.height();
				if (minHeight > 20) textarea.css({ "min-height": minHeight, "height": minHeight });
			}, 150);
		}
	},

	unload: function() {
		//delete this.expressLogin;
		$(document).unbind("click.share");
	}
};

/* Guestbook - Photos & Videos (Media Upload) */
GuestbookEntry.upload = {

	ajaxRequest: false,
	wrapper: "#guestbookEntry",
	list: "#guestbookEntry div.media-preview",

	initialize: function() {
		this.handlers.parent = this;
		this.medias.parent = this;
		this.pager = this.parent.pager;
	},

	show: function() {
		$("div.media-screen, ul.media-options").show();
		$("div.record-screen, div.media-link").hide();
		$("div.flash-recorder div.custom-message").hide().css("opacity", 0);
		this.pager.initialize(this.upload, this.upload.list);
		//GuestbookEntry.expressLogin.show();
	},

	hide: function() {
		$("div.media-screen, ul.media-options").show();
		$("div.record-screen, div.media-link").hide();
		$("div.flash-recorder div.custom-message").hide().css("opacity", 0);
	},

	events: function() {
		var guestBookEntry = $("#shareContent div.line-upload").get(0);
		var PhotosVideos = $("#blockAddMedia").get(0);
		if (!guestBookEntry && !PhotosVideos) return;

		var $this = this;
		this.flashUpload();
		this.videoRecorder();
		$("ul.media-options li.record").click(function() {
			$("div.media-screen").hide();
			$("div.record-screen").show();
			setTimeout(function() {
				$("div.flash-recorder div.custom-message").show().css("opacity", 1); ;
				RoundedCorners.makeCorner($("div.flash-recorder div.custom-message").get(0));
			}, 5000);
		});

		$("ul.media-options li.link").click(function() {
			$("ul.media-options").hide();
			$("div.media-link").show();
		});

		$("#backToMediaOptions, #cancelVideoRecording").click(function(e) {
			e.preventDefault();
			$this.hide();
		});

		$("#txtUrl").focus(function() {
			$(this).get(0).select();
		});

		$("#txtUrl").keypress(function(e) {
			if (e.which == 13) {
				$("#linkVideo").click();
			}
		});

		$("#linkVideo").click(function(e) {
			e.preventDefault();

			if ($("#linkVideo").attr("disabled")) return false;
			$this.linkVideo();
		});
	},

	flashUpload: function() {
		if (!$("#GuestbookMediaUpload").get(0)) return;

		var mediaTypes = "";
		if (LifeTributes.HasOption("enable_photos"))
			mediaTypes += LifeTributes.imageTypes;
		if (LifeTributes.HasOption("enable_videos"))
			mediaTypes += LifeTributes.videoTypes;

		this.mediaUploader = new SWFUpload({
			upload_url: LifeTributes.tributeURL + "/SaveGuestbookMedia",
			flash_url: LifeTributes.rootFolder + "js/swfupload.swf",
			post_params: {
				"ASPSESSID": LifeTributes.User.sessionId
			},
			file_types: mediaTypes,
			file_types_description: "All Files",
			file_size_limit: "200 MB",
			file_upload_limit: "0",
			file_queue_limit: "0",
			assume_success_timeout: -9999999,
			file_queue_error_handler: fileQueueError,
			file_dialog_complete_handler: fileDialogComplete,
			upload_start_handler: this.handlers.start,
			upload_progress_handler: this.handlers.progress,
			upload_error_handler: this.handlers.error,
			upload_success_handler: this.handlers.success,
			upload_complete_handler: uploadComplete,
			button_placeholder_id: "GuestbookMediaUpload",
			button_width: 185,
			button_height: 161,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_action: SWFUpload.BUTTON_ACTION.SELECT_FILES,
			button_cursor: SWFUpload.CURSOR.HAND
		});
		this.mediaUploader.handlers = this.handlers;
		this.mediaUploader.medias = this.medias;
	},

	handlers: {
		start: function(obj) {
			this.media = this.medias.add();
		},
		progress: function(obj, bytes) {
			var percent = Math.ceil((bytes / obj.size) * 100);
			if (bytes > 0) this.medias.progress(this.media, percent);
		},
		error: function(file, errorCode, message) {
			setMessage("An error has ocurred. Please try again.", "error");
			this.medias.remove(this.media);
		},
		success: function(file, response) {
			var json = $.evalJSON(response);
			if (json.status == GeneralLifeTributeStatus.Error) {
				this.medias.remove(this.media);
				setMessage('Error saving media. Please try again.', 'error');
			} else {
				this.medias.setOptions(this.media, json);
				this.medias.completed(this.media, json.storagePath);
			}
		}
	},

	videoRecorder: function() {
		var swf = LifeTributes.rootFolder + "Support/videoUpload.swf";
		swfobject.embedSWF(swf, "videoRecorder", "585", "520", "9.0.0", LifeTributes.rootFolder + "theme/wms/flash/expressInstall.swf", { serverAction: true }, { wmode: "transparent", menu: "false" }, { id: "videoRecorder", name: "videoRecorder" });
		var $this = this;
		window.recordedVideoComplete = function(obj) {
			$this.videoRecorderComplete(obj);
		};
		window.closeVideoWindow = function(obj) {
			$this.hide();
		};
	},

	videoRecorderComplete: function(obj) {
		var $this = this;
		$("div.record-screen").hide();
		$("div.media-screen").show();
		this.media = this.medias.add();
		var videoData = { 'guid': obj.videoId, 'encodedThumbBytes': obj.thumbnail };
		$.ajax({
			url: LifeTributes.rootFolder + "VideoRecorder/Save",
			type: "POST",
			data: videoData,
			dataType: "json",
			success: function(options) {
				$this.medias.setOptions($this.media, options);
				$this.medias.completed($this.media, options.storagePath);
			},
			error: function() {
				$this.medias.remove($this.media);
				setMessage('Error saving video. Please try again.', 'error');
			}
		});
	},

	linkVideo: function(callback) {
		var $this = this;
		var txtUrl = $("#txtUrl").val();
		if (txtUrl.startsWith("http://http://")) {
			txtUrl = txtUrl.replace("http://http://", "http://");
			$("#txtUrl").val(txtUrl);
		}

		var validUrl = /^https?:\/\/[a-z\.]*(vimeo|youtube).com/i;
		if (!validUrl.test(txtUrl)) {
			$("#output").html("Pleaser enter a valid URL.");
			$("#output").fadeIn(300);
			return;
		}

		var videoData = {
			"txtUrl": txtUrl
		};

		if (this.ajaxRequest) {
			this.ajaxRequest.abort();
			this.ajaxRequest = false;
		}

		$("#linkVideo").prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
		$("span.button-loading", "#linkVideo").width($("#linkVideo").parent().width());
		$("#linkVideo").attr("disabled", "disabled");

		this.ajaxRequest = $.ajax({
			url: LifeTributes.tributeURL + "/AddGuestbookMediaFromUrl",
			type: "POST",
			data: videoData,
			dataType: "json",
			beforeSend: function() {
				$("#linkVideo").attr("disabled", "disabled");
			},
			success: function(options) {
				switch (options.status) {
					case GeneralLifeTributeStatus.Success:
						var media = $this.medias.add();
						$this.medias.setOptions(media, options);
						$this.medias.completed(media, options.storagePath);
						$("#txtUrl").val("http://");
						break;
					case GeneralLifeTributeStatus.Error:
						$("#output").html("We couldn't process your request. Please try again.");
						$("#output").fadeIn(300);
						break;
				}
				if (callback) callback.call();
			},
			error: function(status) {
				$("#output").html("We couldn't process your request. Please try again.");
				$("#output").fadeIn(300);
			},
			complete: function() {
				$("span.button-loading", "#linkVideo").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				$("#linkVideo").removeAttr("disabled");
				$this.ajaxRequest = false;
			}
		});
	},

	medias: {
		pageSize: 4,

		add: function() {
			$("div.media-preview").show();
			var ul = $("div.media-items ul:last");
			if (ul.length == 0 || ul.children("li.photo").length >= this.pageSize) {
				ul = $("<ul>").appendTo($("div.media-preview div.slider"));
				this.parent.pager.addPage();
			}
			var li = $("<li>").attr("class", "photo").hide();
			var frame = $("<div>").attr("class", "photo-frame").appendTo(li);
			var loading = $("<div>").attr("class", "loading").appendTo(frame);
			var progress = $("<span>").attr("class", "progress").appendTo(loading);
			var status = $("<span>").attr("class", "status").text("LOADING").appendTo(loading);
			this.parent.pager.setPage("last");
			li.appendTo(ul);

			if (!$.browser.msie) li.fadeIn(300)
			else li.show();

			return li;
		},

		setOptions: function(li, options) {
			if (!options.item) return false;
			options.item.ThumbnailPath.replace(/.flv$/, ".jpg");
			li.get(0).media = options;
			var status = li.find("span.status");
			status.text("CONVERTING");
			return true;
		},

		completed: function(li, src) {
			var $this = this;
			var options = li.get(0).media;
			src = src || LifeTributes.storagePath + options.item.ThumbnailPath;
			var frame = li.children("div.photo-frame").html("");
			var img = $("<img />").attr({ "width": 120, "height": 86, "src": src }).appendTo(frame);
			var caption = $("<div>").attr("class", "edit-caption").appendTo(li);
			var textarea = $("<textarea>").attr("title", "Edit Caption").appendTo(caption).watermark();
			var remove = $("<span>").attr({ "class": "remove" }).text("remove").appendTo(li);
			textarea.focus(function(e) {
				var ul = $(this).parents("ul:first");
				$this.parent.pager.setPage(ul);
				$(this).parent().addClass("edit-caption-focus");
			}).blur(function() {
				$(this).parent().removeClass("edit-caption-focus");
			}).keypress(function(e) {
				var code = e.which || e.keyCode;
				var key = $.keyOf($.ui.keyCode, code);
				key = key || String.fromCharCode(code).toLowerCase();
				var safeKey = $.inArray(key, ["BACKSPACE", "DELETE", "UP", "DOWN", "LEFT", "RIGHT"]) >= 0;
				var maxLength = $(this).val().length <= 100;
				return e.ctrlKey || safeKey || maxLength;
			}).bind('paste', function(e) {
				var textarea = $(this);
				setTimeout(function() {
					var text = textarea.val().substr(0, 101),
						length = text.length;
					textarea.val(text).selectRange(length, length).scrollTo(1000, 0);
				}, 50);
			});
			remove.click(function(e) {
				e.preventDefault();
				$this.remove($(this).parents("li:first"));
			});
			if (options.isAsync) {
				setTimeout(function() {
					$this.removeProcessedFile(options.item.Path);
				}, 500);
			}
		},

		progress: function(li, percent) {
			var frame = li.children("div.photo-frame");
			var progress = frame.find("span.progress");
			progress.css("width", percent);
		},

		remove: function(li) {
			var $this = this;
			var media = li.get(0).media;
			if (!media) {
				this.removed(li);
				return;
			}
			$.ajax({
				url: LifeTributes.rootFolder + "RemoveGuestbookMedia",
				type: "POST",
				data: $.toJSON(media),
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function(options) {
					if (!$.browser.msie) {
						li.fadeOut(300, function() {
							$this.removed(li);
						});
					} else {
						li.hide();
						$this.removed(li);
					}
				}
			});
		},

		removed: function(li) {
			var $this = this;
			li.remove();
			// Last page is empty
			if ($("div.media-items ul:last li.photo").length == 0) {
				$("div.media-items ul:last").remove();
				this.parent.pager.removePage();
			}
			if ($("div.media-items ul li.photo").length == 0) {
				// There no items
				$("div.media-preview").hide();
			} else {
				// Move items to the correspondent page 
				var ul = $("div.media-items ul");
				$("div.media-items ul li").each(function(index) {
					var pageIndex = Math.ceil((index + 1) / $this.pageSize) - 1;
					$(this).appendTo(ul.eq(pageIndex));
				});
			}
		},

		getList: function() {
			return $("div.media-items ul li.photo");
		},

		getByPath: function(path) {
			var list = this.getList();
			var found = false;
			list.each(function() {
				if (this.media && this.media.item.Path == path) found = $(this);
			});
			return found;
		},

		isComplete: function() {
			var list = this.getList();
			return list.filter(":has(div.loading)").length == 0;
		},

		watch: function() {
			var $this = this;
			clearTimeout(this.watcher);
			this.watcher = setTimeout(function() {
				$this.check();
			}, 2500);
		},

		check: function() {
			var $this = this;
			$.ajax({
				url: LifeTributes.rootFolder + "CheckMediaFileActiveState",
				type: "GET",
				dataType: "json",
				success: function(json) {
					$(json).each(function(i, path) {
						var media = $this.getByPath(path);
						if (media) $this.completed(media);
					});
					if (!$this.isComplete()) $this.watch();
				}
			});
		},

		removeProcessedFile: function(file) {
			$.ajax({
				url: LifeTributes.rootFolder + "RemoveProcessedFile",
				type: "POST",
				dataType: "json",
				data: { 'fileName': file }
			});
		},

		clear: function() {
			$("div.media-preview div.media-items ul").remove();
		}
	},

	submit: function() {
		this.createGuestbookEntry();
	}
};

/* Guestbook - Candles */
GuestbookEntry.ajaxRequestCandlesAndGifts = false;

GuestbookEntry.candle = {

	type: 0,
	list: "#candleList",
	url: "/LoadCandles",
	ajaxRequest: false,

	show: function() {
		this.candle.pager = this.pager;
		this.pager.initialize(this.candle, this.candle.list);
		//GuestbookEntry.expressLogin.show();
	},

	events: function() {
		var $this = this, $list = $(this.list);
		// Select Candle
		$("ul.list-candles li a", $list).click(function() {
			$("#hidCandleSelected").val($(this).attr("rel"));
			$("#hidCandlePrice").val($("input", $(this)).val());
			$("#output").fadeOut(300);
			$("a.candle-selected", $list).removeClass("candle-selected");
			$(this).addClass("candle-selected");
		});
		$("#hidCandleSelected").val("");
		$("#hidCandlePrice").val("");
	},

	submit: function() {
		var $this = this;

		$("#output").fadeOut(300);
		if ($("#hidCandleSelected").val() == "") {
			$("#output").html("Please select a candle.").fadeIn(300);
			$("#lnkShare").removeAttr("disabled");
			$("span", $("#lnkShare")).remove();
			$("#lnkShare").parent().removeClass("button-loading-active");
			return;
		}

		var candleData = {
			"text": $("#txtShare").val(),
			"candleId": $("#hidCandleSelected").val(),
			"tributeId": LifeTributes.tributeId
		};

		var loginData = Login.getData();
		if (loginData.source == Login.LoginSources.guest) {
			$.extend(candleData, loginData);
		} else if (!LifeTributes.User.isAuth) {
			Login.open({
				onLogin: function(data) {
					GuestbookEntry.candle.submit.apply(GuestbookEntry);
				}
			});
			return;
		}

		if (this.ajaxRequest) {
			this.ajaxRequest.abort();
			this.ajaxRequest = false;
		}

		this.ajaxRequest = $.ajax({
			url: LifeTributes.tributeURL + "/InsertCandle",
			type: "POST",
			data: candleData,
			dataType: "json",
			beforeSend: function() {
				$("#lnkShare").prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
				$("span.button-loading", "#lnkShare").width($("#lnkShare").parent().width());
				$("#lnkShare").attr("disabled", "disabled");
			},
			success: function(json) {
				switch (json.status) {
					case GeneralLifeTributeStatus.Success:
						if ($("#wallPager").is(':visible')) {
							$("#TributesComments > li:last").remove();
						}
						$("#TributesComments").prepend(json.added);

						$("ul.list-candles .candle-selected").removeClass("candle-selected");
						$this.hide(true);
						TributeWall.setEditFields();

						//$this.expressLogin.logMeIn(json);

						TributeWall.events();

						storeAds.show();

						break;

					case GeneralLifeTributeStatus.Error:
						$("#output").html("An error has ocurred. Please try again.");
						$("#output").fadeIn(300);
						break;

					case GeneralLifeTributeStatus.ReadonlyTribute:
						$("#ReadonlyAlert").click();
						break;

					case GeneralLifeTributeStatus.RegisterExists:
						//$this.expressLogin.registerExists();
						break;

					case GeneralLifeTributeStatus.UserNotFound:
						//$this.expressLogin.userNotFound();
						break;

					case GeneralLifeTributeStatus.RequiredFieldsEmpty:
						//$this.expressLogin.error();
						break;

				}
			},

			error: function(status) {
				$("#output").html("An error has ocurred. Please try again.");
				$("#output").fadeIn(300);
			},

			complete: function() {
				$("span.button-loading", "#lnkShare").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				$("#lnkShare").removeAttr("disabled");
				$this.ajaxRequest = false;
			}
		});
	}
};


/* Guestbook - Virtual Gifts */
GuestbookEntry.virtual = {

	type: 0,
	list: "#virtualList",
	url: "/LoadGifts",
	ajaxRequest: false,

	show: function() {
		this.gift.pager = this.pager;
		this.pager.initialize(this.virtual, this.virtual.list);
	},

	events: function() {
		var $this = this, $list = $(this.list);
		// Select gift
		$("ul.list-gifts li a", $list).click(function() {
			$("#hidGiftSelected").val($(this).attr("rel"));
			$("#hidGiftPrice").val($("input", $(this)).val());
			$("#output").fadeOut("slow");
			$("a.gift-selected", $list).removeClass("gift-selected");
			$(this).addClass("gift-selected");
		});
		$("#hidGiftSelected").val("");
		$("#hidGiftPrice").val("");
	},

	submit: function() {
		var $this = this;
		$("#output").fadeOut("slow");
		if ($("#hidGiftSelected").val() == "") {
			$("#output").html("Please select a gift.").fadeIn("slow");
			$("#lnkShare").removeAttr("disabled");
			$("span", $("#lnkShare")).remove();
			$("#lnkShare").parent().removeClass("button-loading-active");
			return;
		}

		var giftData = {
			"text": $("#txtShare").val(),
			"giftId": $("#hidGiftSelected").val(),
			"giftPrice": $("#hidGiftPrice").val(),
			"tributeId": LifeTributes.tributeId
		};

		if (parseInt($("#hidGiftPrice").val()) > 0) {
			GoToSSL(null, 'GiftPayment', [giftData.giftId, giftData.giftPrice, giftData.text]);
			return;
		}

		var loginData = Login.getData();
		if (loginData.source == Login.LoginSources.guest) {
			$.extend(giftData, loginData);
		} else if (!LifeTributes.User.isAuth) {
			Login.open({
				onLogin: function(data) {
					GuestbookEntry.virtual.submit.apply(GuestbookEntry);
				}
			});
			return;
		}

		if (this.ajaxRequest) {
			this.ajaxRequest.abort();
			this.ajaxRequest = false;
		}
		this.ajaxRequest = $.ajax(
		{
			url: LifeTributes.tributeURL + "/InsertGift",
			type: "POST",
			data: giftData,
			dataType: "json",
			beforeSend: function() {
				$("#lnkShare").prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
				$("span.button-loading", "#lnkShare").width($("#lnkShare").parent().width());
				$("#lnkShare").attr("disabled", "disabled");
			},
			success: function(json) {
				switch (json.status) {
					case GeneralLifeTributeStatus.Success:
						if ($("#wallPager").is(':visible')) {
							$("#TributesComments > li:last").remove();
						}
						$("#TributesComments").prepend(json.added);

						$("ul.list-virtual-gifts .gift-selected").removeClass("gift-selected");
						$this.hide(true);
						TributeWall.setEditFields();

						//$this.expressLogin.logMeIn(json);

						TributeWall.events();

						storeAds.show();

						break;

					case GeneralLifeTributeStatus.Error:
						$("#output").html("Error.");
						$("#output").fadeIn("slow");
						break;

					case GeneralLifeTributeStatus.ReadonlyTribute:
						$("#ReadonlyAlert").click();
						break;

					case GeneralLifeTributeStatus.RegisterExists:
						//$this.expressLogin.registerExists();
						break;

					case GeneralLifeTributeStatus.UserNotFound:
						//$this.expressLogin.userNotFound();
						break;

					case GeneralLifeTributeStatus.RequiredFieldsEmpty:
						//$this.expressLogin.error();
						break;

				}
			},
			error: function(status) {
				$("#output").html("Error.");
				$("#output").fadeIn("slow");
			},
			complete: function() {
				$("span.button-loading", "#lnkShare").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				$("#lnkShare").removeAttr("disabled");
				$this.ajaxRequest = false;
			}
		});
	}
};

/* Guestbook - Gifts */
GuestbookEntry.gift = {

	type: 1,
	initialized: false,
	list: "#giftList",
	url: "/store/api/?method=getcategories",
	ajaxRequest: false,
	step: 1,
	referrerICN: "",
	tmpReferrerICN: "",
	isReseted: false,
	cartItens: 0,
	currentCategoryId: false,
	currentCategoryName: false,
	currentProductId: false,
	currentProductName: false,
	currentProductVariantId: false,
	currentProductVariantName: false,
	checkout: false,
	duration: (navigator.appVersion.indexOf("MSIE") > -1 ? 0 : 500),
	onCartLoadCallback: function() { },
	hasPersonalization: false,
	checkerInterval: false,
	checkerPreviousState: "",
	checkerCurrentState: "",
	backFromCart: false,
	showShoppingCart: true,
	searchQuery: "",
	allowCartRedir: true,

	checker: function() {

		var $this = this;

		var hash = window.location.hash.substr(1);
		this.checkerPreviousState = this.checkerCurrentState;
		this.checkerCurrentState = hash;
		var hashChanged = this.checkerCurrentState != this.checkerPreviousState;

		// Chat
		if ($("div#lpButDivID-1303917086531 span:not(:has(span)):not(:empty)").get(0)) {
			$("div.store-gifts-top div.chat-container").show().css("display", "inline");
			$("div.store-gifts-top div.chat-container a.chat").click(function() {
				$("div#lpButDivID-1303917086531 span:not(:has(span)):not(:empty)").click();
			});
		} else {
			$("div.store-gifts-top div.chat-container").hide();
		}

		// IE Corner Workaround
		if ($.browser.msie) {
			$("div.tabs div.corner div.bottom").css("bottom", "1px");
			$("div.tabs div.corner div.bottom").css("bottom", "0px");
		}

		var anchor = hash.split("/").slice(1);
		if (anchor[anchor.length - 1] == "") anchor.pop();

		if (!$("#storeGifts").is(":visible") && anchor[0] == "GiftStore") MemorialTabs.goToGiftStore();
		if (hash == "/" && $("#storeGifts").is(":visible")) GuestbookEntry.hide();

		if (hash != "" && hashChanged) {

			if (anchor.length > 0 && anchor[0] == "GiftStore") {

				MemorialTabs.goToGiftStore();

				if (anchor.length <= 1 || (anchor.length > 1 && anchor[1] != "Search")) {
					$("#storeSearchQuery").val("").prev("span.watermark").show();
				}

				if (anchor.length <= 1 && anchor[0] == "GiftStore") {
					// Start
					GuestbookEntry.gift.goToTab(1)

				} else if (anchor.length > 1 && anchor[1] == "Cart" || anchor.length > 1 && anchor[1] == "Personalization") {
					// Cart
					GuestbookEntry.gift.goToTab(4);

				} else if (anchor.length > 1 && anchor[1] == "TermsOfUse") {
					// TermsOfUse
					GuestbookEntry.gift.goToTab(5);

				} else if (anchor.length > 1 && anchor[1] == "PrivacyPolicy") {
					// PrivacyPolicy
					GuestbookEntry.gift.goToTab(6);

				} else if (anchor.length > 1 && anchor[1] == "ShippingPolicy") {
					// ShippingPolicy
					GuestbookEntry.gift.goToTab(7);

				} else if (anchor.length > 1 && anchor[1] == "ReturnsPolicy") {
					// ReturnsPolicy
					GuestbookEntry.gift.goToTab(9);

				} else if (anchor.length > 1 && anchor[1] == "Search") {
					// Search
					GuestbookEntry.gift.goToTab(8);

				} else if (anchor.length == 2) {
					// Category
					GuestbookEntry.gift.goToTab(2, anchor[1]);

				} else if (anchor.length == 3) {
					// Product
					GuestbookEntry.gift.goToTab(3, anchor[1], anchor[2]);
				}
			}
		}

	},

	events: function() {
		var $this = this;

		switch ($this.step) {
			case 1:
				if ($("div.pager-items ul li", $($this.list)).length > 6) {
					$("div.pager-box", $($this.list)).show();
				} else {
					$("div.pager-box", $($this.list)).hide();
				}

				if ($.browser.msie) {
					$("#giftList ul.list-gifts li a").click(function() {
						self.location = $(this).attr("href");
					});
				}

				if ($("div.pager-items ul li", $($this.list)).length % 2 != 0) {
					$("ul", $($this.list)).addClass("list-gifts-parent-category-odd");
				} else {
					$("ul", $($this.list)).removeClass("list-gifts-parent-category-odd");
				}

				break;

			case 2:
				var itemCount = 0;
				var itemHeight = 0;

				$("div.control-gift-list-products div.pager-items").css("clear", "both");

				$("div.control-gift-list-products div.pager-items ul.list-gifts li").each(function() {
					if (itemCount == 0) {
						itemHeight = $(this).height();
						$(this).css("clear", "both");
						itemCount++;
					} else {
						if ($(this).height() > $(this).prev().height()) {
							$(this).prev().height($(this).height());
						} else {
							$(this).height($(this).prev().height());
						}

						itemCount++;

						if (itemCount == 4) {
							itemCount = 0;
							itemHeight = 0;
						}
					}
				});

				if ($("div.pager-items ul li", $($this.list)).length > 8) {
					$("div.pager-box", $($this.list)).show();
				} else {
					$("div.pager-box", $($this.list)).hide();
				}

				if (window.breadcrumbCategories && breadcrumbCategories.length) {
					var currentCategory = breadcrumbCategories[breadcrumbCategories.length - 1];
					$this.currentCategoryId = currentCategory.id;
					$this.currentCategoryName = currentCategory.name;
				}

				if ($.browser.msie) {
					if (navigator.appVersion.indexOf("MSIE 7") > -1) {
						$("#giftListProducts span.tag").hide().show();
					}
					$("#giftListProducts ul.list-gifts li a").click(function() {
						self.location = $(this).attr("href");
					});
				}

				break;

			case 3:
				$("#giftProductDetail #btnBackCategory").click(function() {
					self.location = "#/GiftStore/" + $this.currentCategoryId;
				});


				$("#storeProductQty").forceNumericOnly().blur(function() {
					if ($(this).val() == "") $(this).val(1);
				});

				if ($("#storePhotoThumbs").get(0)) {

					if ($("#storePhotoThumbs a").length > 1) {
						var storeProductImages = [];

						$("#storePhotoThumbs a").each(function() {
							storeProductImages.push([$(this).attr("href"), $(this).attr("title")]);
						});

						$("#storePhotosShowAll").bind("click", function() {
							var index = $("#storePhotoThumbs a.zoomThumbActive").index("#storePhotoThumbs a");
							$.slimbox(storeProductImages, index, { loop: true });
						});

						// Thumbs Carousel
						if ($("#storePhotoThumbs a").length > 3) {

							$.ajax({
								url: LifeTributes.rootFolder + "js/jquery.carousel.js",
								cache: true,
								success: function() {

									$("div.store-thumbs-center")
										.addClass("store-thumbs-center-carousel")
									$("div.store-thumbs-center").after("<a href='javascript:void(0);' class='thumbs-next'>Next</a>")
										.before("<a href='javascript:void(0);' class='thumbs-prev'>Prev</a>")
										.jCarouselLite({
											btnNext: "a.thumbs-next",
											btnPrev: "a.thumbs-prev",
											circular: false
										});

								},
								dataType: "script"
							});

						}

						if ($("#storePhotoThumbs a").length == 2) $("#storePhotoThumbs").addClass("store-photo-thumbs-two");

					} else {
						$("#storePhotoThumbs").hide();
						$("#storePhotosShowAll").unbind("click").bind("click", function() {
							$.slimbox($("#storePhotoThumbs a:first").attr("href"), $("#storePhotoThumbs a:first").attr("title"));
						});
					}
				}

				$("ul.store-tabs").find("li").click(function() {
					var li = $(this);
					$("ul.store-tabs").children("li").not(li).removeClass("active");
					$("div.store-block-tabs").children("div").hide().end().children("#" + li.find("a").attr("rel")).show();
					li.addClass("active");
				});

				var itemsAtLine = 3;
				var titleHeight = 0;
				var lineHeight = 0;
				var line = 1;

				var ul = $("div.store-block ul.store-block-products");

				$("li", ul).each(function(i, li) {
					var li = $(this);
					var title = $("strong", li);
					li.attr("rel", "line-" + line);

					if (li.height() > lineHeight) { lineHeight = li.height(); }
					if (title.height() > titleHeight) { titleHeight = title.height(); }

					if (!(i % itemsAtLine)) {
						li.addClass("first");
					} else if (!((i + 1) % itemsAtLine) || li.is(":last-child")) {
						if (jQuery('li[rel=line-' + line + ']', ul).length == itemsAtLine) li.addClass("last");
						jQuery('li[rel=line-' + line + ']', ul).css({ height: lineHeight });
						jQuery('li[rel=line-' + line + '] strong', ul).css({ height: titleHeight });
						lineHeight = 0;
						titleHeight = 0;
						line++;
					}

				});

				if (window.breadcrumbCategories && breadcrumbCategories.length) {
					var currentCategory = breadcrumbCategories[breadcrumbCategories.length - 1];
					$this.currentCategoryId = currentCategory.id;
					$this.currentCategoryName = currentCategory.name;
				}

				if (window.productInfoPage) {
					$this.currentProductId = productInfoPage.productId;
					$this.currentProductName = productInfoPage.name;

					$this.currentProductVariantId = productInfoPage.selectedProductVariant.id;
					$this.currentProductVariantName = productInfoPage.selectedProductVariant.name;
				}

				$("#giftProductDetail #facebookButtonProduct").attr("src", "http://www.facebook.com/plugins/like.php?api_key=" + LifeTributes.ApiKeys.Facebook + "&channel_url=&href=" + $.URLEncode(window.location.protocol + "//" + window.location.host + "/store/ProductShare.aspx?c=" + $this.currentCategoryId + "&p=" + $("#storeProductId").val() + "&w=1&t=" + LifeTributes.tributePossesive + "&t_url=" + LifeTributes.tributeURL) + "&layout=button_count&locale=en_US&node_type=link&sdk=&show_faces=false&width=100").load(function() {
					$(this).css("visibility", "visible");
				});

				$("#storeReviewTitle, #storeReviewComment, #storeReviewName, #storeReviewEmail, #storeReviewCity").watermark();

				if (navigator.appVersion.indexOf("MSIE") > -1) {
					var commentMaxLength = parseInt($("#storeReviewComment").attr("maxlength"));
					$("#storeReviewComment")
						.keyup(function() {
							if ($(this).val().length > commentMaxLength) {
								$(this).val($(this).val().substring(0, commentMaxLength));
							}
						})
						.keypress(function(e) {
							if ((e.keyCode !== 46 && e.keyCode !== 8)) {

								if ($(this).val().length > commentMaxLength) { // Listen for delete & backspace
									$(this).val($(this).val().substring(0, commentMaxLength));
									e.preventDefault();
									return false;
								}
							}
						})
						.blur(function() {
							if ($(this).val().length > commentMaxLength) {
								$(this).val($(this).val().substring(0, commentMaxLength));
							}
						})
						.bind('paste', function(e) {
							var textarea = $(this);
							setTimeout(function() {
								if (textarea.val().length > commentMaxLength) {
									textarea.val(textarea.val().substring(0, commentMaxLength));
								}
							}, 100);
						});
				}

				$("#ReviewState").niceSelect({
					selectCallback: function() {
						if ($("#ReviewState").val().length < 1) {
							$("#valStoreReviewState").siblings("div.control-select-manual").addClass("control-select-error");
							$("#valStoreReviewState").css("display", "block");
						} else {
							$("#valStoreReviewState").siblings("div.control-select-manual").removeClass("control-select-error");
							$("#valStoreReviewState").hide();
						}
					}
				});

				$("a.review-guidelines").click(function(e) {
					e.preventDefault();
					$.superbox.open("iframe", "/store/ReviewGuidelines.aspx?from=wall", "Review Guidelines", {
						boxWidth: 610,
						boxHeight: 605,
						boxClasses: "superbox-review-guidelines",
						roundCorner: "round 5px"
					});
				});

				$("#storeReviewStars a").hover(function() {
					$("#storeReviewStars span.rating-star").removeClass("filled-rating-star").addClass("empty-rating-star");
					$("#storeReviewStars span.rating-star:lt(" + $(this).attr("rel") + ")").removeClass("empty-rating-star").addClass("filled-rating-star");
				});

				$("#storeReviewStars a").click(function() {
					$("#storeReviewRating").val($(this).attr("rel"));
					$("#storeReviewStars span.rating-star").removeClass("filled-rating-star").addClass("empty-rating-star");
					$("#storeReviewStars span.rating-star:lt(" + $(this).attr("rel") + ")").removeClass("empty-rating-star").addClass("filled-rating-star");
				});

				$("#storeReviewStars").hover(function() {

				}, function() {
					$("#storeReviewStars span.rating-star").removeClass("filled-rating-star").addClass("empty-rating-star");
					$("#storeReviewStars span.rating-star:lt(" + $("#storeReviewRating").val() + ")").removeClass("empty-rating-star").addClass("filled-rating-star");
				});

				$("#storeWriteReviewList, #storeWriteReviewTop, #storeWriteReviewListFooter").click(function() {
					// review title
					$("#storeReviewTitle").parents("span.input-text").removeClass("input-text-error");
					$("#valStoreReviewTitle").hide();
					$("#storeReviewTitle").val("").prev("span.watermark").show();
					$("#storeReviewTitle").siblings("span.input-success-icon").remove();
					$("#storeReviewTitle").siblings("span.input-error-icon").remove();

					// textarea error msg
					$("#storeReviewComment").parents("div.input-textarea").removeClass("input-textarea-error");
					$("div.message", $("#storeReviewComment").parent().parent().parent()).remove();
					$("#valStoreReviewDescription").hide();
					$("#storeReviewComment").val("").prev("span.watermark").show();

					$("#storeReviewsList").hide();
					$("#storeNewReview").show();

					$("#storeNewReview #storeReviewComment").val("");
					$("#storeNewReview #storeReviewTitle").val("").focus();
				});

				$("#storeReviewCancel").click(function() {
					$("#storeReviewValSum").hide();
					if ($.browser.msie) {
						$("div#storeReviewForm span.input-text input").blur(function(e) {
							$(this).hide().show().get(0).blur();
						});
					}
					$("#storeReviewsList").show();
					$("#storeNewReview").hide();
					$("#storeReviewRating").val("4");
					$("#storeReviewStars span.rating-star").removeClass("filled-rating-star").addClass("empty-rating-star");
					$("#storeReviewStars span.rating-star:lt(" + $("#storeReviewRating").val() + ")").removeClass("empty-rating-star").addClass("filled-rating-star");
					$("#storeNewReview #storeReviewTitle, #storeNewReview #storeReviewComment").val("");

					// review inputs
					$("#storeReviewTitle, #storeReviewName, #storeReviewEmail, #storeReviewCity").parents("span.input-text").removeClass("input-text-error");
					$("#valStoreReviewTitle, #valStoreReviewEmail, #valStoreReviewCity").hide();
					$("#storeReviewTitle, #storeReviewName, #storeReviewEmail, #storeReviewCity").val("").prev("span.watermark").show();
					$("#storeReviewTitle, #storeReviewName, #storeReviewEmail, #storeReviewCity").siblings("span.input-success-icon").remove();
					$("#storeReviewTitle, #storeReviewName, #storeReviewEmail, #storeReviewCity").siblings("span.input-error-icon").remove();

					// textarea error msg
					$("#storeReviewComment").parents("div.input-textarea").removeClass("input-textarea-error");
					$("div.message", $("#storeReviewComment").parent().parent().parent()).remove();
					$("#valStoreReviewDescription").hide();
					$("#storeReviewComment").val("").prev("span.watermark").show();

					//review select
					$("#Select_ReviewState").parents("div.control-select").removeClass("control-select-error");
					$("#ReviewState").data("niceSelect").select($("ul[rel=ReviewState] li:first"));
					$("#valStoreReviewState").hide();

					setTimeout(function() {
						$("#storeReviewTitle").after("<input>");
						$("#storeReviewTitle").next().focus().remove();
					}, 500);
				});

				$("#storeReviewTitle").keypress(function(event) {
					$("#storeReviewTitle").parent().parent().removeClass("input-text-error");
				});

				var findProductVariant = function(id) {
					var productVariant = null;
					$.each(productInfoPage.productVariants, function(idx, item) { if (item.id == id) productVariant = item; });
					return productVariant
				};

				var updateProductInfo = function(productVariant) {
					productInfoPage.selectedProductVariant = productVariant;

					$("#productPrice").html(productVariant.oldPrice ?
						('<span class="old-price">' + productVariant.oldPrice + '</span><span class="new-price">' + productVariant.price + '</span>') :
						('<span class="productPrice">' + productVariant.price + '</span>'));

					if (productVariant.canAddToCart) {
						$("#btnAddToCart").show();
					} else {
						$("#btnAddToCart").hide();
					}

					if (productVariant.manufacturerPartNumber) {
						$("div.store-product-info span.product-variant-itemnumber").html("Item Number: " + productVariant.manufacturerPartNumber);
						$("div.store-product-info span.product-variant-itemnumber").show();
					} else {
						$("div.store-product-info span.product-variant-itemnumber").hide();
					}

					var productThumb = $("#storePhotoThumbs a.product-thumb:eq(0)");
					if (productThumb.length) {
						productThumb.find("img").attr("src", productVariant.thumbPicture);

						var zoomOpts = eval("(" + productThumb.attr("rel") + ")");
						zoomOpts.smallimage = productVariant.defaultPicture || productVariant.picture;
						zoomOpts.largeimage = productVariant.picture;
						productThumb.attr("href", productVariant.picture)
							.attr("rel", $.toJSON(zoomOpts).replace(/\"/g, "'"))
							.removeClass("zoomThumbActive").click();
					}

					if ($("#storePhotoThumbs a").length > 1) {
						var storeProductImages = [];

						$("#storePhotoThumbs a").each(function() {
							storeProductImages.push([$(this).attr("href"), $(this).attr("title")]);
						});

						$("#storePhotosShowAll").unbind("click").bind("click", function() {
							var index = $("#storePhotoThumbs a.zoomThumbActive").index("#storePhotoThumbs a");
							$.slimbox(storeProductImages, index, { loop: true });
						});
					} else {
						$("#storePhotosShowAll").unbind("click").bind("click", function() {
							$.slimbox($("#storePhotoThumbs a:first").attr("href"), $("#storePhotoThumbs a:first").attr("title"));
						});
					}
				};

				if ($("div.product-variant-option").length) {

					$("div.product-variant-options input[type=radio]").checkBox();
					$("div.product-variant-option span.ui-radio").parent().click(function(e) {
						var productVariant = findProductVariant($("input", this).val());
						updateProductInfo(productVariant);
					});
				}

				if ($("#ddlProductVariantList").length) {
					$("select#ddlProductVariantList").niceSelect({
						selectCallback: function(o) {
							var productVariant = findProductVariant(this.value.val());
							updateProductInfo(productVariant);
						} /*,
						openCallback: function() {
							$("span.location-type").css("zIndex", 2001);
						},
						blurCallback: function() {
							$("span.location-type").css("zIndex", 1999);
						}*/
					});
				}

				$("#giftProductDetail #storePhoto").parent().jqzoom({
					zoomWidth: 225,
					zoomHeight: 225
				});
				$("#storePhotoThumbs a.product-thumb:eq(0)").addClass("zoomThumbActive");
				var zoomInterval = setInterval(function() {
					if ($("#giftProductDetail .zoomPad").length < 1) return false;
					$("#giftProductDetail .zoomPad").append(
						$("<div/>").attr("class", "zoom-hover").append(
							$("<span/>").text("mouse over to zoom")
						)
					);

					$("#giftProductDetail .zoomWindow").hover(function() {
						var $this = $(this);
						setTimeout(function() {
							$this.hide();
						}, 10);
					});

					$("#giftProductDetail div.store-photo-zoom, #giftProductDetail div.zoom-hover, #giftProductDetail div.zoomPup").hover(function() {
						$("#giftProductDetail div.zoom-hover").hide();
					}, function() {
						$("#giftProductDetail div.zoom-hover").show();
					});
					clearInterval(zoomInterval);
				}, 200);

				if (window.productInfoPage && productInfoPage.selectedProductVariant)
					updateProductInfo(productInfoPage.selectedProductVariant);

				var maxHeight = 32;

				$("div.product-variant-option").each(function() {
					if ($(this).height() > maxHeight) $("div.product-variant-options").addClass("product-variant-options-two-columns");
				});

				$("div.product-variant-option").each(function() {
					if ($(this).height() > maxHeight) $("div.product-variant-options").removeClass("product-variant-options-two-columns").addClass("product-variant-options-one-column");
				});

				$("div.product-variant-options").css("visibility", "visible");

				$("#deliveryDate input:eq(0)").focus(function(e) {
					e.preventDefault();
					return false;
				});

				/* Block Recipient */
				if ($("#blockRecipient").get(0)) {

					$("#deliveryDate").click(function() {

						$.superbox.open("iframe", "/store/DeliveryDate.aspx?productId=" + GuestbookEntry.gift.currentProductId + "&tributeid=" + LifeTributes.tributeId, "Delivery Date", {
							boxWidth: 700,
							boxHeight: 465,
							boxClasses: "superbox-delivery-date",
							roundCorner: "round 5px"
						});

						$("#deliveryDateContainer").append($("<input />").attr("type", "text").attr("id", "focusInput"));
						$("#focusInput").focus().remove();

					});

					var locationType = "-1";

					/* Location Type */
					$("select.location-type").niceSelect({
						selectCallback: function(o) {

							$("#locationType").removeClass("control-select-error");
							$("#valLocationType").hide();

							if (o.value == "-1") {
								$("#zipPostalCode").hide();
							} else if (o.value == "1" || o.value == "4") {
								$("#zipPostalCode").show();
							} else {
								$("#zipPostalCode").hide();
							}

							locationType = o.value;
						}
					});
					$("#locationTypeSelect").data("niceSelect").options.selectCallback($("#locationTypeSelect")[0]);

					DefaultTip.events();

					$("#locationType").click(function() {
						$(this).removeClass("control-select-error");
					});

					$("div.form-delivery-date, div.form-delivery-date input").keydown(function(event) {
						if (event.keyCode == 13) {
							event.preventDefault();
							$("#btnAddToCart").click();
							return false;
						}
					});

					$("#deliveryDate input:eq(0)").keydown(function(event) {
						event.preventDefault();
						return false;
					});

					$("#zipPostalCode input[type=text]").keyup(function() {
						if ($.trim($(this).val()).length > 0) {
							$(this).parents("span.input-text").removeClass("input-text-error");
						}
					});

					$("#zipPostalCode input[type=text]").setMask({ mask: '999999999', autoTab: false });

					$("div.form-delivery-date span.input-text span.input input:not(.delivery-date)").blur(function() {
						$("#valInvalidZipCode, #valBlockedStatesZipCode, #valRequiredZipCode").hide();

						if ($(this).val() != "") {

							if ($(this).attr("id") == "txtZipCode") {

								var reg = new RegExp("^[0-9]{5,9}$");

								if ($(this).val().length > 0 && !reg.test($(this).val())) {

									$(this).parents("span.input-text").addClass("input-text-error").find("span.input-success-icon").remove();
									$(this).parents("span.input-text").siblings("#valInvalidZipCode").show().css("display", "block");
									var errorIcon = $("<span />").addClass("input-error-icon");
									$(this).parents("span.input").append(errorIcon);

									return false;
								}
								else {
									if ($.trim($(this).val()).length > 0) {
										$.ajax({
											url: "/store/CheckOutOnePage/ValidateZipCode",
											type: "GET",
											data: { postalcode: $.trim($(this).val()), isBilling: "false" },
											dataType: "json",

											success: function(valid) {
												if (valid.status == false) {

													$("#zipPostalCode span.input-text").addClass("input-text-error").find("span.input-success-icon").remove();

													if (valid.blockedStates)
														$("#zipPostalCode span.input-text").siblings("#valBlockedStatesZipCode").show().css("display", "block");
													else
														$("#zipPostalCode span.input-text").siblings("#valInvalidZipCode").show().css("display", "block");

													var errorIcon = $("<span />").addClass("input-error-icon");
													$("#zipPostalCode span.input").append(errorIcon);

													return false;
												}
											}
										});
									}
								}
							}

							$(this).parents("span.input-text").removeClass("input-text-error").find("span.input-error-icon").remove();
							$(this).parents("span.input-text").siblings("span.validate-message:not(#valInvalidZipCode)").hide();
							var successIcon = $("<span />").addClass("input-success-icon");
							$(this).parents("span.input").append(successIcon);

						} else {
							$(this).parents("span.input-text").addClass("input-text-error").find("span.input-success-icon").remove();
							$(this).parents("span.input-text").siblings("#valRequiredZipCode").show().css("display", "block");
							var errorIcon = $("<span />").addClass("input-error-icon");
							$(this).parents("span.input").append(errorIcon);
						}
					});

					$("div.form-delivery-date span.input-text span.input input").watermark();

					/* Add to Cart */
					$("#btnAddToCart").click(function() {

						var hasErrors = false,
							locationType = $("#locationType input.nice-select").val(),
							hasLocationType = $("#locationType input.nice-select").get(0),
							zipPostalCode = $.trim($("#zipPostalCode input").val()),
							productVariantStockQuantity = 1,
							productCurrentQtd = 1;

						$("#storeDetailValSum").hide().find("li").remove();

						// Validate Quantity
						if ($("#storeProductQty").get(0)) productCurrentQtd = $("#storeProductQty").val();

						if ($("div.product-variant-options").get(0)) {
							productVariantStockQuantity = $("div.product-variant-options span.ui-radio-state-checked").parents("div.product-variant-option").find("#ProductVariantStockQuantity").val();
						} else {
							productVariantStockQuantity = $("#ProductVariantStockQuantity").val()
						}

						if (parseInt(productVariantStockQuantity) < parseInt(productCurrentQtd)) {
							$("div.store-product-price").before('<p class="qtd-exceeds">Your quantity exceeds stock on hand.<br> The maximum quantity that can be added is <strong>' + productVariantStockQuantity + '</strong>.</p>');
							$("#storeProductQty").focus();
							hasErrors = true;
						}

						// Validate Location Type
						if (hasLocationType && locationType == "-1") {
							$("#locationType").addClass("control-select-error");
							$("#valLocationType").show().css("display", "block");
							var errorOverview = $("<li />").text($("#valLocationType").find("input").val());
							$("#storeDetailValSum").find("ul").append(errorOverview);
							hasErrors = true;
						}

						// Validate ZipCode
						if ($("#zipPostalCode").is(":visible")) {

							if ($("#txtZipCode").val() == "") {

								$("#txtZipCode").parents("span.input-text").addClass("input-text-error");

								var errorIcon = $("<span />").addClass("input-error-icon");
								$("#txtZipCode").parents("span.input").append(errorIcon);

								$("#valRequiredZipCode").show().css("display", "block");
								var errorOverview = $("<li />").text($("#valRequiredZipCode").find("input").val());
								$("#storeDetailValSum").find("ul").append(errorOverview);
								hasErrors = true;
							}

							var reg = new RegExp("^[0-9]{5,9}$");

							if (!reg.test($("#txtZipCode").val()) && !$("#valRequiredZipCode").is(":visible")) {

								$("#txtZipCode").parents("span.input-text").addClass("input-text-error").find("span.input-success-icon").remove();
								var errorIcon = $("<span />").addClass("input-error-icon");
								$("#txtZipCode").parents("span.input").append(errorIcon);

								$("#valInvalidZipCode").show().css("display", "block");

								var errorOverview = $("<li />").text($("#valInvalidZipCode").find("input").val());
								$("#storeDetailValSum").find("ul").append(errorOverview);

								$("#storeDetailValSum").show();

								hasErrors = true;
							}
						}

						// Validate Delivery Date
						if ($("#deliveryDate input:eq(0)").val() == "" && $("#deliveryDateContainer").is(":visible")) {
							$("#deliveryDate input:eq(0)").parents(".input-text").addClass("input-text-error");
							$("#valDeliveryDate").show().css("display", "block");

							var errorIcon = $("<span />").addClass("input-error-icon");
							$("#deliveryDate input:eq(0)").parents("span.input").append(errorIcon);

							var errorOverview = $("<li />").text($("#valDeliveryDate").find("input").val());
							$("#storeDetailValSum").find("ul").append(errorOverview);
							hasErrors = true;
						}

						if (hasErrors) {
							$("#storeDetailValSum").show();
							$("html, body").animate({ scrollTop: ($("#storeDetailValSum").offset().top - 30) }, 300);
							return false;
						}

						$this.addProduct(true);

					});

					Date.prototype.format = function(mask, utc) {
						return dateFormat(this, mask, utc);
					};

				}

				var reviewsList = {
					totalPages: 0,
					totalItens: 0,
					currentPage: 0,
					initialize: function() {

						this.totalItens = $("div.product-review-list li.product-review-item").length;
						this.totalPages = parseInt(this.totalItens / 5);

						if (this.totalPages > 0 && this.totalItens > 5) {
							$("#reviewsReadMore").show();
							$("#reviewsReadMore a:eq(0)").click(function() {
								reviewsList.viewMore();
							});

							$("div.product-review-list li.product-review-item:lt(5)").show();

						} else {
							$("div.product-review-list li.product-review-item").show();
						}

					},

					viewMore: function() {

						this.currentPage++;

						$("div.product-review-list li.product-review-item:lt(" + parseInt(5 * (reviewsList.currentPage + 1)) + ")").show();

						if (this.totalPages == this.currentPage) {
							$("#reviewsReadMore").hide();
						}
					}
				};

				reviewsList.initialize();

				$("#storeReviewTitle, #storeReviewCity").keyup(function() {
					if ($.trim($(this).val()).length > 0) {
						$(this).parents("span.input-text").removeClass("input-text-error");
						$(this).parents("div.control").siblings("span.validate-message");

						$(this).parents("span.input-text").find("span.input-error-icon").remove();
						if ($(this).parents("span.input-text").find("span.input-success-icon").length > 0) {
							$(this).parents("span.input-text").find("span.input-success-icon").show();
						} else {
							$(this).after('<span class="input-success-icon"></span>');
						}
					}
				});

				$("#storeReviewTitle, #storeReviewCity").blur(function() {
					var $input = $(this)
					setTimeout(function() {
						if ($.trim($input.val()).length < 1) {
							$input.parents("span.input-text").addClass("input-text-error");
							$input.parents("div.control").siblings("span.validate-message").show().css("display", "inline-block");

							$input.parents("span.input-text").find("span.input-success-icon").remove();
							if ($input.parents("span.input-text").find("span.input-error-icon").length > 0) {
								$input.parents("span.input-text").find("span.input-error-icon").show();
							} else {
								$input.after('<span class="input-error-icon"></span>');
							}
						} else {
							$input.parents("span.input-text").removeClass("input-text-error");
							$input.parents("div.control").siblings("span.validate-message").hide();

							$input.parents("span.input-text").find("span.input-error-icon").remove();
							if ($input.parents("span.input-text").find("span.input-success-icon").length > 0) {
								$input.parents("span.input-text").find("span.input-success-icon").show();
							} else {
								$input.after('<span class="input-success-icon"></span>');
							}
						}
					}, 150);
				});

				$("#storeReviewEmail").blur(function() {
					var $input = $(this)
					setTimeout(function() {
						var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

						if ($.trim($input.val()).length > 0) {
							if (validEmail.test($input.val())) {
								$input.parents("span.input-text").removeClass("input-text-error");
								$input.parents("div.control").siblings("span.validate-message").hide();

								$input.parents("span.input-text").find("span.input-error-icon").remove();
								if ($input.parents("span.input-text").find("span.input-success-icon").length > 0) {
									$input.parents("span.input-text").find("span.input-success-icon").show();
								} else {
									$input.after('<span class="input-success-icon"></span>');
								}
							} else {
								$input.parents("span.input-text").addClass("input-text-error");
								$input.parents("div.control").siblings("span.validate-message").show().css("display", "inline-block");

								$input.parents("span.input-text").find("span.input-success-icon").remove();
								if ($input.parents("span.input-text").find("span.input-error-icon").length > 0) {
									$input.parents("span.input-text").find("span.input-error-icon").show();
								} else {
									$input.after('<span class="input-error-icon"></span>');
								}
							}
						} else {
							$input.parents("span.input-text").removeClass("input-text-error");
							$input.parents("span.input-text").find("span.input-error-icon, span.input-success-icon").remove();
							$input.parents("div.control").siblings("span.validate-message").hide();
						}
					}, 150);
				});

				$("#storeReviewEmail").keyup(function() {
					var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

					if ($.trim($(this).val()).length > 0 && validEmail.test($(this).val())) {
						$(this).parents("span.input-text").removeClass("input-text-error");
						$(this).parents("div.control").siblings("span.validate-message");

						$(this).parents("span.input-text").find("span.input-error-icon").remove();
						if ($(this).parents("span.input-text").find("span.input-success-icon").length > 0) {
							$(this).parents("span.input-text").find("span.input-success-icon").show();
						} else {
							$(this).after('<span class="input-success-icon"></span>');
						}
					} else if ($.trim($(this).val()).length < 1) {
						$(this).parents("span.input-text").removeClass("input-text-error");
						$(this).parents("span.input-text").find("span.input-error-icon, span.input-success-icon").remove();
					}
				});

				$("#storeReviewComment").keyup(function() {
					if ($.trim($("#storeReviewComment").val()).length > 0) {
						$("#storeReviewComment").parents("div.input-textarea").removeClass("input-textarea-error");
						$("div.message", $("#storeReviewComment").parent().parent().parent()).remove();
						$("#valStoreReviewDescription").hide();
					}
				});

				$("#storeReviewComment").blur(function() {
					setTimeout(function() {
						if ($.trim($("#storeReviewComment").val()).length < 1) {
							$("#storeReviewComment").parents("div.input-textarea").addClass("input-textarea-error")
							$("#valStoreReviewDescription").show().css("display", "inline-block");

						} else {
							$("#storeReviewComment").parents("div.input-textarea").removeClass("input-textarea-error");
							$("div.message", $("#storeReviewComment").parent().parent().parent()).remove();
							$("#valStoreReviewDescription").hide();
						}
					}, 150);
				});

				$("#storeReviewAdd").click(function() {
					$("#storeReviewValSum").hide().find("ul").empty();
					$("#storeReviewTitle").parents("span.input-text").removeClass("input-text-error")
					var reviewHasErrors = false;

					if ($.trim($("#storeReviewTitle").val()).length < 1) {
						$("#storeReviewTitle").focus();
						$("#storeReviewTitle").parents("span.input-text").addClass("input-text-error");
						$("#valStoreReviewTitle").show().css("display", "inline-block");

						var errorOverview = $("<li />").text($("#valStoreReviewTitle").find("input").val());
						$("#storeReviewValSum").find("ul").append(errorOverview);

						$("#storeReviewTitle").parents("span.input-text").find("span.input-success-icon").remove();
						if ($("#storeReviewTitle").parents("span.input-text").find("span.input-error-icon").length > 0) {
							$("#storeReviewTitle").parents("span.input-text").find("span.input-error-icon").show();
						} else {
							$("#storeReviewTitle").after('<span class="input-error-icon"></span>');
						}

						reviewHasErrors = true;
					} else {
						$("#storeReviewTitle").parents("span.input-text").removeClass("input-text-error");
						$("#valStoreReviewTitle").hide();

						$("#storeReviewTitle").parents("span.input-text").find("span.input-error-icon").remove();
						if ($("#storeReviewTitle").parents("span.input-text").find("span.input-success-icon").length > 0) {
							$("#storeReviewTitle").parents("span.input-text").find("span.input-success-icon").show();
						} else {
							$("#storeReviewTitle").after('<span class="input-success-icon"></span>');
						}
					}

					if ($.trim($("#storeReviewComment").val()).length < 1) {
						$("#storeReviewComment").parents("div.input-textarea").addClass("input-textarea-error")
						if (!reviewHasErrors) $("#storeReviewComment").focus();
						$("#valStoreReviewDescription").show().css("display", "inline-block");

						var errorOverview = $("<li />").text($("#valStoreReviewDescription").find("input").val());
						$("#storeReviewValSum").find("ul").append(errorOverview);

						reviewHasErrors = true;
					} else {
						$("#storeReviewComment").parents("div.input-textarea").removeClass("input-textarea-error");
						$("div.message", $("#storeReviewComment").parent().parent().parent()).remove();
						$("#valStoreReviewDescription").hide();
					}

					var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

					if ($.trim($("#storeReviewEmail").val()).length > 0) {
						if (validEmail.test($("#storeReviewEmail").val())) {
							$("#storeReviewEmail").parents("span.input-text").removeClass("input-text-error");
							$("#storeReviewEmail").parents("div.control").siblings("span.validate-message").hide();

							$("#storeReviewEmail").parents("span.input-text").find("span.input-error-icon").remove();
							if ($("#storeReviewEmail").parents("span.input-text").find("span.input-success-icon").length > 0) {
								$("#storeReviewEmail").parents("span.input-text").find("span.input-success-icon").show();
							} else {
								$("#storeReviewEmail").after('<span class="input-success-icon"></span>');
							}
						} else {
							if (!reviewHasErrors) $("#storeReviewEmail").focus();
							$("#storeReviewEmail").parents("span.input-text").addClass("input-text-error");
							$("#storeReviewEmail").parents("div.control").siblings("span.validate-message").show().css("display", "inline-block");

							$("#storeReviewEmail").parents("span.input-text").find("span.input-success-icon").remove();
							if ($("#storeReviewEmail").parents("span.input-text").find("span.input-error-icon").length > 0) {
								$("#storeReviewEmail").parents("span.input-text").find("span.input-error-icon").show();
							} else {
								$("#storeReviewEmail").after('<span class="input-error-icon"></span>');
							}

							var errorOverview = $("<li />").text($("#valStoreReviewEmail").find("input").val());
							$("#storeReviewValSum").find("ul").append(errorOverview);

							reviewHasErrors = true;
						}
					} else {
						$("#storeReviewEmail").parents("span.input-text").removeClass("input-text-error");
						$("#storeReviewEmail").parents("span.input-text").find("span.input-error-icon, span.input-success-icon").remove();
						$("#storeReviewEmail").parents("div.control").siblings("span.validate-message").hide();
					}

					if ($.trim($("#storeReviewCity").val()).length < 1) {
						if (!reviewHasErrors) $("#storeReviewCity").focus();
						$("#storeReviewCity").parents("span.input-text").addClass("input-text-error");
						$("#valStoreReviewCity").show().css("display", "inline-block");

						var errorOverview = $("<li />").text($("#valStoreReviewCity").find("input").val());
						$("#storeReviewValSum").find("ul").append(errorOverview);

						$("#storeReviewCity").parents("span.input-text").find("span.input-success-icon").remove();
						if ($("#storeReviewCity").parents("span.input-text").find("span.input-error-icon").length > 0) {
							$("#storeReviewCity").parents("span.input-text").find("span.input-error-icon").show();
						} else {
							$("#storeReviewCity").after('<span class="input-error-icon"></span>');
						}

						reviewHasErrors = true;
					} else {
						$("#storeReviewCity").parents("span.input-text").removeClass("input-text-error");
						$("#valStoreReviewCity").hide();

						$("#storeReviewCity").parents("span.input-text").find("span.input-error-icon").remove();
						if ($("#storeReviewCity").parents("span.input-text").find("span.input-success-icon").length > 0) {
							$("#storeReviewCity").parents("span.input-text").find("span.input-success-icon").show();
						} else {
							$("#storeReviewCity").after('<span class="input-success-icon"></span>');
						}
					}

					if ($.trim($("#ReviewState").val()).length < 1) {
						$("#valStoreReviewState").siblings("div.control-select-manual").addClass("control-select-error");
						$("#valStoreReviewState").css("display", "block");

						var errorOverview = $("<li />").text($("#valStoreReviewState").find("input").val());
						$("#storeReviewValSum").find("ul").append(errorOverview);

						reviewHasErrors = true;
					} else {
						$("#valStoreReviewState").siblings("div.control-select-manual").removeClass("control-select-error");
						$("#valStoreReviewState").hide();
					}

					if (reviewHasErrors) {
						$("#storeReviewValSum").show();
						return false;
					}

					var dataToSend = {
						productId: $.trim($("#storeProductId").val()),
						title: $.trim($("#storeReviewTitle").val()),
						text: $.trim($("#storeReviewComment").val()),
						name: $.trim($("#storeReviewName").val()),
						email: ($.trim($("#storeReviewEmail").val()) || LifeTributes.User.email),
						city: $.trim($("#storeReviewCity").val()),
						stateprovinceid: $.trim($("#ReviewState").val()),
						rating: $.trim($("#storeReviewRating").val())
					}

					$.ajax({
						url: "/store/api/?method=writeProductReview",
						type: "POST",
						data: dataToSend,
						beforeSend: function() {
							$("#storeReviewForm, #storeNewReview div.store-rating").hide();
							$("#loadingNewReview").show();
						},
						success: function(responseText) {
							$("#storeReviewMessage").show();
							$("#loadingNewReview").hide();

							setTimeout(function() {
								$("#storeReviewCancel").click();
								$("#storeReviewMessage").hide();
								$("#storeReviewForm, #storeNewReview div.store-rating").show();
							}, 7000);
						},
						error: function() {
							setMessage("An error has ocurred. Please try again.", "error");
						}
					});

				});

				$("#storeReviewsList li:last").addClass("last");

				setTimeout(function() {
					$("div.store-product-description a").click(function() {
						$("ul.memorial-tabs.store-tabs li:eq(0) span a").click();
						$("html, body").animate({ scrollTop: $("div.store-product-price").offset().top }, 500);
					});
				}, 500);

				break;

			case 8:

				if ($("#storeCategoryRedirect").get(0)) {

					self.location.hash = "#/GiftStore/" + $("#storeCategoryRedirect").val();

				} else {

					var itemCount = 0;
					var itemHeight = 0;

					$("div.control-gift-list-search div.pager-items").css("clear", "both");

					$("div.control-gift-list-search div.pager-items ul.list-gifts li").each(function() {
						if (itemCount == 0) {
							itemHeight = $(this).height();
							$(this).css("clear", "both");
							itemCount++;
						} else {
							if ($(this).height() > $(this).prev().height()) {
								$(this).prev().height($(this).height());
							} else {
								$(this).height($(this).prev().height());
							}

							itemCount++;

							if (itemCount == 4) {
								itemCount = 0;
								itemHeight = 0;
							}
						}
					});

					if ($("div.pager-items ul li", $($this.list)).length > 8) {
						$("div.pager-box", $($this.list)).show();
					} else {
						$("div.pager-box", $($this.list)).hide();
					}

					if ($.browser.msie) {
						if (navigator.appVersion.indexOf("MSIE 7") > -1) {
							$("#giftListProducts span.tag").hide().show();
						}
						$("#giftListProducts ul.list-gifts li a").click(function() {
							self.location = $(this).attr("href");
						});
					}
				}

				$("#storeCategoryRedirect").remove();

				break;
		}

		$("#storeGifts span.old-price").next().addClass("new-price");

		$this.updateBreadcrumb();

	},

	addProduct: function(isFlower) {

		var $this = this;
		$this.hasPersonalization = false;

		var storeProductVariantId = productInfoPage.selectedProductVariant.id;
		var locationType = $("#locationTypeSelect").length == 0 ? "1" : $("#locationTypeSelect").val();
		var data = {
			method: "addProductToCart",
			productVariantId: storeProductVariantId,
			qty: $("#storeProductQty").length == 0 ? "1" : $("#storeProductQty").val(),
			locationType: locationType
		};
		if (locationType == "0")
			data["tributeId"] = LifeTributes.tributeId;
		else if (locationType == "1" || locationType == "4")
			data["zipPostalCode"] = $.trim($("#zipPostalCode input").val());
		if (isFlower)
			data["deliveryDate"] = $.datepicker.formatDate('mm/dd/yy', new Date($("#deliveryDate input:eq(0)").val()));

		$.ajax({
			url: "/store/api",
			data: data,
			dataType: "json",
			type: "POST",
			success: function(response) {

				var json = response;

				if (json.status == "true") {

					if (json.hasPersonalization == "true") {
						$this.hasPersonalization = true;
					} else {
						if (json.urlToCheckout != "") {
							var url = json.urlToCheckout;
							
							if (!!gaGroup.accounts) gaGroup.push(['_link', url]);
							else self.location = url;
							
							setTimeout(function() {
								self.location = url;
							}, (1000 * 60));
							
							return false;
						}
					}

					if ($this.hasPersonalization) {
						self.location = "#/GiftStore/Personalization/" + $this.currentCategoryId + "/" + $this.currentProductId + "/" + storeProductVariantId;
					} else {
						self.location = "#/GiftStore/Cart";
					}

				} else {

					// Invalid Zip Code
					$("#txtZipCode").parents("span.input-text").addClass("input-text-error").find("span.input-success-icon").remove();
					var errorIcon = $("<span />").addClass("input-error-icon");
					$("#txtZipCode").parents("span.input").append(errorIcon);

					var errorOverview;

					if (json.blockedStates == true) {
						$("#valBlockedStatesZipCode").show().css("display", "block");
						errorOverview = $("<li />").text($("#valBlockedStatesZipCode").find("input").val());
					}
					else {
						$("#valInvalidZipCode").show().css("display", "block");
						errorOverview = $("<li />").text($("#valInvalidZipCode").find("input").val());
					}

					$("#storeDetailValSum").find("ul").append(errorOverview);

					$("#storeDetailValSum").show();

				}

			},
			error: function() {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});

	},

	initialize: function() {

		var $this = this;

		if (!$this.initialized) {

			$this.currentCategoryId = false;
			$this.currentCategoryName = false;
			$this.currentProductId = false;
			$this.currentProductName = false;
			$this.currentProductVariantId = false;
			$this.currentProductVariantName = false;

			if ($.cookie("storeWallPersonalizated") != null) {
				$.cookie("storeWallPersonalizated", null);
				history.back();
			}

			$this.checkerInterval = setInterval(function() {
				$this.checker();
			}, 200);

			$this.initialized = true;

			var hash = window.location.hash.substr(1);

			var anchor = hash.split("/").slice(1);
			if (anchor.length == 3 && anchor[1] == "Search") {
				$("#storeSearchQuery").val($.URLDecode(anchor[2]));
				GuestbookEntry.gift.searchQuery = $("#storeSearchQuery").val();
			}

		}

		$this.build();

	},

	bindEvents: function() {
		if (this.eventsBinded) return;
		this.eventsBinded = true;
		var $this = this;

		$("#storeYourCart").click(function() {

			$this.hasPersonalization = false;

			var hash = window.location.hash.substr(1);
			var anchor = hash.split("/").slice(1);

			if (anchor.length > 1 && anchor[1] == "Cart") {
				GuestbookEntry.gift.goToTab(4);
			} else {
				self.location = "#/GiftStore/Cart";
			}
		});

		$("#btnStoreContinue").click(function() {
			$("#giftStoreFrame").contents().find("input.update-cart-button").click();

			if ($this.currentCategoryName) {
				self.location.hash = "#/GiftStore/" + $this.currentCategoryId;
			} else {
				self.location.hash = "#/GiftStore";
			}
		});

		$("div.store-checkout span.button-checkout").click(function() {

			$this.checkout = true;

			$this.onCartLoadCallback = function() {
				$("#giftStoreForm").submit();
				$this.onCartLoadCallback = function() { };
			};

			$("#giftStoreFrame").contents().find("input.update-cart-button").click();

		});

		$("div.store-checkout #btnStoreBackPersonalization").click(function() {
			if ($this.currentProductId && !$this.backFromCart) {
				self.location = "#/GiftStore/" + $this.currentCategoryId + "/" + $this.currentProductId;
			} else {
				$("#btnStoreSkipPersonalization").click();
			}
		});

		$("#btnStoreBackInfo").click(function() {
			history.back();
		});

		$("div.store-search a").click(function() {
			GuestbookEntry.gift.searchQuery = $("#storeSearchQuery").val();

			self.location.hash = "#/GiftStore/Search/" + $.URLEncode($.trim($("#storeSearchQuery").val()));
			/*if($("#storeSearchQuery").val() == "") {
			return false;
			} else {
			self.location.hash = "#/GiftStore/Search/" + $.URLEncode($.trim($("#storeSearchQuery").val()));
			}*/
		});

		$("#storeSearchQuery")
			.focus(function() {
				$(this).prev("span.watermark").hide();
			})
			.keypress(function(e) {
				$("#storeSearchQuery").parent().removeClass("store-search-input-error");
				if (e.which == 13) {
					$("div.store-search a").click();
				}
			});
	},

	build: function() {
		this.bindEvents();
		$("#storeSearchQuery").watermark();
	},

	show: function() {

		var $this = GuestbookEntry.gift;

		GuestbookEntry.gift.pager = GuestbookEntry.pager;
		GuestbookEntry.pager.initialize(GuestbookEntry.gift, GuestbookEntry.gift.list);

		$("#formShareComment:visible").hide();
		$("#formShareControls").hide();

		if (!$this.isReseted) {

			$.ajax({
				url: "/store/api/?method=resetCart",
				type: "GET",
				dataType: "json",
				success: function(response) {
					if (eval(response.storeClosed)) $this.storeClosed();
					$this.showShoppingCart = response.showShoppingCart;

					if (!eval($this.showShoppingCart)) {
						$("#storeYourCart").remove();
						$("#btnStoreContinue").remove();
					} else {
						if ($.browser.msie && parseInt($.browser.version) <= 7) {
							$("#storeYourCart").show().css("display", "inline");
						} else {
							$("#storeYourCart").show().css("display", "inline-block");
						}

						$("#btnStoreContinue").css("visibility", "visible");

						$this.updateCartTotals(response.shoppingCartCount);

					}

				},
				error: function() {
					$this.storeClosed();
				}
			});

			$this.isReseted = true;

		}
	},

	updateCartTotals: function(itemsCount) {

		var $this = this;

		$("#loadingGiftCheckout").hide();
		$("#giftStoreFrame").show();

		if ($("#giftStoreFrame").contents().find("#ShoppingCartItemsCount").get(0) || itemsCount != "") {

			$("div.store-checkout-buttons:first").show();

			if (itemsCount != "") {
				var itens = parseInt(itemsCount);
			} else {
				var itens = $("#giftStoreFrame").contents().find("#ShoppingCartItemsCount").val();
			}
			$this.cartItens = itens;

			if (itens <= 0) {
				$("#storeCart").html("");
				$("#storeBreadcrumb").removeClass("store-breadcrumb-cart");
			} else {
				$("#storeCart").html((itens > 1 ? "(" + itens + " Items)" : "(" + itens + " Item)"));
				$("#storeBreadcrumb").addClass("store-breadcrumb-cart");
			}

			if (itens >= 1) {
				$("div.store-checkout span.button-checkout, div.store-checkout-buttons-bottom span.button-checkout").show();
			} else {
				$("div.store-checkout span.button-checkout, div.store-checkout-buttons-bottom span.button-checkout").hide();
				$("div.store-checkout-buttons-bottom").show();
			}

			$("div.store-checkout #btnStoreSkipPersonalization, div.store-checkout #btnStoreContinuePersonalization, div.store-checkout #btnStoreBackPersonalization").hide();
			$("div.store-checkout #btnStoreContinueBottom").show();

		}
	},

	updateCart: function() {
		var $this = this;

		$("div.store-checkout div.store-checkout-buttons-bottom").hide();
		$("div.store-checkout-buttons-bottom").removeClass("store-checkout-buttons-personalization");
		$("#giftStoreFrame").css("border", "1px solid #FFF");
		// if loading from the back button...
		var hashParts = self.location.hash.split("/").slice(1);
		if (hashParts[1] == "Personalization") {
			$this.hasPersonalization = true;
			$this.currentCategoryId = hashParts[2];
			$this.currentProductId = hashParts[3];
			$this.currentProductVariantId = hashParts[4];
		}

		if ($this.hasPersonalization) {
			$("#giftStoreFrame").hide().attr("src", "/store/mwsPersonalization.aspx?productVariantId=" + $this.currentProductVariantId + "&rootFolder=" + LifeTributes.rootFolder + "&skin=" + LifeTributes.skin);
			$this.allowCartRedir = false;
			$this.backFromCart = false;
		} else if ($this.allowCartRedir && hashParts[1] == "Personalization") {
			self.location = "#/GiftStore/" + hashParts[2] + "/" + hashParts[3];
		} else {
			$("#giftStoreFrame").hide().attr("src", "/store/mwsCart.aspx?rootFolder=" + LifeTributes.rootFolder + "&skin=" + LifeTributes.skin);
			$this.backFromCart = true;
		}

		$("#loadingGiftCheckout").show();

		$("#giftStoreFrame").load(function() {
			$("#loadingGiftCheckout").hide();

			if ($("#giftStoreFrame").contents().find("div.block-gift-message").get(0)) {
				history.go(-2);
			}

			$("div.store-checkout div.store-checkout-buttons-bottom").show();

			$("#giftStoreFrame").show();

			if (!$this.hasPersonalization) {
				$this.updateTitle("Your Shopping Cart");
				$this.updateCartTotals();
				$this.updateBreadcrumb();
			}

			var perso = $this.hasPersonalization;
			setTimeout(function() {
				var navStr = navigator.appVersion;
				$("#giftStoreFrame").css("border", "0");

				if (navStr.indexOf("MSIE") > -1 && perso) {
					if (navStr.indexOf("MSIE 8") > -1) {
						$("#giftStoreFrame").css("left", "-1px");
					} else if (navStr.indexOf("MSIE 7") > -1) {
						$("#giftStoreFrame").css({ "left": "1px", "width": "585px" });
					}
				} else if (navStr.indexOf("MSIE") > -1 && !perso) {
					if (navStr.indexOf("MSIE 8") > -1) {
						$("#giftStoreFrame").css("left", "0");
					} else if (navStr.indexOf("MSIE 7") > -1) {
						$("#giftStoreFrame").css({ "left": "0", "width": "586px" });
					}
				}
			}, 100);

			$this.hasPersonalization = false;

			var iframeHeightInterval = false;

			iframeHeightInterval = setInterval(function() {
				if ($("#giftStoreFrame").is(":visible")) {
					$("#giftStoreFrame").contents().find('body').css({ "min-height": "100", "overflow": "hidden" });
					$("#giftStoreFrame").height($("#giftStoreFrame").contents().find("body").height() + 20);
				} else {
					clearInterval(iframeHeightInterval);
				}
			}, 200);

			setTimeout(function() {
				$this.updatebreadcrumbWidth();
			}, 500);

		});

	},

	updateTitle: function(title) {
		$("#storeTitle").html(title);
	},

	updatebreadcrumbWidth: function() {

		var breadCrumbWidth = $("#storeBreadcrumb").width();
		var totalItemsWidth = 0;
		var totalItemsWidthNoLast = 0;

		$("#storeBreadcrumb a").each(function() {

			var $this = $(this);
			totalItemsWidth = totalItemsWidth + $(this).width() + 25;

			if ($this.index() != $this.siblings().length) totalItemsWidthNoLast = totalItemsWidth;

		});

		if (totalItemsWidth > breadCrumbWidth) $("#storeBreadcrumb a.last").widthTruncate({ width: (breadCrumbWidth - totalItemsWidthNoLast) - 30 });

	},

	updateBreadcrumb: function() {

		var $this = this;

		$("#storeBreadcrumb").empty();

		if ($this.step > 1) {
			$("#storeBreadcrumb").append('<a class="back">Back</a>');
			$("#storeBreadcrumb a:last").click(function() {
				history.back();
				if (location.hash == "") location.hash = "#/GiftStore/";
			});
		}

		if ($this.step == 1) {

			$("#storeBreadcrumb").append('<a href="#/GiftStore" class="home home-store"><span class="home"></span>Welcome to the Sympathy Store</a>');

		} else {

			$("#storeBreadcrumb").append('<a href="#/GiftStore" class="home"><span class="home"></span> Home</a>');
			$("#storeBreadcrumb a:last").click(function() {
				$this.goToTab(1);
			});

		}

		if ($this.step == 4) {
			$("#storeBreadcrumb a:last").click(function() {
				$("#giftStoreFrame").contents().find("input.update-cart-button").click();
			});

			if (!$this.hasPersonalization) {
				$("#storeBreadcrumb").append('<a>Cart</a>');
			} else {
				$("#storeBreadcrumb").append('<a>Personalize this product</a>');
			}

		} else if ($this.step == 5) {
			$("#storeBreadcrumb a:last").click(function() {
				$("#giftStoreFrame").contents().find("input.update-cart-button").click();
			});
			$("#storeBreadcrumb").append('<a>Terms of Use</a>');

		} else if ($this.step == 6) {
			$("#storeBreadcrumb a:last").click(function() {
				$("#giftStoreFrame").contents().find("input.update-cart-button").click();
			});
			$("#storeBreadcrumb").append('<a>Privacy Policy</a>');

		} else if ($this.step == 7) {
			$("#storeBreadcrumb a:last").click(function() {
				$("#giftStoreFrame").contents().find("input.update-cart-button").click();
			});
			$("#storeBreadcrumb").append('<a>Shipping Policy</a>');

		} else if ($this.step == 8) {
			$("#storeBreadcrumb a:last").click(function() {
				$("#giftStoreFrame").contents().find("input.update-cart-button").click();
			});
			$("#storeBreadcrumb").append('<a>Search</a>');

		} else if ($this.step == 9) {
			$("#storeBreadcrumb a:last").click(function() {
				$("#giftStoreFrame").contents().find("input.update-cart-button").click();
			});
			$("#storeBreadcrumb").append('<a>Returns Policy</a>');

		} else {
			if ($this.currentCategoryId) {
				if (window.breadcrumbCategories && breadcrumbCategories.length) {
					var currentCategory = breadcrumbCategories[breadcrumbCategories.length - 1];

					$.each(breadcrumbCategories, function(i, category) {
						$("#storeBreadcrumb").append('<a href="#/GiftStore/' + category.id + '">' + category.name + '</a>');
					});

				} else {
					$("#storeBreadcrumb").append('<a href="#/GiftStore/' + $this.currentCategoryId + '">' + $this.currentCategoryName + '</a>');
				}
			}
		}

		if ($("#storeBreadcrumb a").length > 1) $("#storeBreadcrumb a:last").addClass("last");

		setTimeout(function() { $this.updatebreadcrumbWidth(); }, 500);

	},

	setPersonalization: function(isUpdate) {

		var $this = this;

		$this.updateTitle("Personalizate Your Gift");
		$this.hasPersonalization = true;

		$this.updateBreadcrumb();

		// tooltip personalization
		$("#giftStoreFrame").contents().find("span.input-text input").bind("blur", function() {
			$("#StorePersonalizationSkipTooltip .default-tip:visible").hide();
		});

		$("#StorePersonalizationSkipTooltip .default-tip a:not(.hasEvent)").addClass("hasEvent").click(function(e) {
			e.preventDefault();
			$("#giftStoreFrame").contents().find("input.store-skip-personalization").click();
		});

		$("div.store-checkout-buttons:first").hide();
		$("div.store-checkout span.button-checkout, div.store-checkout-buttons-bottom span.button-checkout").hide();
		$("div.store-checkout-buttons-bottom").show();
		$("div.store-checkout #btnStoreContinue").css("visibility", "hidden");
		$("div.store-checkout #btnStoreContinueBottom").hide();
		
		if ($("#giftStoreFrame").contents().find(".product-attributes-line-crystal").length > 0) {
			$("div.store-checkout #btnStoreSkipPersonalization").hide();
		} else {
			$("div.store-checkout #btnStoreSkipPersonalization").show();
		}
		
		$("div.store-checkout #btnStoreContinuePersonalization, div.store-checkout #btnStoreBackPersonalization").show();
		
		$("div.store-checkout-buttons-bottom").addClass("store-checkout-buttons-personalization");

		if (!isUpdate) {
			$("div.store-checkout #btnStoreSkipPersonalization").text("Skip Personalization");
			$("div.store-checkout #btnStoreContinuePersonalization a").html("Continue");

			if (!$("div.store-checkout div.store-product-buttons").hasClass("store-product-buttons-update")) {
				$("div.store-checkout div.store-product-buttons").addClass("store-product-buttons-update");
			}
		} else {
			$("div.store-checkout #btnStoreSkipPersonalization").text("Cancel Changes");
			$("div.store-checkout #btnStoreContinuePersonalization a").html("Update");

			if (!$("div.store-checkout div.store-product-buttons").hasClass("store-product-buttons-new")) {
				$("div.store-checkout div.store-product-buttons").addClass("store-product-buttons-new");
			}
		}

		if (!$("div.store-checkout div.store-product-buttons").hasClass("store-product-buttons-ready")) {
			$("div.store-checkout #btnStoreSkipPersonalization").click(function() {
				var filled = false;
				$("#giftStoreFrame").contents().find("span.input-text input").each(function() {
					if ($.trim($(this).val()).length > 0) filled = true;
				});

				if (filled && !$("#giftStoreFrame").contents().find("div.store-product-personalization div.validation-summary").is(":visible")) {
					$("#StorePersonalizationSkipTooltip .default-tip").show();
				} else {
					$("#giftStoreFrame").contents().find("input.store-skip-personalization").click();
				}
			});

			$("div.store-checkout #btnStoreContinuePersonalization a").click(function() {
				$("#giftStoreFrame").contents().find("input.store-update-personalization").click();
			});

			$("div.store-checkout #btnStoreContinuePersonalization a").click(function() {
				$("#giftStoreFrame").contents().find("input.store-continue-personalization").click();
			});

			$("div.store-checkout #btnStoreSkipPersonalization").click(function() {
				$("#giftStoreFrame").contents().find("input.store-cancel-personalization").click();
			});

			$("div.store-checkout div.store-product-buttons").addClass("store-product-buttons-ready");

			$("div.store-checkout #btnStoreContinuePersonalization a, div.store-checkout #btnStoreSkipPersonalization").click(function() {
				//$.cookie("storeWallPersonalizated","true");
			});
		}
	},

	goToTab: function(step, idCategory, idProduct) {

		var $this = this;

		$this.step = step;
		var tabId = "storeCategories";

		$this.backFromCart = false;

		$("div.store-checkout-buttons-bottom").hide();

		$("#StorePersonalizationSkipTooltip .default-tip").hide();

		switch (step) {
			case 1:

				tabId = "storeCategories";
				$this.updateTitle("Choose Your Gift");
				$this.list = "#giftList";
				$this.url = "/store/api/?method=getcategories";
				$this.currentCategoryId = false;
				$this.currentCategoryName = false;
				$this.show();

				var gaGroup = window.gaGroup || [];
				gaGroup.push(['global._setAccount', LifeTributes.gaGlobalAccount]);
				gaGroup.push(['website._setAccount', LifeTributes.gaWebsiteAccount]);
				gaGroup.push(['store._setAccount', LifeTributes.gaStoreAccount]);
				gaGroup.push(['_setDomainName', 'none']);
				gaGroup.push(['_setAllowLinker', true]);
				gaGroup.push(['_trackPageview', '/store?icn=' + GuestbookEntry.gift.referrerICN + '&icc=em_store']);

				break;

			case 2:

				tabId = "storeProducts";
				$this.updateTitle("Choose Your Gift");
				$this.list = "#giftListProducts";
				$this.url = "/store/api/?method=getproductsbycategoryid&categoryId=" + idCategory;
				$this.show();
				break;

			case 3:

				tabId = "storeDetail";
				$this.updateTitle("Choose Your Gift");

				$.ajax({
					url: "/store/api/?method=getproductdetail&productId=" + idProduct + "&categoryId=" + idCategory,
					beforeSend: function() {
						$("#loadingGiftsDetail").fadeIn(300);
						$("#giftProductDetail").empty();
					},
					success: function(responseText) {
						$("#loadingGiftsDetail").fadeOut(300, function() {
							try {
								$("#giftProductDetail").html(responseText);
								$this.events();
								$("#storeInfoLinks").show();
							} catch (e) {
								console.error(e);
							}
						});
					},
					error: function() {
						setMessage("An error has ocurred. Please try again.", "error");
						$("#loadingGiftsDetail").fadeOut(300);
					}
				});

				break;

			case 4:

				tabId = "storeViewCart";
				$this.updateCart();

				break;

			case 5:

				tabId = "storeViewInfo";
				$this.updateTitle("Terms of Use");
				$this.updateBreadcrumb();

				$.ajax({
					url: "/store/api/?method=getTopicText&topicName=TermsOfUse",
					beforeSend: function() {
						$("#loadingGiftsInfo").fadeIn(300);
						$("#giftListContent").empty();
					},
					success: function(responseText) {
						$("#loadingGiftsInfo").fadeOut(300, function() {
							try {
								$("div.store-checkout-buttons-bottom").show();
								$("#giftListContent").html(responseText);
							} catch (e) { console.error(e); }
						});
					},
					error: function() {
						setMessage("An error has ocurred. Please try again.", "error");
						$("#loadingGiftsInfo").fadeOut(300);
					}
				});

				break;

			case 6:

				tabId = "storeViewInfo";
				$this.updateTitle("Privacy Policy");
				$this.updateBreadcrumb();

				$.ajax({
					url: "/store/api/?method=getTopicText&topicName=PrivacyPolicy",
					beforeSend: function() {
						$("#loadingGiftsInfo").fadeIn(300);
						$("#giftListContent").empty();
					},
					success: function(responseText) {
						$("#loadingGiftsInfo").fadeOut(300, function() {
							try {
								$("div.store-checkout-buttons-bottom").show();
								$("#giftListContent").html(responseText);
							} catch (e) { console.error(e); }
						});
					},
					error: function() {
						setMessage("An error has ocurred. Please try again.", "error");
						$("#loadingGiftsInfo").fadeOut(300);
					}
				});

				break;

			case 7:

				tabId = "storeViewInfo";
				$this.updateTitle("Shipping Policy");
				$this.updateBreadcrumb();

				$.ajax({
					url: "/store/api/?method=getTopicText&topicName=ShippingPolicy",
					beforeSend: function() {
						$("#loadingGiftsInfo").fadeIn(300);
						$("#giftListContent").empty();
					},
					success: function(responseText) {
						$("#loadingGiftsInfo").fadeOut(300, function() {
							try {
								$("div.store-checkout-buttons-bottom").show();
								$("#giftListContent").html(responseText);
							} catch (e) { console.error(e); }
						});
					},
					error: function() {
						setMessage("An error has ocurred. Please try again.", "error");
						$("#loadingGiftsInfo").fadeOut(300);
					}
				});

				break;

			case 8:

				tabId = "storeSearch";
				$this.updateTitle("Search");
				$this.list = "#giftListSearch";
				if (!!GuestbookEntry.gift.searchQuery) {
					$("#storeSearchQuery").val(GuestbookEntry.gift.searchQuery).prev("span.watermark").hide();
				}
				$this.url = "/store/api/?method=searchproducts&query=" + $.URLEncode(GuestbookEntry.gift.searchQuery);
				$this.url += "&searchListAll=" + (!!GuestbookEntry.gift.searchQuery ? 0 : 1);
				$this.currentCategoryId = false;
				$this.currentCategoryName = false;
				$this.show();

				break;

			case 9:

				tabId = "storeViewInfo";
				$this.updateTitle("Returns Policy");
				$this.updateBreadcrumb();

				$.ajax({
					url: "/store/api/?method=getTopicText&topicName=ReturnsPolicy",
					beforeSend: function() {
						$("#loadingGiftsInfo").fadeIn(300);
						$("#giftListContent").empty();
					},
					success: function(responseText) {
						$("#loadingGiftsInfo").fadeOut(300, function() {
							try {
								$("div.store-checkout-buttons-bottom").show();
								$("#giftListContent").html(responseText);
							} catch (e) { console.error(e); }
						});
					},
					error: function() {
						setMessage("An error has ocurred. Please try again.", "error");
						$("#loadingGiftsInfo").fadeOut(300);
					}
				});

				break;
		}

		$("div.store-body").css("height", "1px");
		$("#" + tabId).css("height", "auto");
		$("#storeGifts").removeClass("store-gifts-spaced");
		$("#storeInfoLinks").hide().removeClass().addClass("store-info-links store-info-links-step" + step);

		setTimeout(function() {
			$("#screenStore").scrollTo("#" + tabId, { duration: $this.duration, axis: "x", onAfter: function() {
				$("div.store-body-active").removeClass("store-body-active");
				$("#" + tabId).addClass("store-body-active");
				$("#storeGifts").addClass("store-gifts-spaced");
			}
			});
		}, 100);

	},

	storeClosed: function() {

		$("#storeGifts div.store-gifts-top-options").remove();
		$("#storeGifts div.store-gifts-header").html("");
		$("#storeGifts #screenStore")
			.after('<img src="' + LifeTributes.rootFolder + 'theme/wms/img/store-closed.jpg">')
			.remove();

	}

};

/* Guestbook - Pager for Candles and Gifts */
GuestbookEntry.pager = {

	initialize: function(parent) {
		this.parent = parent;
		this.list = $(parent.list);

		if (this.parent.url) {
			var $this = this;
			var ajaxRequest = GuestbookEntry.ajaxRequestCandlesAndGifts;
			if (ajaxRequest) {
				ajaxRequest.abort();
				ajaxRequest = false;
			}
			GuestbookEntry.ajaxRequestCandlesAndGifts = $.ajax({
				url: (this.parent.type == 0 ? LifeTributes.tributeURL + this.parent.url + "/1" : this.parent.url),
				beforeSend: function() {
					$this.list.empty();
					$("div.ajax-loading-inside", $this.list.parent()).fadeIn(300);
				},
				success: function(responseText) {
					$("div.ajax-loading-inside", $this.list.parent()).fadeOut(300, function() {
						try {
							$this.list.html(responseText);
							$this.pager = $("div.pager-box", $this.list);

							if ($this.parent.type == 1) GuestbookEntry.gift.events();

							$this.events();

							TributeWall.setEditFields();
						} catch (e) { console.error(e); }
					});
				},
				error: function() {
					setMessage("An error has ocurred. Please try again.", "error");
					$("div.ajax-loading-inside", $this.list.parent()).fadeOut(300);
				}
			});
		} else {
			this.pager = $("div.pager-box", this.list);
			this.events();
		}
	},

	events: function() {
		var $this = this;

		var pagesTotal = this.pagesTotal();
		if (pagesTotal > 0) {
			if (this.parent.events) this.parent.events();
			var currentPage = this.getPage();
			var pages = $("div.page-number ul li", this.pager);
			$("div.page-number ul", this.pager).css("display", (pages.length <= 1) ? "none" : "");
			$("a", pages).click(function(e) {
				e.preventDefault();
				var li = $(this).parents("li:first");
				if (li.hasClass("selected")) return;
				$this.setPage(pages.index(li) + 1);
			});
			$("a.prev", this.pager)[(currentPage > 1) ? "removeClass" : "addClass"]("prev-disabled");
			$("a.next", this.pager)[(currentPage < pages.length) ? "removeClass" : "addClass"]("next-disabled");
		} else {
			this.pager.hide();
		}

		$("a.prev", this.pager).click(function(e) {
			e.preventDefault();
			if ($(this).hasClass("prev-disabled")) return;
			$this.prev();
		});
		$("a.next", this.pager).click(function(e) {
			e.preventDefault();
			if ($(this).hasClass("next-disabled")) return;
			$this.next();
		});

	},

	prev: function() {
		var currentPage = this.getPage();
		if (currentPage > 1) {
			this.setPage(currentPage - 1);
		}
	},

	next: function() {
		var currentPage = this.getPage();
		var pagesTotal = this.pagesTotal();
		if (currentPage < pagesTotal) {
			this.setPage(currentPage + 1);
		}
	},

	setPage: function(page) {
		var pagesTotal = this.pagesTotal();
		var current = this.getPage();
		var slider = this.list.find("div.slider");
		var wrapper = slider.parent();
		var delay = 500;
		if (typeof page == "object") {
			var pages = $("ul", wrapper);
			page = pages.index(page) + 1;
			delay = 0;
		} else if (page == "last") {
			page = pagesTotal;
		}
		if (page == current) return;

		if (page - 1 >= 0) {
			var ul = $("ul", slider).eq(page - 1);
			var scrollLeft = parseInt(slider.css("margin-left")) - ul.position().left;
			slider.animate({ marginLeft: scrollLeft }, delay);
			$("ul li.selected", this.pager).removeClass("selected");
			$("ul li", this.pager).eq(page - 1).addClass("selected");
			$("a.prev", this.pager)[(page > 1) ? "removeClass" : "addClass"]("prev-disabled");
			$("a.next", this.pager)[(page < pagesTotal) ? "removeClass" : "addClass"]("next-disabled");
		} else {
			slider.parents("div.media-preview").hide();
			slider.css("marginLeft", 0);
			this.pager.hide();
			$("a.prev, a.next", this.pager).addClass("disabled");
			$("ul li", this.pager).remove();
		}

	},

	getPage: function() {
		var pages = $("div.page-number ul li", this.pager);
		var current = pages.filter(".selected");
		return pages.index(current) + 1;
	},

	pagesTotal: function() {
		return $("ul li", this.pager).length;
	},

	addPage: function() {
		var $this = this;
		var li = $("<li>").attr("class", "selected");
		var anchor = $("<a>").attr("href", "#").appendTo(li);
		$("ul", this.pager).append(li);
		var pages = $("div.page-number ul li", this.pager);
		anchor.click(function(e) {
			e.preventDefault();
			var li = $(this).parents("li:first");
			if (li.hasClass("selected")) return;
			$this.setPage(pages.index(li) + 1);
		});
		if (pages.length > 1) {
			this.pager.show();
			this.setPage(pages.length);
		}
	},

	removePage: function() {
		var li = $("ul li:last", this.pager);
		if (li.hasClass("selected")) {
			this.setPage(this.getPage() - 1);
		}
		li.remove();
		if (this.pagesTotal() <= 1) this.pager.hide();
	}
};

/*
* Express Login
*
* Description:
*   Express Login for GuestbookEntry, Photos & Videos, Recomments and Comments for Media
*/
var ExpressLogin = function(wrapper, options) {
	this.options = $.extend({}, ExpressLogin.defaultOptions, options);
	this.initialize(wrapper);
};

ExpressLogin.instances = [];
ExpressLogin.defaultOptions = {
	clone: false,
	container: false
};

ExpressLogin.loginSources = {
	lifetributes: 0,
	twitter: 1,
	facebook: 2
};

ExpressLogin.logMeIn = function(loginData, source) {
	if (!LifeTributes.HasOption("enable_express_sign_up") && !LifeTributes.HasOption("enable_sign_up"))
		return;

	if (!!source && source == ExpressLogin.loginSources.twitter) {
		$("div.express-login div.tab-twitter div.button").hide();
		$("div.express-login div.tab-twitter > p").hide();
		$("div.express-login div.tab-twitter div.logged").show();
		//$("#btnShare", "#guestbookEntry").find("a").text("Share");
	}

	Login.loginSuccess(loginData, source);
};

ExpressLogin.loginFacebook = function() {
	if (this.fbRequest) {
		this.fbRequest.abort();
		this.fbRequest = false;
	}

	this.fbRequest = $.ajax({
		type: "POST",
		url: LifeTributes.rootFolder + "Login/Facebook",
		dataType: "json",
		success: function(json) {
			if (json && json.status == GeneralLifeTributeStatus.Success) {
				ExpressLogin.logMeIn(json, 2);
				$("div.express-login div.tab-facebook div.button").hide();
				$("div.express-login div.tab-facebook > p").hide();
				$("div.express-login div.tab-facebook div.logged").show();
				$("#btnShare", "#guestbookEntry").find("a").text("Share");
				LifeTributes.User.loginSource = 2;
			} else {
				ExpressLogin.logoutFacebook(true);
			}
		}
	});

	FB.XFBML.parse();
};

ExpressLogin.logoutFacebook = function(force) {
	var isFacebook = LifeTributes.User.loginSource == ExpressLogin.loginSources["facebook"];
	if (isFacebook || force) {
		try {
			FB.Connect.logout(function(response) { });
		} catch (ex) { }
		$("div.express-login div.tab-facebook div.button").show();
		$("div.express-login div.tab-facebook > p").show();
		$("div.express-login div.tab-facebook div.logged").hide();
	}
};

ExpressLogin.loginTwitter = function() {
	Login.loginTwitter();
};

ExpressLogin.logoutTwitter = function(force) {
	var isTwitter = LifeTributes.User.loginSource == ExpressLogin.loginSources["twitter"];
	if (isTwitter || force) {
		$("div.express-login div.tab-twitter div.button").show();
		$("div.express-login div.tab-twitter > p").show();
		$("div.express-login div.tab-twitter div.logged").hide();
	}
};

ExpressLogin.destroy = function() {
	// Remove and clean instances
	$.each(ExpressLogin.instances, function(n, instance) {
		instance.wrapper.empty().remove();
		if (!instance.options.container) clearInterval(instance.autoToggle);
		delete ExpressLogin.instances[n];
	});
	ExpressLogin.instances = [];
	// Remove TributeWall and PhotosVideos references
	TributeWall.Recomment = PhotosVideos.Recomment = {};
};

ExpressLogin.prototype = {
	ajaxRequest: false,

	initialize: function(wrapper) {
		this.wrapper = $(wrapper);
		if (this.wrapper.data("expressLogin")) return;
		ExpressLogin.instances.push(this);
		this.build();
		this.events();
	},

	build: function() {
		if (this.options.clone) {
			var newWrapper = $(this.options.clone).clone();
			newWrapper.attr("id", this.wrapper.attr("id"));
			newWrapper.attr("class", this.wrapper.attr("class"));
			newWrapper.find("span.watermark").remove();
			newWrapper.find("input").removeClass("watermark");
			newWrapper.find("span.input-text input").val("");
			newWrapper.find("span.input-text").removeClass("input-text-error");
			this.wrapper.after(newWrapper);
			this.wrapper.remove();
			this.wrapper = newWrapper;
		}
		this.tabs = this.wrapper.find("div.login-tabs ul li");
		this.content = this.wrapper.find("div.login-content div.tab-item");
		this.normalLogin = this.wrapper.find("div.normal-login");
		this.otherLogin = this.wrapper.find("div.other-login");
		this.closeButton = this.otherLogin.find("a.close-button");
		this.wrapper.find("span.input-text input").watermark();
		this.currentTab = "";
		this.wrapper.data("expressLogin", this);
		this.sentData = {};
		if (typeof FB != "undefined" && FB.init && !FB.initialized) {
			FB.init(LifeTributes.ApiKeys.Facebook, LifeTributes.baseURL + "/XdReceiver", { permsToRequestOnConnect: 'email,publish_stream' });
			FB.initialized = true;
		}
	},

	events: function() {
		var $this = this;
		// Tab events
		this.tabs.find("a").click(function(e) {
			e.preventDefault();
			var a = $(this), li = a.parents("li:first"), ul = a.parents("ul:first");
			var isLocked = $this.otherLogin.data("locked") || false;
			if (!li.hasClass("selected") && !isLocked) {
				var index = $this.tabs.index(li.get(0));
				$this.setTab(index);
			}
		});

		// Close Tabs
		this.closeButton.click(function(e) {
			e.preventDefault();
			$this.closeTabs();
		});

		// Footer Links
		this.content.find("a.login-open").click(function(e) {
			e.preventDefault();
			$this.setTab("lifetributes", 0);
			$this.show();
		});

		this.content.find("a.create-account").click(function(e) {
			e.preventDefault();
			$this.setTab("lifetributes", 1);
		});

		this.content.find("a.forgot-password").click(function(e) {
			e.preventDefault();
			var emailLt = $this.content.filter("div.tab-lifetributes").find("div.tab-login input[name=txtUserMail]").val();
			var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			if (validEmail.test(emailLt)) { $this.content.find("div.tab-forgot-password input[name=Email]").val(emailLt); }
			$this.setTab("lifetributes", 2);
		});

		// Forgot Password
		this.content.find("div.tab-forgot-password input[name=Email]").keydown(function(e) {
			if (e.keyCode == 13) $this.forgotPassword();
		});

		this.content.find("div.tab-forgot-password a.forgot-password-submit").click(function(e) {
			e.preventDefault();
			$this.forgotPassword();
		});

		// Life Tributes Login & Twitter Login
		$("div.tab-lifetributes input[name=txtUserPass], div.tab-twitter input[name=txtUserPass], div.tab-create-account input[name=txtUserMail], div.normal-login input[name=txtUserMail]", this.wrapper).keydown(function(e) {
			if (e.keyCode == 13) $(this).parents($this.wrapper.hasClass("express-login-recomment") ? ".recent-comments-field-body" : "#guestbookEntry").find(".button-share a").click();
		});

		// Validate Emails
		var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		this.wrapper.find("input[name=txtUserMail]").change(function() {
			if (!validEmail.test($(this).val())) {
				$(this).parents("span.input-text:first").addClass("input-text-error");
			} else {
				$(this).parents("span.input-text:first").removeClass("input-text-error");
			}
		});

		// Store original paragraphs
		this.content.find("p:not(.no-restore)").each(function() {
			$(this).data("html", $(this).html());
		});

		// Show / Hide
		if (this.options.container) {
			var container = $(this.options.container).get(0);
			var textArea = $("textarea:not(.growfieldDummy):first", container);

			textArea.focus(function() {
				$this.show();
			});
			$(document).bind("click.express-login", function(e) {
				if ($this.locked) return;
				var target = e.target || e.originalTarget;
				var isOutside = !($.inArray(container, $(target).parents()) != -1);
				var isEmpty = !textArea.get(0) || (textArea.length > 0 && textArea.val() == "");
				$this[isOutside && isEmpty ? "hide" : "show"]();
			});
		} else {
			this.show();
			this.autoToggle = setInterval(function() {
				$this[LifeTributes.User.isAuth ? "hide" : "show"]();
			}, 1000);
		}
	},

	show: function() {
		if (!LifeTributes.User.isAuth && this.wrapper.is(":hidden")) {
			this.wrapper.show();
			if (this.options.container) {
				var button = $("#btnShare", this.options.container);
				var btnText = "Share";

				//if (LifeTributes.HasOption("enable_express_sign_up") || LifeTributes.HasOption("enable_sign_up"))
				//	btnText = "Login & " + btnText;

				button.addClass("button-small").find("a").text(btnText);
			}
		}
	},

	hide: function() {
		if (this.wrapper.is(":hidden")) return;
		this.closeTabs();
		this.wrapper.hide();
		if (this.options.container) {
			var button = $("#btnShare", this.options.container);
			button.removeClass("button-small").find("a").text("Share");
		}
	},

	lock: function() {
		this.locked = true;
	},

	unlock: function() {
		this.locked = false;
	},

	clearForms: function() {
		this.wrapper.find("span.input-text input").val("");
		this.wrapper.find("span.input-text span.watermark").show();
	},

	validate: function() {
		if (!LifeTributes.User.isAuth && this.wrapper.is(":visible")) {
			var fields = this.wrapper.find("input[type!=hidden]:visible");
			// empty fields
			fields.filter("input[value=]").parents("span.input-text").addClass("input-text-error");
			fields.filter("input[value!=]").parents("span.input-text").removeClass("input-text-error");
			// invalid email
			var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			var txtUserMail = fields.filter("input[name=txtUserMail]");
			if (!validEmail.test($(txtUserMail).val())) {
				$(txtUserMail).parents("span.input-text").addClass("input-text-error");
				this.setMessage("Please enter a valid Email Address.", "error")
			} else {
				$(txtUserMail).parents("span.input-text").removeClass("input-text-error");
				this.unsetMessage();
			}
			return (fields.parents("span.input-text-error").length == 0);
		}
		return true;
	},

	error: function() {
		// Required Fields Empty
		this.wrapper.find("input[type!=hidden]:visible").parents("span.input-text").addClass("input-text-error");
		if (this.getSource() == ExpressLogin.loginSources.twitter) {
			this.setMessage("Please enter your Name and Password.", "error");
		} else {
			this.setMessage("Please enter your Name and Email address.", "error");
		}
	},

	data: function() {
		var fields = {};
		LifeTributes.User.loginSource = ExpressLogin.loginSources[this.currentTab] || 0;
		fields['source'] = LifeTributes.User.loginSource;
		this.wrapper.find("input:visible").each(function() {
			fields[$(this).attr("name")] = $(this).val();
		});
		this.sentData = fields;
		return fields;
	},

	closeTabs: function() {
		this.otherLogin.hide();
		this.content.hide();
		this.normalLogin.show();
		this.tabs.filter(".selected").removeClass("selected");
		this.currentTab = "";
	},

	setTab: function(index, sub) {
		var $this = this;
		var tab, content;
		// codigo da nasa
		if (typeof index == typeof 1) {
			tab = this.tabs.eq(index);
			content = this.content.eq(index);
		} else if (typeof index == typeof "") {
			tab = this.tabs.filter("." + index);
			content = this.content.filter(".tab-" + index);
			if (!tab.get(0)) return false;
		}
		var isEmpty = (content.children().length == 0);
		if (!isEmpty) {
			// Set current tab
			this.tabs.filter(".selected").removeClass("selected");
			this.currentTab = tab.attr("class").split(" ")[0] || "";
			this.content.hide();
			tab.addClass("selected");
			// Reset forms
			this.content.find("span.input-text-error").removeClass("input-text-error");
			// Restore original paragraphs
			this.content.find("p:not(.no-restore)").each(function() {
				$(this).html($(this).data("html"));
				$(this).attr("class", "");
			});
			// Show content
			this.normalLogin.hide();
			this.otherLogin.show();
			// Show sub content
			var subItems = content.children("div.tab-subitem");
			if (subItems.length > 0) {
				subItems.hide().css("visibility", "hidden");
				subItems.eq(sub || 0).show().css("visibility", "visible");
			};
			content.show();
			try {
				this.wrapper.find("input[type=text]:visible:first").focus();
			} catch (ex) { }
		}
	},

	lockTabs: function(lock) {
		this.otherLogin.data("locked", lock);
	},

	isTabsLocked: function() {
		return this.otherLogin.data("locked");
	},

	getSource: function() {
		return this.sentData["source"] || ExpressLogin.loginSources[this.currentTab] || 0;
	},

	logMeIn: function(loginData) {
		userName = loginData.user.username || this.sentData["txtUserName"] || "";
		ExpressLogin.logMeIn(loginData, this.getSource());
		this.hide();
		this.closeTabs();
		this.clearForms();
	},

	forgotPassword: function() {
		var content = this.content.find("div.tab-forgot-password");
		var message = content.find("p:first");
		var txtEmail = content.find("input[name=Email]");
		var button = this.content.find("a.forgot-password-submit");
		if (button.attr("disabled") == "disabled") return;

		var validEmail = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

		if (!validEmail.test(txtEmail.val())) {
			this.setMessage("Please enter a valid Email address.", "error");
			txtEmail.parents("span.input-text:first").addClass("input-text-error");
			try {
				txtEmail.focus();
			} catch (ex) { }
			return false;
		} else {
			this.unsetMessage("error");
			txtEmail.parents("span.input-text:first").removeClass("input-text-error");
		}

		if (this.ajaxRequest) {
			this.ajaxRequest.abort();
			this.ajaxRequest = false;
		}

		var $this = this;

		this.ajaxRequest = $.ajax({
			url: LifeTributes.rootFolder + "Register/RecoverPassword",
			type: "POST",
			data: { "Email": $("div.tab-forgot-password input[name=Email]", this.wrapper).val() },
			dataType: "json",
			beforeSend: function() {
				button.attr("disabled", "disabled");
				$this.lockTabs(true);
				button.prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
				$("span.button-loading", button).width(button.parent().width());
			},
			success: function(json) {
				switch (json.status) {
					case GeneralLifeTributeStatus.Success:
						txtEmail.val("");
						$this.setTab("lifetributes", 3);
						break;
					case GeneralLifeTributeStatus.Error:
						$this.error();
						$this.setMessage("There was an error processing your request. The recover e-mail was not send.", "error");
						break;
					case GeneralLifeTributeStatus.UserNotFound:
						$this.error();
						$this.setMessage("Email not found.", "error");
						break;
				}
			},
			complete: function() {
				$("span.button-loading", button).fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				button.removeAttr("disabled");
				$this.ajaxRequest = false;
				$this.lockTabs(false);
			}
		});
		return true;
	},

	setMessage: function(text, className) {
		if (!!this.currentTab) {
			var message = this.content.find("p:visible:first");
		} else {
			var header = this.normalLogin.children("h3");
			var message = this.normalLogin.children("p:first");
			if (!message.get(0)) message = $("<p>").insertAfter(header);
		}
		message.text(text).addClass(className);
	},

	unsetMessage: function(className) {
		if (!!this.currentTab) {
			var message = this.content.find("p:visible:first");
			message.html(message.data("html")).removeClass(className);
		} else {
			var message = this.normalLogin.children("p:first");
			message.remove();
		}
	},

	userNotFound: function() {
		this.wrapper.find("input:visible").parents("span.input-text").addClass("input-text-error");
		this.setMessage("Woopss! There was a problem with your login or password. Please try again.", "error");
	},

	registerExists: function() {
		this.setTab("lifetributes", 0);
		var userName = this.sentData["txtUserMail"];
		var txtUserMail = this.content.find("div.tab-login input[name=txtUserMail]");
		var txtUserPass = this.content.find("div.tab-login input[name=txtUserPass]");
		txtUserMail.val(userName);
		txtUserMail.prev("span.watermark").hide();
		this.setMessage("Woops... the email you entered is already in use. Please login below.");
		try {
			txtUserPass.focus();
		} catch (ex) { }
	}

};

/*
* Photos & Videos
*
* Description:
*   Upload Media Albums
*/
var PhotosVideos = {

	ajaxRequest: false,
	list: "#blockAddMedia div.media-preview",

	initialize: function() {
		var options = {};
		this.Recomment = {};
		this.upload = GuestbookEntry.upload;
		this.upload.parent = GuestbookEntry;
		this.upload.wrapper = "#PhotosVideos";
		this.upload.initialize();
		if (typeof FB != "undefined") FB.initialized = false;

		$("#memorialExpressLogin").addClass("express-login-media form");

		if ($("#mediaComment").get(0)) {
			$("#Comment").growfield({}).height(25);
			$("#Comment").watermark();
			options.container = "#mediaComment"
		}
		if ($("#blockAddMedia").get(0)) {
			this.pager = GuestbookEntry.pager;
			this.pager.initialize(this, this.list);
		}

		//this.expressLogin = new ExpressLogin("#memorialExpressLogin", options);
		this.events();
		this.upload.events();
	},

	events: function() {
		var $this = this;

		$("#addMedia").click(function() {
			$("#blockAddMedia").show();
			//$this.expressLogin.show();
			$(this).hide();
		});

		$("#closeAddMedia, #cancelAddMedia").click(function() {
			$("#blockAddMedia").hide();
			$this.upload.hide();
			$this.upload.medias.clear();
			//$this.expressLogin.clearForms();
			//$this.expressLogin.closeTabs();
			$("div.media-preview").hide();
			$("#addMedia").show();
		});

		$("#lnkShare").click(function(e) {
			e.preventDefault();
			if ($(this).attr("disabled")) return false;
			var albumList = $("#albumList").data("niceSelect");
			if (albumList) albumList.collapse();
			//if (!$this.expressLogin.validate()) return false;
			$this.submit();
		});

		if ($("#blockAddMedia").get(0) && !$("#albumId").get(0)) {
			// niceSelect
			$("#albumList").niceSelect({
				forceSelection: false,
				doQuery: false,
				selectCallback: function(item, el) {
					if (item.value == 0) {
						this.input.val("").watermark("Enter a name for this album").focus();
					} else {
						this.input.prev("span.watermark").remove();
					}
				}
			});
			var niceSelect = $("#albumList").data("niceSelect");
			var color = $("div.media-screen div.link-options a").css("color") || "";
			niceSelect.items.eq(0).css({ "font-weight": "bold", "color": color });

		} else {
			var wrapper = $("#PhotosVideos div.media-screen");
			var line = $("<div>").attr("class", "line-share");
			var button = $("#lnkShare").parent();
			var album = $("<input />").attr({ "id": "albumList", "type": "hidden", "value": $("#albumId").val() });
			line.append(album, button).appendTo(wrapper);
			$("div.select-album", wrapper).remove();
		}

		// Comment link event
		$("#commentsListContainer > li a.comment-link").live("click", function(e) {
			e.preventDefault();
			var el = $(this),
				id = el.attr("rel"),
				ulRecomments = $("ul#recomments-" + id);

			if (el.hasClass("showing")) {
				el.removeClass("showing");
				ulRecomments.find("textarea[name=txtRecomment]").blur();
			} else {
				//PhotosVideos.Recomment[id] = new ExpressLogin("#memorialExpressLogin" + id, { container: $("ul#recomments-" + id).parents("li:first"), clone: "#memorialExpressLogin" });
				el.addClass("showing");
				ulRecomments.show();
				ulRecomments.find("textarea[name=txtRecomment]").focus();
			}
		});

		// Recomments
		$("#commentsListContainer > li ul.recomment-list-item").each(function() {
			$this.recommentEvents(this);
		});

		// Fix quotes
		setTimeout(function() {
			$this.fixQuotes();
		}, 500);
	},

	unload: function() {
		$("#commentsListContainer > li a.comment-link").die();
		delete this.expressLogin;
	},

	recommentEvents: function(recomments) {
		var $this = this;
		if ($(recomments).hasClass("recomment-ready")) return;
		$(recomments).addClass("recomment-ready");
		var id = $(recomments).attr("id").split("-")[1],
			form = $("#recommentForm" + id);
		// cancel button
		form.find("span.button-cancel a").click(function(e) {
			e.preventDefault();
			e.stopPropagation();
			TributeWall.cancelRecommentEntry(this, id);
		});
		// textarea focus
		$("#txtRecomment" + id).simpleautogrow().height(16).watermark().focus(function(e) {
			$(this).parents("div.input-textarea:first").addClass("input-textarea-focus");
			$("#btnRecomment" + id).show();
			$("#btnRecommentCancel" + id).show();
			//if ($this.Recomment[id] == undefined) {
			//	$this.Recomment[id] = new ExpressLogin("#memorialExpressLogin" + id, { container: $("ul#recomments-" + id).parents("li:first"), clone: "#memorialExpressLogin" });
			//}
			//$this.Recomment[id].show();
			$(document).unbind("click.recomment").bind("click.recomment", function(e) {
				TributeWall.closeRecommentEntry(e, id);
			});
		});

	},

	fixQuotes: function() {
		$("#commentsListContainer li div.comment blockquote").each(function() {
			var p = $("p", this), html = p.html(), quote = $("div.blockquote-close", this);
			html = p.html(html.replace(/(<br>|\s)+$/, "")).html();
			var blockHeight = p.height() + p.position().top - 14;
			var endPos = quote.position().top;
			if (endPos > blockHeight) {
				p.html(html.replace(/\S+$/, "<br />$&"));
			}
		});
	},

	refresh: function() {
		var albumRoute = $("#albumRoute").val();
		var url = LifeTributes.tributeURL;
		url += albumRoute ? "/InnerTabs/Albums/" + albumRoute + "/ListFiles" : "/InnerTabs/Albums/List";
		$.ajax({
			url: url,
			type: "POST",
			success: function(responseText) {
				$("#albumsContainer").html(responseText);
			}
		});
	},

	addComment: function(itemId, mediaRoute) {
		var sender = $("#lnkSendComment");
		var commentText = $("#Comment").val();

		if ($(sender).attr("disabled")) {
			return false;
		} else if (!commentText || commentText == "") {
			$("#outputComment").html("Please enter a comment.");
			$("#outputComment").fadeIn(250);
			return false;
		}

		var currentFile = Media.currentFile();
		var commentData = { 'comment': commentText, 'mediaId': currentFile.id, 'mediaRoute': currentFile.route };

		var loginData = Login.getData();
		if (loginData.source == Login.LoginSources.guest) {
			$.extend(commentData, loginData);
		} else if (!LifeTributes.User.isAuth) {
			Login.open({
				onLogin: function(data) {
					PhotosVideos.addComment(itemId, mediaRoute);
				}
			});
			return;
		}

		$.ajax({
			url: LifeTributes.tributeURL + "/InnerTabs/Comments/New",
			type: "POST",
			dataType: "json",
			data: commentData,
			beforeSend: function() {
				$(sender).prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
				$("span.button-loading", sender).width($(sender).parent().width());
				$(sender).attr("disabled", "disabled");
			},
			success: function(json) {

				switch (json.status) {
					case GeneralLifeTributeStatus.Success:
						$("#outputComment").fadeOut("slow");
						$("#commentsListContainer").prepend(json.added);
						var recomments = $("#commentsListContainer > li:first ul.recomment-list-item");
						PhotosVideos.recommentEvents(recomments);
						setTimeout(function() {
							PhotosVideos.fixQuotes();
						}, 500);
						$("#Comment").val("").focus();
						TributeWall.setEditFields();
						break;

					case GeneralLifeTributeStatus.UserNotLogged:
						Login.open({
							onLogin: function() {
								$("#lnkSendComment").click();
							}
						});
						break;

					case GeneralLifeTributeStatus.Error:
						$("#outputComment").html("An error has ocurred. Please try again.");
						$("#outputComment").fadeIn("slow");
						break;

					case GeneralLifeTributeStatus.ReadonlyTribute:
						$("#ReadonlyAlert").click();
						break;

					case GeneralLifeTributeStatus.RegisterExists:
						//expressLogin.registerExists();
						break;

					case GeneralLifeTributeStatus.UserNotFound:
						//expressLogin.userNotFound();
						break;

					case GeneralLifeTributeStatus.RequiredFieldsEmpty:
						//expressLogin.error();
						break;

				} //end switch

			},
			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			},
			complete: function() {
				$("span.button-loading", sender).fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				$(sender).removeAttr("disabled");
			}
		});
	},

	submit: function() {
		var $this = this;

		$("#output").fadeOut(300);

		var albumId = isNaN(parseInt($("#albumList").val())) ? 0 : $("#albumList").val();
		var newAlbumName = $("#Select_albumList").val() || "New Album Name";
		var comment = {
			"ItemId": albumId,
			"Text": newAlbumName,
			"Medias": []
		};

		var medias = $("li.photo", $("div.media-preview"));
		if (medias.length == 0) {
			$("#output").html("Please add at least one file.").fadeIn(300);
			$("span.button-loading", "#lnkShare").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
			$("#lnkShare").removeAttr("disabled");
			return;
		}

		var loginData = Login.getData();
		if (loginData.source == Login.LoginSources.guest) {
			$.extend(comment, loginData);
		} else if (!LifeTributes.User.isAuth) {
			Login.open({
				onLogin: function(data) {
					PhotosVideos.submit();
				}
			});
			return;
		}

		medias.each(function(i) {
			if (this.media) {
				var title = $(this).find("textarea").val();
				comment.Medias[i] = this.media.item;
				comment.Medias[i].Title = title || "";
			}
		});

		if (this.ajaxRequest) {
			this.ajaxRequest.abort();
			this.ajaxRequest = false;
		}

		this.ajaxRequest = $.ajax({
			url: LifeTributes.tributeURL + "/CreateAlbumEntry",
			type: "POST",
			dataType: "json",
			data: $.toJSON(comment),
			contentType: "application/json; charset=utf-8",
			beforeSend: function() {
				$("#lnkShare").prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
				$("span.button-loading", "#lnkShare").width($("#lnkShare").parent().width());
				$("#lnkShare").attr("disabled", "disabled");
			},
			success: function(json) {
				switch (json.status) {
					case GeneralLifeTributeStatus.Success:
						if (json.approvalStatus == 1) {
							setCustomMessage("Your entry has been submitted to approval.", {
								referenceElement: "ul#MemorialTabs",
								insertType: "after",
								type: "success",
								cssRules: { "width": 706, "margin": "1px 0 0" }
							});
						} else {
							$this.refresh();
						}
						$("div.media-preview ul").remove();
						$("div.media-preview").hide();
						//$this.expressLogin.logMeIn(json);
						if (typeof (updateTributeCompletion) != "undefined") {
							updateTributeCompletion();
						}

						storeAds.show();

						break;

					case GeneralLifeTributeStatus.UserNotLogged:
						Login.open({
							onLogin: function() {
								$this.submit();
							}
						});
						break;

					case GeneralLifeTributeStatus.Error:
						$("#output").html("An error has ocurred. Please try again.");
						$("#output").fadeIn(300);
						break;

					case GeneralLifeTributeStatus.ReadonlyTribute:
						$("#ReadonlyAlert").click();
						break;

					case GeneralLifeTributeStatus.RegisterExists:
						//$this.expressLogin.registerExists();
						break;

					case GeneralLifeTributeStatus.UserNotFound:
						//$this.expressLogin.userNotFound();
						break;

					case GeneralLifeTributeStatus.RequiredFieldsEmpty:
						//$this.expressLogin.error();
						break;

				}
			},
			error: function() {
				$("#output").html("An error has ocurred. Please try again.");
				$("#output").fadeIn(300);
			},
			complete: function() {
				this.ajaxRequest = false;
				$("span.button-loading", "#lnkShare").fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				$("#lnkShare").removeAttr("disabled");
			}
		});

	}
};

/*
* Profile Picture
*
* Description:
*   Change Tribute Picture
*/
var ProfilePicture = {
	imageName: null,
	imagePath: null,
	defaultWidth: 207,
	defaultHeigth: 207,
	originalWidth: null,
	originalHeight: null,
	currentProgressInfo: "Initializing...",
	isUploadedComplete: false,

	initialize: function() {
		if (!$("#FlaUplPicProf").get(0)) return;

		$("#openCropBox").createModal({
			urlRequest: LifeTributes.TributesRootFolder + 'ShowCropBox',
			cssClass: 'modal-crop'
		});

		if (LifeTributes.isExpired) {
			$("#goToPhotosVideos").css("cursor", "default");
		} else {
			$("#goToPhotosVideos").click(function() {
				self.location = LifeTributes.TributeURL + "/#/PhotosVideos";
			});
		}

		$('div.photo-memorial, div.photo-memorial-upload').bind('mouseover', function() {
			$("div.change-photo-memorial-active").show();
		}).bind('mouseout', function() {
			$("div.change-photo-memorial-active").hide();
		});

		var swfu = new SWFUpload({

			// Backend Settings
			upload_url: LifeTributes.TributeURL + "/ProcessUpdateTributePicture",

			post_params: {
				"TRIBUTEID": LifeTributes.TributeId
			},

			file_size_limit: "100 MB",
			file_types: LifeTributes.ImageTypes,
			file_types_description: "Images",
			file_upload_limit: "0",
			file_queue_error_handler: fileQueueError,
			file_dialog_complete_handler: fileDialogComplete,
			upload_start_handler: this.ProfilePictureUploadStart,
			upload_progress_handler: this.ProfilePictureUploadProgress,
			upload_error_handler: uploadError,
			upload_success_handler: this.ProfilePictureUploaded,
			upload_complete_handler: uploadComplete,

			button_placeholder_id: "FlaUplPicProf",
			button_width: 112,
			button_height: 23,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
			button_cursor: SWFUpload.CURSOR.HAND,

			flash_url: LifeTributes.TributesRootFolder + "js/swfupload.swf",

			debug: false
		});
	},

	setCropBoxParameters: function(pImageName, pImagePath, pOriginalWidth, pOriginalHeight) {
		this.imageName = pImageName;
		this.imagePath = pImagePath;
		this.originalWidth = pOriginalWidth;
		this.originalHeight = pOriginalHeight;
	},

	setCroppedImage: function(imageName, imagePath) {
		$("div.photo-memorial div.loading").remove();
		$("div.photo-memorial img").attr("src", this.imagePath + "?r=" + Math.floor(Math.random() * 100000)).show();
		$("#PicturePath").val(imageName);

		$.ajax({
			type: "POST",
			url: LifeTributes.TributeURL + "/SaveTributePicture",
			data: { 'fileName': this.imageName },
			dataFilter: function(data) {
				if (typeof (JSON) !== 'undefined' &&
						typeof (JSON.parse) === 'function')
					return JSON.parse(data);
				else
					return $.evalJSON(data);
			},
			success: function(jsonResult) {
			},
			error: function() {
				setMessage('Error cropping the image.', 'error');
			}
		});
	},

	// Start
	ProfilePictureUploadStart: function(fileObj) {
		this.isUploadedComplete = false;
		$("div.modal").remove();
		$("#openCropBox").click();
	},

	// Progress
	ProfilePictureUploadProgress: function(fileObj, bytesLoaded) {
		var percent = Math.ceil((bytesLoaded / fileObj.size) * 100);
		this.currentProgressInfo = percent;
	},

	// Complete
	ProfilePictureUploaded: function(file, response) {
		var jsonResult = $.evalJSON(response);
		this.isUploadedComplete = true;
		setCropBoxParameters(jsonResult.imageName, jsonResult.imagePath, jsonResult.originalWidth, jsonResult.originalHeight);
	}
};

/*
* Memorial Tabs
*
* Description:
*	All memorial tabs events
*/
var MemorialTabs = {

	isAdminTabActive: false,
	history: [],

	onBeforeLoad: function(tabId) { },
	onAfterLoad: function(tabId) { },


	initialize: function() {
		this.wrapper = $("#MemorialTabs");
		if (!this.wrapper.get(0)) return false;
		this.build();
		this.events();
	},

	pages: [
		{ "page": "Obituary", "url": "/Obituary/", "name": "Obituary", "admin": false },
		{ "page": "ServicesEvents", "url": "/Events/", "name": "Services & Events", "admin": false },
		{ "page": "Subscribe", "url": "/Subscribe/", "name": "Subscribe", "admin": false },
		{ "page": "Approvals", "url": "/Approvals/", "name": "Approvals", "admin": true },
		{ "page": "Following", "url": "/Following/", "name": "Following", "admin": true },
		{ "page": "Configuration", "url": "/Configuration/", "name": "Configuration", "admin": true },
		{ "page": "Administrators", "url": "/Administrators/", "name": "Administrators", "admin": true },
		{ "page": "SendEmail", "url": "/TabSendEmail/", "name": "Send Email", "admin": true },
		{ "page": "FriendsRequests", "url": "/FriendsRequests/", "name": "Friends Requests", "admin": true }
	],

	build: function() {

		var $this = this;

		$this.onAfterLoad = function() {
			GuestbookEntry.gift.initialize();
			$this.onAfterLoad = function() { };
		};

		if ($.browser.msie && $.browser.version == '6.0') {
			var marginWidth = parseInt($('#screen').css('margin-left')) - parseInt($('#screen').css('margin-right')),
				newWidth = $('#screen').parent().width() - marginWidth;
			$('#screen').width(newWidth);
		}

		$("ul.tabs li:not(.tab-disabled:has(.submenu), .tab-magic) span a").each(function() {
			var currentTabId = $(this).attr("tabId");
			if (!currentTabId) return true;
			$.History.bind("/" + currentTabId, function(state) {
				MemorialTabs.go($("a[tabId=" + currentTabId + "]")[0]);
			});
		});

		$.History.bind(function(state) {
			var regexGuid = "([a-z0-9]{8})-([a-z0-9]{4})-([a-z0-9]{4})-([a-z0-9]{4})-([a-z0-9]{12})";
			var photosVideosUrl = new RegExp("\/PhotosVideos\/" + regexGuid + "\/" + regexGuid + "(\/{0,1})$", "i");
			var isPhotosVideosUrl = photosVideosUrl.test(document.location.href);
			var isIE7 = navigator.appVersion.indexOf("MSIE 7") > -1;
			if (!ajaxRequest && ((isIE7 > -1 && !isPhotosVideosUrl) || !isIE7)) {
				if (!$("#TributesComments").is(":visible")) {
					MemorialTabs.go($("a[tabId=TributeWall]")[0]);
				}
			}
		});

		$("ul.tabs li:not(.tab-disabled:has(.submenu), .tab-magic) span a").click(function() {
			var currentTabId = $(this).attr("tabId");
			if (!currentTabId) return true;
			self.location.href = LifeTributes.baseTabsUrl + "/#/" + currentTabId;
		});

		$("ul.tabs li:has(.submenu) a[rel]").each(function() {
			var link = $(this);
			$.History.bind("/" + link.attr("rel"), function(state) {
				if (!link.hasClass("requesting")) {
					link.click();
				}
			}, true);
		});

		$("ul.tabs li:has(.submenu)").hover(function() {
			$("div.submenu", $(this)).show();
		}, function() {
			$("div.submenu", $(this)).hide();
		});

		$("ul.tabs li:has(.submenu) a").click(function() {
			$(this).parents("div.submenu").hide()
		});

		var queryString = self.location.hash.split("/");
		var len = queryString.length;
		if (len >= 3) {
			if (queryString[1] == "PhotosVideos") {
				MemorialTabs.go($("a[tabId=PhotosVideos]")[0], true);
				$("div.tabs #PhotosVideos").css("visibility", "visible");
				MemorialTabs.goToMedia(len - 1, LifeTributes.tributeURLSingle, queryString[2], (len >= 4) ? queryString[3] : '');
			}
		}

		$("#MemorialTabs > li > span > a").click(function(e) {
			e.preventDefault();
		});

		$.each(MemorialTabs.pages, function(i, item) {
			$.History.bind("/" + item.page, function(state) {
				MemorialTabs.go($("#MagicTab a"), false, item);
			});
		});

		if (LifeTributes.isExpired) {
			$("#PhotosVideosTab, #FamilyTreeTab").each(function() {
				$("span a", this).unbind("click").click(function(e) {
					e.preventDefault();
					return false;
				}).attr("href", "#");
				$(this).addClass("tab-disabled").removeClass("submenu");
			});
		}

		$("#obituaryGiftStoreBanner").click(function(e) {
			if($("ul.memorial-tabs li.active span a").html() == "Obituary") {
				GuestbookEntry.gift.tmpReferrerICN = "memorial_page_obituary_banner";
			} else {
				GuestbookEntry.gift.tmpReferrerICN = "memorial_page_events_banner";
			}
		});

		$("#obituaryGiftStoreBanner, #obituaryGiftStoreBannerTop").click(function(e) {
			MemorialTabs.goToGiftStore();
		});

		$("#viewGiftStore").click(function() {

			GuestbookEntry.gift.tmpReferrerICN = "memorial_page_banner";

			if (!$("#shareContent .line-gift").is(":visible")) {
				MemorialTabs.goToGiftStore();
			} else {
				$.scrollTo($('#MemorialTabs'), { duration: (navigator.appVersion.indexOf("MSIE") > -1 ? 0 : 500), axis: 'y' });
			}

		});

		// Go to active tab
		var stateExists = $.History.stateExists(window.location.hash);
		if ($("ul#MemorialTabs").get(0) && !stateExists) {
			var activeTab = $("#MemorialTabs li.active a");
			this.go(activeTab);
		}
		// Fix menu width
		this.fixMenuWidth();
	},

	fixMenuWidth: function() {
		var totalWidth = $("#MemorialTabs").width();
		var tabsWidth = 0;
		$("#MemorialTabs > li:visible").each(function() {
			tabsWidth += $(this).outerWidth(true)
		});
		var paddingRight = parseInt($("#MemorialTabs > li.last > span > a").css("padding-right"));
		var paddingRight = parseInt($("#MemorialTabs > li.last > span > a").css("paddingRight"));
		var paddingLeft = parseInt($("#MemorialTabs > li.last > span > a").css("paddingLeft"));
		var remainWidth = totalWidth - tabsWidth;

		remainWidth = Math.ceil(remainWidth / 2);

		if (remainWidth > 0) {
			remainWidth = remainWidth > 30 ? 30 : remainWidth;
			$("#MemorialTabs > li.last > span > a")
				.css({
					paddingRight: paddingRight + remainWidth,
					paddingLeft: (paddingLeft + remainWidth - 1)
				});
		}
	},

	clear: function() {
		$("div.tabs div.tab-item:not(" + currentTab + ")").css("visibility", "hidden");
		$("#screen div.tab-item object").each(function() {
			try {
				this.parentNode.removeChild(this);
			} catch (ex) { }
		});
		ExpressLogin.destroy();
		var View = window[this.lastTab];
		if (typeof View == "object" && !!View.unload) View.unload();

		$("#screen div.tab-item").empty();
		if (typeof FB != "undefined") FB.initialized = false;
	},

	load: function(responseText) {
		$("#" + MemorialTabs.currentTab).html(responseText).fadeIn(250, function() {
			$(this).css("visibility", "visible");
		});

		var View = window[this.currentTab];
		if (typeof View == "object" && !!View.initialize) View.initialize();

		TributeWall.setEditFields();
	},

	go: function(o, loaded, magicItem) {

		$("#image-annotate-edit-form").remove();
		$("#output").hide();
		$("#obituaryGiftStoreBanner").hide();
		$("#PhotosVideos div.video").empty();
		this.isAdminTabActive = false;
		this.lastTab = this.currentTab || "TributeWall";
		this.currentTab = $(o).attr("tabId");
		this.history.unshift(this.currentTab);
		currentTab = "#" + this.currentTab;

		if (this.currentTab == "Magic") {
			$("#FamilyTreeTab").hide();
			$("#MagicTab").show();
			$("#MagicTab a").text(magicItem.name);
			$("#MoreTab li.magic-item").show();
			$("#Magic").empty();
			if (magicItem.admin) this.isAdminTabActive = true;
		} else {
			$("#FamilyTreeTab").show();
			$("#MagicTab").hide();
			$("#MoreTab li.magic-item").hide();
		}

		if (this.currentTab == "TributeWall") {
			if (!LifeTributes.HasOption("display_obituary_tab")) {
				$("#screen").scrollTo({ top: 0, left: 0 }, { duration: 0, axis: "x" });
			} else {
				$("#screen").scrollTo(currentTab, { duration: 0, axis: "x" });
			}
		} else {
			$("#screen").scrollTo(currentTab, { duration: 0, axis: "x" });
		}

		$("div.tabs div.tab-item:not(" + currentTab + ")").css("visibility", "hidden");
		$("div.tabs div.tab-item").removeClass("tab-active");
		$(currentTab).addClass("tab-active");

		$("div.tabs ul.tabs li").removeClass("active");
		$(o).parent().addClass("active");

		if ((!$(o).attr("loaded") || $(o).attr("force")) && !loaded) {

			if (ajaxRequest) {
				ajaxRequest.abort();
				ajaxRequest = false;
			}

			MemorialTabs.onBeforeLoad(this.currentTab);

			ajaxRequest = $.ajax({
				url: (magicItem ? LifeTributes.tributeURL + magicItem.url : $(o).attr("url")),
				beforeSend: function() {
					MemorialTabs.startLoading(o);
				},
				success: function(responseText, textStatus, xhr) {
					if (xhr.status) {
						$("span.tab-loading", o).fadeOut(250, function() {
							try {
								$(this).remove();

								MemorialTabs.clear();
								MemorialTabs.load(responseText);

								if (!magicItem) $(o).attr("loaded", true);
								listPager.Current = 1;
								ajaxRequest = false;
								MemorialTabs.onAfterLoad(MemorialTabs.currentTab);
							} catch (e) { console.error(e); }
						});
					} else {
						MemorialTabs.clear();
					}
				},
				error: function(req, status, error) {
					MemorialTabs.clear();
					setMessage("An error has ocurred. Please try again.", "error");
					ajaxRequest = false;
				}
			});
		}

	},

	goToMedia: function(tabNumber, url, albumRoute, fileRoute, page) {

		currentUrl = url;

		if (ajaxRequest) {
			ajaxRequest.abort();
			ajaxRequest = false;
		}

		this.startLoading($("#PhotosVideosTab a"));

		var newHash = "";

		switch (tabNumber) {
			case 1:

				newHash = "/PhotosVideos/" + page;
				if (!$.History.handlers.specific[newHash]) {
					$.History.bind(newHash, function(state) {
						MemorialTabs.go($("a[tabId=PhotosVideos]")[0], true);
						$("#PhotosVideos").css("visibility", "visible");
						MemorialTabs.goToMedia(1, url, albumRoute, fileRoute, page);
					});
				} else {
					ajaxRequest = $.ajax({
						url: LifeTributes.rootFolder + url + "/InnerTabs/Albums/Page/" + page,
						beforeSend: function() {
							$("div.ajax-loading-inside", $("div.tabs")).fadeIn(250);
						},
						success: function(responseText) {
							$("div.ajax-loading-inside", $("div.tabs")).fadeOut(250);
							MemorialTabs.clear();
							$("#PhotosVideos").html(responseText);
							PhotosVideos.initialize();
							TributeWall.setEditFields();
						},
						complete: function() {
							MemorialTabs.stopLoading($("#PhotosVideosTab a"));
							ajaxRequest = false;
						}
					});
				}
				break;

			case 2:

				currentAlbum = albumRoute;
				currentfileRoute = fileRoute;

				newHash = "/PhotosVideos/" + albumRoute;
				if (!$.History.handlers.specific[newHash]) {
					$.History.bind(newHash, function(state) {
						MemorialTabs.go($("a[tabId=PhotosVideos]")[0], true);
						$("#PhotosVideos").css("visibility", "visible");
						MemorialTabs.goToMedia(2, url, albumRoute, "");
					});
				} else {
					ajaxRequest = $.ajax({
						url: LifeTributes.rootFolder + url + "/InnerTabs/Albums/" + albumRoute + '/Files/' + fileRoute,
						beforeSend: function() {
							$("div.ajax-loading-inside", $("div.tabs")).fadeIn(250);
						},
						success: function(responseText) {
							$("div.ajax-loading-inside", $("div.tabs")).fadeOut(250);
							MemorialTabs.clear();
							$("#PhotosVideos").html(responseText);
							PhotosVideos.initialize();
							TributeWall.setEditFields();
						},
						error: function(req, status, error) {
							$("div.ajax-loading-inside", $("div.tabs")).fadeOut(250);
							setMessage("An error has ocurred. Please try again.", "error");
						},
						complete: function() {
							MemorialTabs.stopLoading($("#PhotosVideosTab a"));
							ajaxRequest = false;
						}
					});
				}
				break;

			case 3:

				currenMediatFile = fileRoute;

				newHash = "/PhotosVideos/" + albumRoute + "/" + fileRoute;
				if (!$.History.handlers.specific[newHash]) {
					$.History.bind(newHash, function(state) {
						MemorialTabs.go($("a[tabId=PhotosVideos]")[0], true);
						$("#PhotosVideos").css("visibility", "visible");
						MemorialTabs.goToMedia(3, url, albumRoute, fileRoute);
					});
				} else {
					ajaxRequest = $.ajax({
						url: LifeTributes.rootFolder + url + "/InnerTabs/Albums/" + albumRoute + '/Files/' + fileRoute,
						beforeSend: function() {
							$("div.ajax-loading-inside", $("div.tabs")).fadeIn(250);
						},
						success: function(responseText) {
							$("div.ajax-loading-inside", $("div.tabs")).fadeOut(250);
							MemorialTabs.clear();
							$("#PhotosVideos").html(responseText);
							PhotosVideos.initialize();
							TributeWall.setEditFields();
						},
						complete: function() {
							MemorialTabs.stopLoading($("#PhotosVideosTab a"));
							ajaxRequest = false;
						}
					});
				}
				break;

			case 4:

				currenMediatFile = fileRoute;

				newHash = "/PhotosVideos/" + albumRoute + "/" + fileRoute;
				if (!$.History.handlers.specific[newHash]) {
					$.History.bind(newHash, function(state) {
						MemorialTabs.go($("a[tabId=PhotosVideos]")[0], true);
						$("#PhotosVideos").css("visibility", "visible");
						MemorialTabs.goToMedia(3, url, albumRoute, fileRoute);
					});
				} else {
					ajaxRequest = $.ajax({
						url: LifeTributes.rootFolder + url + "/InnerTabs/Albums/" + albumRoute + '/Files/' + fileRoute,
						beforeSend: function() {
							$("div.ajax-loading-inside", $("div.tabs")).fadeIn(250);
						},
						success: function(responseText) {
							$("div.ajax-loading-inside", $("div.tabs")).fadeOut(250);
							MemorialTabs.clear();
							$("#PhotosVideos").html(responseText);
							PhotosVideos.initialize();
							TributeWall.setEditFields();
						},
						complete: function() {
							MemorialTabs.stopLoading($("#PhotosVideosTab a"));
							ajaxRequest = false;
						}
					});
				}
				break;
		}

		if (newHash != "")
			$.History.setHash(newHash);

	},

	goToFile: function(albumRoute, fileRoute) {

		if (ajaxRequest) {
			ajaxRequest.abort();
			ajaxRequest = false;
		}

		this.goToMedia(3, currentUrl, albumRoute, fileRoute, 0);
	},

	goToGiftStore: function() {
		if ($("#shareTabs a.icon-gift").is(":visible")) {
			if (!$("#shareTabs a.icon-gift").closest("li").hasClass("active")) {
				$("#shareTabs a.icon-gift").click();
				GuestbookEntry.gift.build();
			}
			$.scrollTo($('#MemorialTabs'), { duration: 500, axis: 'y' });
		} else {
			MemorialTabs.onAfterLoad = function() {
				if (!$("#shareTabs a.icon-gift").closest("li").hasClass("active")) {
					$("#shareTabs a.icon-gift").click();
					GuestbookEntry.gift.build();
				}
				$.scrollTo($('#MemorialTabs'), { duration: 500, axis: 'y' });
				self.location = "#/GiftStore";

				MemorialTabs.onAfterLoad = function() { };
			};
			$.scrollTo($('#MemorialTabs'), { duration: 500, axis: 'y' });
			self.location = "#/TributeWall";
		}
	},

	backToWall: function() {
		this.go($("a[tabId=TributeWall]")[0]);
	},

	backToAlbums: function() {
		$("#PhotosVideos").empty();
		this.go($("a[tabId=PhotosVideos]")[0]);
	},

	backToAlbum: function() {
		this.goToMedia(2, MemorialTabs.tributeURLSingle, currentAlbum, '');
	},

	events: function() {
		this.submenuEvents();
		this.obituaryServices();
		this.profileEvents();
	},

	submenuEvents: function() {
		this.moreTab();
		this.familyTreeTab();
	},

	profileEvents: function() {
		$("#tributeDonationsFree").click(function(e) {
			e.preventDefault();
			GoToSSL(null, 'Donations');
		});
	},

	fixTabs: function() {
		var maxWidth = $("#MemorialTabs").width(),
				tabsWidth = 0,
				tabsLength = $("#MemorialTabs > li:visible").length;

		$("#MemorialTabs > li:visible").each(function() {
			tabsWidth += $(this).outerWidth(true);
		});

		if (tabsWidth > maxWidth) {
			var toSubtract = Math.ceil((tabsWidth - maxWidth) / (tabsLength * 2));
			$("#MemorialTabs > li > span > a").each(function() {
				var leftPad = parseInt($(this).css("padding-left"));
				var rightPad = parseInt($(this).css("padding-right"));
				$(this).css("padding-left", leftPad - toSubtract);
				$(this).css("padding-right", rightPad - toSubtract)
			});
		}
	},

	obituaryServices: function() {
		if ($("div.obituary-services div.item-events span.type").height() <= 18) {
			$("div.obituary-services div.item-events span.type").css("marginBottom", 5);
		}

		var heightToMatch = $("div.obituary-services").height();

		if ($.browser.mozilla) {
			$("div.lt-memorial div.obituary-services div.item-events span.type").heightTruncate();
		}

		$("div.obituary-services div.item:not(.item-events)").each(function() {
			var square = $(this);
			if (square.height() < heightToMatch) {
				var difference = heightToMatch - square.height();
				if (navigator.appVersion.indexOf("MSIE 8") > -1) difference += 1;
				var padding = parseInt(square.find("div.middle-content").css("paddingBottom").replace(/[^0-9]/g, "")) + difference;
				square.find("div.middle-content").css("paddingBottom", padding);
			}
		});

		$("div.lt-memorial div.obituary-services div.item").each(function() {
			var link = $(this).find("a");
			if (link.get(0)) {
				link.click(function(e) {
					e.stopPropagation();
				});
				$(this).click(function(e) {
					window.location = link.attr("href");
					link.triggerHandler("click");
				});
			} else {
				$(this).css("cursor", "default");
			}
		});

		$("div.lt-memorial div.obituary-services div.item-obituary p").heightTruncate();

		$("div.lt-memorial div.obituary-services div.item-memories a").click(function() {
			MemorialTabs.onAfterLoad = function() {
				setTimeout(function() {
					$("#txtShare").focus();
				}, 250);
				MemorialTabs.onAfterLoad = function() { };
			};
		});
	},

	familyTreeTab: function() {

		if (LifeTributes.isExpired) return false;
		var $this = this;

		$("#FamilyTreeTab a").click(function(e) {
			e.preventDefault();
			var link = $(this);
			self.location.href = LifeTributes.baseTabsUrl + "/#/" + link.attr("rel");

			$this.startLoading(this);

			$("#FamilyTreeTab a[rel=" + link.attr("rel") + "]").addClass("requesting");
			var requestUrl = window.location.pathname + link.attr("rel");

			if (window.ajaxRequest) {
				window.ajaxRequest.abort();
				window.ajaxRequest = false;
			}

			$("#obituaryGiftStoreBanner").hide();
			$("#FamilyTreeTab").show();
			$("#MagicTab").hide();
			$("#MoreTab li.magic-item").hide();

			window.ajaxRequest = $.ajax({
				url: requestUrl,
				beforeSend: function() {
					$("#FamilyTree").html("");
					$("#screen div.tab-item").html("");
					$("#FamilyTree").css("visibility", "visible");
					$("#screen").scrollTo("#FamilyTree", { duration: 0, axis: "x" });
				},
				success: function(html) {
					$this.stopLoading(link, {
						time: 250,
						callback: function() {
							$("#FamilyTree").html(html);
						}
					});
				}
			});
			$("#FamilyTreeTab a[rel=" + link.attr("rel") + "]").ajaxStop(function() {
				MemorialTabs.stopAllLoadingElements();
				$(this).removeClass("requesting");
			});
		});
	},

	moreTab: function() {
		var $this = this;

		$("#makeDonation").click(function() {
			GoToSSL(null, 'Donations');
		});
	},

	startLoading: function(el) {
		this.stopAllLoadingElements();

		el = $(el);
		if (!el.parent().is("span")) {
			el = $(el).parents("li:eq(1)").find("span a");
		}

		if (!el.parents("li").hasClass("active")) {
			el.parents("ul.memorial-tabs").children("li.active").removeClass("active");
			el.parents("li").addClass("active");
		}

		var width = el.width();
		var height = el.height();

		if ($("span.tab-loading", el).length == 0) {
			el.prepend(
				$("<span/>").attr({ "class": "tab-loading" }).css("display", "none").append($("<em/>").css({ "width": width, "height": height }).text("Loading..."))
			);
		}
	},

	stopLoading: function(el, options) {
		var params = { time: 0, callback: null };
		$.extend(params, options);
		el = $(el);

		if (!el.parent().is("span")) {
			el = $(el).parents("li:eq(1)").find("span a"); ;
		}

		if (!el.parents("li").hasClass("active")) {
			el.parents("ul.memorial-tabs").children("li.active").removeClass("active");
			el.parents("li").addClass("active");
		}

		var callback = function() {
			$("span.tab-loading", el).remove();

			if (typeof params.callback == "function") { params.callback(); }
		}

		callback();
	},

	stopAllLoadingElements: function() {
		var $this = this;
		$("ul.memorial-tabs span.tab-loading").each(function() {
			$this.stopLoading($(this).parents("a"));
		});
	}
};

/*
* Tribute Wall
*
* Description:
*   Events for Tribute Wall comments
*/
var TributeWall = {

	initialize: function() {
		GuestbookEntry.initialize();
		this.Recomment = {};
		this.events();
	},

	events: function() {
		var $this = this;

		// Recomments
		$("#TributesComments > li a.comment-link").live("click", function(e) {
			e.preventDefault();
			e.stopPropagation();
			var el = $(this),
				id = el.attr("rel"),
				ulRecomments = $("ul#recomments-" + id);

			if (el.hasClass("showing")) {
				el.removeClass("showing");
				ulRecomments.find("textarea[name=txtRecomment]").blur();
			} else {
				//TributeWall.Recomment[id] = new ExpressLogin("#memorialExpressLogin" + id, { container: $("ul#recomments-" + id).parents("li:first"), clone: "#memorialExpressLogin" });
				el.addClass("showing");
				ulRecomments.show();
				ulRecomments.find("textarea[name=txtRecomment]").focus();
			}
		});

		this.recommentEvents();

		setTimeout(function() {
			$this.fixQuotes();
		}, 500);

		$("#printLoading").createModal({
			cssClass: 'modal-print-loading',
			content: '<span class="title">The print will start shortly...</span><span class="loading">Loading...</span><div class="loading"></div>',
			disableClose: true
		});

		$(window).bind('scroll.lazyload', function() {
			if (($(window).scrollTop() >= ($(document).height() - ($(window).height() / 2)) - $(window).height())) {
				if ($('#wallPager').parent().is(':visible') && !$('#wallPager').parent().hasClass('button-loading-active')) {
					$('#wallPager').click();
				}
			}
		});

	},

	unload: function() {
		GuestbookEntry.unload();
		$(window).unbind('scroll.lazyload');
	},

	recommentEvents: function() {
		$("#TributesComments > li ul.recomment-list-item:not(.recomment-ready)").each(function() {
			$(this).addClass("recomment-ready");
			var id = $(this).attr("id").split("-")[1],
				form = $("#recommentForm" + id);
			// cancel button
			form.find("span.button-cancel a").click(function(e) {
				e.preventDefault();
				e.stopPropagation();
				TributeWall.cancelRecommentEntry(this, id);
			});
			// textarea focus
			$("#txtRecomment" + id).simpleautogrow().height(16).watermark().focus(function(e) {
				$(this).parents("div.input-textarea:first").addClass("input-textarea-focus");
				$("#btnRecomment" + id).show();
				$("#btnRecommentCancel" + id).show();
				//if (TributeWall.Recomment[id] == undefined) {
				//	TributeWall.Recomment[id] = new ExpressLogin("#memorialExpressLogin" + id, { container: $("ul#recomments-" + id).parents("li:first"), clone: "#memorialExpressLogin" });
				//}
				//TributeWall.Recomment[id].show();
				$(document).unbind("click.recomment").bind("click.recomment", function(e) {
					TributeWall.closeRecommentEntry(e, id);
				});
			});
		});
	},

	setEditFields: function() {

		if (!setEditFieldsLoading) {
			setEditFieldsLoading = $.ajax({
				url: LifeTributes.tributeURL + "/TributeInfoUser",
				dataType: "json",
				success: function(responseText) {
					LifeTributes.User.isAuth = responseText.isAuth;
					if (responseText.isAuth) {
						if (responseText.isTributeAdmin) {

							$("#changeTributePhoto").addClass("change-photo-memorial-active");
							$("div.photo-memorial-upload").show();
							$("#isTributeAdmin").val("true");
							$("*[admin='true']").show();
							if ($("#MemorialTabs > li[admin=true]").length > 0) {
								MemorialTabs.fixTabs()
							}

							var selectorString = "a.edit:not(a.edit-ready)";
						} else {
							var selectorString = "a.edit[userId='" + responseText.userId + "']:not(a.edit-ready)";
						}
						$(selectorString).click(function() {
							var currentValue = $(this).html();
							var currentContainer = $(this)[0];
							var serverAction = $(this).attr("serverAction");
							var fieldType = $(this).attr("fieldType");
							var successCallback = $(this).attr("successCallback");

							$(currentContainer.parentNode).addClass("editing");

							if (fieldType == "textarea") {

								currentValue = currentValue.replace(/<br>/g, '\r\n');
								currentValue = currentValue.replace(/<BR>/g, '\r\n');
								currentValue = currentValue.replace(/<br\/>/g, '\r\n');
								currentValue = currentValue.replace(/<BR\/>/g, '\r\n');

								var fieldHtml = "<span class='textbox'><textarea>" + currentValue + "</textarea></span> ";
							} else {
								fieldType = "input";
								var fieldHtml = "<span class='textbox'><input type='textbox' value='" + currentValue + "'/></span> ";
							}
							$(this).before("<div class='edit-textbox " + $(this).attr("editClass") + "'>" + fieldHtml + "<span class='input-button-submit'><a href='javascript:void(0);'>Submit</a></span> <span class='input-button-cancel'><a href='javascript:void(0);'>Cancel</a></span> </div>");
							var editTextbox = $("div.edit-textbox", $(this.parentNode))[0];

							var editTextbox = $("span.textbox " + fieldType, $(this.parentNode))[0];

							if (fieldType == "textarea") {
								$(editTextbox).growfield({});
							}

							$(editTextbox).focus();

							$("span.input-button-cancel a", $(this.parentNode)).click(function() {
								$(editTextbox.parentNode.parentNode).remove();
								$(currentContainer).show();
								$(currentContainer.parentNode).removeClass("editing");
							});

							var submitButton = $("span.input-button-submit a", $(this.parentNode))[0];
							$(submitButton).click(function() {
								var editTextboxText = escape($(editTextbox).val());

								$.ajax({
									type: "POST",
									url: "/" + serverAction,
									data: "editedValue=" + editTextboxText,
									dataType: "json",

									success: function(responseText) {
										if (responseText.status == 1) {
											var formattedText = $(editTextbox).val();
											formattedText = formattedText.replace(/\n\r/g, '<br>');
											formattedText = formattedText.replace(/\r\n/g, '<br>');
											formattedText = formattedText.replace(/\n/g, '<br>');
											$(currentContainer).html(formattedText).show();
										}
										$("div.ajax-loading-inside", $(submitButton.parentNode)).hide();
										$(submitButton).removeClass("loading");
										$(currentContainer.parentNode).removeClass("editing");
										$($(editTextbox)[0].parentNode.parentNode).remove();

										if (successCallback) {
											eval(successCallback).call(formattedText, submitButton, $("span.input-button-cancel a", $(this.parentNode))[0]);
										}
									},
									error: function(req, status, error) {
										alert("An error has ocurred. Please try again.");
										$("div.ajax-loading-inside", $(submitButton.parentNode)).hide();
										$(submitButton).removeClass("loading");
										$($(editTextbox)[0].parentNode.parentNode).remove();
									},
									beforeSend: function() {
										$("div.ajax-loading-inside", $(submitButton.parentNode)).show();
										$(submitButton).addClass("loading");
									}
								});
							});

							$(this).hide();

						});

						$(selectorString).addClass("edit-ready");

						if (responseText.isTributeAdmin) {
							var selectorStringButtonDelete = "span.input-button-delete";
							var selectorStringButtonMessage = "span.input-button-message";
							var selectorStringButtonComment = "a.button-comment-delete";
							var selectorStringButtonReply = "a.button-reply-delete";
							var selectorStringButtonApprove = "a.button-approve";
							var selectorStringButtonDeny = "a.button-deny";

						} else {
							var selectorStringButtonDelete = "span.input-button-delete[userId='" + responseText.userId + "']";
							var selectorStringButtonMessage = "span.input-button-message[userId='" + responseText.userId + "']";
							var selectorStringButtonComment = "a.button-comment-delete[userId='" + responseText.userId + "']";
							var selectorStringButtonReply = "a.button-reply-delete[userId='" + responseText.userId + "']";
							var selectorStringButtonApprove = "a.button-approve[userId='" + responseText.userId + "']";
							var selectorStringButtonDeny = "a.button-deny[userId='" + responseText.userId + "']";
						}

						$(selectorStringButtonDelete).addClass("input-button-delete-active");
						$(selectorStringButtonMessage).addClass("input-button-message-active");
						$(selectorStringButtonComment).show();
						$(selectorStringButtonReply).show();
						$(selectorStringButtonApprove).show();
						$(selectorStringButtonDeny).show();

						if (responseText.isTributeAdmin) {
							var selectorStringButton = "span.remove";
						} else {
							var selectorStringButton = "span.remove[userId='" + responseText.userId + "']";
						}

						$(selectorStringButton).addClass("remove-active").click(function(e) {
							e.stopPropagation();
						});

						$("ul.list-content img[userId='" + responseText.userId + "']").attr("onclick", "self.location='/" + LifeTributes.rootFolder + "RegisterCompletion'").addClass("register");

						if (responseText.isTributeAdmin) {
							$("#editDates:not(a.edit-ready-date)").click(function() {

								var currentValue = $(this).html();
								var currentContainer = $(this)[0];

								$(this).before("<div class='edit-textbox edit-dates'><span class='textbox'><input type='text' id='dateBirth' name='dateBirth' /></span> <span style='float:left; margin:7px;'>-</span> <span class='textbox'><input type='text' id='dateDeath' name='dateDeath' /></span><span class='input-button-submit'><a href='javascript:void(0);'>Submit</a></span><span class='input-button-cancel'><a href='javascript:void(0);'>Cancel</a></span></div>");

								$('#dateBirth, #dateDeath').datepicker({ showAnim: 'fadeIn', changeMonth: true, changeYear: true, yearRange: '1900:2015', dateFormat: 'mm/dd/yy' }).attr("readonly", "readonly");

								$('#dateBirth').val($("#hidBirth").val());
								$('#dateDeath').val($("#hidDeath").val());

								var editTextbox = $("span.textbox input", $(this.parentNode))[0];

								$("span.input-button-cancel a", $(this.parentNode)).click(function() {
									$(editTextbox.parentNode.parentNode).remove();
									$(currentContainer).show();
									$(currentContainer.parentNode).removeClass("editing");
								});

								var submitButton = $("span.input-button-submit a", $(this.parentNode))[0];

								$(submitButton).click(function() {
									$.ajax({
										type: "POST",
										url: LifeTributes.tributeURL + "/" + LifeTributes.tributeId + "/ProcessUpdateTributeLifeDates?r=" + Math.floor(Math.random() * 100000),
										data: "dateBirth=" + $("#dateBirth").val() + "&dateDeath=" + $("#dateDeath").val(),
										dataType: "json",

										success: function(responseText) {

											if (responseText.status == 1) {
												$(currentContainer).html(responseText.dateFormated).show();
											}
											$("div.ajax-loading-inside", $(submitButton.parentNode)).hide();
											$(editTextbox.parentNode.parentNode).remove();
											$(currentContainer).show();
											$(currentContainer.parentNode).removeClass("editing");
										},
										error: function(req, status, error) {
											alert("An error has ocurred. Please try again.");
											$("div.ajax-loading-inside", $(submitButton.parentNode)).hide();
											$(submitButton).removeClass("loading");
											$($(editTextbox)[0].parentNode.parentNode).remove();
										},
										beforeSend: function() {
											$("div.ajax-loading-inside", $(submitButton.parentNode)).show();
											$(submitButton).addClass("loading");
										}
									});
								});

								$(this).hide();

							});

							$("#editDates").addClass("edit-ready-date");
						}
					} else {
						$("ul.list-content img").attr("onclick", "").removeClass("register");
					}

					setEditFieldsLoading = false;
				}
			});
		}
	},

	fixQuotes: function() {
		$("#TributesComments li div.comment blockquote").each(function() {
			var p = $("p", this), html = p.html(), quote = $("div.blockquote-close", this);
			if (quote.get(0)) {
				html = p.html(html.replace(/(<br>|\s)+$/, "")).html();
				var blockHeight = p.height() + p.position().top - 14;
				var endPos = quote.position().top;
				if (endPos > blockHeight) {
					p.html(html.replace(/\S+$/, "<br />$&"));
				}
			}
		});
	},

	deleteComment: function(o, cId, recomment) {
		$.ajax({
			url: LifeTributes.tributeURL + "/" + cId + "/GuestbookCommentDelete",
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {

					var li = $(o).parents("li:first"),
						ie7 = $.browser.msie && parseInt($.browser.version) < 8,
						delay = ie7 ? 0 : 250;

					var currentScope = $(o).parents("ul:first").parents("li:last");

					li.fadeOut(delay, function() {
						li.remove();
					});

					if (recomment) {
						setTimeout(function() {
							var totalRecomments = $("li.recent-comments-list > ul > li", currentScope).length;
							var visibleRecomments = $("li.recent-comments-list > ul > li:visible", currentScope).length;

							if ($("a.comment-link-comments span", currentScope).get(0))
								$("a.comment-link-comments span", currentScope).html(parseInt($("a.comment-link-comments span", currentScope).text()) - 1);

							// last recomment is deleted
							if (totalRecomments <= 1) {
								$("ul.recomment-list-item", currentScope).hide();
								//case show all comments exists, remove it
								if ($("a.comment-link-comments", currentScope).get(0))
									$("a.comment-link-comments", currentScope).remove();
								//case there more recomments, show the last li hidden
							} else if (totalRecomments > visibleRecomments && visibleRecomments < 3) {
								$("li.recent-comments-list > ul > li:hidden:last", currentScope).show();
							}

							// case doesnt exists more recomments to show, remove the link show all comments
							if ($("ul.recomment-list-item", currentScope).is(":visible") && totalRecomments == visibleRecomments) {

								if ($("a.comment-link-comments", currentScope).get(0))
									$("a.comment-link-comments", currentScope).remove();
							}
						}, 270);
					}
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	deleteCommentFile: function(o, mId) {
		$.ajax({
			url: LifeTributes.tributeURL + "/" + mId + "/GuestbookMediaDelete",
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {
					$(o).parents("li:first").fadeOut(250);
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	approveComment: function(o, cId) {
		$.ajax({
			url: LifeTributes.tributeURL + "/" + cId + "/GuestbookCommentApprove",
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {
					if ($(o).parents("div#Approvals").get(0)) {
						$(o).closest("li").hide($.browser.msie ? 0 : 250);
						if ($("ul#ApprovalComments li:visible").length == 0) {
							$("#PagerComments").hide();
						}
					} else {
						var li = $(o).parents("li:first");
						li.removeClass("candle-pending-approval gift-pending-approval");
						$("a.button-deny, a.button-approve, p.pending-approval", li).remove();
						$("div.comment-info-container", li).removeClass("comment-info-container-hidden");
						$("div.comment-info-container p", li).replaceWith(responseText.buttons);
						$("div.comment-info-container a.button-comment-delete").show();
					}
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	denyComment: function(o, cId) {
		$.ajax({
			url: LifeTributes.tributeURL + "/" + cId + "/GuestbookCommentDeny",
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {
					$(o).parents("li:first").hide(250);
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	approveRequest: function(o, cId) {
		$.ajax({
			url: LifeTributes.tributeURL + "/TributeRequestAccessApprove",
			data: "userId=" + cId,
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {
					$('#btnApprove' + cId.toString()).hide("slow");
					$('#btnDeny' + cId.toString()).hide("slow");
					$('#comment' + cId.toString()).html("<strong>" + $('#comment' + cId.toString() + " strong").html() + "</strong> Access granted");
					$('#comment' + cId.toString()).parent().after("<a onclick=\"TributeWall.removeAccess(this," + cId.toString() + ");\" class=\"button-comment-delete\" href=\"javascript:void(0);\" admin=\"true\" style=\"display: inline;\">Remove</a>");
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	denyRequest: function(o, cId) {
		$.ajax({
			url: LifeTributes.tributeURL + "/TributeRequestAccessDeny",
			data: "userId=" + cId,
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {
					$(o).parents("li:first").fadeOut(250);
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	removeAccess: function(o, cId) {
		$.ajax({
			url: LifeTributes.tributeURL + "/TributeAccessRemove",
			data: "userId=" + cId,
			dataType: "json",

			success: function(responseText) {
				if (responseText.status == 1) {
					$(o).parents("li:first").fadeOut(250);
				}
			},

			error: function(req, status, error) {
				setMessage("An error has ocurred. Please try again.", "error");
			}
		});
	},

	addMediaFileForCycleList: function(photoRoute) {
		mediaFiles.push(photoRoute);
	},

	showRecomments: function(o, commentId) {
		if (!$.browser.msie) {
			$(o).fadeOut(250, function() {
				$("#liReccoments" + commentId + " li").fadeIn(250);
			});
		} else {
			$(o).hide();
			$("#liReccoments" + commentId + " li").show();
		}
	},

	createRecommentEntry: function(o, commentId) {

		//var expressLogin = $("#memorialExpressLogin" + commentId).data("expressLogin");

		if ($("#txtRecomment" + commentId).val() == "") {
			$("#txtRecomment" + commentId).focus();
		} else {
			//if (expressLogin && !expressLogin.validate()) return false;

			if (ajaxRequest) {
				ajaxRequest.abort();
				ajaxRequest = false;
			}

			$(o).prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
			$("span.button-loading", o).width($(o).parent().width());

			var recommentData = {
				"txtComment": $("#txtRecomment" + commentId).val(),
				"commentId": commentId
			};

			var loginData = Login.getData();
			if (loginData.source == Login.LoginSources.guest) {
				$.extend(recommentData, loginData);
			} else if (!LifeTributes.User.isAuth) {
				Login.open({
					onLogin: function(data) {
						TributeWall.createRecommentEntry(o, commentId);
					}
				});
				return;
			}

			ajaxRequest = $.ajax({
				type: "POST",
				url: LifeTributes.tributeURL + "/createRecommentEntry",
				data: recommentData,
				dataType: "json",
				success: function(responseText) {
					switch (responseText.status) {
						case GeneralLifeTributeStatus.Success:

							//if (expressLogin) expressLogin.logMeIn(responseText);

							if ($("#liReccoments" + commentId).parents("li").find("a.comment-link-comments span").get(0)) {
								var totalRecomments = parseInt($("#liReccoments" + commentId).parents("li").find("a.comment-link-comments span").text());
								$("#liReccoments" + commentId).parents("li").find("a.comment-link-comments span").text(totalRecomments + 1);
							}
							$("#liReccoments" + commentId + " > ul > li:last").before(responseText.added);

							$("#liReccoments" + commentId).next().removeClass("recent-comments-field-no-items");
							$("span.watermark", $("#txtRecomment" + commentId).parent()).remove();
							$("#txtRecomment" + commentId).val("").height(16).watermark();
							$("#btnRecomment" + commentId).hide().removeClass("button-loading-active");
							$("#txtRecomment" + commentId).parent().parent().removeClass("input-textarea-focus");
							TributeWall.cancelRecommentEntry($("a", $("#memorialExpressLogin" + commentId).next()), commentId);

							TributeWall.setEditFields();

							storeAds.show();

							break;

						case GeneralLifeTributeStatus.UserNotLogged:
							Login.open({
								onLogin: function(data) {
									$(o).click();
								}
							});

							secondTracker._trackEvent('General', 'Tribute Pages', 'Tribute Box - Submit');

							break;

						case GeneralLifeTributeStatus.Error:

							break;

						case GeneralLifeTributeStatus.ReadonlyTribute:
							$("#ReadonlyAlert").click();
							break;

						case GeneralLifeTributeStatus.RegisterExists:
							expressLogin.registerExists();
							break;

						case GeneralLifeTributeStatus.UserNotFound:
							expressLogin.userNotFound();
							break;

						case GeneralLifeTributeStatus.RequiredFieldsEmpty:
							expressLogin.error();
							break;
					}
				},
				complete: function() {
					ajaxRequest = false;
					$("span.button-loading", o).fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				}

			});
		}
	},

	cancelRecommentEntry: function(o, commentId) {
		var ulRecomments = $("ul#recomments-" + commentId);

		$("#txtRecomment" + commentId).val("").height(16).watermark();
		$("#btnRecomment" + commentId).hide();
		$("#btnRecommentCancel" + commentId).hide();
		$("#memorialExpressLogin" + commentId).hide();
		$("#txtRecomment" + commentId).parents("div.input-textarea:first").removeClass("input-textarea-focus");
		$("a.comment-link[rel=" + commentId + "]").removeClass("showing");
		$(document).unbind("click.recomment");

		if (ulRecomments.find("li.recent-comments-list > ul > li").length <= 1) {
			ulRecomments.hide();
		}
	},

	closeRecommentEntry: function(e, commentId) {
		var target = e.target || e.originalTarget;
		var form = $("#recommentForm" + commentId).get(0);
		var isEmpty = ($("#txtRecomment" + commentId).val() == "");
		var isOutside = !($.inArray(form, $(target).parents()) != -1);
		if (isEmpty && isOutside) {
			TributeWall.cancelRecommentEntry($("#btnRecommentCancel" + commentId).get(0), commentId);
		}
	}
};

/*
* List Pager
*
* Description:
*   Pager
*/

var listPager = {
	Current: 1,
	More: function(o, s, e, ctl) {

		$(o).prepend("<span class=\"button-loading\"><em>Loading...</em></span>").parent().addClass("button-loading-active");
		$("span.button-loading", o).width($(o).parent().width());

		if ($(o).attr("rel") != "") {
			this.Current = parseInt($(o).attr("rel")) || 1;
		}

		this.Current++;
		$(o).attr("rel", this.Current);

		if (!ajaxRequestPager) {
			ajaxRequestPager = $.ajax({
				url: LifeTributes.tributeURL + "/" + ctl + "/" + this.Current,
				success: function(responseText) {
					$("#" + s).append(responseText);
					// IE6/7 bugfix (force css refresh)
					if ($.browser.msie && parseInt($.browser.version) <= 7) {
						$("body").css("visibility", "hidden").css("visibility", "visible");
					}
					TributeWall.setEditFields();
					TributeWall.events();
				},
				complete: function() {
					ajaxRequestPager = false;
					$("span.button-loading", o).fadeOut(250, function() { $(this).remove(); }).parent().parent().removeClass("button-loading-active");
				}
			});
		}
	},

	PrintAll: function(s, ctl) {
		if (ajaxRequestPager) {
			ajaxRequestPager.abort();
			jaxRequestPager = false;
		}
		ajaxRequestPager = $.ajax({
			url: LifeTributes.tributeURL + "/" + ctl + "/",
			beforeSend: function() {
				$("#printLoading").click();
			},
			success: function(responseText) {
				$("#" + s).html(responseText);
				// IE6/7 bugfix (force css refresh)
				if ($.browser.msie && parseInt($.browser.version) <= 7) {
					$("body").css("visibility", "hidden").css("visibility", "visible");
				}
				TributeWall.setEditFields();
				$.closeDialog();
				$('#wallPager').parent().fadeOut(250, function() {
					window.print();
				});
				ajaxRequestPager = false;
			},
			error: function(req, status, error) {
				ajaxRequestPager = false;
			}
		});
	},

	setPager: function(b, o) {
		if ($('#' + o).length <= 0) {
			$(document).ready(function() {
				if ($('#' + o).get(0)) listPager.setPager(b, o);
			});
		} else {
			var button = $('#' + o).parent("span").get(0) || $('#' + o).get(0);
			$(button)[b ? "fadeIn" : "fadeOut"](250);
		}
	}
}

/*
* Default Tip
*
* Description:
*   Default tip events
*/
var DefaultTip = {
	timeout: false,
	showDelay: 250,
	hideDelay: 1000,

	initialize: function() {
		this.build();
	},

	build: function() {
		this.events();
	},

	events: function() {
		$(".call-default-tip-click")
			.click(function() {
				DefaultTip.hideOthers(this);
				DefaultTip.show(this);
			})
			.live("mouseout", function() {
				DefaultTip.hide(this);
			});

		$(".call-default-tip:not(.call-default-tip-click)")
			.click(function() {
				DefaultTip.hideOthers(this);
			})
			.live("mouseover", function() {
				DefaultTip.show(this);
			})
			.live("mouseout", function() {
				DefaultTip.hide(this);
			});

		$(".default-tip")
			.live("mouseover", function() {
				DefaultTip.clear();
			})
			.live("mouseout", function() {
				DefaultTip.hide($("#" + $(this).attr("rel")));
			});
	},

	show: function(el) {
		var $this = this;
		el = $(el);
		var offset = el.position();
		var defaultTip = $(".default-tip[rel=" + el.attr("id") + "]");

		defaultTip.css({
			"left": offset.left - (defaultTip.width() / 2) + (el.width() / 2) + 10,
			"top": offset.top - 10 - defaultTip.height()
		});

		if (window.ajaxRequestPager) {
			window.ajaxRequestPager.abort();
			window.ajaxRequestPager = false;
		}

		$this.clear();
		$this.timeout = setTimeout(function() {
			$this.hideOthers();
			$(defaultTip).fadeIn(100);
		}, $this.showDelay);
	},

	hide: function(el) {
		var defaultTip = $(".default-tip[rel=" + $(el).attr("id") + "]");
		this.clear();
		this.timeout = setTimeout(function() {
			$(defaultTip).fadeOut(100);
		}, this.hideDelay);
	},

	hideOthers: function() {
		this.clear();
		$("div.default-tip").hide();
	},

	clear: function() {
		clearTimeout(this.timeout);
	}
};

/*
* PreLoad
*
* Description:
*	
*/
var Preload = {

	initialize: function() {
		this.events();
	},

	events: function() {
		this.images.initialize();
	},

	images: {
		initialize: function() {
			$.each(Preload.images.data, function(i, src) {
				window["image" + i] = new Image();
				window["image" + i].src = src;
			});
		},

		data: []
	}
};

/*
* Rounded Corners
*
* Description:
*	
*/
var RoundedCorners = {
	settings: {
		tl: { radius: 5 },
		tr: { radius: 5 },
		bl: { radius: 5 },
		br: { radius: 5 },
		antiAlias: true
	},

	makeCorner: function(obj, settings) {
		settings = $.extend({}, this.settings, settings);
		if (!$(obj).hasClass("cornered")) {
			$(obj).addClass("cornered");
			curvyCorners(settings, obj);
		}
	}
};

/*

Workaround Solution Gambi for IE Border Radius :)

*/
var BorderRadius = {
	initialize: function() {

		if (navigator.appVersion.indexOf("MSIE") > -1) {
			var $this = this;

			this.createDivs(".borderMe", { hover: false });
			this.createDivs(".borderMeWithHover", { hover: true });
		}

	},

	createDivs: function(selector, opts) {
		var opts = $.extend({}, { hover: false, tl: false, tr: false, bl: true, br: true }, opts);

		$(selector).each(function() {
			var elm = $(this);

			if (opts.hover) {
				elm.hover(function() {
					$(".border-radius", this).addClass("border-radius-hover");
				}, function() {
					$(".border-radius", this).removeClass("border-radius-hover");
				});
			}

			if (opts.tl) {
				var topLeft = $("<div/>").attr({ "class": "border-radius border-radius-top-left" });
				elm.append(topLeft);
			}

			if (opts.tr) {
				var topRight = $("<div/>").attr({ "class": "border-radius border-radius-top-right" });
				elm.append(topRight);
			}

			if (opts.bl) {
				var bottomLeft = $("<div/>").attr({ "class": "border-radius border-radius-bottom-left" });
				elm.append(bottomLeft);
			}

			if (opts.br) {
				var bottomRight = $("<div/>").attr({ "class": "border-radius border-radius-bottom-right" });
				elm.append(bottomRight);
			}

		});
	}
};


/*
* Share
*
* Description:
*	
*/
var Share = {

	initialize: function() {

		$("div.tip span.close, div.tip a.share-link").live("click", function() {
			clearTimeout(tributeWallTipTimeout);
			var tip = $(this).parents("div.tip");

			tip.addClass("tip-removing");
			tip.fadeOut(250, function() {
				if (navigator.appVersion.indexOf("MSIE 7") > -1) {
					$(this).parents("li:first").css("zIndex", "auto");
				}
				$(tip).removeClass("tip-removing");
			});
		});

		$("#txtUserMail").keydown(function(e) {
			if (e.keyCode == 13) {
				$("#lnkShare").click();
			}
		});

		$("a.share-link[rel=nofollow]").live("click", function(e) {
			e.preventDefault();
			window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent($(this).attr("href")) + '&t=' + encodeURIComponent('Life Tributes'), 'sharer', 'toolbar=0,status=0,width=626,height=436');
		});

		$(".integration-buttons > strong")
			.live("mouseover", function() {
				var tip = $("div.tip", this);
				var li = $("div.tip", this).parents("li:first");
				var sharelinkOffset = $("a.share-button", this).position();
				tip.css({
					"left": sharelinkOffset.left - 75,
					"top": sharelinkOffset.top + 22
				});

				if (tip.hasClass("tip-removing")) { return false; }
				$(".integration-buttons > strong div.tip:visible").not(tip).fadeOut(250, function() {
					var mode = document.documentMode || 0;
					if ($.browser.msie && ($.browser.version < 8 || mode < 8)) {
						$(this).parents("li:first").css("zIndex", "auto");
					}
				});

				if (ajaxRequestPager) {
					ajaxRequestPager.abort();
					ajaxRequestPager = false;
				}

				clearTimeout(tributeWallTipTimeout);
				tributeWallTipTimeout = setTimeout(function() {
					var mode = document.documentMode || 0;
					if ($.browser.msie && ($.browser.version < 8 || mode < 8)) {
						li.css("zIndex", 100);
					}
					$(tip).fadeIn(250);
				}, 250);
			})
			.live("mouseout", function() {
				var tip = $("div.tip", this);
				var li = $("div.tip", this).parents("li:first");
				clearTimeout(tributeWallTipTimeout);
				tributeWallTipTimeout = setTimeout(function() {
					$(tip).fadeOut(250, function() {
						if (navigator.appVersion.indexOf("MSIE 7") > -1) {
							li.css("zIndex", "auto");
						}
					});

				}, 1000);
			});
	},

	twitterForm: function(o, commentId) {

		if ($("ul.twitter-form", $(o).parents("ul#TributesComments")).length > 0) {
			$("ul.twitter-form", $(o).parents("ul#TributesComments")).fadeOut(180, function() {
				$("ul.twitter-form", $(o).parents("ul#TributesComments")).remove();
			});
		}

		if (ajaxRequestPager) {
			ajaxRequestPager.abort();
			ajaxRequestPager = false;
		}

		if (ajaxRequest) ajaxRequest.abort();

		ajaxRequest = $.ajax({
			url: LifeTributes.tributeURL + "/TwitterMessageForm",
			type: "POST",
			data: "commentId=" + commentId,
			success: function(responseText) {
				$("div.comment:eq(0)", $(o).parents("li")).after(responseText);
				$("#txtTwitterMessage" + commentId).simpleautogrow().height(16).keyup(function() {
					if ($(this).val().length > 140) {
						$(this).val($(this).val().substring(0, 140));
						return false;
					}
				}).focus();
			}
		});
	},

	twitterCancel: function(o, commentId) {
		$("#TwitterMessage" + commentId).remove();
	},

	twitterShare: function(o, cId, message) {
		$.ajax({
			type: "POST",
			url: LifeTributes.tributeURL + "/twitterShare",
			data: { "commentId": cId, "message": $("#txtTwitterMessage" + cId).val() },
			dataType: "json",

			beforeSend: function() {
				$("#outputTwitter").hide();
			},

			success: function(responseText) {
				switch (responseText.status) {
					case GeneralLifeTributeStatus.Success:
						$("ul.twitter-form", $(o).parents("li")).remove();
						break;
					case GeneralLifeTributeStatus.UserNotLogged:
						Login.open({
							title: "Who are you?",
							onLoad: function() {
								Login.showOnlyOption("twitter");
							},
							onLogin: function(data) {
								Share.twitterShare(o, cId, message);
							}
						});
						break;
				}
			},
			error: function(req, status, error) {
				$(o).parent().show();
				$("#outputTwitter").show();
			}
		});
	}

}

/*
* Facebook Remover
*
* Description:
*	
*/
var FacebookRemover = {
	interval: null,

	initialize: function() {
		if (typeof FB == "undefined" && $("div.lt-memorial-search").length == 0)
			this.start();
	},

	start: function() {
		var $this = this;
		this.interval = setInterval(function() {
			$this.remove();
		}, 500);
	},

	stop: function() {
		if (!!this.interval) clearInterval(this.interval);
	},

	remove: function() {
		$("#FB_HiddenContainer, .login-tabs li.facebook, a.facebook-icon, iframe[src*=facebook]").remove();
		$(".login-type-facebook").parents("li").remove();
		$(".tribute-recommend-button").css("visibility", "hidden");
	}
};

/*
* Feedback
*
* Description:
*	Feedback Button
*/
var Feedback = {
	initialize: function() {

	}
};

/*
* New Login
*
* Description:
*	
*/
var Login = {

	LoginSources: {
		lifetributes: 0,
		twitter: 1,
		facebook: 2,
		guest: 3
	},

	data: {},
	tooltipElement: null,
	mediaPhotoUploader: null,

	defaults: {
		title: "",
		onLoad: function() { },
		onClose: function(success) { },
		onLogin: function(data) { },
		onLogout: function() { }
	},


	setOptions: function(options) {
		this.options = $.extend({}, this.defaults, options);
	},

	initialize: function() {
		this.upload.parent = this;
		this.preload();
	},

	preload: function() {
		var $this = this;
		this.options = this.defaults;

		$("#Login").click(function(e) {
			e.preventDefault();
			Login.open({
				title: "Who are you?",
				onLoad: function() {
					Login.hideGuest();
				}
			});
		});

		$("#UserLogin #Login").click(function(e) {
			e.preventDefault();
			try {
				secondTracker._trackEvent('General', 'Tribute Pages', 'Login');
			} catch (e) { }
		});

		$("#UserLogged .user-options li #LogOut").click(function(e) {
			e.preventDefault();
			$this.logout();
		});

		this.userboxEvents();
	},

	userboxEvents: function() {
		var timeoutHide = null;

		$("#UserLogged").hover(function() {
			var userLogged = $(this);
			clearTimeout(timeout);
			timeout = setTimeout(function() {
				$(".user-options", userLogged).slideDown(100);
			}, 100);
		}, function() {
			var userLogged = $(this);
			clearTimeout(timeout);
			timeout = setTimeout(function() {
				$(".user-options", userLogged).slideUp(100);
			}, 200);
		});
	},

	open: function(options) {
		this.setOptions(options);
		Login.data = {};
		$("<a>").createModal({
			cssClass: 'modal-login modal-login-new',
			urlRequest: LifeTributes.rootFolder + 'Register',
			disableClose: true,
			loadCallback: function() {
				Login.events();
				Login.options.onLoad();
				Login.formFocus();
			},
			beforeShowCallback: function() {
				$(".video").css("visibility", "hidden");
			},
			afterHideCallback: function() {
				Login.data = {};
				$(".video").css("visibility", "visible");
				$("div.login-tooltip").remove();
				if (Login.mediaPhotoUploader) Login.mediaPhotoUploader.destroy();
			}
		}).click();
	},

	close: function(success) {
		if (!$(".modal-login").get(0) || $(".modal-store-ads").get(0)) return;
		this.options.onClose(success);
		if (this.mediaPhotoUploader) this.mediaPhotoUploader.destroy();
		$.closeDialog({
			afterHideCallback: function() {
				$(".video").css("visibility", "visible");
				$("div.login-tooltip").remove();
			}
		});
	},

	setData: function(data, register) {
		if (data) {
			Login.data = data;
		} else {
			Login.data = {};
			var form = this.body.find("div.tab-active form");
			if (register) form = $("#ltRegistration");
			form.find("input, select, textarea").each(function() {
				if ($(this).attr("type") == "checkbox" && !$(this).get(0).checked) return;
				Login.data[$(this).attr("name")] = $(this).val();
			});
		}
		return Login.data;
	},

	getData: function() {
		return Login.data;
	},

	events: function() {
		this.data = {};
		var $this = this;
		this.modal = $("div.modal-login");
		this.wrapper = $("div.modal-login div.body");
		this.header = $("div.modal-login div.body div.signup-header");
		this.body = $("div.modal-login div.body div.signup-body");
		this.footer = $("div.modal-login div.body div.signup-footer");

		if (this.options.title) {
			this.setTitle(this.options.title);
		}
		// Tooltips
		var tooltip = this.wrapper.find("div.login-tooltip");
		tooltip.find("a.tooltip-close").click(function(e) {
			e.preventDefault();
			Login.hideTooltip();
		});
		this.modal.after(tooltip);

		// Forms
		this.body.find("input[type=checkbox], input[type=radio]").checkBox();
		this.body.find("span.input-text input").focus(function(e) {
			$(this).closest("span.input-text").addClass("input-text-focus");
			Login.showError(this);
		}).blur(function(e) {
			$(this).closest("span.input-text").removeClass("input-text-focus");
		});
		this.body.find("span.input-text").click(function(e) {
			$(this).find("input").focus();
		});
		this.body.find("form").find("span.input-text input:last").keypress(function(e) {
			var code = e.which || e.keyCode;
			var key = $.keyOf($.ui.keyCode, code);
			key = key || String.fromCharCode(code).toLowerCase();
			if (key == 'ENTER') {
				$(this).closest("form").submit();
			}
		}).keydown(function(e) {
			var code = e.which || e.keyCode;
			var key = $.keyOf($.ui.keyCode, code);
			key = key || String.fromCharCode(code).toLowerCase();
			if (key == 'TAB') {
				e.preventDefault();
				return false;
			}
		});

		// Links
		this.body.find("a.create-account").click(function(e) {
			e.preventDefault();
			$this.createAccount();
		});
		this.body.find("a.forgot-password").click(function(e) {
			e.preventDefault();
			$this.forgotPassword();
		});

		this.body.find("a.signin-twitter").click(function(e) {
			e.preventDefault();
			$this.loginTwitter();
		});
		this.body.find("a.terms-conditions").click(function(e) {
			e.preventDefault();
			$this.termsConditions();
		});
		this.header.find("a.return-options").click(function(e) {
			e.preventDefault();
			$this.loginOptions();
		});
		this.header.find("a.return-register").click(function(e) {
			e.preventDefault();
			$this.createAccount();
		});

		// Custom tooltips
		this.body.find("a.create-account-why").hover(function() {
			$this.hereswhy = setTimeout(function() {
				$this.body.find("div.hereswhy-tooltip").show();
			}, 250);
		}, function() {
			clearTimeout($this.hereswhy);
			setTimeout(function() {
				$this.body.find("div.hereswhy-tooltip").hide();
			}, 250);
		});
		this.footer.find("a.learn-more").hover(function() {
			$this.learnmore = setTimeout(function() {
				$this.footer.find("div.learnmore-tooltip").show();
			}, 250);
		}, function() {
			clearTimeout($this.learnmore);
			setTimeout(function() {
				$this.footer.find("div.learnmore-tooltip").hide();
			}, 250);
		});

		// Create Account
		this.body.find("div.create-account span.input-text input").watermark();
		this.body.find("div.create-account div.control-gender input").bind('checkBoxchange', function(e, ui) {
			if (ui.checked) {
				$("#memberPhotoGeneric").attr("class", "avatar avatar-" + ($(this).val() == 1 ? "male" : "female"));
			}
		});
		this.body.find("#Terms").bind('checkBoxchange', function(e, ui) {
			if (ui.checked) {
				$this.hideTooltip($(this).parent());
			}
		});
		this.body.find("div.create-account a.customize-photo").click(function(e) {
			e.preventDefault();
			$this.body.find("div.create-account div.member-photo-body > div").removeClass("content-active");
			$this.body.find("div.create-account div.member-photo-body > div.custom-photo").addClass("content-active");
		});
		this.body.find("div.create-account a.change-photo").click(function(e) {
			e.preventDefault();
			$this.body.find("div.create-account div.member-photo-body > div").removeClass("content-active");
			$this.body.find("div.create-account div.member-photo-body > div.custom-photo").addClass("content-active");
		});
		this.body.find("div.create-account a.generic-photo").click(function(e) {
			e.preventDefault();
			$("#picturePath").val("");
			$this.body.find("div.create-account div.member-photo-body > div").removeClass("content-active");
			$this.body.find("div.create-account div.member-photo-body > div.generic-photo").addClass("content-active");
		});
		this.body.find("div.create-account div.custom-photo div.avatar-take").click(function(e) {
			$this.takePhoto();
		});

		this.setupTabs();
		this.formEvents();

		// Facebook
		this.facebookSetup();
		this.body.find("#fbControl a").click(function(e) {
			e.preventDefault();
			if (typeof FB != "undefined" && FB.initialized) {
				FB.login(function(response) {
					if (response.authResponse) {
						Login.loginFacebook(response.authResponse);
					}
				}, { scope: 'email,user_birthday' });
			}
		});

		this.uploadEvents();

		/* IE9 Cursor Bug */
		if ($.browser.msie) {
			this.body.find("span.input-text input").blur(function(e) {
				$(this).hide().show().get(0).blur();
			});
		}
	},

	facebookSetup: function() {
		if (typeof FB != "undefined" && FB.init && !FB.initialized) {
			//FB.init(LifeTributes.ApiKeys.Facebook, LifeTributes.baseURL + "/XdReceiver", { permsToRequestOnConnect: 'email,publish_stream' });

			FB.init({
				appId: LifeTributes.ApiKeys.Facebook,
				channelUrl: LifeTributes.baseURL + "/FBChannel", // Channel File
				status: true, // check login status
				cookie: true, // enable cookies to allow the server to access the session
				xfbml: true,  // parse XFBML
				oauth: true
			});

			FB.initialized = true;
		} else if (typeof FB != "undefined" && FB.XFBML) {
			FB.XFBML.parse();
		}
	},

	formFocus: function() {
		this.body.find("span.input-text input[value=]:visible:first").focus();
	},

	setTitle: function(title) {
		this.header.find("h1").text(title);
	},

	showTooltip: function(options) {
		if (!options || !options.element) return;
		Login.tooltipElement = $(options.element).find("input").get(0);
		var tooltip = $("div.login-tooltip");
		tooltip.find("h3").html(options.title);
		tooltip.find("p").html(options.text);
		if (typeof options.link == "function") {
			tooltip.find("p a").click(function(e) {
				e.preventDefault();
				options.link();
			});
		}
		if (options.tail) {
			tooltip.addClass("login-tooltip-" + options.tail + "-tail");
		} else {
			tooltip.removeClass("login-tooltip-left-tail");
			tooltip.removeClass("login-tooltip-center-tail");
		}
		tooltip.show();
		var positionTop = options.element.offset().top - tooltip.outerHeight() + options.offset.top;
		var positionLeft = options.element.offset().left + options.element.outerWidth() - tooltip.outerWidth() + options.offset.left;
		tooltip.css({
			top: positionTop,
			left: positionLeft
		});
		return tooltip;
	},

	showError: function(element) {
		var input = $(element).closest(".input-text");
		var hasError = input.hasClass("input-text-error");
		var hasFocus = input.hasClass("input-text-focus");
		var tooltip = $(element).data("tooltip");
		if (hasError && tooltip) {
			Login.showTooltip({
				element: input,
				offset: { top: -5, left: 0 },
				title: tooltip.title,
				text: tooltip.text
			});
		}
	},

	setTooltip: function(element, error) {
		element.data("tooltip", error);
		if (this.tooltipElement == element) {
			var tooltip = $("div.login-tooltip");
			tooltip.find("h3").html(error.title);
			tooltip.find("p").html(error.text);
		}
	},

	hideTooltip: function(element) {
		if (!element || (this.tooltipElement && element == this.tooltipElement)) {
			var tooltip = $("div.login-tooltip");
			this.tooltipElement = null;
			tooltip.hide();
		} else if (element) {
			var input = $(element).closest(".input-text");
			var hasError = input.hasClass("input-text-error");
			if (!hasError) $(element).removeData("tooltip");
		}
	},

	formEvents: function() {
		this.wrapper.find("form a.button").click(function(e) {
			e.preventDefault();
			$(this).closest("form").submit();
		});

		// Guest Account
		$("#guestAccount").submit(function(e) {
			e.preventDefault();
			if ($("#guestAccount").valid()) {
				Login.hideTooltip();
				if ($("#guestCreateAccount").get(0).checked) {
					$("#registerEmail").val($("#guestEmail").val()).prev(".watermark").hide();
					$("#registerName").val($("#guestName").val()).prev(".watermark").hide();
					$("#picturePath").val("");
					Login.createAccount("generic-photo");
					$("#registerPassword").val("").focus();
					$("#registerPassword").parent().children("watermark").addClass("watermark-active").show();
				} else {
					Login.close(true);
					var data = Login.setData();
					Login.options.onLogin(data);
					Login.setData({});
				}
			} else {
				var error = $("#guestAccount").validate().errorList[0];
				if (error && error.element) error.element.focus();
			}
			return false;
		});

		$("#guestAccount").validate({
			rules: {
				txtUserMail: {
					required: true,
					email: true
				},
				txtUserName: {
					required: true
				}
			},
			messages: {
				txtUserMail: {
					required: "Please enter your email.",
					email: "Please enter a valid email address."
				},
				txtUserName: {
					required: "Please enter your name."
				}
			},
			errorClass: "input-text-error",
			highlight: function(element, errorClass) {
				$(element).closest(".input-text").addClass(errorClass);
				Login.showError(element);
			},
			unhighlight: function(element, errorClass) {
				$(element).closest(".input-text").removeClass(errorClass);
				Login.hideTooltip(element);
			},
			errorPlacement: function(error, element) {
				Login.setTooltip(element, { title: "Wooops!", text: error.html() });
			}
		});

		// LifeTributes Account
		$("#ltAccount").ajaxForm({
			beforeSubmit: function() {
				if ($("#ltAccount").hasClass("form-loading")) return false;
				if (!$("#ltAccount").valid()) {
					var error = $("#ltAccount").validate().errorList[0];
					if (error && error.element) error.element.focus();
					return false;
				} else {
					$("#ltAccount").addClass("form-loading");
					Login.hideTooltip();
					Login.setData(false, true);
				}
			},
			complete: function() {
				$("#ltAccount").removeClass("form-loading");
			},
			success: function(response, statusText) {
				switch (response.status) {
					case GeneralLifeTributeStatus.Success:
						Login.loginSuccess(response, Login.LoginSources.lifetributes);
						Login.close(true);
						var data = Login.getData();
						Login.options.onLogin(data);
						Login.setData({});
						break;
					case GeneralLifeTributeStatus.UserNotLogged:
						var email = $("#ltAccount input[name=Email]").parent(),
							password = $("#ltAccount input[name=Password]").parent();
						Login.showTooltip({
							element: email,
							offset: { top: -5, left: 0 },
							title: "Wooops!",
							text: "The username / password you entered was incorrect. If you've forgotten your username / password click <a>here</a>.",
							link: function() {
								Login.forgotPassword();
							}
						});
						email.addClass("input-text-error");
						password.addClass("input-text-error");
						break;
					case GeneralLifeTributeStatus.UserNotFound:
						var email = $("#ltAccount input[name=Email]").parent();
						Login.showTooltip({
							element: email,
							offset: { top: -5, left: 0 },
							title: "Wooops!",
							text: "We didn't find your email. Please check it and try again."
						});
						email.addClass("input-text-error");
						break;
					case GeneralLifeTributeStatus.Error:
						var email = $("#ltAccount input[name=Email]").parent();
						Login.showTooltip({
							element: el,
							offset: { top: -5, left: 0 },
							title: "Wooops!",
							text: "We couldn't process your request. Please try again."
						});
						email.addClass("input-text-error");
						break;
				}
			}
		});

		$("#ltAccount").validate({
			rules: {
				Email: {
					required: true,
					email: true
				},
				Password: {
					required: true
				}
			},
			messages: {
				Email: {
					required: "Please enter your email.",
					email: "Please enter a valid email address."
				},
				Password: {
					required: "Please enter your password."
				}
			},
			errorClass: "input-text-error",
			highlight: function(element, errorClass) {
				$(element).closest(".input-text").addClass(errorClass);
				Login.showError(element);
			},
			unhighlight: function(element, errorClass) {
				$(element).closest(".input-text").removeClass(errorClass);
				Login.hideTooltip(element);
			},
			errorPlacement: function(error, element) {
				Login.setTooltip(element, { title: "Wooops!", text: error.html() });
			}
		});

		// Registration
		$("#ltRegistration").ajaxForm({
			beforeSubmit: function() {
				if ($("#ltRegistration").hasClass("form-loading")) return false;
				if (!$("#ltRegistration").valid()) {
					var error = $("#ltRegistration").validate().errorList[0];
					if (error && error.element) error.element.focus();
					return false;
				} else {
					$("#ltRegistration").addClass("form-loading");
					Login.hideTooltip();
					//secondTracker._trackEvent('Login - New Account', 'Signup', 'Btn - Sign Up');
				}
			},
			complete: function() {
				$("#ltRegistration").removeClass("form-loading");
			},
			success: function(response, statusText) {
				switch (response.status) {
					case GeneralLifeTributeStatus.Success:
						Login.loginSuccess(response, Login.LoginSources.lifetributes);
						Login.close(true);
						var data = Login.getData();
						Login.options.onLogin(data);
						Login.setData({});
						break;
					case 2:
						var email = $("#ltRegistration input[name=Email]").parent();
						Login.showTooltip({
							element: email,
							offset: { top: -5, left: 0 },
							title: "Wooops!",
							text: "This email is already in use. If you don't remember your password, <a>click here</a>.",
							link: function() {
								Login.forgotPassword();
							}
						});
						email.addClass("input-text-error");
						break;
					case GeneralLifeTributeStatus.Error:
						var email = $("#ltRegistration input[name=Email]").parent();
						Login.showTooltip({
							element: email,
							offset: { top: -5, left: 0 },
							title: "Wooops!",
							text: "We couldn't process your request. Please try again."
						});
						email.addClass("input-text-error");
						break;
					case 4:
						var firstName = $("#ltRegistration input[name=FirstName]").parent(); ;
						Login.showTooltip({
							element: firstName,
							offset: { top: -5, left: 0 },
							title: "Wooops!",
							text: " Please enter your name."
						});
						firstName.addClass("input-text-error");
						break;
					case 7:
						Login.showTooltip({
							element: $("#ltRegistration input[name=Terms]").parent(),
							offset: { top: 0, left: 80 },
							title: "Wooops!",
							text: "You must agree with the terms and conditions to proceed.",
							tail: "left"
						});
						break;
				}
			}
		});
		$("#ltRegistration").validate({
			rules: {
				Email: {
					required: true,
					email: true
				},
				FirstName: {
					required: true
				},
				Password: {
					required: true,
					minlength: 6
				}
			},
			messages: {
				Email: {
					required: "Please enter your email.",
					email: "Please enter a valid email address."
				},
				FirstName: {
					required: "Please enter your name."
				},
				Password: {
					required: "Please enter your password.",
					minlength: "Your password must be at least 6 characters."
				}
			},
			errorClass: "input-text-error",
			highlight: function(element, errorClass) {
				$(element).closest(".input-text").addClass(errorClass);
				Login.showError(element);
			},
			unhighlight: function(element, errorClass) {
				$(element).closest(".input-text").removeClass(errorClass);
				Login.hideTooltip(element);
			},
			errorPlacement: function(error, element) {
				Login.setTooltip(element, { title: "Wooops!", text: error.html() });
			}
		});

		// Lost Password
		$("#recoverPassword").ajaxForm({
			beforeSubmit: function() {
				if ($("#recoverPassword").hasClass("form-loading")) return false;
				if (!$("#recoverPassword").valid()) {
					var error = $("#recoverPassword").validate().errorList[0];
					if (error && error.element) error.element.focus();
					return false;
				} else {
					$("#recoverPassword").addClass("form-loading");
					Login.hideTooltip();
				}
			},
			complete: function() {
				$("#recoverPassword").removeClass("form-loading");
			},
			success: function(response, statusText) {
				switch (response.status) {
					case GeneralLifeTributeStatus.Success:
						var message = Login.body.find("div.tab-recover div.info-message p");
						message.removeClass("error").text("Please follow the instructions that were sent to your email in order to reset your password.").fadeIn();
						break;
					case GeneralLifeTributeStatus.Error:
						var message = Login.body.find("div.tab-recover div.info-message p");
						message.addClass("error").text("There was an error processing your request. The recover e-mail was not send.").fadeIn();
						break;
					case GeneralLifeTributeStatus.UserNotFound:
						var email = $("#recoverEmail");
						email.addClass("input-text-error");
						Login.setTooltip(email, { title: "Wooops!", text: "We didn't find your email. Please check it and try again." });
						Login.showError(email);
						break;
				}
			}
		});

		$("#recoverPassword").validate({
			rules: {
				Email: {
					required: true,
					email: true
				}
			},
			messages: {
				Email: {
					required: "Please enter your email.",
					email: "Please enter a valid email address."
				}
			},
			errorClass: "input-text-error",
			highlight: function(element, errorClass) {
				$(element).closest(".input-text").addClass(errorClass);
				Login.showError(element);
			},
			unhighlight: function(element, errorClass) {
				$(element).closest(".input-text").removeClass(errorClass);
				Login.hideTooltip(element);
			},
			errorPlacement: function(error, element) {
				Login.setTooltip(element, { title: "Wooops!", text: error.html() });
			}
		});
	},

	setupTabs: function() {
		var $this = this;
		var ul = this.wrapper.find("div.signup-options ul.options");
		var tabs = ul.find("li");
		var content = this.wrapper.find("div.signup-options div.tab-options div.tab-option");
		tabs.find("a").click(function(e) {
			e.preventDefault();
			var li = $(this).closest("li");
			tabs.removeClass("active");
			var name = $.trim(li.attr("class"));
			li.addClass("active");
			content.removeClass("tab-active");
			content.filter(".tab-" + name).addClass("tab-active");
			$this.formFocus();
			$this.hideTooltip();
		});
	},

	hideGuest: function() {
		this.body.find("div.signup-options ul.options li.guest").removeClass("active").hide();
		this.body.find("div.signup-options div.tab-options div.tab-guest").removeClass("tab-active").hide();
		this.body.find("div.signup-options ul.options li.lifetributes").addClass("active");
		this.body.find("div.signup-options div.tab-options div.tab-lifetributes").addClass("tab-active");
	},
	showOnlyOption: function(option) {
		this.body.find("div.signup-options ul.options > li").removeClass("active").hide();
		this.body.find("div.signup-options div.tab-options > div").removeClass("tab-active").hide();
		this.body.find("div.signup-options ul.options li." + option).addClass("active").show();
		this.body.find("div.signup-options div.tab-options div.tab-" + option).addClass("tab-active").show();
		this.body.find("div.signup-options div.tab-options div.tab-" + option + " div.text-footer").hide();
	},
	forgotPassword: function() {
		this.loginOptions();
		this.body.find("div.signup-options div.tab-options div.tab-option").removeClass("tab-active");
		this.body.find("div.signup-options div.tab-options div.tab-recover").addClass("tab-active");
		this.body.find("div.signup-options div.tab-options div.tab-recover div.info-message p").hide();
		this.body.find("#recoverEmail").focus();
	},
	loginOptions: function() {
		this.hideTooltip();
		this.body.children("div").hide();
		this.body.children("div.signup-options").show();
		this.header.find("a.return").hide();
	},
	createAccount: function(contentPhoto) {
		this.hideTooltip();
		this.body.children("div").hide();
		var wrapper = this.body.children("div.create-account");
		wrapper.show();
		wrapper.children("div").hide();
		wrapper.children("div.registration").show();
		if (contentPhoto) {
			wrapper.find("div.member-photo-body > div").removeClass("content-active");
			wrapper.find("div.member-photo-body > div." + contentPhoto).addClass("content-active");
		}
		this.header.find("a.return").hide();
		this.header.find("a.return-options").show();
	},
	termsConditions: function() {
		this.hideTooltip();
		this.body.children("div").hide();
		this.body.children("div.terms-conditions").show();
		this.header.find("a.return").hide();
		this.header.find("a.return-register").show();
	},

	uploadEvents: function() {
		this.mediaPhotoUploader = new SWFUpload({
			upload_url: LifeTributes.rootFolder + "RegisterCompletion/UpdatePicture",
			file_size_limit: "100 MB",
			file_types: LifeTributes.imageTypes,
			file_types_description: "Media Files",
			file_upload_limit: "0", // unlimited
			file_queue_error_handler: fileQueueError,
			file_dialog_complete_handler: fileDialogComplete,
			upload_start_handler: this.upload.start,
			upload_progress_handler: this.upload.progress,
			upload_error_handler: uploadError,
			upload_success_handler: this.upload.success,
			upload_complete_handler: uploadComplete,
			button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
			button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
			button_cursor: SWFUpload.CURSOR.HAND,
			button_placeholder_id: "FlashMediaPhotoUpload",
			button_width: 119,
			button_height: 118,
			flash_url: LifeTributes.rootFolder + "js/swfupload.swf",
			debug: false
		});
		this.mediaPhotoUploader.parent = this;
		this.mediaPhotoUploader.wrapper = this.body.find("div.create-account div.member-photo");
	},

	upload: {
		start: function(obj) {
			this.wrapper.children("div").removeClass("content-active");
			this.wrapper.children("div.photo-uploading").addClass("content-active");
			this.wrapper.find("div.photo-uploading strong.bar").css("width", 0);
			this.wrapper.find("div.photo-uploading span.percentual").text("0%");
		},
		progress: function(obj, bytes) {
			var percent = Math.ceil((bytes / obj.size) * 100);
			if (bytes > 0) {
				this.wrapper.find("div.photo-uploading strong.bar").css("width", percent + "%");
				this.wrapper.find("div.photo-uploading span.percentual").text(percent + "%");
			}
		},
		success: function(file, response) {
			var json = $.evalJSON(response);
			this.wrapper.find("div.photo-uploading strong.bar").css("width", "100%");
			this.wrapper.find("div.photo-uploading span.percentual").text("100%");
			this.parent.cropPhoto(json.imageName, json.imagePath);
		},
		error: function(file, errorCode, message) {
		}
	},

	takePhoto: function() {
		this.hideTooltip();
		this.header.find("a.return").hide();
		this.header.find("a.return-register").show();
		var wrapper = this.body.children("div.create-account");
		wrapper.children("div").hide();
		wrapper.children("div.take-photo").show();
		swfobject.embedSWF(LifeTributes.rootFolder + "Support/webcamPhotoLogin.swf",
			"webcamPhotoContainer", "375", "343", "9.0.0",
			LifeTributes.rootFolder + "theme/wms/flash/expressInstall.swf", {
				serverAction: true,
				jsCallBack: function(data) { Login.takePhotoComplete(data); }
			},
			{ wmode: "Transparent", menu: "false" },
			{ id: "webcamPhotoContainer", name: "webcamPhotoContainer" });
		window.closePhotoWindow = this.takePhotoCancel;
	},

	takePhotoComplete: function(photo) {
		var $this = this;
		$.ajax({
			type: "POST",
			dataType: "json",
			url: LifeTributes.rootFolder + "RegisterCompletion/SaveUploadedPhoto",
			data: {
				'guid': photo.photoId,
				'encodedThumbBytes': photo.thumbnail
			},
			success: function(response) {
				$this.cropPhoto(response.item.Path, response.storagePath);
			},
			error: function() {
			}
		});
	},

	takePhotoCancel: function() {
		var wrapper = Login.body.children("div.create-account");
		var container = $("<div>").attr("id", "webcamPhotoContainer");
		wrapper.find("div.take-photo div.take-photo-body").empty().append(container);
		Login.createAccount("custom-photo");
	},

	cropPhoto: function(imageName, imagePath) {
		this.hideTooltip();
		this.header.find("a.return").hide();
		this.header.find("a.return-register").show();
		var wrapper = this.body.children("div.create-account");
		wrapper.children("div").hide();
		wrapper.children("div.crop-photo").show();
		swfobject.embedSWF(LifeTributes.rootFolder + "Support/photoCropper.swf",
			"cropPhotoContainer", "314", "291", "9.0.0",
			LifeTributes.rootFolder + "theme/wms/flash/expressInstall.swf",
			{
				imageURL: imagePath,
				jsCallBack: function(data) { Login.cropPhotoComplete(data); }
			},
			{ wmode: "Transparent", menu: "false" },
			{ id: "cropPhotoContainer", name: "cropPhotoContainer" });
		this.picturePath = imageName;
		window.closePhotoWindow = this.cropPhotoCancel;
	},

	cropPhotoComplete: function(cropInfo) {
		var $this = this;
		$.ajax({
			type: "POST",
			url: LifeTributes.rootFolder + "CropBox/Apply",
			data: {
				fileName: $this.picturePath,
				imgX: cropInfo.cropX,
				imgY: cropInfo.cropY,
				imgW: cropInfo.cropWidth,
				imgH: cropInfo.cropHeight,
				defaultWidth: cropInfo.newImageWidth,
				defaultHeight: cropInfo.newImageHeight
			},
			dataType: "json",
			success: function(response) {
				$("#picturePath").val($this.picturePath);
				var src = response.imagePath.toString().replace(response.imageName, response.imageName.toString().replace(".", "_croped."));
				src = src + "?r=" + (+new Date());
				var avatar = $("<img />").attr("src", src);
				$("#memberPhoto").empty().append(avatar);
				$this.createAccount("photo-cropped");
			},
			error: function() {
			}
		});
	},

	cropPhotoCancel: function() {
		var wrapper = Login.body.children("div.create-account");
		var container = $("<div>").attr("id", "cropPhotoContainer");
		wrapper.find("div.crop-photo div.crop-photo-body").empty().append(container);
		Login.createAccount("custom-photo");
	},

	loginFacebook: function(authResponse) {
		if (!authResponse) return false;
		if (this.fbRequest) {
			this.fbRequest.abort();
			this.fbRequest = false;
		}
		FB.api("/me?fields=id,email,username,first_name,last_name,picture,birthday", function(response) {
			response.authResponse = authResponse;
			this.fbRequest = $.ajax({
				type: "POST",
				url: LifeTributes.rootFolder + "Login/Facebook",
				dataType: "json",
				data: response,
				success: function(response) {
					if (response.status == GeneralLifeTributeStatus.Success) {
						Login.loginSuccess(response, Login.LoginSources.facebook);
						Login.close(true);
						Login.options.onLogin(response);
					} else {
						Login.logoutFacebook(true);
					}
				}
			});
		});


	},

	logoutFacebook: function(force) {
		if (typeof FB != "undefined" && FB.initialized) {
			FB.getLoginStatus(function(response) {
				if (response.status == "connected") {
					FB.logout();
				}
			});
		}
	},

	loginTwitter: function() {
		/*if (this.twitterRequest) {
		this.twitterRequest.abort();
		this.twitterRequest = false;
		}*/

		window.twitterPopup = window.open(LifeTributes.baseURL + "/Login/Twitter", "Twitter", "toolbar=0,status=0,width=800,height=520");
		if (!window.twitterPopup) {
			var message = Login.body.find("div.signup-options div.tab-options div.tab-twitter div.info-message p");
			message.html("A popup blocker may be preventing this website from opening the Twitter sign-in page. If you have a popup blocker, try disabling it to open the window.").addClass("error");
		}

		/*
		this.twitterRequest = $.ajax({
		url: LifeTributes.baseURL + "/Login/User",
		type: "POST",
		cache: false,
		data: {
		"source": Login.LoginSources.twitter
		},
		dataType: "json",
		success: function(response) {
		window.twitterPopup = window.open(response.url, "Twitter", "toolbar=0,status=0,width=800,height=520");
		if (!window.twitterPopup) {
		var message = Login.body.find("div.signup-options div.tab-options div.tab-twitter div.info-message p");
		message.html("A popup blocker may be preventing this website from opening the Twitter sign-in page. If you have a popup blocker, try disabling it to open the window.").addClass("error");
		}
		}
		});*/
	},

	logoutTwitter: function(force) {
	},

	loginSuccess: function(loginData, source) {
		var $this = this;
		if (LifeTributes.User.isAuth && (!source || source != Login.LoginSources.twitter)) return;
		LifeTributes.User.isAuth = true;
		LifeTributes.User.loginSource = source;
		$("#userNameLogged").val(loginData.user.username);
		$(".userbox img", "#UserLogged").attr("src", loginData.user.picturepath);
		$(".userbox span.username", "#UserLogged").text("Hello " + loginData.user.firstname);
		$("img.photo-profile-replace").attr("src", loginData.user.picturepath).removeClass("photo-profile-replace");
		LifeTributes.User.email = loginData.user.email;
		LifeTributes.User.firstName = loginData.user.firstname;

		if (loginData.user.source == "0") {
			$("#MyAccount").show();
		} else {
			$("#MyAccount").hide();
		}

		$("#UserLogin").fadeOut(300, function() {
			$("#UserLogged").fadeIn(300, function() {
				$("div#UserData").removeClass("user-logged");
			});
		});

		if (callbackLogin) {
			callbackLogin.call();
		}

		TributeWall.setEditFields();

		if (!!source && source == Login.LoginSources.twitter && typeof window.twitterPopup != "undefined") window.twitterPopup.close();
	},

	logout: function() {
		var loginSource = LifeTributes.User.loginSource;
		$.ajax({
			url: LifeTributes.rootFolder + 'Login/LogOutUser',
			dataType: "json",
			success: function(responseText) {
				switch (responseText.status) {
					case 1:
						$("#UserLogged").fadeOut(300, function() {
							$(".user-options", this).hide();
							$("#UserLogin").fadeIn(300);
							$("div.user").removeClass("user-logged");
							$(".userbox img", this).attr("src", "");
							$(".userbox span.username", this).text("");
						});

						$("#userNameLogged").val("");
						$("ul.recomment-list-item li.recomment-container img.photo-profile").attr("src", LifeTributes.rootFolder + "img/defaultProfilePhoto_Thumb.jpg");

						$("*[admin='true']").hide();

						LifeTributes.User.isAuth = false;

						if (MemorialTabs.isAdminTabActive) MemorialTabs.backToWall();

						if (!LifeTributes.isPublic) self.location = LifeTributes.tributeURL;

						if (callbackLogout) {
							callbackLogout.call();
						}

						if (loginSource == Login.LoginSources.facebook) Login.logoutFacebook(true);
						else if (loginSource == Login.LoginSources.twitter) Login.logoutTwitter(true);

						break;
				}
			}
		});
	}
}

/*
* Store Ads
*
* Description:
*	
*/
var storeAds = {

	show: function(options) {

		var $this = this;

		if (!eval($.cookie("storeAdsDontShow")) && LifeTributes.hasStore) {

			var modal = $("<a>").createModal({
				cssClass: 'modal-login modal-login-new modal-store-ads',
				urlRequest: '/store/api/?method=getstoreads',
				disableClose: true,
				loadCallback: function() {
					$("#storeAds #tributeFirstName").text(LifeTributes.tributeFirstName);
					$("div.store-ads-categories li a").click(function(e) {

						var storeCatItem = $(this);
						e.preventDefault();
						self.location = "#/";
						setTimeout(function() {
							self.location = storeCatItem.attr("href");
							$this.close();
						}, 100);

						GuestbookEntry.gift.tmpReferrerICN = "memorial_page_popup_afterpost";

					});

					$("div.store-ads-banner p a").click(function() {
						$this.close();
					});

					$("#dontShowStoreAds").click(function() {
						$.cookie("storeAdsDontShow", "true", { expires: 7 });
						$this.close();
					});

				},
				beforeShowCallback: function() {
					$(".video").css("visibility", "hidden");
				},
				afterHideCallback: function() {
					$(".video").css("visibility", "visible");
				}
			});

			setTimeout(function() {
				modal.click();
			}, 250);

		}
	},

	close: function(success) {
		$.closeDialog({
			afterHideCallback: function() {
				$(".video").css("visibility", "visible");
			}
		});
	}

}

/*
* Recorded Photo Complete 
*
* Description:
*	Callback (Flex App)
*/
var isProcessingSave = false;

function recordedPhotoComplete(returnObject) {
	if (!isProcessingSave) {
		isProcessingSave = true;
		if ($("#photoManagement").length == 0) {
			if (currentTab == "#TributeWall") {
				recordedWallPhotoComplete(returnObject);
			} else if (currentTab == "#PhotosVideos") {
				recordedAlbumPhotoComplete(returnObject);
			}
		}
		isProcessingSave = false;
	}
}

/*
* UTC Date Helper
*
* Description:
*	UTC Date Helper
*/
function getUTCDateFromJSON(json_date) {
	return getUTCDate(new Date(parseInt(json_date.match(/\d+/i)[0])));
}

function getUTCDate(date) {
	if (date) {
		date.setMinutes(date.getMinutes() - (60 * 5));

		return new Date(
			date.getUTCFullYear(),
			date.getUTCMonth(),
			date.getUTCDate(),
			date.getUTCHours(),
			date.getUTCMinutes(),
			date.getUTCSeconds(),
			date.getUTCMilliseconds());
	}

	return null;
}

/*
* Global Facebook
*
* Description:
*	Function Facebook Click
*/
function fbs_click() {
	u = location.href;
	t = document.title;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), ' sharer', 'toolbar=0, status=0, width=626, height=436');
}

/*
* Start Functions on Page Load
*/
$(document).ready(function() {
	Login.initialize();
	BorderRadius.initialize();
	MemorialTabs.initialize();
	DefaultTip.initialize();
	Preload.initialize();
	Share.initialize();
	FacebookRemover.initialize();
	Feedback.initialize();
});
