// This file should include only single line DOM ready handler assignments.
//
// AX.load_once will be called once for every full page load.  Include handlers
// that affect the document, window, or template shell in load_once.  These
// handlers will not be assigned to elements loaded later via XHR.
//
// For handlers that will be assigned to every element of some selector pattern,
// include the handler in AX.onload.  These events will bind on page load
// and on the DOM portion inserted by XHR requests.
//
// Try to keep callbacks down to single lines, put logic elsewhere if possible.

// American Express namespace
// Global namespace
var AX = AX || {};

AX.session_timer = null;

$.fn.debug_links = function() {
  return this.each(function() {
	/*	$(this).hover(function() {
			$(this).css({cursor: 'not-allowed'});
		}, function() {
			$(this).css({cursor: 'auto'});
		});
	*/
		$(this).click(function() {
			alert("Sorry, this link is not implemented yet.");
			return false;
		});
	});
};

// Functions applied on page load and on the inserted DOM in any XHR request,
// don't forget to scope the Selectors.
AX.onload = function(scope) {
  scope = scope || $(document);
	
	//$('a[href=OPEN_TEST]', scope).debug_links();
};

AX.timeout_warning = function() {
	
	// session timeout warning
	if($('body').hasClass('AuthLoggedIn') && !$.cookie('SupressReminder')) {
		// total time before showing warning | 8.5 minutes == 510000 milliseconds
		var default_warning_interval = 510000;
		//var default_warning_interval = 510;
		// time between authentication check intervals | 5 minutes == 300000 milliseconds
		var time_check_interval = 300000;
		//var time_check_interval = 300;
		var timestamp = new Date();
		var current_time = timestamp.getTime();
		var cookie = $.cookie('AXTimeoutWarning');
		var cookie_timestamp;
		
		if( cookie === null || current_time - cookie > time_check_interval) {
			$.cookie('AXTimeoutWarning', current_time);
			cookie_timestamp = current_time;
		} else {
			cookie_timestamp = cookie;
		}
		
		time_to_warning = default_warning_interval - (current_time - cookie_timestamp);
		
		// removed from first sysmessage below: <a id="dismiss_reminder" href="#">don\'t remind me again</a>
		return setTimeout(function() {
			$('body').sysmessage('<p id="warning">Due to inactivity, you will be logged out in: <em id="timer">60</em> seconds.</p><p id="call_to_action"><a id="cancel_timeout" href="#">remain logged in</a> <a id="logout" \ href="https://sso.americanexpress.com/SSO/request?request_type=un_logoff&amp;SSOURL=http://www.openforum.com">log out now</a></p><p id="legal">At American Express we take your account security seriously. That\'s why we automatically log you out of our system if you\'ve been inactive for an extended period of time.</p>', {type: 'error timeout_warning', autoDismiss: false});
			var count = parseInt(document.getElementById('timer').innerHTML, 10);
			var timer;
			timer = setInterval(function() {
				if( count > 0 ) {
					count--;
					$('#warning #timer').html(count);
				} else {
					clearInterval(timer);
					$('#warning').html('Due to a period of inactivity, you have been logged out');
					$.cookie('NucleusAuth', '', { path: '/' });
					$.cookie('AXTimeoutWarning', '', { path: '/' });
					var $login = $("<a id=\"log_back_in\"  href=\""+AX.login_link+"\">Log Back In</a>").click(function() {
						window.location.href = $(this).attr('href');
						return false;
					});
					$('#call_to_action').html($login);
				}
			}, 1000);
			$('#cancel_timeout').click(function(e) {
				e.preventDefault();
				var $obj = $(this);
				AX.reset_warning();
				clearInterval(timer);
				var sessionFrame = $('<iframe src="/home/profile/youprovideseek"></iframe>');
				sessionFrame.css('display', 'none');
				$('body').append(sessionFrame);
				$obj.parent().parent().parent().find('.sysmessage-close').trigger('click');
				return false;
			});
			
			$('#dismiss_reminder').click(function(e) {
				e.preventDefault();
				$.cookie('SupressReminder', true);
				$('#cancel_timeout').trigger('click');
				return false;
			});

			$('.timeout_warning #logout').click(function(e) {
				e.preventDefault();
				var redirectURL = $(this).attr('href');
				$.cookie('NucleusAuth', '', { path: '/' });
				$.cookie('AXTimeoutWarning', '', { path: '/' });
				window.location.href = redirectURL;
			});

		}, time_to_warning);
	}
};

AX.reset_warning = function() {
	clearTimeout(AX.session_timer);
	AX.session_timer = AX.timeout_warning();
};

// block framing of the site
// if (top !== self) {
// 	top.location.replace(self.location.href);
// }

// Functions only applied on DOM ready, includes AX.onload.
AX.load_once = function () {

	AX.onload();
	$('#PageWrapper').ax();

	// Global fixer for all form text and textarea fields
	$('#ContentWell input:text, #ContentWell textarea')
	  .not('#questions_popup input[type=text], #questions_popup textarea')
	  .not('#ask_the_show_form input[type=text], #ask_the_show_form textarea')
	  .formKit();

	// Start default text plugin site-wide
	$('input:text, textarea').defaultText();

	// Set up system message listener on documents
	$.ax.sysmessageListner();

	// Initiate NavColumn function and accordian plugin
	$.ax.NavColumn();

	// Help links
	$.fn.helpLinks();

	// Open all links (external) to acceptpay.com with an interstitial message
	acceptpayInterstitial();

	// Open all links (external) to insuranceedge.com with an interstitial message
	//insuranceedgeInterstitial();	

	// Global session timeout warning
	AX.session_timer = AX.timeout_warning();

	// Global instantiation of personacard hovers 
	$('.ContactIcon').personaCard();

	$.ajaxSetup({
		global: true,
		timeout: 15000,
		type: 'GET',
		contentType: 'application/x-www-form-urlencoded',
		processData: true,
		error: function () {
			$('body').sysmessage('Your request could not be processed', { type: 'error' });
		}
	});

	$(window).ajaxComplete(function (e, request, settings) {
		try {
			if (request.status == 302) {
				window.location.reload(true);
			}
		} catch (caughtEvent) { }
	});

	var loaderTimeout;

	$(window).ajaxStart(function () {
		AX.reset_warning();
		loaderTimeout = setTimeout(function () {
			$('<div id="AjaxLoader">Loading...</div>').appendTo('#PageWrapper');
		}, 100);
	});

	$(window).ajaxStop(function () {
		clearTimeout(loaderTimeout);
		$('#AjaxLoader').remove();
	});

	$.ax.sysmessageInline('.sysmessageInline');

	$('#SectionNav li, #UtilityControl #Login').hover(function () {
		$(this).addClass('hover');
	}, function () {
		$(this).removeClass('hover');
	});

	$('#iNavLnkLog').click(function (e) {
		e.preventDefault();
		if ($(this).html().toLowerCase() == 'log out') {
			e.preventDefault();
			AX.logout($("#Global_Auth li.log_out a").attr("href"));
			//$.cookie('NucleusAuth', '', { expires: -1, path: '/' });
			//$.cookie('AXTimeoutWarning', '', { expires: -1, path: '/' });
			//$.cookie('SessionKey', '', { expires: -1, path: '/' });
		} else {
			destinationUrl = $("#Login").attr('href');
			window.location.href = destinationUrl;
		}

	});

	$('#Global_Auth').delegate('a', 'click', function (e) {
		if ($(this).parent().hasClass('log_out')) {
			e.preventDefault();
			if ($(this).html().toLowerCase() == 'log out') {
				e.preventDefault();
				AX.logout($("#Global_Auth li.log_out a").attr("href"));
				//$.cookie('NucleusAuth', '', { path: '/' });
				//$.cookie('AXTimeoutWarning', '', { path: '/' });
				//window.location.href = $(this).attr('href');
			}
		}
	});

	$('#footer_logout').click(function (e) {
		e.preventDefault();
		AX.logout($("#Global_Auth li.log_out a").attr("href"));
	});

	/* BEGIN: iFrame shim */

	(function ($) {
		// setup shim if IE6
		if ($.browser.msie && $.browser.version < 7) {
			$('#UtilityControl #Login').append('<iframe>');
		}
	})(jQuery);

	/* END: iFrame shim */

};

$(function() { AX.load_once(); });
/* LOAD OPTIMIZATION */
AX.preloadImage = new Image();
AX.preloadImage.src = '/images/nav/bkg.left-nav-sprite.gif';

AX.stringSanitize = function(inputString){
	return inputString.toString().replace(/\<|\>/g,"");
};

// This calls the 3.0 application's method to unset a bunch of cookies to log the user out of a session.
AX.logout = function (destinationURL) {
	$.post('/Authentication/OpenForumLogOut', function (data) {
	  window.location.href = destinationURL;
	});
};

