/*
	************************************************
	*  File: es-survey.js
	*  Last Updated: 01/29/09
	*  Author: Eric Wright <eric@rapidsynergy.com> , Updated by - Second Vue
	************************************************
	
	Details: 
		
	This JavaScript file generates an animated survey invitation utilizing the jQuery library. 
	A compressed version of the jQuery library is embedded within this file to allow the inclusion
	of a single script line within the Marriott home page. Optionally, a separate script line may be inserted
	with a reference to jquery.js or jquery.pack.js (for performance) both of which are included as part of this kit. 
	These external files must be used with survey-invitation.lean.js.
	
	This file works in tandem with survey-invitation.css which handles the presentation of the survey invite. Please
	see this file for additional details.
	
	The global variable _surveyConfig is a hash/associative array for storing configuration parameters for this script and 
	is used in order to avoid potential namespace collisions with other scripts. You can modify these values to 
	determine the behavior of the survey invitation script.
	
	Options include:

	@param delay 
		
		The number of milliseconds before the animation begins. It is recommended to leave this at at least
		1000 milliseconds to allow most browsers time to load the entire DOM and avoid performance/memory issues 
		while rendering the animation.
		
	@param startLeft 
		
		Number of pixels from the left of the browser viewport to mark the starting position of the survey invitation. 
		The survey will slide from here to the endLeft position during initial animation. 

	@param startTop
		
		Number of pixels from the top of the browser viewport to mark the starting position of the survey invitation. 
		The survey will slide from here to the endTop position during initial animation. 

	@param endLeft 
		
		Number of pixels from the left of the browser viewport to mark the ending position of the survey invitation. 
		The survey will slide to here from the startLeft position during initial animation. 

	@param endTop
		
		Number of pixels from the top of the browser viewport to mark the ending position of the survey invitation. 
		The survey will slide to here from startTop position during initial animation. 	
		
	@param animationRate 
	
		Time window (Amount in milliseconds) in which to perform the animation. Increase this value to slow down the animation. Reduce to speed up.
		
	@param probability
	
		Probability percentage that an eligible user will be offered an invitation to take the survey. 
		
		e.g. 0 is never, 100 is all the time, 50 is a flip of the coin, 16.666666 a roll of the die, etc.
		
	@param surveyTitle
	
		Title of survey
		
	@param introCopy
		
		Introductory copy to include with survey invite. IMPORTANT: Escape quotes for JavaScript!!
		
	@param expireDays 
	
		Number of days before cookie expires and user may be invited to take another invitation.
		
	@param requireAcknowledge
		
		If true, requires that the user respond to the invite in some way before setting the cookie to no longer show the survey. 
		If false, the cookie will be set regardless and the invite will only ever appear once within the expire period.
		
	@param surveyUrl
	
		Where to take the user if they opt for the survey.
	
*/	

// initialize the configuration hash 
var _surveyConfig =
{
	delay : 1000,
	
	startRight : 290,
	
	startTop : 40,
	
	endRight : screen.availWidth - 750,
	
	endTop : 150,
	
	animationRate : 2000,
	
	probability : 25,
	
	surveyTitle : 'Marriott Opinion Survey',
	
	introCopy : 'We want to hear from you.<br/> We would appreciate your feedback on your experience with our website so we can make future visits better. The interview takes most people a few minutes. Please click \'Yes\' to accept or \'No\' to decline.',
	
	expireDays : 0,
	
	requireAcknowledge : true,
	
	surveyUrl : 'https://www.mymarriottvoice.com/R.aspx?a=134'
	
}

/**********************************************************
 *																											 	*
 * 	DO NOT MODIFY ANYTHING PAST THIS POINT !							*
 *																												*
 *	...unless of course you know what you're doing :-) 		*
 *																												*
 **********************************************************/

															
//additional configuration parameters
_surveyConfig.id = 'p_main';																						
_surveyConfig.cookie = 'es-survey-cookie';

jQuery(document).ready(doInvite);

function doInvite()
{
	if (!alreadyInvited() && rollTheDice())
		setTimeout('renderInvite()', _surveyConfig.delay);		
}

// DHTML to render and animate survey invite as per survey configuration settings.
function renderInvite()
{	
	jQuery('body').append(buildInviteHtml());

	jQuery('#' + _surveyConfig.id + ' a').click(closeInvite);
	
	jQuery('#' + _surveyConfig.id + ' #p_body_ans_yes').click(function(){openCenteredWindow(_surveyConfig.surveyUrl)});
	
	if (_surveyConfig.requireAcknowledge)
		jQuery('#' + _surveyConfig.id + ' a').click(setSurveyCookie);
	else
		setSurveyCookie();
	
	var survey = jQuery('#' + _surveyConfig.id);
		
	survey.css('display', 'none')
				.css('right', _surveyConfig.startRight)
				.css('top', _surveyConfig.startTop)
				.animate( 
					{  
						right : _surveyConfig.endRight, 
						top : _surveyConfig.endTop,
						opacity: 'show' 
					}, 
					_surveyConfig.animationRate, 
					'linear'
				);
}

// Function to create HTML for survey invitation
function buildInviteHtml()
{
	var html = '<div id="' + _surveyConfig.id + '"><div id="p_main_inner" class="p_i_fix">';
	html += '<a href="#"><img id="p_close" src="/assets/new/images/popupclose.png"/></a>';
	html += '<img id="p_title" src="/assets/new/images/popuptitle.png"/>';
	html += '<div id="p_body"><div id="p_body_txt"><span>'+ _surveyConfig.introCopy +'</span></div>';
	html += '<div id="p_body_ans_con"><div id="p_body_ans_yes"><a href="#" class="button"><img src="/assets/new/images/popupyes.png" class="img_hol"/></a><span>I\'d like to take the survey</span></div>';
	html += '<div id="p_body_ans_no"><a href="#"><img src="/assets/new/images/popupno.png" class="img_hol"/></a><span>Please close the invitation</span></div>	';			
	html += '</div><div class="clear"/>';
	html += '</div>';
	html += '</div>';
	html += '</div>';
	return html;
}

// @return boolean if the probability test passes
function rollTheDice()
{
	return (Math.random() * 100) <= _surveyConfig.probability; 
}

// @return boolean if the user has already been invited once within the specified expire period
function alreadyInvited()
{
	return getCookie(_surveyConfig.cookie) == 1;
}

// Function to close the invitation 
function closeInvite()
{
	jQuery('#' + _surveyConfig.id).fadeOut(500);	
}

// Function to set the cookie to indicate that this user has already been invited
function setSurveyCookie()
{
	var expires = new Date();	
	expires.setTime(expires.getTime() + (_surveyConfig.expireDays * 24 * 60 * 60 * 1000)); // days * hrs * min * seconds * milliseconds
	setCookie(_surveyConfig.cookie, 1, expires, '/');
}

/* Cookie manipulation functions ala Bill Dortch '96 */

//
//  Function to return the value of the cookie specified by "name".
//    name - String object containing the cookie name.
//    returns - String object containing the cookie value, or null if
//      the cookie does not exist.
//
function getCookie(name) 
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}

// "Internal" function to return the decoded value of a cookie
//
function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1)
    endstr = document.cookie.length;
  return unescape(document.cookie.substring(offset, endstr));
}

//
//  Function to create or update a cookie.
//    name - String object containing the cookie name.
//    value - String object containing the cookie value.  May contain
//      any valid string characters.
//    [expires] - Date object containing the expiration data of the cookie.  If
//      omitted or null, expires the cookie at the end of the current session.
//    [path] - String object indicating the path for which the cookie is valid.
//      If omitted or null, uses the path of the calling document.
//    [domain] - String object indicating the domain for which the cookie is
//      valid.  If omitted or null, uses the domain of the calling document.
//    [secure] - Boolean (true/false) value indicating whether cookie transmission
//      requires a secure channel (HTTPS).  
//
//  The first two parameters are required.  The others, if supplied, must
//  be passed in the order listed above.  To omit an unused optional field,
//  use null as a place holder.  For example, to call SetCookie using name,
//  value and path, you would code:
//
//      SetCookie ("myCookieName", "myCookieValue", null, "/");
//
//  Note that trailing omitted parameters do not require a placeholder.
//
//  To set a secure cookie for path "/myPath", that expires after the
//  current session, you might code:
//
//      SetCookie (myCookieVar, cookieValueVar, null, "/myPath", null, true);
//
function setCookie(name, value, expires, path, domain, secure) 
{
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

//  Function to delete a cookie. (Sets expiration date to start of epoch)
//    name -   String object containing the cookie name
//    path -   String object containing the path of the cookie to delete.  This MUST
//             be the same as the path used to create the cookie, or null/omitted if
//             no path was specified when creating the cookie.
//    domain - String object containing the domain of the cookie to delete.  This MUST
//             be the same as the domain used to create the cookie, or null/omitted if
//             no domain was specified when creating the cookie.
//
function deleteCookie (name, path, domain) 
{
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function openCenteredWindow(url) {
    var width = 600;
    var height = 500;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var windowFeatures = "width=" + width + ",height=" + height + ",status,resizable,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
    window.open(url, "subWind", windowFeatures);
}