
//Initialize
$(document).ready(function()
{
	//Mouse animations
	xInstallStandardHandlers();

	//Adjust the height of the 'spacer' graphics based on main content height
	var interiorHeight = $('#xMainContent').height();
	var frameSpacerHeight = Math.max(1, interiorHeight  - $('#xFrameLeftUpper').height() - $('#xFrameLeftLower').height());
	$('#xFrameLeftSpacer').css('height', frameSpacerHeight + 'px');
	$('#xFrameRightSpacer').css('height', frameSpacerHeight + 'px');
	var backgroundHeight = $('#xMainBackground').height();
	$('#xBackgroundSpacer').css('height', Math.max(1, (interiorHeight - backgroundHeight + 1)) + 'px');

	/*
	//Animate the special-offer gauge
	if ($('#xSpecialOfferGauge').length)
	{
		xSpecialOfferGuageTimer = setInterval(xAnimateSpecialOfferGauge, 200);
	}
	*/
});

//General animations for mouse hover and click actions
function xInstallStandardHandlers()
{
	//Swap images when the mouse hovers/leaves the area
	$('img.xHoverImage').hover(
		function()
		{
			this.src = this.src.replace(/-on\.(.{3})$/i, '-hover.$1');
		},
		function()
		{
			this.src = this.src.replace(/-hover\.(.{3})$/i, '-on.$1');
		}
	);

	//Swap images when the mouse hovers/leaves the area (for "active" images)
	$('img.xHoverImageActive').hover(
		function()
		{
			this.src = this.src.replace(/-active\.(.{3})$/i, '-hover.$1');
		},
		function()
		{
			this.src = this.src.replace(/-hover\.(.{3})$/i, '-active.$1');
		}
	);

	//Shift an object by one pixel diagonally (down and to the right) when it's clicked, by adjusting its margins
	var jqSelector = '.xClickableButton';
	$(jqSelector).mousedown(function()
	{
		$(this).addClass('xButtonClicked');
	});
	$(jqSelector).mouseup(function()
	{
		$(this).removeClass('xButtonClicked');
	});
	$(jqSelector).mouseleave(function()
	{
		$(this).removeClass('xButtonClicked');
	});

	//Left/right arrows on the coupon strip
	var jqSelector = '#xCouponStripArrowLeft, #xCouponStripArrowRight';
	$(jqSelector).mousedown(function()
	{
		$(this).addClass('xCouponStripArrow_Clicked');
		$(this).removeClass('xCouponStripArrow_On');
	});
	$(jqSelector).mouseup(function()
	{
		$(this).addClass('xCouponStripArrow_On');
		$(this).removeClass('xCouponStripArrow_Clicked');
	});
	$(jqSelector).mouseleave(function()
	{
		this.src = this.src.replace(/-hover\.(.{3})$/i, '-on.$1');
		$(this).addClass('xCouponStripArrow_On');
		$(this).removeClass('xCouponStripArrow_Clicked');
	});

	//Purple buttons
	var jqSelector = 'div.xButtonPurple';
	$(jqSelector).hover(
		function()
		{
			$(this).addClass('xButtonPurple_Hover');
			$(this).removeClass('xButtonPurple_On');
		},
		function()
		{
			$(this).addClass('xButtonPurple_On');
			$(this).removeClass('xButtonPurple_Hover');
			$(this).removeClass('xButtonPurple_Clicked');
		}
	);
	$(jqSelector).mousedown(function()
	{
		$(this).addClass('xButtonPurple_Clicked');
		$(this).removeClass('xButtonPurple_Hover');
	});
	$(jqSelector).mouseup(function()
	{
		$(this).addClass('xButtonPurple_Hover');
		$(this).removeClass('xButtonPurple_Clicked');
	});
}

//Animation handler for the special-offer fuel gauge
var xSpecialOfferGuageTimer = null;
var xSpecialOfferGuageStates = [100, 95, 90, 85, 80, 75, 70, 65, 50, 45, 40, 35, 30, 25, 15, 10, 0];
var xSpecialOfferGuageStateIndex = 0;
function xAnimateSpecialOfferGauge()
{
	xSpecialOfferGuageStateIndex++;
	if (xSpecialOfferGuageStateIndex >= xSpecialOfferGuageStates.length) xSpecialOfferGuageStateIndex = 0;

	var src = $('#xSpecialOfferGauge').attr('src');
	src = src.replace(/gauge-\d{1,3}/i, 'gauge-' + xSpecialOfferGuageStates[xSpecialOfferGuageStateIndex]);
	$('#xSpecialOfferGauge').attr('src', src);
}

//Validate a text field to make sure it has some data
function xValidateTextField(elementID, fieldName)
{
	//If (the text field is basically empty)...
	var txt = $(elementID).get(0);
	if ($.trim(txt.value) == '')
	{
		alert('Please enter a value for "' + fieldName + '".');
		txt.focus();
		return false; //Validation failure
	}

	//Validation success
	return true;
}

//Validate an email field
function xValidateEmailField(elementID, fieldName)
{
	//
	var txt = $(elementID).get(0);
	var email = txt.value.match(/[\w-_\.]+@[\w-\.]*\.[a-zA-Z]{2,}/);
	if (email == null || email.index != 0)
	{
		alert('Please enter a valid email address for "' + fieldName + '".');
		txt.focus();
		return false; //Validation failure
	}

	//Validation success
	return true;
}

//Validate a 10-digit phone number field
function xValidatePhoneField(elementID, fieldName)
{
	//Extract all digits such that "(651) 555-1212" becomes "6515551212", effectively stripping off any markup or formatting.
	var txt = $(elementID).get(0);
	var phone = txt.value.replace(/[^0-9]/gi, ''); //Replace all non-digit characters with an empty string, including any whitespace

	//Ignore leading 1's for 11-digit numbers
	if (phone.length == 11 && phone.charAt(0) == '1')
	{
		return true; //These phone numbers are OK
	}

	//Validate the correct number of digits
	if (phone.length != 10)
	{
		alert('Please enter a 10-digit phone number for "' + fieldName + '".');
		txt.focus();
		return false; //Validation failure
	}

	//Validation success
	return true;
}

//A coupon detail link was clicked on, so popup its details page
function xShowCouponPopup(couponID)
{
	var popupW = 400;
	var popupH = 660;
	var locationLeft = (screen.width  - popupW) / 2;
	var locationTop  = (screen.height - popupH) / 2;
	var isIpod = (window.orientation != undefined);
	if (isIpod)
	{
		window.open('popup-send-coupon.php?couponID=' + couponID, 'niCouponDetails', '');
	}
	else
	{
		window.open('popup-send-coupon.php?couponID=' + couponID, 'niCouponDetails', 'width=' + popupW + ', height=' + popupH + ', left=' + locationLeft + ', top=' + locationTop + ', scrollbars=no');
	}
	return false;
}

//Return a timestamp (number of milliseconds since 1/1/1970)
function xNow()
{
	return (new Date).valueOf();
}

//Markup strings such that they don't break any HTML
function xEscapeHTML(html)
{
	return (new String(html)).replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');
}














//Standard AJAX handler
function xAjax(controls)
{
	//Add a timestamp to the POST request to prevent browser caching
	controls.xData.noCache = xNow();

	//Launch the AJAX request
	var xhr = $.ajax(
	{
		'url'      : controls.url,
		'type'     : 'POST',             //Send data as a POST request
		'dataType' : 'json',             //Evaluate the response as JSON and return a JavaScript object
		'data'     : controls.xData,
		'success'  : controls.onSuccess, //onSuccess(data, textStatus, XMLHttpRequest)
		'error'    : controls.onError,   //onError(XMLHttpRequest, textStatus, errorThrown)
		'cache'    : false               //NOTE: 'cache = false' doesn't work on jQuery 1.4.2 for POST requests (only supports GET requests)
	});

	//Return XMLHttpRequest to allow aborting the request, etc.
	return xhr;
}

//Disable an AJAX form and display the "wait" spinner, prior to running an AJAX query
function xDisableAjaxForm(formID, formWidth, formHeight)
{
	var paddingTop = Math.floor((formHeight - 32) / 2); //32px is the height of the AJAX "wait" spinner graphic
	$(formID + ' div.xInnerFormContainer').after('<div class="center xFormAjaxWaitSpinner" style="width: ' + formWidth + 'px; height: ' + formHeight + 'px; padding-top: ' + paddingTop + 'px;"><img src="/Resources/images/ajax-wait.gif"/></div>'); //Insert the AJAX spinner after the form's HTML, but still inside the outer container
	$(formID + ' div.xInnerFormContainer').hide(); //Hide the form's HTML (which is all inside the inner container), allowing the AJAX spinner to "bubble up" into the visible area
	$(formID).data('isProcessing', 'true'); //Set the "processing" flag
}

//Generic AJAX error handler to alert the user and re-enable the form (so the whole process can be tried again without reloading the page)
function xAjaxFormErrorHandler(formID, errorMessage)
{
	//Alert the user
	var message = '';
	if (errorMessage != '')
	{
		message = '\n\n' + errorMessage;
	}
	alert('Oops! We are sorry, but an error occured. Please try again later.' + message);

	//Enable the form again, with the data entry intact
	$(formID + ' div.xFormAjaxWaitSpinner').remove(); //Delete the AJAX spinner HTML that we added before the AJAX call
	$(formID + ' div.xInnerFormContainer').show(); //Show the form's HTML again
	$(formID).data('isProcessing', ''); //Clear the "processing" flag

	//Set focus to the first <input> field
	var field = $(formID + ' input').get(0);
	if (field) field.focus();
}

//Send the Xtra! mobile site's link to a cell phone
function xSendXtraLink(formID, formWidth, formHeight)
{
	//If (the form isn't already processing)...
	var isProcessing = $(formID).data('isProcessing') == 'true';
	if (!isProcessing)
	{
		//Validate the form
		var bValid = xValidatePhoneField('#xSendMeALinkPhoneNumber', 'Mobile Number');
		if (bValid)
		{
			//Get the field values
			var mobileNumber = $('#xSendMeALinkPhoneNumber').val();

			//Disable the form while we process the AJAX query
			xDisableAjaxForm(formID, formWidth, formHeight);

			//Create and run the query
			xAjax(
			{
				'url' : '/includes/ajax-server-xtra.php', //URL of the AJAX data server
				'xData' :
				{
					'ajaxCommand'  : 'niSendMobileSiteLinkBySMS',
					'mobileNumber' : mobileNumber
				},
				'onSuccess' : function (jsonObject, textStatus, xhr) //OnSuccess
				{
					if (jsonObject)
					{
						var response = jsonObject.response;
						if (response == '') response = '99 General Server Error';

						//Integrate the AJAX response into the page content
						if (response.indexOf('01 Success') > -1)
						{
							//Success
							$(formID).html('<div style="width: ' + formWidth + 'px; height: ' + formHeight + 'px; color: #A000A0;">Check your phone for a text message with a link to the Xtra! Mobile Coupons site!</div>');
						}
						else
						{
							//Error message
							xAjaxFormErrorHandler(formID, response);
						}
					}
					else
					{
						//Error message
						xAjaxFormErrorHandler(formID, '98 General Server Error');
					}
				},
				'onError' : function() //OnFailure
				{
					//Error message
					xAjaxFormErrorHandler(formID, '97 General Server Error');
				}
			});
		}
	}
}

//Send an "Account Request" form
function xSendAccountRequest(formID, formWidth, formHeight)
{
	xSendRequest('xSendAccountRequest', 'xAccountRequest', formID, formWidth, formHeight);
}

//Send a "Request Partnering Info" form
function xSendPartneringInfoRequest(formID, formWidth, formHeight)
{
	xSendRequest('xSendPartneringInfoRequest', 'xPartnerInfo', formID, formWidth, formHeight);
}

//Generic request to handle different form types with the same fields
function xSendRequest(ajaxCommand, fieldPrefix, formID, formWidth, formHeight)
{
	//If (the form isn't already processing)...
	var isProcessing = $(formID).data('isProcessing') == 'true';
	if (!isProcessing)
	{
		//Validate the form
		var bValid = true;
		if (bValid && !xValidateTextField('#' + fieldPrefix + 'FirstName', 'First Name')) bValid = false;
		if (bValid && !xValidateTextField('#' + fieldPrefix + 'LastName', 'Last Name')) bValid = false;
		if (bValid && !xValidateTextField('#' + fieldPrefix + 'Company', 'Company')) bValid = false;
		if (bValid && !xValidateEmailField('#' + fieldPrefix + 'Email', 'Email')) bValid = false;
		if (bValid && !xValidatePhoneField('#' + fieldPrefix + 'Phone', 'Phone Number')) bValid = false;
		if (bValid)
		{
			//Get the field values
			var firstName = $('#' + fieldPrefix + 'FirstName').val();
			var lastName = $('#' + fieldPrefix + 'LastName').val();
			var company = $('#' + fieldPrefix + 'Company').val();
			var email = $('#' + fieldPrefix + 'Email').val();
			var phone = $('#' + fieldPrefix + 'Phone').val();

			//Disable the form while we process the AJAX query
			xDisableAjaxForm(formID, formWidth, formHeight);

			//Create and run the query
			xAjax(
			{
				'url' : '/includes/ajax-server-xtra.php', //URL of the AJAX data server
				'xData' :
				{
					'ajaxCommand'  : ajaxCommand,
					'firstName'    : firstName,
					'lastName'     : lastName,
					'company'      : company,
					'email'        : email,
					'phone'        : phone
				},
				'onSuccess' : function (jsonObject, textStatus, xhr) //OnSuccess
				{
					if (jsonObject)
					{
						var response = jsonObject.response;
						if (response == '') response = '99 General Server Error';

						//Integrate the AJAX response into the page content
						if (response.indexOf('01 Success') > -1)
						{
							//Success
							$(formID).html('<div style="width: ' + formWidth + 'px; height: ' + formHeight + 'px; color: #00FF00;">Thank you for your inquiry. An Xtra! account representative will contact you shortly.</div>');
						}
						else
						{
							//Error message
							xAjaxFormErrorHandler(formID, response);
						}
					}
					else
					{
						//Error message
						xAjaxFormErrorHandler(formID, '98 General Server Error');
					}
				},
				'onError' : function() //OnFailure
				{
					//Error message
					xAjaxFormErrorHandler(formID, '97 General Server Error');
				}
			});
		}
	}
}

//Send a "Question/Issue" form
function xSendQuestion(formID, formWidth, formHeight)
{
	//If (the form isn't already processing)...
	var isProcessing = $(formID).data('isProcessing') == 'true';
	if (!isProcessing)
	{
		//Validate the form
		var bValid = true;
		if (bValid && !xValidateTextField('#xQuestionFirstName', 'First Name')) bValid = false;
		if (bValid && !xValidateTextField('#xQuestionLastName', 'Last Name')) bValid = false;
		if (bValid && !xValidateTextField('#xQuestionCompany', 'Company')) bValid = false;
		if (bValid && !xValidateEmailField('#xQuestionEmail', 'Email')) bValid = false;
		if (bValid && !xValidatePhoneField('#xQuestionPhone', 'Phone Number')) bValid = false;
		if (bValid && !xValidateTextField('#xQuestionText', 'Question/Issue')) bValid = false;
		if (bValid)
		{
			//Get the field values
			var firstName = $('#xQuestionFirstName').val();
			var lastName = $('#xQuestionLastName').val();
			var company = $('#xQuestionCompany').val();
			var email = $('#xQuestionEmail').val();
			var phone = $('#xQuestionPhone').val();
			var question = $('#xQuestionText').val();

			//Disable the form while we process the AJAX query
			xDisableAjaxForm(formID, formWidth, formHeight);

			//Create and run the query
			xAjax(
			{
				'url' : '/includes/ajax-server-xtra.php', //URL of the AJAX data server
				'xData' :
				{
					'ajaxCommand'  : 'xSendQuestion',
					'firstName'    : firstName,
					'lastName'     : lastName,
					'company'      : company,
					'email'        : email,
					'phone'        : phone,
					'question'     : question
				},
				'onSuccess' : function (jsonObject, textStatus, xhr) //OnSuccess
				{
					if (jsonObject)
					{
						var response = jsonObject.response;
						if (response == '') response = '99 General Server Error';

						//Integrate the AJAX response into the page content
						if (response.indexOf('01 Success') > -1)
						{
							//Success
							$(formID).html('<div style="width: ' + formWidth + 'px; height: ' + formHeight + 'px; color: #00FF00;">Thank you for your inquiry. An Xtra! account representative will contact you shortly.</div>');
						}
						else
						{
							//Error message
							xAjaxFormErrorHandler(formID, response);
						}
					}
					else
					{
						//Error message
						xAjaxFormErrorHandler(formID, '98 General Server Error');
					}
				},
				'onError' : function() //OnFailure
				{
					//Error message
					xAjaxFormErrorHandler(formID, '97 General Server Error');
				}
			});
		}
	}
}









//
function xGoogleAnalyticsTracking()
{
	var gaJsHost = (('https:' == document.location.protocol) ? 'https://ssl.' : 'http://www.');
	document.write(unescape('%3Cscript src="' + gaJsHost + 'google-analytics.com/ga.js" type="text/javascript"%3E%3C/script%3E'));
	try
	{
		var pageTracker = _gat._getTracker('"UA-7419534-3');
		pageTracker._trackPageview();
	} catch(e) {}
}

