﻿$(function () {
	$('div#shop').mvc({
    
        'home': function (e) {
			this.index = function (view) {
				$.mvc('shop', 'browse', 28);
			};
		},

		'faq': function (e) {
			this.index = function (view) {
				view(gameslave.views.faq());
			};
		},

		'about': function (e) {
			this.index = function (view) {
				view(gameslave.views.about());
			};
		},

		'contact': function (e) {
			this.index = function (view) {
				view(gameslave.views.contact());
			};
		},

		'done': function (e) {
			this.index = function (view) {
				view(gameslave.views.done());
				
				var script = document.createElement("script");
				
				script.src = 'http://www.googleadservices.com/pagead/conversion.js';
				
				document.getElementsByTagName('head')[0].appendChild(script);
			}
		},

		'shop': function (e) {
			var service = astoria.query('api.svc');

			this.index = function (view) {
				view('Shop!');
			};

			this.browse = function (view, market) {
				view('<img class="load" src="/asset/img/ajaxcircle.gif" />');

				if (!market) {
					view('Please select a market.');
				} else {
					(function (fn) {
						var o1, o2, o3;

						service('Market').fetch({ marketId: market }, function (o) {
							o1 = o[0]; go();
						});

						service('Market').fetch({ parentId: market }, function (o) {
							o2 = o; go();
						});

						service('Product').fetch({ marketId: market, discount: "'" + escape(getQuery()['discount']) + "'" }, function (o) {
							o3 = o; go();							
						});

						function go() {
							if (o1 && o2 && o3) {
								setTimeout(function () { fn(o1, o2, o3); }, 1000);
							}
						}
					})(function (market, markets, products) {
						var title = market.Path.split(',').join(' :: ');

						var items = [];

						$.each(products, function () {
							if (!this.Available) return;

							var stock = (this.Stock / 1000) + 'k';
							var title = stock + ' ' + this.Name;
							var price = '$' + parseFloat(this.Price).toFixed(2);

							items.push({ id: this.Id, title: title, price: price });
						});

						view(gameslave.views.market({ market: title, markets: markets, products: items }));

						if (markets.length) {
							var ul = e.find('ul.markets');
							var height = ul.children().height();
							var rows = markets.length / 2 + (markets.length % 2);

							ul.height(height * rows);
						}

						e.find('img.buy').click(function () {
							var product = $(this).attr('product');
							
							var modal = $(gameslave.views.checkout());

							modal.modal({
								close: false,
								minWidth: 225,
								minHeight: 50
							});

							function trim(s) {
								return s.replace(/^\s*/, '').replace(/\s*$/, '');
							};

							modal.find('button#order').attr('disabled', true).css('opacity', 0.5);

							modal.find('input#character').keyup(function () {
								var $this = $(this);

								var disabled = !trim($this.val()).length;

								modal.find('button#order').attr('disabled', disabled).fadeTo(500, disabled ? 0.5 : 1.0);
							});
							
							modal.find('button#cancel').click(function () {
								$.modal.close();
							});

							modal.find('button#order').click(function () {
								modal.find('h3').text('Placing Your Order...');
								
								modal.find('label').hide();
								modal.find('button').hide();
								modal.find('input#character').hide();

								$('<div id="ajax"></div>').append('<img src="/asset/img/ajaxbar.gif" />').appendTo(modal);

								service('PayPal').fetch({
									'marketId': market.Id,
									'character': "'" + trim(modal.find('input#character').val()) + "'",
									'productId': product,
                                    'discount': "'" + escape(getQuery()['discount']) + "'"
								}, function (o) {
									o = o.PayPal;

									if (o == "outofstock") {
										modal.empty().html('<h3>The product you\'re attempting to purchase is now out of stock.  Please refresh the page for an updated list of products.');
									} else {
										modal.find('h3').text('Redirecting to PayPal...');

										var form = $('<form method="post" action="https://www.paypal.com" />');

										$('<input type="hidden"/>').attr('name', 'cmd').val('_s-xclick').appendTo(form);
										$('<input type="hidden"/>').attr('name', 'encrypted').val(o).appendTo(form);

										form.appendTo($('body')).submit().remove();
									}
								});
							});
						});
					});
				}
			};
		}
	});

	if (location.hash.indexOf('/') != 1)
		$.mvc('shop', 'browse', 28);
});

function getQuery() {
  var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

  while (m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }

  return result;
}
