
var MiscEffects = {
	
	ToggleSlider: function(slider) {
		slider = $(slider);
		var sliderContent = $(slider).select('div.content').first();
	    if (!sliderContent.visible()) {
	        new Effect.Parallel([new Effect.BlindDown(sliderContent, {sync:true}), new Effect.Appear(sliderContent, {sync:true})], {duration:0.3});
	    	slider.select('h3').first().toggleClassName('active');
		} else {
	        new Effect.Parallel([new Effect.BlindUp(sliderContent, {sync:true}), new Effect.Fade(sliderContent, {sync:true})], {duration:0.3});
			slider.select('h3').first().toggleClassName('active');
	    }
	},
	
	ToggleTab: function(tab_section_id, active_tab_id, active_tab_content_id) {
		active_tab_id = $(active_tab_id);
		active_tab_content_id = $(active_tab_content_id);
		if(!active_tab_id.hasClassName('active'))
		{
			$(tab_section_id).select("div.tabs li a.active").first().removeClassName('active');
			$(tab_section_id).select("div.tab_bottom div.active").first().removeClassName('active');
			active_tab_id.addClassName('active');
			active_tab_content_id.addClassName('active');
		}
	}
	
 }

var Products = {
	
	SelectPic: function(link, imageId) {
		link = $(link);
		if(!link.hasClassName('active'))
		{
			$("picture_frame").select("img.active").first().removeClassName('active');
			$("pic_list").select("li a.active").first().removeClassName('active');
			
			link.addClassName('active');
			$(imageId).addClassName('active');
		}
	}
}

// login widget
function toggleLoginWidget() {
	Effect.toggle('loginWidgetLink','blind', {duration: .1});
	Effect.toggle('loginWidget','blind', {duration: .2});
}

//cookie handling for contest
function contest_set_rating(cookie_name, story_id) {
	   jar = new CookieJar({
		   expires:31536000, // seconds (year)
		   path: '/'
	   });
	   incomingVal = jar.get(cookie_name);
	   fullCookieValue = story_id;
	   
	   alreadyWritten = false;
	   if (incomingVal != null) { 
		   fullCookieValue = incomingVal + "|" + story_id;
		   alreadyWritten = incomingVal.include(story_id);
	   }

	   //only write cookie once
	   if (!alreadyWritten) {
		   jar.put(cookie_name, fullCookieValue);
	   }
	  
}

function contest_get_rating(cookie_name, story_id) {
	jar = new CookieJar({
		   expires:31536000, // seconds (year)
		   path: '/'
	});
	incomingVal = jar.get(cookie_name);
	//check to make sure initial cookie set
	if(incomingVal != null) { 
		if (incomingVal.include(story_id)) {
		   // user already voted on story
			$("Review_Submit").actn.value = "";
			$("Review_Submit").action = $("Review_Submit").action += "?dsp=250510";
		}
	}
	
}

function lockRelativeURLs(content, externalHost) {
	var lockedContent = content.replace(/"\/([^\/][^"]*)"/g, "\"//" + externalHost + "/$1\"");
	return lockedContent;
}

function loadExternalFrame(externalDocument, frameId, externalHost) {
	$(frameId).innerHTML = lockRelativeURLs(externalDocument.getElementById(frameId).innerHTML, externalHost);
	externalDocument.getElementById(frameId).innerHTML = '';
}

/* Referrer/Affiliate Tracking System */

Object.extend(String.prototype, {
	unescapeNumericHTMLCodes: function() {
		return this.replace(/&#(\d+);/g, function(s, code) {
			return String.fromCharCode(parseInt(code));
		});
	}
});

// Warning: This is not a robust IP address validator.  It simply checks to see if address is in a plausible IP address format (and not a domain name).
function isIPAddressFormat(address) {
	var ipAddressFormat = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
	if (address) {
		return address.match(ipAddressFormat);
	}
	return false;
}

function isThirdLevelDomain(domain) {
	if (domain) {
		var domainTokens = domain.split('.');
		if (domainTokens.length > 2 && !isIPAddressFormat(domain)) {
			return true;
		}
	}
	return false;
}

function extractBaseDomain(fullDomain) {
	if (fullDomain && isThirdLevelDomain(fullDomain)) {
		var domainTokens = fullDomain.split('.');
		domainTokens.shift();
		return domainTokens.join('.');
	}
	return fullDomain;
}

var ComPaceEComRATS = Class.create();

ComPaceEComRATS.prototype = {
	cookieName: "comPaceEComReferrer",
	cookieDomain: '',
	cookieDuration: 5184000, // = 60 * 60 * 24 * 60; (60 days)
	noReferrerValue: "direct",
	emailQueryKey: "emr_mid",
	emailReferrerValue: "email",
	bridaluxeHost: "tracking.bridaluxe.com",
	buyatRefID: "buyat",
	pmdigitalRefID: "pmdigital",
	avantlinkRefID: "avant",
	googleaffiliatenetworkRefID: "gan",
	commissionjunctionRefID: "cjunction",
	linkshareRefID: "linkshare",

	initialize: function() {
		// init cookieDomain
		var myHost = window.location.host;
		if (isThirdLevelDomain(myHost)) {
			this.cookieDomain = '.' + extractBaseDomain(myHost);
		}
	},

	getReferrer: function() {
		jar = new CookieJar({expires: this.cookieDuration, domain: this.cookieDomain, path: '/'});

		return jar.get(this.cookieName) || this.noReferrerValue;
	},

	saveReferrer: function(refid, emailQueryKey, httpReferer) {
		jar = new CookieJar({expires: this.cookieDuration, domain: this.cookieDomain, path: '/'});

		if (refid) {
			// refid exists -> always use it
			jar.remove(this.cookieName);
			jar.put(this.cookieName, refid);
		} else if (emailQueryKey) {
			// emr_mid exists -> use this instead
			jar.remove(this.cookieName);
			jar.put(this.cookieName, this.emailReferrerValue);
		} else if (httpReferer) {
			// httpReferer exists -> process it
			var httpRefererHost = parseUri(httpReferer).host;

			if (httpRefererHost) {
				// httpRefererHost exists -> process it
				var selfDomain = extractBaseDomain(window.location.host);

				if (selfDomain) {
					 // successfully obtained our own website's domain -> compare it with httpRefererHost
					if (!httpRefererHost.include(selfDomain)) {
						// httpRefererHost does not contain our own website's domain -> save or overwrite the referrer cookie with it
						jar.remove(this.cookieName);
						jar.put(this.cookieName, httpRefererHost);
					} else {
						// httpRefererHost contains our own website's domain -> keep current cookie if exist or set as direct load
						if (!jar.get(this.cookieName)) {
							jar.put(this.cookieName, this.noReferrerValue);
						}
					}
				} else {
					// could not obtain our own website's domain -> something is wrong with the window, so don't do anything with the referrer cookie
				}
			} else {
				// no host could be extracted from httpReferer -> keep current cookie if exist or set as direct load
				if (!jar.get(this.cookieName)) {
					jar.put(this.cookieName, this.noReferrerValue);
				}
			}
		} else {
			// no refid, emr_mid, or httpReferer -> keep current cookie if exist or set as direct load
			if (!jar.get(this.cookieName)) {
				jar.put(this.cookieName, this.noReferrerValue);
			}
		}
	},

	isReferredBy: function(referrer) {
		return this.getReferrer().include(referrer);
	}
};

var myRATS = new ComPaceEComRATS();

/* External iframe integration with Thanx Media */

function setDomain() {
	if (window.location.host.include("search.exclusivelyweddings.com")) {
		document.domain = "exclusivelyweddings.com";
	}
	if (window.location.host.include("search.eweddings.com")) {
		document.domain = "eweddings.com";
	}
}

setDomain();


/* SessionCookieMgr handles external parameters passed in from vendors */
var SessionCookieMgr = Class.create();
SessionCookieMgr.prototype = {
		cookieNames: [ "nlid", "eid", "emr_mid" ],
		
		initialize: function() {
		},
		
		saveAllParams: function(myQueryKeys) {
			this.cookieNames.each(function(cname, index) {
				if(myQueryKeys[cname]) {
					this.setParam(cname, unescape(myQueryKeys[cname]));
				}
			}, this);
		},
		
		getParam: function(req) {
			if (this.cookieNames.include(req)) {
				jar = new CookieJar({ path: '/'});
				return jar.get(req);
			}
		},
		
		setParam: function(name, value) {
			jar = new CookieJar({ path: '/'});
			jar.put(name, value);
		}
};
var mySessionCookieMgr = new SessionCookieMgr();
mySessionCookieMgr.saveAllParams(parseUri(document.URL.replace('@','%40')).queryKey);
/* End SessionCookieMgr */ 

/* Mini-Cart */
function isChildOf(target, ancestor) {
	while (target) {
		if (target == ancestor) {
			return true;
		}
		target = target.parentNode;
	}
	return false;
}

function onclickHideMiniCart(e) {
	var target = (e && e.target) || (event && event.srcElement);
	var showMiniCartLink = $$('.shoppingcart')[0];
	var overlay = $('cartOverlay');
	if (!isChildOf(target, showMiniCartLink) && !isChildOf(target, overlay))
		hideMiniCart();
}

function hideMiniCart() {
	if ($('cart'))
		$('cart').blindUp({ duration: .2 });
}

function showMiniCart() {
	Effect.toggle('cart','blind', {duration: .2});
}

document.onclick = onclickHideMiniCart;

/* Held Cart Overlay */
function closeCartOverlay()	{
	$('cartOverlay').fade({ duration: .2 });
	if(typeof document.loggedinhost != 'undefined') {
		document.location.href = "http://" + document.loggedinhost + "/cart.html";
	}
}

function size_iframe(height) {
	$('pc_login_frame').height = height + 10;
}

/* Eventum Issue #194 - Streamline Checkout Process */

function maintainAJAXCheckoutContactState() {
	if (typeof billSameAsContact == "undefined") {
		billSameAsContact = $('billsameascontact').checked;
	} else {
		$('billsameascontact').checked = billSameAsContact;
	}
	if (typeof shipSameAsContact == "undefined") {
		shipSameAsContact = $('shipsameascontact').checked;
	} else {
		$('shipsameascontact').checked = shipSameAsContact;
	}
}

function maintainAJAXCheckoutSteps() {
	updateStepNumbers();
	if (!billSameAsContact) {
		$('Step_Billing').show();
	}
	if (!shipSameAsContact) {
		$('Step_Shipping').show();
	}
	$('Step_ShipPay').show();
}

function updateStepNumbers() {
	var nextNumber = 3;
	if (typeof billSameAsContact != "undefined" && !billSameAsContact) {
		$$('#Step_Billing .circle')[0].innerHTML = nextNumber;
		nextNumber++;
	}
	if (typeof shipSameAsContact != "undefined" && !shipSameAsContact) {
		$$('#Step_Shipping .circle')[0].innerHTML = nextNumber;
		nextNumber++;
	}
	$$('#Step_ShipPay .circle')[0].innerHTML = nextNumber;
}

function setBillSameAsContact(checked) {
	if (billSameAsContact != checked) {
		billSameAsContact = checked;
		updateStepNumbers();
		if (!billSameAsContact)
			$('Step_Billing').blindDown({duration: 0.2});
		else
			$('Step_Billing').blindUp({duration: 0.2});
	}
}

function setShipSameAsContact(checked) {
	if (shipSameAsContact != checked) {
		shipSameAsContact = checked;
		updateStepNumbers();
		if (!shipSameAsContact)
			$('Step_Shipping').blindDown({duration: 0.2});
		else
			$('Step_Shipping').blindUp({duration: 0.2});
	}
}

/* Eventum Issue #2539 - Product review upgrade phase 2 */

function showAllReviews(link, reviewClass) {
	$$(reviewClass).each(Element.show);
	$(link).hide();
}

/* Eventum Issue #2728 - update catalog request page */

function handleOtherField(selectedValue, otherElement, displayValue) {
	if (selectedValue == displayValue) {
		otherElement.show();
		otherElement.focus();
	} else {
		otherElement.hide();
	}
}

function processOtherField(selectElement, otherElement, otherValue, defaultValue) {
	var returnValue = "";
	returnValue = selectElement.options[selectElement.selectedIndex].value;
	if (returnValue == otherValue)
		returnValue = otherElement.value;
	if (returnValue == defaultValue)
		returnValue = "";
	return returnValue;
}

/* Eventum Issue #3064 - Hard good personalization charges not reflected in running total */

function updateRunningTotal(form, selecteditemcompid, itemcompid, itemcompkittype) {
	var ajaxURL = "/servlet/AJAXActionServlet";
	var ajaxParameters = new Hash();
	ajaxParameters.set('optionskufallback', form.optionskufallback.value);
	ajaxParameters.set('ITMSUF', form.ITMSUF.value);
	ajaxParameters.set('PCR', form.PCR.value);
	ajaxParameters.set('ITMTYP', form.ITMTYP.value);
	ajaxParameters.set('IID', form.IID.value);
	ajaxParameters.set('ITMUOM', form.ITMUOM.value);
	ajaxParameters.set('embellishmentsackitemkey', form.embellishmentsackitemkey.value);
	ajaxParameters.set('sackname', form.sackname.value);
	ajaxParameters.set('selecteditemcompid', selecteditemcompid);
	ajaxParameters.set('itemcompid', itemcompid);
	ajaxParameters.set('itemcompkittype', itemcompkittype);
	ajaxParameters.set('actn', 141007);
	var ajaxRequest = new Ajax.Request( ajaxURL, {
		method: 'post',
		parameters: ajaxParameters.toObject(),
		onComplete: function (response) {
			var ajaxRunningTotalParameters = new Hash();
			ajaxRunningTotalParameters.set('dnXMLNodeName', 'embellish_running_total');
			ajaxRunningTotalParameters.set('dsp', 30709);
			ajaxRunningTotalParameters.set('PCR', ajaxParameters.get('PCR'));
			ajaxRunningTotalParameters.set('IID', ajaxParameters.get('IID'));
			ajaxRunningTotalParameters.set('ITMSUF', ajaxParameters.get('ITMSUF'));
			ajaxRunningTotalParameters.set('itemkey', ajaxParameters.get('embellishmentsackitemkey'));
			ajaxRunningTotalParameters.set('newshipto', ajaxParameters.get('sackname'));
			var ajaxRequest = new Ajax.Request( ajaxURL, { method: 'post', parameters: ajaxRunningTotalParameters.toObject(), onComplete: ajaxShopResponse, encoding:'UTF-8' });
		},
		encoding:'UTF-8'
	});
}

/* Eventum Issue #3030 - GWO HP TEST: Email sign up placement/messaging */

function validateFooterEmailField(field) {
	field = $(field);
	var email = field.value;
	if (email == "") {
		field.value = "Enter Email Address";
	}
	if (!email.match(/^[\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Z]{2,4}$/i)) {
		field.addClassName("invalid");
		return false;
	} else {
		field.removeClassName("invalid");
		return true;
	}
}

function validateFooterWeddingDateField(field) {
	field = $(field);
	if (!field.value.match(/\d\d\/\d\d\/\d\d\d\d/)) {
		field.addClassName("invalid");
		return false;
	} else {
		field.removeClassName("invalid");
		return true;
	}
}

function submitFooterEmailForm(form) {
	form = $(form);
	var valid = validateFooterEmailField(form.email);
	if (!validateFooterWeddingDateField(form.weddingdate)) {
		valid = false;
	}
	if (valid) {
		recordSubmittedEmail();
		if (form.fname.value == "First Name") {
			form.fname.value = "";
		}
		var ajaxURL = "/servlet/AJAXActionServlet";
		var ajaxParameters = getFormData(form.name, '', '', 'false', 'true');
		var ajaxRequest = new Ajax.Request( ajaxURL, {
			method: 'post',
			parameters: ajaxParameters,
			onComplete: function (response) {
				var effect = new Effect.Move(form, { x: form.getWidth(), mode: 'relative', duration: 0.2 });
				form.fade({ duration: 0.2 });
				$('sprite_footerEmailSuccess').appear({duration: 0.2});
				cmCreateRegistrationTag(form.email.value, form.email.value);
				_gaq.push(['_trackEvent', "E-mail-Addresses", "Sign-Up", "Footer-Bar", 1]);
			},
			encoding:'UTF-8'
		});
	}
	return false;
}

function validateEmailSignupOverlayEmailField(field) {
	field = $(field);
	var email = field.value;
	if (email == "") {
		field.value = "ENTER EMAIL ADDRESS";
	}
	if (!email.match(/^[\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Z]{2,4}$/i)) {
		field.addClassName("invalid");
		return false;
	} else {
		field.removeClassName("invalid");
		return true;
	}
}

function validateEmailSignupOverlayWeddingDateField(field) {
	field = $(field);
	if (!field.value.match(/\d\d\/\d\d\/\d\d\d\d/)) {
		field.addClassName("invalid");
		return false;
	} else {
		field.removeClassName("invalid");
		return true;
	}
}

function submitCartEmailSignupOverlayForm(form, successMessage) {
	form = $(form);
	var valid = validateEmailSignupOverlayEmailField(form.email);
	if (!validateEmailSignupOverlayWeddingDateField(form.weddingdate)) {
		valid = false;
	}
	if (valid) {
		recordSubmittedEmail();
		if (form.fname.value == "FIRST NAME") {
			form.fname.value = "";
		}
		var ajaxURL = "/servlet/AJAXActionServlet";
		var ajaxParameters = getFormData(form.name, '', '', 'false', 'true');
		var ajaxRequest = new Ajax.Request( ajaxURL, {
			method: 'post',
			parameters: ajaxParameters,
			onComplete: function (response) {
				form.fade({ duration: 0.2 });
				successMessage.appear({duration: 0.2});
				cmCreateRegistrationTag(form.email.value, form.email.value);
				_gaq.push(['_trackEvent', "E-mail-Addresses", "Sign-Up", "Cart-Popup", 1]);
				setTimeout(function() {$('emailSignupOverlay').fade({ duration: 0.2 })}, 3000);
			},
			encoding:'UTF-8'
		});
	}
	return false;
}

/* Eventum Issue #3240 - GWO Test: Email pop up at product detail page */

function submitProductEmailSignupOverlayForm(form, successMessage) {
	form = $(form);
	var valid = validateEmailSignupOverlayEmailField(form.email);
	if (!validateEmailSignupOverlayWeddingDateField(form.weddingdate)) {
		valid = false;
	}
	if (valid) {
		recordSubmittedEmail();
		if (form.fname.value == "FIRST NAME") {
			form.fname.value = "";
		}
		var ajaxURL = "/servlet/AJAXActionServlet";
		var ajaxParameters = getFormData(form.name, '', '', 'false', 'true');
		var ajaxRequest = new Ajax.Request( ajaxURL, {
			method: 'post',
			parameters: ajaxParameters,
			onComplete: function (response) {
				form.fade({ duration: 0.2 });
				successMessage.appear({duration: 0.2});
				cmCreateRegistrationTag(form.email.value, form.email.value);
				_gaq.push(['_trackEvent', "E-mail-Addresses", "Sign-Up", "Product-Page-Popup", 1]);
				setTimeout(function() {$('emailSignupOverlay').fade({ duration: 0.2 })}, 3000);
			},
			encoding:'UTF-8'
		});
	}
	return false;
}

function recordSubmittedEmail() {
	var cookieDomain = '';
	var cookieName = "comPaceEComEmailSubmitted";
	var cookieDuration = 63072000; // = 60 * 60 * 24 * 365 * 2; (2 years)
	var myHost = window.location.host;
	if (isThirdLevelDomain(myHost)) {
		cookieDomain = '.' + extractBaseDomain(myHost);
	}
	var jar = new CookieJar({expires: cookieDuration, domain: cookieDomain, path: '/'});
	if (!jar.get(cookieName)) {
		jar.put(cookieName, 1);
	}
}
function hasSignedUpForEmail() {
	var cookieDomain = '';
	var cookieName = "comPaceEComEmailSubmitted";
	var cookieDuration = 63072000; // = 60 * 60 * 24 * 365 * 2; (2 years)
	var myHost = window.location.host;
	if (isThirdLevelDomain(myHost)) {
		cookieDomain = '.' + extractBaseDomain(myHost);
	}
	var jar = new CookieJar({expires: cookieDuration, domain: cookieDomain, path: '/'});
	return jar.get(cookieName);
}

/* Eventum Issue #3013 - Manage Preference Center (for emails) */

function submitUnsubscribeEmailForm(form, emailAddress) {
	form = $(form);
	var u = document.createElement('input');
	u.type = "hidden";
	u.name = "unsub";
	u.value = "1";
	form.appendChild(u);
	form.email.value = emailAddress;
	form.submit();
	return false;
}

function validateEmailPreferencesForm(form, errorTable) {
	errorTable.innerHTML = '';
	var valid = true;
	var errors = [];

	var email = form.email.value;
	if (!email.match(/^[\w\-]([\.\w])+[\w]+@([\w\-]+\.)+[A-Z]{2,4}$/i)) {
		errors.push({name: "E-Mail:", message: "Required field"});
		valid = false;
	}
	var weddingDate = form.weddingdate.value;
	if (!weddingDate.match(/\d\d\/\d\d\/\d\d\d\d/)) {
		errors.push({name: "Wedding Date:", message: "Required field"});
		valid = false;
	}

	while (errors.length > 0) {
		var error = errors.pop();
		var er = document.createElement('tr');
		er.innerHTML = '<td class="errorMessageLabel">' + error.name + '</td><td>' + error.message + '</td>';
		errorTable.appendChild(er);
	}

	return valid;
}

/* Eventum Issue #3173 - Change VeriSign logo to DigiCert seal in the footer */

function VerifySSL(num,old) {
	var width=490;
	var height=550;
	var ww=screen.width;
	var hh=screen.height;
	var left=(ww - width) / 2;
	var top=(hh - height) / 2;
	window.open('https://www.digicert.com/custsupport/sspopup.php?order_id=' + num + '&hostname=http%3A%2F%2Fwww.exclusivelyweddings.com','oo',"dependent=1,height="+height+",width="+width+",left="+left+",top="+top+",location=0,menubar=0,resizable=1,scrollbars=yes,status=0,toolbar=0");
	return false;
}

/* Eventum Issue #1683 - Solicit Reviews Functionality */

function validateRequiredField(field) {
	if (!field.disabled && field.value.strip() == '') {
		field.addClassName('invalid');
		return false;
	} else {
		field.removeClassName('invalid');
		return true;
	}
}
function validateRequiredRadios(radios, label) {
	if (radios.pluck('disabled').include(false) && !radios.pluck('checked').include(true)) {
		label.addClassName('invalidLabel');
		return false;
	} else {
		label.removeClassName('invalidLabel');
		return true;
	}
}

function prepareOrderReviewLoginForm(form, errors) {
	form.observe('submit', function(event) {
		var valid = true;
		valid = validateRequiredField($(form['order'])) && valid;
		valid = validateRequiredField($(form['zip'])) && valid;
		if (!valid) {
			event.stop();
		}
	});
}

function prepareOrderReviewForm(form, errors) {
	form.select('.js-reviewSkipCheckbox').each(function(element) {
		element.observe('change', function(event) {
			if (this.checked) {
				this.up('.orderReviewItem').select('input').invoke('disable');
				this.up('.orderReviewItem').select('textarea').invoke('disable');
				this.enable();
			} else {
				this.up('.orderReviewItem').select('input').invoke('enable');
				this.up('.orderReviewItem').select('textarea').invoke('enable');
			}
		});
		element.up('label').observe('mouseup', function(event) {
			setTimeout(function() {element.blur();}, 0);
		});
	});

	function validateOrderReviewItem(orderReviewItem) {
		var valid = true;
		valid = validateRequiredField(orderReviewItem.down('.orderReviewTitleField')) && valid;
		valid = validateRequiredField(orderReviewItem.down('.orderReviewTextField')) && valid;
		valid = validateRequiredRadios(orderReviewItem.select('.orderReviewItemRecommendFieldValue input'), orderReviewItem.down('.orderReviewItemRecommendFieldLabel')) && valid;
		valid = validateRequiredRadios(orderReviewItem.select('.orderReviewItemRatingFieldValue input'), orderReviewItem.down('.orderReviewItemRatingFieldLabel')) && valid;
		return valid;
	}

	form.observe('submit', function(event) {
		if (this.select('.orderReviewItem').reject(validateOrderReviewItem).size() > 0) {
			errors.innerHTML = "";
			var error = document.createElement('span');
			error.innerHTML = 'Sorry, we were unable to save your reviews.  Please check the fields below for errors.';
			error.addClassName('message_error');
			errors.appendChild(error);
			window.location.hash = "";
			window.location.hash = errors.id;
			event.stop();
		}
	});
}

/* Eventum Issue #3278 - Extend Session Timeout via Trigger */

var PersonalizationSessionTimer = Class.create();
PersonalizationSessionTimer.prototype = {
	autoExtendTimer: null,
	timeoutWarningTimer: null,
	sessionTimeout: 2700000, // = 1000 * 60 * 45; (45 minutes)

	initialize: function() {
		this.scheduleAutoExtend();
	},

	scheduleAutoExtend: function() {
		clearTimeout(this.autoExtendTimer);
		clearTimeout(this.timeoutWarningTimer);
		this.autoExtendTimer = setTimeout(this.autoExtendSession.bind(this), this.sessionTimeout - 60000); // (1 minute margin of error)
	},

	autoExtendSession: function() {
		var ajaxURL = "/Weddings";
		var ajaxRequest = new Ajax.Request( ajaxURL, {
			method: 'get',
			parameters: 'rand=' + Math.round(Math.random() * 2147483647),
			onComplete: this.scheduleTimeoutWarning(),
			encoding:'UTF-8'
		});
	},

	scheduleTimeoutWarning: function() {
		clearTimeout(this.autoExtendTimer);
		clearTimeout(this.timeoutWarningTimer);
		this.timeoutWarningTimer = setTimeout(this.showTimeoutWarning.bind(this), this.sessionTimeout - 180000); // (3 minute warning)
	},

	showTimeoutWarning: function() {
		var alertTime = new Date();
		alert("We haven't heard from you in a while.  Your personalization information may be expiring soon.  Please click OK to let us know you're still here.");
		var returnTime = new Date();
		if (returnTime - alertTime < 175000) { // = 1000 * 60 * 3 - 1000 * 5; (3 minute window of opportunity - 5 second margin of error for round-trip times)
			var ajaxURL = "/Weddings";
			var ajaxRequest = new Ajax.Request( ajaxURL, {
				method: 'get',
				parameters: 'rand=' + Math.round(Math.random() * 2147483647),
				onComplete: this.scheduleAutoExtend(),
				encoding:'UTF-8'
			});
		} else {
			alert("Sorry, it looks like it's too late.  Please save what you can (take a screenshot or copy/paste into another application) and refresh the page to continue shopping.");
		}
	}
};

