﻿var _map = null;
var _countdown = null;
var _txtDays = "";
var _meterBought = null;
var _meterAnimationTime = 1500;
var _currentCardNoPrefix = "";
var _paymentCurrencyCode = "";
var _paymentZero = "";
var _paymentFeeText = "";
var _paymentFeeHandler = "/getCheckoutPaymentFee.ashx";

/*************************/
/* User Interface        */
/*************************/
var UI =
{

	/*************************/
	/* Initialize            */
	/*************************/
	init: function ()
	{

		//UI.adjustPageHeight();
		$(window).resize(UI.adjustPageHeight);

		$('#topNav ul li:first').addClass('first');

		UI.DisplayCities.init();

		UI.Map.init();

		UI.HighSlide.init();

		UI.InviteYourFriends.init();

	},


	/*************************/
	/* Adjust Page Height    */
	/*************************/
	adjustPageHeight: function ()
	{
		var pageHeight = $('#page').height();
		var windowHeight = $(window).height();

		var topHeight = 134;
		var mainHeight = $('#main').height();
		var footerHeight = 56;
		var totalHeight = topHeight + mainHeight + footerHeight;

		if (pageHeight < windowHeight)
			$('#page').css('height', windowHeight + 'px');

		if (pageHeight > totalHeight && pageHeight > windowHeight)
			$('#page').css('height', windowHeight + 'px');
	},


	/*************************/
	/* Display Cities        */
	/*************************/
	DisplayCities:
	{
		init: function ()
		{
			$('a.toggleCities').click(function ()
			{
				$('#cityOverview').slideToggle();
				$('#toggleCities a').toggleClass('open');
				$(this).blur();
				return false;
			});
		}
	},


	/*************************/
	/* Invite your friends   */
	/*************************/
	InviteYourFriends:
	{
		init: function ()
		{
			var defaultValue = $('#shareByEmail input.txt').val();

			$('#shareByEmail input.txt').focus(function ()
			{
				if ($(this).val() == defaultValue)
					$(this).val('');

				$('#shareByEmail .success').hide();
			});

			$('#shareByEmail input.txt').blur(function ()
			{
				if ($(this).val() == '')
					$(this).val(defaultValue);
			});
		}
	},



	/*************************/
	/* HighSlide             */
	/*************************/

	HighSlide:
	{
		init: function ()
		{
			if (typeof (hs) == 'undefined')
				return;

			if (navigator.userAgent.toLowerCase().indexOf('iphone') >= 0 ||
			 navigator.userAgent.toLowerCase().indexOf('ipod') >= 0 ||
			 navigator.userAgent.toLowerCase().indexOf('android') >= 0)
			{
				hs = 'undefined';
				return;
			}

			hs.expandDuration = 0;
			hs.restoreDuration = 0;

			hs.dimmingOpacity = 0.50;
			hs.dimmingDuration = 150;
			hs.dimmingGeckoFix = true;

			hs.dragByHeading = false;

			hs.onKeyDown = function (sender, e)
			{
				return false;
			}

			hs.width = 682;
			hs.height = 422;
			hs.align = 'center';

			hs.preserveContent = false;

			hs.showCredits = false;
			//hs.graphicsDir = 'highslide/graphics/';
			hs.wrapperClassName = 'downtown-iframe';


			// Highslide fixed popup mod. Requires the "Events" component.
			if (!hs.ie || hs.uaVersion > 6) hs.extend(hs.Expander.prototype, {
				fix: function (on)
				{
					var sign = on ? -1 : 1;
					var stl = this.wrapper.style;

					if (!on) hs.getPageSize(); // recalculate scroll positions

					hs.setStyles(this.wrapper, {
						position: on ? 'fixed' : 'absolute',
						zoom: 1, // IE7 hasLayout bug,
						left: (parseInt(stl.left) + sign * hs.page.scrollLeft) + 'px',
						top: (parseInt(stl.top) + sign * hs.page.scrollTop) + 'px'
					});

					if (this.outline)
					{
						stl = this.outline.table.style;
						hs.setStyles(this.outline.table, {
							position: on ? 'fixed' : 'absolute',
							zoom: 1, // IE7 hasLayout bug,
							left: (parseInt(stl.left) + sign * hs.page.scrollLeft) + 'px',
							top: (parseInt(stl.top) + sign * hs.page.scrollTop) + 'px'
						});
					}

					// flag for use on dragging
					this.fixed = on;
				},
				onAfterExpand: function ()
				{
					this.fix(true); // fix the popup to viewport coordinates

					// Set Focus
					var iframe = window.frames[this.iframe.name];
					var doc = iframe.document;
					$(doc).find('input.txt.focus').focus();
				},
				onBeforeClose: function ()
				{
					// unfix to get the animation right
					this.fix(false);
				},
				onDrop: function ()
				{
					// fix it again after dragging
					this.fix(true);
				},
				onDrag: function (sender, args)
				{
					// only unfix it on the first drag event
					if (this.fixed)
						this.fix(false);
				}
			});

			// Window Resize Mod
			hs.addEventListener(window, 'resize', function ()
			{
				var i, exp;
				hs.getPageSize();

				for (i = 0; i < hs.expanders.length; i++)
				{
					exp = hs.expanders[i];
					if (exp)
					{
						var x = exp.x;
						var y = exp.y;

						// get new thumb positions
						exp.tpos = hs.getPosition(exp.el);
						x.calcThumb();
						//y.calcThumb();

						// calculate new popup position
						x.pos = x.tpos - x.cb + x.tb;
						x.scroll = hs.page.scrollLeft;
						x.clientSize = hs.page.width;
						//y.pos = y.tpos - y.cb + y.tb;
						//y.scroll = hs.page.scrollTop;
						//y.clientSize = hs.page.height;
						exp.justify(x, true);
						//exp.justify(y, true);

						// set new left and top to wrapper and outline
						exp.moveTo(x.pos, y.pos);
					}
				}
			});



			//			hs.registerOverlay({
			//				html: '<div class="closebutton" onclick="return hs.close(this)" title="Close"></div>',
			//				position: 'top right',
			//				fade: 0 // fading the semi-transparent overlay looks bad in IE
			//			});

			//			//http://highslide.com/ref/hs.onActivate
			//			hs.onActivate = function()
			//			{
			//				var theForm = document.forms[0];
			//				if (theForm) theForm.appendChild(hs.container);
			//			}

			$('a[rel=popup]').click(function ()
			{
				return hs.htmlExpand(this,
				{
					objectType: 'iframe',
					src: $(this).attr('href')
				});
			});
		},

		popUpStaticOnLoad: function (url, width, height)
		{
			UI.HighSlide.popUpOnLoad(url, width, height, true);
		},

		popUpOnLoad: function (url, width, height, disableClose)
		{
			hs.addEventListener(window, "load", function ()
			{
				hs.htmlExpand(null,
				{
					objectType: 'iframe',
					src: url,
					width: width != undefined ? (width + 2) : hs.width,
					height: height != undefined ? (height + 2) : hs.height,
					wrapperClassName: disableClose ? 'downtown-iframe disable-close' : 'downtown-iframe'
				});

				if (disableClose == true)
					hs.onDimmerClick = function () { return false; }
			});
		},

		breakOut: function ()
		{
			if (top.location != self.location)
			{
				top.location = self.location.href
			}
		},

		enableClose: function ()
		{
			$('.highslide-wrapper', parent.document.body).removeClass('disable-close');
		}
	},


	/*************************/
	/* Google Map            */
	/*************************/

	Map:
	{
		init: function ()
		{
			if (typeof (google) != 'undefined')
			{
				$('.dealLocation .mapIt a[rel^=map]').each(function ()
				{
					var coords = $(this).attr('rel').replace('map:', '');
					var lat = coords.split(',')[0];
					var lng = coords.split(',')[1];
					var addressHtml = $(this).parent().prev('address').html();

					UI.Map.addMarker('mapLocation', lat, lng, addressHtml);

					$(this).click(function ()
					{
						UI.Map.panTo(lat, lng);
						return false;
					});
				});

				$('.dealLocation .showAll').click(UI.Map.expandLocations);
			}
			else
				UI.Map.expandLocations();
		},

		addMarker: function (objId, lat, lng, infoHtml)
		{
			var latlng = new google.maps.LatLng(lat, lng);

			var options = {
				zoom: 15,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				mapTypeControl: false,
				navigationControl: true,
				navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }
			};

			if (_map == null)
				_map = new google.maps.Map(document.getElementById(objId), options);

			var marker = new google.maps.Marker({
				position: latlng,
				map: _map,
				title: $.trim(infoHtml.split('<')[0])
			});

			if (infoHtml != null && infoHtml != '')
			{
				var infowindow = new google.maps.InfoWindow({
					content: infoHtml
				});

				google.maps.event.addListener(marker, 'click', function ()
				{
					infowindow.open(_map, marker);
				});
			}
		},

		panTo: function (lat, lng)
		{
			if (_map != null)
			{
				var latlng = new google.maps.LatLng(lat, lng);

				_map.setZoom(15);
				_map.panTo(latlng);
			}
		},

		expandLocations: function ()
		{
			$('.dealLocation p.showAll').remove();
			$('.dealLocation').addClass('expanded');
			$('.dealLocation .location').removeClass('collapsed');

			if (_map != null)
				google.maps.event.trigger(_map, 'resize');
			else
				$('.dealLocation .col.map, .dealLocation .mapIt').remove();

			return false;
		}
	},


	/*************************/
	/* Countdown Timer       */
	/*************************/

	Timer:
	{
		init: function (seconds, txtDays)
		{
			_txtDays = txtDays;
			_countdown = parseFloat(seconds);

			UI.Timer.update();
		},

		update: function ()
		{
			// Calculate the number of days left
			var days = Math.floor(_countdown / 86400);
			// After deducting the days calculate the number of hours left
			var hours = Math.floor((_countdown - (days * 86400)) / 3600)
			// After days and hours , how many minutes are left
			var minutes = Math.floor((_countdown - (days * 86400) - (hours * 3600)) / 60)
			// Finally how many seconds left after removing days, hours and minutes.
			var secs = Math.floor((_countdown - (days * 86400) - (hours * 3600) - (minutes * 60)))

			var display = '';

			if (days > 0)
			{
				$('.dealTimer').addClass('long');
				display += '<span class="days">' + days + ' ' + _txtDays + '</span><br />';
			}
			display += hours > 9 ? hours : '0' + hours;
			display += ':';
			display += minutes > 9 ? minutes : '0' + minutes;
			display += ':';
			display += secs > 9 ? secs : '0' + secs;

			$('.dealTimer .timer').html(display);

			_countdown--;

			if (_countdown >= 0)
				setTimeout('UI.Timer.update()', 1000)
		}
	},


	/*************************/
	/* Countdown Meter       */
	/*************************/

	Meter:
	{
		init: function (bought, goal)
		{
			var totalWidth = 185;
			var width = parseFloat(bought / goal * totalWidth);
			width = parseInt(width, 10);
			if (width > totalWidth)
				width = totalWidth;

			var speed = width * 20;

			var remaining = goal - bought;
			if (remaining < 0)
				remaining = 0;

			$('.dealMeter .bought').text(bought)
			$('.dealMeter .goal').text(goal);
			$('.dealMeter span.remaining').text(remaining);

			var markerStart = parseInt($('.dealMeter .marker').css('left'));
			$('.dealMeter .marker').animate({ left: markerStart + width }, speed);
			$('.dealMeter .bar').animate({ width: width }, speed);
		}
	},


	/*************************/
	/* Payment               */
	/*************************/

	Payment:
	{
		calculateFee: function ()
		{

			var merchantnumber = $('input[name=merchantnumber]').val();
			var cardno = $('#txtCardNumber').val();
			var amount = parseInt($('input[name=amount]').val());
			var currency = $('input[name=currency]').val();

			if (cardno.length < 6)
				return false;

			cardno = cardno.substr(0, 6);

			if (_currentCardNoPrefix != cardno)
			{
				$('tr.paymentfee td.fee,tr.total td.amount').html('<img src="images/graphics/gx_ajaxloading.gif" alt="loading" />');

				var xmlHttpReq = false;
				var self = this;

				if (window.ActiveXObject)
				{
					// IE
					self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
				}
				else if (window.XMLHttpRequest)
				{
					// Mozilla/Safari
					self.xmlHttpReq = new XMLHttpRequest();
				}

				self.xmlHttpReq.open('POST', _paymentFeeHandler + "?mercahntnumber=" + merchantnumber + "&cardno_prefix=" + cardno + "&amount=" + amount + "&currency=" + currency, true);
				self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				self.xmlHttpReq.onreadystatechange = function ()
				{
					if (self.xmlHttpReq.readyState == 4)
					{

						var response = self.xmlHttpReq.responseText;
						var data;

						if (window.DOMParser)
						{
							var parser = new DOMParser();
							data = parser.parseFromString(response, "text/xml");
						}
						else // Internet Explorer
						{
							data = new ActiveXObject("Microsoft.XMLDOM");
							data.async = "false";
							data.loadXML(response);
						}

						if (data.getElementsByTagName("status")[0].childNodes[0].nodeValue == 'OK')
						{
							var fee = parseInt(data.getElementsByTagName('feeMinorUnit')[0].childNodes[0].nodeValue);
							var cardtype = data.getElementsByTagName('cardType')[0].childNodes[0].nodeValue;
							var cardtext = data.getElementsByTagName('cardTypeText')[0].childNodes[0].nodeValue;

							$('tr.paymentfee td.amount').text(UI.Payment.CurrencyFormatted(fee / 100) + ' ' + _paymentCurrencyCode);
							$('tr.total td.amount').text(UI.Payment.CurrencyFormatted((amount + fee) / 100) + ' ' + _paymentCurrencyCode);
							$('tr.paymentfee td:eq(0)').text(_paymentFeeText + ' (' + cardtext + ')');
							$('input[name=transfee]').val(fee);
						}
						else
						{
							$('tr.paymentfee td:eq(0)').text(_paymentFeeText);
							$('tr.paymentfee td.amount').text(UI.Payment.CurrencyFormatted(0) + ' ' + _paymentCurrencyCode);
							$('tr.total td.amount').text(UI.Payment.CurrencyFormatted((amount) / 100) + ' ' + _paymentCurrencyCode);
							$('input[name=transfee]').val('');
						}
					}
				}

				self.xmlHttpReq.send();
				_currentCardNoPrefix = cardno;
			}
		},

		CurrencyFormatted: function (num)
		{
			num = num.toString().replace(/\$|\,/g, '');
			if (isNaN(num))
				num = "0";

			var sign = (num == (num = Math.abs(num)));
			num = Math.floor(num * 100 + 0.50000000001);

			var cents = num % 100;
			num = Math.floor(num / 100).toString();

			if (cents < 10)
				cents = "0" + cents;

			for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
				num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));

			return (((sign) ? '' : '-') + num + ',' + cents);
		}
	}
}


/*************************/
/* Initialize            */
/*************************/
$(document).ready(UI.init);