/// <reference path="jquery-vsdoc.js"/>
litium.cc.poker = {

	tournaments: (function () {
		var self = {};
		var settings = {
			'addThis': {
				'text': '',
				'username': ''
			},
			'gridProductIDColumnKey': 'ProductID',
			'gridUrlNameColumnKey': 'UrlName',
			'language': 'sv',
			'overlaySelector': '',
			'productId': '',
			'updatePanelId': '',
			'updateProgressId': ''
		};

		self.updatePanelId = '';

		self.tournament = (function () {
			var self = {};
			var currentStep = '',
				title = '',
				url = '',
				maxAllowedBirthDate = null;

			self.refresh = function (options) {
				addthis_config = { //global!
					'addthis_default_style': false,
					'data_use_flash': false,
					'ui_click': true,
					'ui_language': settings.language,
					'ui_use_css': false,
					'username': settings.addThis.username
				};

				var $productOverlay = $(settings.overlaySelector);

				// This function is executed when the content inside the product tournament update panel
				// is reloaded. It sets event listeners for close buttons and other elements.
				var initAddThis = function (url, title) {
					if (typeof addthis !== 'undefined') {
						addthis.button('#share', addthis_config, {
							'url': url,
							'title': title
						});
					}
				};

				var initTools = function () {
					// Register hover event handlers for buttons that should switch, their images.
					$productOverlay.find('img.close,#share img,#email img,#print img').each(function () {
						var url = $(this).attr('src'),
							urlAlt = url.replace('.png', '-alt.png');
						var $tmp = $(document.createElement('img')).attr({
							'alt': '',
							'src': urlAlt
						});
						$tmp.one('load', function () {
						}).each(function () { // Hack. Ensures the load event of the image will be triggered (for IE7 only?).
							if (this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) === 6)) {
								$(this).trigger('load');
							}
						});
						$(this).hover(function () {
							$(this).attr('src', urlAlt);
						}, function () {
							$(this).attr('src', url);
						});
					});

					// Set click event for the email button.
					addthis.toolbox('#email', addthis_config, {
						'url': url,
						'title': title
					});

					// Set click event for the print button.
					$productOverlay.find('.tools #print').one('click', function (e) {
						window.print();
					});
				};

				var initAgeLimitWarning = function () {
					$('div[id*=m_agelimitnotice]').hide();

					var $container = $(settings.overlaySelector + ' #ptaccountinfo .agelimit'),
						$year = $container.find('select.year'),
						$month = $container.find('select.month'),
						$day = $container.find('select.day');
					var selectOnChange = function () {
						var birthDate = new Date($year.val(), $month.val() - 1, $day.val());
						$('div[id*=m_agelimitnotice]').toggle(birthDate > maxAllowedBirthDate);
					};
					$container.find('select').load().change(selectOnChange);
					selectOnChange();
				};

				var initRequestSMSReminder = function () {
					$('#requestSmsReminder').click(function () {
						var orderId = litium.cc.poker.tournaments.orderConfirmation.orderID;
						App_Code.Site.UI.WebServices.UserService.RequestSMSReminder(
							orderId,
							function (data) {
								$('#requestSmsReminderMessageDefault').hide();
								if (data) { // Success.
									$('#requestSmsReminderMessageRegistered').show();
									$('img#requestSmsReminder').unbind('click').removeClass('enabled');
								} else {
									$('#requestSmsReminderMessageError').show();
								}
							},
							function (data) { // Fail.
								$('#requestSmsReminderMessageDefault').hide();
								$('#requestSmsReminderMessageError').show();
							}
						);
					});
				};

				$(document).ready(function () {
					$(settings.overlaySelector).initOverlayCloseButtons();
					initTools();
					$(settings.overlaySelector).inlineFormLabels();
					initAddThis(url, title);
					$('.message').message();

					switch (currentStep) {
						case 'AccountInfo':
							initAgeLimitWarning();
							break;
						case 'OrderConfirmation':
							initRequestSMSReminder();
							break;
					}
				});
			};

			self.init = function (options) {

				if (options) {
					currentStep = options.currentStep;
					url = options.url;
					title = options.title;
					maxAllowedBirthDate = new Date(Date.parse(options.maxAllowedBirthDate));
				}

				self.refresh(settings);
			};

			return self;
		})();

		// Initializes the grid displaying tournaments.
		var initGrid = function () {
			$('#Content table.tournaments tbody tr').mouseover(function () {
				$(this).addClass('active');
			}).mouseout(function () {
				$(this).removeClass('active');
			});
		};

		self.showTournament = function () {
			// Creates and loads the overlay displaying the tournament.
			var api,
				$overlay = $(settings.overlaySelector);

			if (!$overlay.length) {
				return;
			}

			api = $overlay.data('overlay');

			if (!api) {
				$overlay.overlay({
					close: '.close',
					closeOnClick: false,
					closeOnEsc: false,
					effect: 'casino',
					fixed: false,
					left: 'center',
					load: false,
					onClose: function (e) {
						document.location.hash = '/';
						// Event listener triggered when the overlay has been completely hidden.
						App_Code.Site.UI.WebServices.UserService.ClearCurrentCheckoutSession();
						$('body:first').removeClass('overlay'); // For print css and progress animation.
					},
					onLoad: function (e) {
						// Event listener triggered when the overlay has been completely displayed.
						$('body:first').addClass('overlay'); // For print css and progress animation.
					},
					mask: {
						closeSpeed: 0,
						color: '#000',
						loadSpeed: 0,
						opacity: 0.33
					},
					speed: 0,
					top: 'center'
				});

				api = $overlay.data('overlay');
			}

			api.load();
		};

		// Click event handler for the tournament list grid rows.
		self.gridOnRowClick = function (sender, args) {
			var productId = args.getDataKeyValue(settings.gridProductIDColumnKey),
				urlName = args.getDataKeyValue(settings.gridUrlNameColumnKey);
			__doPostBack(settings.updatePanelId, productId); // Postback to the updatepanel
			document.location.hash = urlName;
		};

		self.orderConfirmation = {
			wsCall: null,
			orderID: '',
			postBackArgument: '',
			checkWS: function () {
				App_Code.Site.Utilities.OrderHandlerService.OrderIsFinished(
					litium.cc.poker.tournaments.orderConfirmation.orderID,
					function (data) {
						if (data) {
							clearInterval(litium.cc.poker.tournaments.orderConfirmation.wsCall);
							__doPostBack(litium.cc.poker.tournaments.updatePanelId, litium.cc.poker.tournaments.orderConfirmation.postBackArgument); // Postback to handle the finished order in codebehind.
						}
					}
				);
			},
			init: function (orderId, postBackArgument) {
				$('body:first').addClass('orderconfirmation');
				$('#' + settings.updateProgressId).hide();
				litium.cc.poker.tournaments.orderConfirmation.orderID = orderId;
				litium.cc.poker.tournaments.orderConfirmation.postBackArgument = postBackArgument;
				litium.cc.poker.tournaments.orderConfirmation.wsCall = setInterval(litium.cc.poker.tournaments.orderConfirmation.checkWS, 1000);
			}
		};

		// Called from the page on load.
		self.init = function (options) {
			settings = jQuery.extend(settings, options);
			self.updatePanelId = settings.updatePanelId;

			$(document).ready(function () {
				initGrid();
				$(settings.overlaySelector).addOverlayCorners();
				if (settings.productId && (settings.showOverlay || document.location.hash.length > 0)) {
					// Show the product overlay if we have a valid product id
					self.showTournament();
				}
			});
		};

		return self;
	})()
};
