addEvent(window,"load",CV_Initialise, false);

var currentPage = 1;
var numCols;
var perPage = 8;
var numProducts = 0;
var numPages = 0;
var vouchersOnly = 0;
///var categoryId;
///var productStyle;
//var sortBy;
var productList = new Array();

var cookieName;

///// Product Class /////
function Product(){
	this.id;
	this.image;
	this.supplier;
	this.productRange;
	this.productStyle;
	this.lowestPrice;
	this.productType;
	this.productName;
}
//// End Product Class ////

function CV_Initialise(){
	
	// First make sure all the product items are the same size
	setProductHeights();

	//// Sort out the pagination and load stuff ////
	
	// Get variables from the html
	numProducts = $('numProducts').value;
	//categoryId = $('categoryId').value;
	//productStyle = $('productStyle').value;
	//sortBy = $('sortBy').value;
	vouchersOnly = $('vouchersOnly').value;
	
	// Cookie Name
	cookieName = "giftShopPage";
	
	// Work out the perPage
	getPerPage();

	// How many pages?
	numPages = Math.ceil(numProducts / perPage);
	makePagination();

	var newPage = getCookie(cookieName);
	if(newPage){
		currentPage = newPage;
		setCookie(cookieName, null, -1);
	}

	loadPage();
	
} // end CV_Initialise

function makePagination(){

	// Empty the current pagination box
	var myElements = $('Pagination').childElements();
	for(var i = 0;i < myElements.length;i++){
		myElements[i].remove();
	}

	// Rebuild Pagination
	var pageList = document.createElement('p');
	addClass(pageList,'PageList');
	pageList.appendChild(document.createTextNode('PAGE '));
	for(var i = 0;i < numPages;i++){
		var pageLink = document.createElement('a');
		pageLink.setAttribute('href','javascript:void(0)');
		pageLink.appendChild(document.createTextNode(i+1));
		if(currentPage == i + 1){
			addClass(pageLink,'Selected');
		}else{
			addEvent(pageLink,"click",pageLinkClick, false);
		}
		pageList.appendChild(pageLink);
		if(i<numPages-1){
			pageList.appendChild(document.createTextNode(" / "));
		}
	}
	$('Pagination').appendChild(pageList);

} // end makePagination

function pageLinkClick(e){
if(!e) var e = window.event;
if(e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;

	var newPage = targ.firstChild.nodeValue;
	currentPage = newPage;
	
	// Set Cookie
	setCookie(cookieName, currentPage);
	
	// What page are we going to
	//	alert(targ.firstChild.nodeValue);
	loadPage();

} // end pageLinkClick

function loadPage(){
	// Load stuff
//	var query = 'cmd=xml&page=' + currentPage + '&perPage=' + perPage + '&sortBy=' + sortBy;
	var query = 'cmd=xml&page=' + currentPage + '&perPage=' + perPage + '&vouchersOnly=' + vouchersOnly;
	new Ajax.Request('gift_shop.php', {asynchronous: true, method: 'post', postBody: query, onSuccess: processLoad, onFailure: function(){alert("Failed to fetch data. Please try again");} });	
} // end loadPage

function processLoad(response){

	productList.clear();
	var rootEntries = response.responseXML.getElementsByTagName('products');
	var entries = rootEntries[0].getElementsByTagName('product');
	for(var i=0;i<entries.length;i++){

		//// Get individual parts
		var myProduct = new Product();

		// ID
		myProduct.id = getFirstNodeValue(entries[i], 'id');
		myProduct.image = getFirstNodeValue(entries[i], 'image');
		myProduct.supplier = getFirstNodeValue(entries[i], 'supplier');
		myProduct.productRange = getFirstNodeValue(entries[i], 'productrange');
		myProduct.productStyle = getFirstNodeValue(entries[i], 'productstyle');
		myProduct.lowestPrice = getFirstNodeValue(entries[i], 'lowestprice');
		myProduct.productType = getFirstNodeValue(entries[i], 'producttype');
		myProduct.productName = getFirstNodeValue(entries[i], 'productname');
		productList[productList.length] = myProduct;
	}

	renderProducts();
	makePagination();
} // end processLoad

function getFirstNodeValue(node, name){
	var list = node.getElementsByTagName(name);
	var entry = list[0].firstChild.data;
	return entry;
} // end getFirstNodeValue

function renderProducts(){
	// Clear the grid
	var myElements = $('ProductGrid').childElements();
	for(var i = 0;i < myElements.length;i++){
		myElements[i].remove();
	}

	// Create new grid
	var colCount = 0;
	for(var i = 0;i<productList.length;i++){

		if((i % 2) == 0){
			colCount++;
			var pc = document.createElement('div');	
			addClass(pc,'ProductColumn');
			if(colCount == numCols){
			addClass(pc,'Last');	
			}
		}

		/// Grid Entry
		
			var myLink = 'product.php?id=' + productList[i].id;
		
			var ge = document.createElement('div');
			addClass(ge,'GridEntry');
			
			/// Top Image & Link
			var imLink = document.createElement('a');
			imLink.setAttribute('href',myLink);
			var im = document.createElement('img');
			im.setAttribute('src',productList[i].image);
			im.setAttribute('alt',productList[i].productName);
			im.setAttribute('width','200');
			im.setAttribute('height','356');
			imLink.appendChild(im);
			ge.appendChild(imLink);
			
			/// Split Depending On Product Type
			if(productList[i].productType == 'Clothing'){
				// Product Name Link
				var pName = document.createElement('p');
				addClass(pName,'ProdName');
				var pNameLink = document.createElement('a');
				pNameLink.setAttribute('href',myLink);
				addClass(pNameLink, 'DetailsLink');
				pNameLink.appendChild(document.createTextNode(productList[i].supplier));
				pNameLink.appendChild(document.createElement('br'));
				pNameLink.appendChild(document.createTextNode(productList[i].productRange + ", " + productList[i].productStyle));
				pName.appendChild(pNameLink);
				ge.appendChild(pName);				

			}else if(productList[i].productType == "Gift Voucher"){
				// Product Name Link
				var pName = document.createElement('p');
				addClass(pName,'ProdName');
				var pNameLink = document.createElement('a');
				pNameLink.setAttribute('href',myLink);
				addClass(pNameLink, 'DetailsLink');
				pNameLink.appendChild(document.createTextNode(productList[i].productName));
				pName.appendChild(pNameLink);
				ge.appendChild(pName);
				
			}

			// Product Price
			var pPrice = document.createElement('p');
			addClass(pPrice, 'ProdPrice');
			pPriceLink = document.createElement('a');
			pPriceLink.setAttribute('href',myLink);
			addClass(pPriceLink, 'Price');
			pPriceLink.appendChild(document.createTextNode('£' + productList[i].lowestPrice));
			pPrice.appendChild(pPriceLink);
			ge.appendChild(pPrice);
			
			var fullDetails = document.createElement('p');
			addClass(fullDetails,'FullDetails');
			var fullDetailsLink = document.createElement('a');
			addClass(fullDetailsLink, 'FullDetails');
			fullDetailsLink.setAttribute('href', myLink);
			fullDetailsLink.appendChild(document.createTextNode('Full Details'));
			fullDetails.appendChild(fullDetailsLink);
			ge.appendChild(fullDetails);
			
			var clearFloats = document.createElement('div');
			addClass(clearFloats,'ClearFloats');
			clearFloats.appendChild(document.createTextNode(" "));
			ge.appendChild(clearFloats);

			pc.appendChild(ge);
		/// End Grid Entry
		
		if((i % 2) == 0){
			$('ProductGrid').appendChild(pc);
		}
	}
	setProductHeights();
} // end renderProducts

function setProductHeights(){
	var gridEntryHeight = 0;
	
	var elementArray = new Array();
	elementArray = document.getElementsByTagName('div');
	for(var i = 0; i < elementArray.length; i++){
		// Check for class
		var pattern = new RegExp("(^| )" + "GridEntry" + "( |$)");
		if(pattern.test(elementArray[i].className)){
			var myHeight = $(elementArray[i]).getHeight();
			if(myHeight > gridEntryHeight){
			gridEntryHeight = myHeight;
			}
		}
	} // end loop through items

	for(var i = 0; i < elementArray.length; i++){
		var pattern = new RegExp("(^| )" + "GridEntry" + "( |$)");
		if(pattern.test(elementArray[i].className)){
			$(elementArray[i]).style.height = gridEntryHeight + "px";
		}
	}

} // end setProductHeights

function getPerPage(){
	var totalWidth = parseInt($('ProductGrid').getWidth());
//	totalWidth -= 30;
	numCols = Math.floor(totalWidth / 234);
	perPage = numCols * 2;

} // end getPerPage