
//Global variables
var CurrentCategory,FormatError,PicPos,ShowPic,ShowTitle,PicTimer=-1,MinProductsPerPage=6,MaxProductsPerPage=40,ProductsPerLine=4;

//Indexes into card data
var inCat=0,inImage=1,inTitle=2,inDesc=3,inPrice=4,inImages=5,inSubProd=6,inType=7,inFlags=8;

function PriceToString(Float)
{
	var String,temp,ind;

	String = ""+(Math.round(Float*100)/100);
	if ((ind = String.indexOf(".")) == -1)
	{
		return String + ".00";
	}
	temp = String.substring(ind+1);
	if (temp.length > 2) return String.substring(0,ind+3);
	else if (temp.length < 2) return String + "0";
	return String;
}

function FormatHTML(layerHTML,n,image)
{
	var html="",layerHTML,tag;
	var curIndex=0,index=0,end,subProd;

	//Loop until all HTML written
	curIndex = 0;
	FormatError = false;
	while (curIndex < layerHTML.length)
	{
		//Find first [ from index
		if ((index = layerHTML.indexOf("[",curIndex)) == -1)
			break;

		//Find index of ] after [
		if ((end = layerHTML.indexOf("]",index)) == -1)
		{
			FormatError = true;
			return "<H1>Tag end not found!</H1>";
		}

		//Add html before [
		html += layerHTML.substring(curIndex,index);

		//Get text in tag
		tag = layerHTML.substring(index+1,end);

		//If showing just any pic then handle differently
		if (n == -1)
		{
			if (tag == "BigImage")
			{
				tag = "<img src='Images/"+ShowImage+"' width=400 height=410 border=0>";
			}
			else if (tag == "Title")
			{
				tag = "<p id=Std>" + ShowTitle + "</p>";
			}
			else if (tag == "ImageNo")
			{
				tag = "1";
			}
			else if (tag == "Images")
			{
				tag = "1";
			}
			else if (tag == "Close")
			{
				tag = "<a href='JavaScript:ClosePic();' id=Menu>";
			}
			else if (tag == "/Close")
			{
				tag = "</a>";
			}
			else tag = "";
		}
		else
		{
			//Check text after [
			if (tag == "Image")
			{
				if (cardData[n][inImage] != "")
				{
					tag = "<img src='Images/"+cardData[n][inImage]+"' width=75 height=125 border=0>";
				}
				else
				{
					tag = "<img src='Images/NoImage.gif' width=75 height=125 border=0>";
				}
			}
			else if (tag == "BigImage")
			{
				tag = "";
				if (cardData[n].length > inImages)
				{
					if (image < cardData[n][inImages].length)
					{
						tag = "<img src='Images/"+cardData[n][inImages][image]+"' width=400 height=410 border=0>";
					}
				}
			}
			else if (tag == "Title")
			{
				tag = "<p id=Std>" + cardData[n][inTitle] + "</p>";
			}
			else if (tag == "Description")
			{
				if (cardData[n][inDesc] != "")
				{
					if (cardData[n][inFlags]&1)
					{
						tag = "<p id=Std>" + cardData[n][inDesc] + ". Temporarily out of Stock.</p>";
					}
					else
					{
						tag = "<p id=Std>" + cardData[n][inDesc] + "</p>";
					}
				}
				else
				{
					if (cardData[n][inFlags]&1)
					{
						tag = "<p id=Std>Temporarily out of Stock.</p>";
					}
					else
					{
						tag = "<p id=Std>&nbsp;</p>";
					}
				}
			}
			else if (tag == "Price")
			{
				//if (cardData[n][inPrice] == "")
				if (cardData[n][inFlags]&1)
				{
					tag = tag = "<a id=Menu href='JavaScript:ShowBiggerPic("+n+",0);'>more</a>";
				}
				else if (typeof(cardData[n][inPrice]) == "string" && cardData[n][inPrice] == "")
				{
					tag = tag = "<a id=Menu href='JavaScript:"+cardData[n][inImages]+"'>more</a>";
				}
				else if (typeof(cardData[n][inPrice]) == "number" && cardData[n][inPrice] == 0)
				{
					tag = tag = "<a id=Menu href='JavaScript:ShowBiggerPic("+n+",0);'>more</a>";
				}
				else
				{
					//If is sale item then colour price red
					saleItem = false;
					tag = "<p id=Std>";
					if (typeof(cardData[n][inCat]) == "object")
					{
						for(var c=0;c<cardData[n][inCat].length;c++)
						{
							if (cardData[n][inCat][c] == "SaleProd")
							{
								saleItem = true;
							}
						}
					}
					else if (cardData[n][inCat] == "SaleProd")
					{
						saleItem = true;
					}
					if (saleItem)
					{
						tag = "<font color=#ff0000>";
					}

					//If price is array then find first price
					if (cardData[n][inPrice].length > 1)
					{
						tag += "£" + PriceToString(cardData[n][inPrice][1]);
					}
					else
					{
						tag += "£" + PriceToString(cardData[n][inPrice]);
					}

					//Terminate red colour text for sale items
					if (saleItem)
					{
						tag += "</font>";
					}
					
					//Add basket icon
					tag += "<a id=Menu href='JavaScript:AddToBasket(" + n +");'><img border=0 src=Images/Basket.gif></a></p>";
				}
			}
			else if (tag == "ImageNo")
			{
				if (cardData[n].length > inImages)
				{
					tag = "" + (image+1);
				}
				else tag = "";
			}
			else if (tag == "Images")
			{
				if (cardData[n].length > inImages)
				{
					tag = "" + cardData[n][inImages].length;
				}
				else tag = "";
			}
			else if (tag == "Link")
			{
				if (cardData[n].length > inImages)
				{
					if (typeof(cardData[n][inImages]) == "string")
					{
						tag = "<a href='JavaScript:"+cardData[n][inImages]+"'>";
					}
					else if (cardData[n][inImages].length > 0)
					{
						tag = "<a id=Menu href='JavaScript:ShowBiggerPic("+n+",0);'>";
					}
					else tag = "";
				}
				else tag = "";
			}
			else if (tag == "/Link")
			{
				if (cardData[n].length > inImages)
				{
					if (typeof(cardData[n][inImages]) == "string")
					{
						tag = "</a>";
					}
					else if (cardData[n][inImages].length > 0)
					{
						tag = "</a>";
					}
					else tag = "";
				}
				else tag = "";
			}
			else if (tag == "Prev")
			{
				tag = "";
				if (cardData[n].length > inImages)
				{
					if (image > 0)
					{
						tag = "<a href='JavaScript:ShowBiggerPic("+n+","+(image-1)+");' id=Menu>";
					}
				}
			}
			else if (tag == "/Prev")
			{
				tag = "";
				if (cardData[n].length > inImages)
				{
					if (image > 0)
					{
						tag = "</a>";
					}
				}
			}
			else if (tag == "Next")
			{
				tag = "";
				if (cardData[n].length > inImages)
				{
					if (image < cardData[n][inImages].length-1)
					{
						tag = "<a href='JavaScript:ShowBiggerPic("+n+","+(image+1)+");' id=Menu>";
					}
				}
			}
			else if (tag == "/Next")
			{
				tag = "";
				if (cardData[n].length > inImages)
				{
					if (image < cardData[n][inImages].length-1)
					{
						tag = "</a>";
					}
				}
			}
			else if (tag == "Close")
			{
				tag = "<a href='JavaScript:ClosePic();' id=Menu>";
			}
			else if (tag == "/Close")
			{
				tag = "</a>";
			}
			else 
			{
				FormatError = true;
				return ("<H1>Unknown tag: "+tag+"!</H1>");
			}
		}

		//Add value of tag instead of tag
		html += tag;
		curIndex = end+1;
	}

	//Add last part of layer html
	if (curIndex < layerHTML.length)
	{
		html += layerHTML.substring(curIndex,layerHTML.length);
	}

	return html;
}

function SetupPicPosition()
{
	if (PicTimer != -1)
	{
		clearTimeout(PicTimer);
		PicTimer = -1;
	}

	//Calc starting position of the Pic
	if (obj = FindObj("BiggerPic"))
	{
		PicPos = (((document.body.clientHeight - parseInt(obj.style.height))/2) + document.body.scrollTop);
		if (PicPos < 0) PicPos = 0;

		//Set the position of the Pic
		obj.style.top = PicPos;
	}

	//Set timer to update postion of Pic
	PicTimer = setTimeout("ScrollPicWithWindow();",100);
}

function ScrollPicWithWindow()
{
	//Calc ramped position of the Pic with window scroll
	if (obj = FindObj("BiggerPic"))
	{
		PicPos = ((((document.body.clientHeight - parseInt(obj.style.height))/2) + document.body.scrollTop) - PicPos)/2 + PicPos;
		if (PicPos < 0) PicPos = 0;

		if (parseInt(obj.style.height) < document.body.clientHeight)
		{
			//Set the position of the Pic
			obj.style.top = PicPos;
		}
	}

	//Set the timer again
	PicTimer = setTimeout("ScrollPicWithWindow();",100);
}

function ClosePic()
{
	if (PicTimer != -1)
	{
		clearTimeout(PicTimer);
		PicTimer = -1;
	}
	if (obj = FindObj("BiggerPic")) 
	{
		obj.style.visibility = "hidden";
		obj.style.top        = 50;
	}
}

function ShowBiggerPic(ItemIndex,PicIndex)
{
	var html;

	if (PicIndex >= 0 && PicIndex < cardData[ItemIndex][inImages].length)
	{
		//Get template layer
		if (obj = FindObj("BiggerPicTemp"))
		{
			//Generate HTML for layer and calc starting position of pic
			html = FormatHTML(obj.innerHTML,ItemIndex,PicIndex);
			SetupPicPosition();

			//Set HTML on layer and show layer
			if (obj = FindObj("BiggerPic"))
			{
				obj.innerHTML = html;
				obj.style.visibility = "visible";
			}

			//Make sure the basket is closed
			CloseBasket();
		}
	}
};

function ShowPicture(Image,Title)
{
	var html;

	//Get template layer
	if (obj = FindObj("BiggerPicTemp"))
	{
		//Store image and title strings
		ShowImage = Image;
		ShowTitle = Title;

		//Generate HTML for layer and calc starting position of pic
		html = FormatHTML(obj.innerHTML,-1,-1);
		SetupPicPosition();

		//Set HTML on layer and show layer
		if (obj = FindObj("BiggerPic"))
		{
			obj.innerHTML = html;
			obj.style.visibility = "visible";
		}

		//Make sure the basket is closed
		CloseBasket();
	}
};

function FindCategory(ID)
{
	for(var n=0;n<categoryData.length;n++)
	{
		if (categoryData[n][0] == ID)
		{
			return n;
		}
	}
	return -1;
}

function AddCategoryHeader(Title)
{
	var html="<p id=Title>",Index=-1,ParentIndex,FullName;

	//Find full name for CurrentCategory
	Index = FindCategory(CurrentCategory);

	//If not found then return category id
	if (Index == -1) 
	{
		html += Title + "</p>";
	}
	else
	{
		//Loop from last parent category
		for(var n=categoryData[Index].length-1;n>1;n--)
		{
			ParentIndex = FindCategory(categoryData[Index][n]);
			if (ParentIndex == -1) FullName = categoryData[Index][n];
			else FullName = categoryData[ParentIndex][1];
			html += "<a id=TitleMenu href='JavaScript:ShowPage(\"" + categoryData[Index][n] + "\");'>" + FullName + "</a> - "; 
		}

		//Add this category name
		html += categoryData[Index][1] + "</p>";
	}

	//Additional category header?
	for(var n=0;n<categoryHeader.length;n++)
	{
		if (categoryHeader[n][0] == CurrentCategory)
		{
			html += "<p id=Std>" + categoryHeader[n][1]+ "<p>";
		}
	}
	return html;
}

function GenerateHTML(PageNo)
{
	var html="",recordHTML,layerHTML,bodyHTML,layerHeight,newHTML,count=0,startingresult=0,results=0,totalresults=0,padding,min;
	var page,pages,show=false,search=false,SearchKeywords=new Array(),TitleStr;

	//Get HTML for product template
	if (obj = FindObj("ProductCell"))
	{
		layerHTML   = obj.innerHTML;
		layerHeight = obj.style.height;
	}

	CategoryHeader = CurrentCategory;
	if (CurrentCategory.substring(0,7) == "Search?")
	{
		SearchKeywords = CurrentCategory.substring(7).toLowerCase().split(" ");

		CategoryHeader = "Search results for keywords: ";
		for(var s=0;s<SearchKeywords.length;s++)
		{
			CategoryHeader += SearchKeywords[s] + " ";
		}
	}

	//Add table so 2 products can be shown on each line
	html = AddCategoryHeader(CategoryHeader);
	bodyHTML = "<table width=100% height=" + (layerHeight*3 + 30) +" border=0 cellspacing=0 cellpadding=0><tr height=" + layerHeight + ">";

	//Calc starting result for pageno
	startingresult = PageNo*MaxProductsPerPage;

	//Loop for all records
	for(var n=0;n<cardData.length;n++)
	{
		//If product is out of stock then ignore
		if (cardData[n][inFlags]&2)
		{
			continue;
		}

		if (SearchKeywords.length > 0)
		{
			show = false;
			search = true;
			TitleStr = cardData[n][inTitle].toLowerCase();
			//Cat = cardData[n][inCat].toLowerCase();

			//Check if to ignore this category
			for (var ignore=0;ignore<searchIgnoreCategories.length;ignore++)
			{
				if (typeof(cardData[n][inCat]) == "object")
				{
					if (cardData[n][inCat][0] == searchIgnoreCategories[ignore])
					{
						search = false;
						break;
					}
				}
				else if (cardData[n][inCat] == searchIgnoreCategories[ignore])
				{
					search = false;
					break;
				}
			}
			if (search)
			{
				for(var s=0;s<SearchKeywords.length;s++)
				{
					if (TitleStr.indexOf(SearchKeywords[s]) != -1)
					{
						show = true;
						break;
					}
				}
			}
		}
		else
		{
			//If item is for current category
			show = false;
			if (typeof(cardData[n][inCat]) == "object")
			{
				for(var c=0;c<cardData[n][inCat].length;c++)
				{
					if (cardData[n][inCat][c] == CurrentCategory)
					{
						show = true;
					}
				}
			}
			else if (cardData[n][inCat] == CurrentCategory)
			{
				show = true;
			}
		}

		if (show)
		{
			totalresults++;
			if (totalresults > startingresult && totalresults <= startingresult+MaxProductsPerPage)
			{
				//Format this product into HTML, return Error string if error occurred
				recordHTML = "<td align=center>";
				newHTML = FormatHTML(layerHTML,n,0);
				if (FormatError) return newHTML;

				//Count number of results found
				results++;
				
				//Add new HTML
				recordHTML += newHTML;
				recordHTML += "</td>";

				//Add new row if reached max results for current line
				count++;
				if (count >= ProductsPerLine) 
				{
					recordHTML += "</tr><tr height=10><td colspan=ProductsPerLine></td></tr><tr height=" + layerHeight + ">";
					count = 0;
				}
				else
				{
					recordHTML += "<td width=20></td>";
				}
				bodyHTML += recordHTML;
			}
		}
	}

	//Make sure that table contains 6 entries
	min = MinProductsPerPage;
	if (results & 0x01 && results > MinProductsPerPage) min = results+1;
	padding = results;
	while(padding < min)
	{
		bodyHTML += "<td></td>";
		count++;
		padding++;

		if (count >= ProductsPerLine)
		{
			bodyHTML += "</tr><tr height=10><td colspan=ProductsPerLine></td></tr><tr height=" + layerHeight + ">";
			count = 0;
		}
		else
		{
			bodyHTML += "<td width=20></td>";
		}
	}

	//Add table footer
	bodyHTML += "</table>";

	//Add footer - Previous page
	page = PageNo+1;pages = Math.ceil(totalresults/MaxProductsPerPage);
	pagenumHTML = "<p id=Std>";
	if (page > 1)		pagenumHTML += "<a id=Menu href='Javascript:ShowPage(\"" + CurrentCategory + "\"," +(PageNo-1) + ");'>Previous &lt</a>";
	else				pagenumHTML += "";//"Previous &lt";

	//Add numbers for each page
	pagenumHTML += " Page "
	for(p=1;p<=pages;p++)
	{
		if (p == page)
		{
			pagenumHTML += p + " ";
		}
		else
		{
			pagenumHTML += "<a id=Menu href='Javascript:ShowPage(\"" + CurrentCategory + "\"," + (p-1) + ");'>"+p+"</a> ";
		}
	}

	//Next page
	pagenumHTML += " ";
	if (page < pages)	pagenumHTML += "<a id=Menu href='Javascript:ShowPage(\"" + CurrentCategory + "\"," +(PageNo+1) + ");'>&gt Next</a>"
	else				pagenumHTML += "";//"&gt Next";
	pagenumHTML += "</p>";

	//Add page numbers - top
	html += pagenumHTML;

	//Add body
	html += bodyHTML;

	//Add page numbers - bottom
	html += pagenumHTML;

	//If found entries
	if (results == 0)
	{
		//html = "<H3>No products found for category: "+CurrentCategory+"!</H3>";
		if (SearchKeywords.length > 0)
		{
			html = "<H3>No search results found!</H3>";
		}
		else
		{
			html = "<H3>Coming soon, under construction!</H3>";
		}
	}
	return html;
}

function ListProducts()
{
	//Generate HTML and write to document
	document.write(GenerateHTML(0));
}

function WriteProducts(PageNo)
{
	//Generate HTML and copy to main division
	if (obj = FindObj("Main"))	obj.innerHTML = GenerateHTML(PageNo);
}

function SetCategory(Cat)
{
	CurrentCategory = Cat;
}
