var productsXML;
var categoriesXML;
var currentCategory = null;
var currentProduct = null;
var currentCategoryText = '';
var txtDisclaimer='<p>Please Note that not all items are available in some countries.</p><p>Check the PokerStars client for the latest information about what you can buy in the VIP store, including how many points each item is worth. Simply click \'Cashier\' and select \'VIP Store\'.</p>';
var txtExtendedDisclaimer ='<p>PlatinumStar+ VIPs can use FPPs for packages and/or seats to most PokerStars sponsored live events. If the live event package you wish to purchase is not available in the VIP Store, please email the vipclub@pokerstars.com for further assistance.</p>';
/**
 *	extract a querystring paramter
 */

function parseURL(name)
{
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  
  if( results == null ) {
    return "";
  }
  else {
    return results[1];
  }
}


$(document).ready(function() {	
	$.ajax({
		url: "/vip/store/xml/categories.xml",
		success: function(data){ 
		categoriesXML = data; //store for later use

		$.ajax({
			url: "/vip/store/xml/products.xml",
			success: function(data){
				productsXML = data; //store for later use
					
				//parse url
				currentCategory = parseURL('cat');
				currentProduct = parseURL('prod');
				
				//build left nav passing categories element as parameter
				buildMenu($(categoriesXML).find('categories')[0]);
				//update contents of menu element
				$('#menu').html(menuOutput + '<li class="second"> </li>');
				
				//select any li elements in the menu that have child elements with class .children
				var subHead = $('.children').parent();
				//hide everything and then show the element matching the current category - and all its parents
				subHead.children('ul').hide();
				$('a[title=' + currentCategory + ']', subHead).parents().children('ul').slideDown('fast');
				//add the pressed class
				$('a[title=' + currentCategory + ']', '#menu').addClass('pressed');
				//get the header text
				currentCategoryText = $('a[title=' + currentCategory + ']', '#menu').text();
				
				
				//if we have a productID display product detail
				if (currentProduct != '') {
					showDetail(currentProduct,currentCategory);
				}
				else if (currentCategory != '') {
					buildProductList(currentCategory);
				}
				else {
					$('#home').css("display","block");
					$("#header").html('Welcome');
				}
			}
		 });
		 }
	 });
});

//set up initial values for the left nav
var level = 1;
var menuOutput = '\n<ul>';
var menuOutput = menuOutput + '<li title="VIP Store Home"><a href="index.html" class="main" title="Home">VIP Store Home</a></li>';
menuOutput = menuOutput + '<li title="VIP Store FAQs"><a href="faq/index.html" class="main bb" title="FAQs">VIP Store FAQs</a></li>';

/**
 *	build left menu nav from xml using recursion
 *	also assign classes from Pokerstars house style
 */

function buildMenu(xmlRoot)
{	
	for (var i=0; i < xmlRoot.childNodes.length; i++)
	{	
		if (xmlRoot.childNodes[i].nodeType != 1) continue;
		if (xmlRoot.childNodes[i].hasChildNodes() == true) {
		    menuOutput = menuOutput + '\n\t<li>';
			menuOutput = menuOutput + '<a href="?cat=' + xmlRoot.childNodes[i].nodeName + '" ';
			menuOutput = menuOutput + 'title="' + xmlRoot.childNodes[i].nodeName + '">';  
			menuOutput = menuOutput + xmlRoot.childNodes[i].getAttribute('title') + '</a>';
			
			//apply styles to use existing formatting
			if (level <= 1){
				menuOutput = menuOutput + '<ul class="children subNav">';
			}
			else {
				menuOutput = menuOutput + '<ul class="children subNav' + level +'">';
			}
			
			level++;
			buildMenu(xmlRoot.childNodes[i]);
			level--;
			menuOutput = menuOutput + '</ul></li>';
		}
		else {
			var strInsert = '>';
		    if (xmlRoot.childNodes[i].getAttribute('title') == "New") {strInsert = ' class="liPSIcon">';}
		    menuOutput = menuOutput + '\n\t<li' + strInsert;
			menuOutput = menuOutput + '<a href="?cat=' + xmlRoot.childNodes[i].nodeName + '" ';
			menuOutput = menuOutput + 'title="' + xmlRoot.childNodes[i].nodeName + '" >';
			menuOutput = menuOutput + '' + xmlRoot.childNodes[i].getAttribute('title') + '</a></li>';
		}
	}
}


/**
 *	Build the list of products for the current category from the loaded XML
 */

function buildProductList(currentCategory)
{		
	var content = '<table class="products" id="productsTable">'; 
	var inCategory = false;
	$('product',productsXML).each(function(i) {
		categories = $(this).find("categories").text();
		productID = $(this).attr("id");

		if (categories.indexOf('_' + currentCategory) != -1) {
			inCategory = true;
			content = content + '<tr><td>';
			content = content + '<a href="?cat=' + currentCategory + '&prod=' + productID + '">';
			content = content + '<img class="productImage" alt="' + $(this).find("name").text() + '"';
			content = content + ' src="http://www.pokerstars.com/vip/store/images/small/';
			
			//check for flash movie
			var imageName = $(this).find("imgpath").text();
			
			if (imageName.substring(imageName.lastIndexOf('.')+1) == 'swf') { //it's a flash movie
				content = content + imageName.substring(0,imageName.lastIndexOf('.')+1) + 'gif'; //show a gif thumbnail instead
			}
			else {
				content = content + imageName;
			}
			
			content = content + '" /></a></td>';
			content = content + '<td><h3>';
			content = content + $(this).find("name").text() + '</h3>';
			//substring the description to get an intro
			var description = $(this).find("description").text().substring(0,100);
			var shortDescription = description.substring(0,description.lastIndexOf(' '));
			content = content + shortDescription + ' ... <a href="?cat=' + currentCategory + '&prod=' + productID + '" >';
			content = content + 'view&nbsp;details&nbsp;&raquo;</a></td>';
			content = content + '<td class="fppLevel">' + $(this).find("price").text() + '<br />';
			content = content + '<img src="http://www.pokerstars.com/vip/store/images/';
			content = content + $(this).find("level").text() + '.gif" alt="" /><br />';
			content = content + $(this).find("level").text() + '</td>';
			content = content + '<td style="text-align:center;"><a href="?cat=' + currentCategory + '&prod=' + productID + '">';
			content = content + '<img src="http://www.pokerstars.com/vip/store/images/view-details.gif" alt="View details" /></a>';
			
			if (currentCategory=="live-tournaments"||currentCategory=="ept"||currentCategory=="appt"||currentCategory=="pca"||currentCategory=="lapt"||currentCategory=="napt"||currentCategory=="wsop") {
			if ($(this).find("instock").text() != 'true') {
				content = content + '<span class="stockOut">Out of Stock</span></td>';
			}
			else {
				content = content + '<span class="stockIn">In Stock</span></td>';
			}
			}
			content = content + '</tr>';
		}
	});
		
		if (inCategory != false) {
			$("#header").html(currentCategoryText);
			$("#store").html(content);
			if(currentCategory=='live-tournaments'||currentCategory=='pca'||currentCategory=='appt'||currentCategory=='ept'||currentCategory=='appt'||currentCategory=='lapt') txtDisclaimer += txtExtendedDisclaimer;
			$("#note").html(txtDisclaimer);
		}			
}

/**
 *	Build the product detail page from the loaded XML
 */

function showDetail(selectedProduct,currentCategory)
{
	var content = '';
	var thisProduct = null
	$('product', productsXML).each(function (i) {
		thisProduct = $(this).attr("id");

		if (thisProduct == selectedProduct) {
			content = '<h2>' + $(this).find("name").text() + '</h2>';

			var backNavigationString = '<div id="topNav"><a href="?cat=' + currentCategory + '" class="back">&laquo; Back to ' + currentCategoryText + '</a>';

			content = content + backNavigationString;
			content = content + '<a href="index.html">&laquo; Back to VIP Store Home Page</a></div>';
			content = content + '<table id="productDetail">';
			content = content + '<tr><td class="detailImg">';

			//check for flash movie
			var imageName = $(this).find("imgpath").text();

			if (imageName.substring(imageName.lastIndexOf('.') + 1) == 'swf') { //it's a flash movie

				content = content + '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase=   "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="539" height="454"><param name="movie" value="http://www.pokerstars.com/vip/store/images/large/' + imageName + '"><param name="quality" value="high"><embed src="/vip/store/images/large/' + imageName + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="539" height="454"></embed></object>'

			}
			else {
				content = content + '<img src="http://www.pokerstars.com/vip/store/images/large/' + imageName + '" /><br />';
			}
			content = content + '<span class="fppLevel">' + $(this).find("price").text();
			content = content + '<img src="http://www.pokerstars.com/vip/store/images/';
			content = content + $(this).find("level").text() + '.gif" alt="" />';
			content = content + $(this).find("level").text() + '</span>';
			content = content + '</td></tr>';
			content = content + '<tr id="desc' + thisProduct + '"><td>' + $(this).find("description").text() + '</td></tr>';
			content = content + '</table>';
			content = content + backNavigationString;
			content = content + '<a href="index.html">&laquo; Back to VIP Store Home Page</a></div>';
		};
	});
	$("#store").html(content);
	$("#header").html(currentCategoryText);
	getSizingChart(selectedProduct);
}

function getSizingChart(productID) {
	var returnString = '';
	var SizingChartText = "Sizing Chart";
	var SizeText = "Size";
	var HeadingCount = 0;
	$.ajax({
		url: "/vip/store/xml/sizing/" + productID + ".xml",
		success: function (data) {
			returnString = '<tr><td><div><a href="javascript:void(0)" onclick="var t=document.getElementById(\'chart' + productID + '\');t.style.display=(t.style.display==\'none\')?\'\':\'none\';">' + SizingChartText + '</a><table class="tbl_basic" id="chart' + productID + '" style="display:none;">';
			var Headings = '<tr><th>' + SizeText + '</th>';
			$(data).find("HeadingText").each(function (i) {
				Headings += "<th>" + $(this).text() + "</th>";
				HeadingCount++;
			})
			Headings += '</tr>';
			returnString += '<tr><th></th><th colspan="' + HeadingCount / 2 + '"> European (cm) </th><th colspan="' + HeadingCount / 2 + '"> USA (in)</th></tr>';
			returnString += Headings;
			$(data).find("Size").each(function () {
				returnString += '<tr><th class="size">' + $(this).attr("title") + '</th>';
				$(this).find("Value").each(function () {
					returnString += '<td style="text-align:center">' + $(this).text() + '</td>';
				})
				returnString += '</tr>'
			})
			returnString += "</table></div></td></tr>";
			var t = document.getElementById("desc" + productID);
			var nTR = document.createElement("tr");
			var nTD = document.createElement("td");
			nTR.appendChild(nTD)
			nTD.innerHTML = returnString
			t.parentNode.insertBefore(nTR, t.nextSibling);
		}
	})
}

