var productsXML;
var categoriesXML;
var currentCategory = null;
var currentProduct = null;
var currentCategoryText = '';
var txtViewDetails;
var txtInStock;
var txtOutOfStock;
var txtBackLink;
var txtHomeLink;
var txtDisclaimer;
var txtExtendedDisclaimer

/**
 *	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];
  }
}


//relative path to pick up translated version
$(document).ready(function() {	
	$.ajax({
		url: "xml/categories.xml",
		success: function(data){ 
		categoriesXML = data; //store for later use

		$.ajax({
			url: "xml/products.xml",
			success: function(data){
				productsXML = data; //store for later use
					
				//store translations for later use
				txtViewDetails = $('translations',productsXML).find('view-details').text();
				txtInStock = $('translations',productsXML).find('in-stock').text();
				txtOutOfStock = $('translations',productsXML).find('out-of-stock').text();
				txtBackLink = $('translations',productsXML).find('back-link').text();
				txtHomeLink = $('translations',productsXML).find('back-link-home').text();
				txtDisclaimer = $('translations',productsXML).find('disclaimer').text();
				txtExtendedDisclaimer = $('translations',productsXML).find('extendedisclaimer').text();
				
				//parse url
				currentCategory = parseURL('cat');
				currentProduct = parseURL('prod');
				
				//build left nav passing categories element as parameter
				buildMenu($(categoriesXML).find('categories')[0]);
				//insert navigation after second li element
				$('#menu > ul > li:last-child').append(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($('translations',productsXML).find('welcome').text());
				}
			}
		 });
		 }
	 });
});

//set up initial values for the left nav
var level = 1;
var menuOutput = '';

/**
 *	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 += '\n\t<li>';
			menuOutput += '<a href="?cat=' + xmlRoot.childNodes[i].nodeName + '" ';
			menuOutput += 'title="' + xmlRoot.childNodes[i].nodeName + '" >';
			menuOutput += xmlRoot.childNodes[i].getAttribute('title') + '</a>';
			
			//apply styles to use existing formatting
			if (level <= 1){
				menuOutput += '<ul class="children subNav">';
			}
			else {
				menuOutput += '<ul class="children subNav' + level +'">';
			}
			
			level++;
			buildMenu(xmlRoot.childNodes[i]);
			level--;
			menuOutput += '</ul></li>';
		}
		else {
			var strInsert = '>';
		    if (xmlRoot.childNodes[i].getAttribute('title') == "New") {strInsert = ' class="liPSIcon">';}
		    menuOutput = menuOutput + '\n\t<li' + strInsert;
			menuOutput += '<a href="?cat=' + xmlRoot.childNodes[i].nodeName + '" ';
			menuOutput += 'title="' + xmlRoot.childNodes[i].nodeName + '" > ';
			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 += '<tr><td>';
			content += '<a href="?cat=' + currentCategory + '&prod=' + productID + '">';
			content += '<img class="productImage" alt="' + $(this).find("name").text() + '"';
			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 += imageName.substring(0,imageName.lastIndexOf('.')+1) + 'gif'; //show a gif thumbnail instead
			}
			else {
				content += imageName;
			}
			
			content += '" /></a></td>';
			content += '<td><h3>' + $(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(' '));
			
			var txtLevel = $('translations',productsXML).find($(this).find("level").text()).text();
			
			content += shortDescription + ' ... <a href="?cat=' + currentCategory + '&prod=' + productID + '" >';
			content += txtViewDetails + '&nbsp;&raquo;</a></td>';
			content += '<td class="fppLevel">' + $(this).find("price").text() + '<br />';
			content += '<img src="http://www.pokerstars.com/vip/store/images/';
			content += $(this).find("level").text() + '.gif" alt="' + txtLevel + '" /><br />';
			content += txtLevel + '</td>';
			content += '<td style="text-align:center;"><a href="?cat=' + currentCategory + '&prod=' + productID + '">';
			content += '<img src="images/view-details.gif" alt="' + txtLevel + '" /></a>';
			
			if (currentCategory=="live-tournaments"|currentCategory=="ept"|currentCategory=="appt"|currentCategory=="pca"|currentCategory=="lapt"|currentCategory=="napt"|currentCategory=="wsop") {
			if ($(this).find("instock").text() != 'true') {	
				content += '<span class="stockOut">' + txtOutOfStock + '</span></td></tr>';
			}
			else {
				content += '<span class="stockIn">' + txtInStock + '</span></td></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 = '';
	
	$('product',productsXML).each(function(i) {	
		var 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; ' + txtBackLink + ' ' + currentCategoryText + '</a>';
			
			content = content + backNavigationString;
			content += '<a href="index.html">&laquo; ' + txtHomeLink + '</a></div>';
			content += '<table id="productDetail">';	
			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 += '<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="/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 += '<img src="http://www.pokerstars.com/vip/store/images/large/' + imageName + '" /><br />';
			}
			var txtLevel = $('translations',productsXML).find($(this).find("level").text()).text();
			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 + txtLevel + '</span>';
			content += '</td></tr>';
			content += '<tr><td>' + $(this).find("description").text() + '</td></tr>';
			content += '</table>';
			content = content + backNavigationString;
			content += '<a href="index.html">&laquo; ' + txtHomeLink + '</a></div>';
		}
	});
	
	$("#store").html(content);
	$("#header").html(currentCategoryText);	
}
