﻿function GetIdentifierFromString(sIdentifier)
{
	if (!sIdentifier || sIdentifier.length <= 0 || sIdentifier == ' ')
		return '';
	return sIdentifier; 
}

////////////////////////////////////
// CCartItem

function CalculatePrice(sNativePrice, sSizePricePercent, sSizePriceAdditional, sColorPricePercent, sColorPriceAdditional, sInstallPrice)
{
	var fCurrentPrice = sNativePrice.length ? parseFloat(sNativePrice) : 0;
	if (sSizePricePercent.length)
		fCurrentPrice += fCurrentPrice * (parseFloat(sSizePricePercent)/100);
	if (sSizePriceAdditional.length)
		fCurrentPrice += parseFloat(sSizePriceAdditional);
	if (sColorPricePercent.length)
		fCurrentPrice += fCurrentPrice * (parseFloat(sColorPricePercent)/100);
	if (sColorPriceAdditional.length)
		fCurrentPrice += parseFloat(sColorPriceAdditional);
	if (sInstallPrice.length)
		fCurrentPrice += parseFloat(sInstallPrice);
	return RoundFloat(fCurrentPrice);
}

function CCartItemColor(sGroupId, sId)
{
	this.sGroupId = sGroupId;
	this.sId = sId;
	this.sTitle = '';
	this.sImageBig = '';
	this.Compare = 
		function(Color)
		{
			return Color.sGroupId == this.sGroupId && Color.sId == this.sId;
		}
}

function CCartItem(sId, sSizeGroupId, sSizeId, Colors, bUseMulticolor, bInstall, nCount)
{
// Variables
	this.sId = sId;
	this.sSizeGroupId = sSizeGroupId;
	this.sSizeId = sSizeId;
	this.Colors = Colors;
	this.bUseMulticolor = bUseMulticolor;
	this.bInstall = bInstall;
	this.nCount = nCount ? nCount : 1;
	// Xml data
	this.ReinitializeXmlData =
		function()
		{
			// Xml item titles
			this.sTitle = '';
			this.sSizeGroupTitle = '';
			this.sSizeTitle = '';
			// Images
			this.sImageThumbnail = '';
			this.sImageBig = '';
			// Xml item payment details
			this.sPrice = '';
			this.sSizePricePercent = '';
			this.sSizePriceAdditional = '';		
			this.sColorPricePercent = '';
			this.sColorPriceAdditional = '';
			this.sInstallPrice = '';
		}
	this.ReinitializeXmlData();
	
// Methods
	this.LoadFromString = CCartItem_LoadFromString;
	this.GetAsString = CCartItem_GetAsString;
	this.UpdateXmlData = CCartItem_UpdateXmlData;
	this.Compare = CCartItem_Compare;
	this.GetItemPrice = 
		function()
		{
			return CalculatePrice(this.sPrice, this.sSizePricePercent, this.sSizePriceAdditional, this.sColorPricePercent, this.sColorPriceAdditional, this.sInstallPrice);
		}
	this.GetTotalPrice =
		function()
		{
			return RoundFloat(this.GetItemPrice() * this.nCount);
		}
}
// Implementation
	function CCartItem_LoadFromString(sItemArg)
	{
		var sItem = sItemArg;
		while (sItem.search(',,') >= 0)
			sItem = sItem.replace(',,', ', ,');
		var sItems = sItem.split(',');
		this.sId = GetIdentifierFromString(sItems[0]);
		this.sSizeGroupId = GetIdentifierFromString(sItems[1]);
		this.sSizeId = GetIdentifierFromString(sItems[2]);
		this.bUseMulticolor = GetIdentifierFromString(sItems[3]) == 1;
		this.bInstall = GetIdentifierFromString(sItems[4]) == 1;
		this.nCount = GetIdentifierFromString(sItems[5]);
		var nColorCount = GetIdentifierFromString(sItems[6]);
		this.Colors = new Array();
		for (var nIndex = 0; nIndex < nColorCount; nIndex++)
		{
			var sColorGroupId = GetIdentifierFromString(sItems[7 + (nIndex * 2)]);
			var sColorId = GetIdentifierFromString(sItems[7 + (nIndex * 2) + 1]);
			this.Colors[this.Colors.length] = new CCartItemColor(sColorGroupId, sColorId);
		}
	}
	function CCartItem_GetAsString()
	{
		var sResult = '';
		sResult += this.sId + ','; // 0
		sResult += this.sSizeGroupId + ','; // 1
		sResult += this.sSizeId + ','; // 2
		sResult += (this.bUseMulticolor ? '1' : '0') + ','; // 3
		sResult += (this.bInstall ? '1' : '0') + ','; // 4
		sResult += this.nCount + ','; // 5
		sResult += this.Colors.length; // 6 
		for (var nIndex = 0; nIndex < this.Colors.length; nIndex++)
			sResult += ',' + this.Colors[nIndex].sGroupId + ',' + this.Colors[nIndex].sId; // 7, 8 ...
		sResult += ':';
		return sResult;
	}
	function CCartItem_UpdateXmlData(xmlColors, xmlItems)
	{
		this.ReinitializeXmlData();
		var xmlItem = GetElementByAttribute(xmlItems, 'id', this.sId);
		var xmlSizeGroup = null;
		var xmlSize = null;
		if (this.sSizeGroupId.length)
		{
			xmlSizeGroup = GetElementByAttribute(GetChildNodesByTagName(xmlItem, 'sizegroup'), 'id', this.sSizeGroupId);
			if (!xmlSizeGroup)
				alert('Cookie error: !xmlSizeGroup');
			if (!this.sSizeId.length)
				alert('Cookie error: !sSizeId.length');
			xmlSize = GetElementByAttribute(GetChildNodesByTagName(xmlSizeGroup, 'size'), 'id', this.sSizeId);
			if (!xmlSize)
				alert('Cookie error: !xmlSize');
		}
		this.sTitle = GetTitle(xmlItem);
		this.sPrice = GetAttribute(xmlItem, 'price');
		if (this.bInstall)
			this.sInstallPrice = GetAttribute(xmlItem, 'install');
		var xmlItemImages = GetItemImages(xmlItem);
		this.sImageThumbnail = GetItemImageThumbnail(xmlItemImages, 0);
		this.sImageBig = GetItemImageBig(xmlItemImages, 0);
		if (xmlSize)
		{
			this.sSizeGroupTitle = GetTitle(xmlSizeGroup);
			this.sSizeTitle = GetTitle(xmlSize);
			this.sSizePricePercent = GetAttribute(xmlSize, 'priceper');
			this.sSizePriceAdditional = GetAttribute(xmlSize, 'price');
		}
		if (this.Colors.length)
		{
			var xmlItemColors = GetChildNodesByTagName(xmlItem, 'colors')[0];
			if (!xmlItemColors)
				alert('Xml Error: unable to find colors node');	
			// Titles
			for (var nIndex = 0; nIndex < this.Colors.length; nIndex++)
			{
				var xmlColor = GetElementByAttribute(xmlColors, 'id', this.Colors[nIndex].sId);
				if (!xmlColor)
					alert('Xml Error: unable to find ' + this.Colors[nIndex].sId + ' color');
				this.Colors[nIndex].sTitle = GetTitle(xmlColor);
				this.Colors[nIndex].sImageBig = GetItemImageBig(GetItemImages(xmlColor), 0);
				if (!this.bUseMulticolor)
				{
					if (nIndex > 0)
						alert('Cookie Error: invalid selection');					 
					var xmlColorGroup = GetElementByAttribute(GetChildNodesByTagName(xmlItemColors, 'colorgroup'), 'id', this.Colors[nIndex].sGroupId);
					this.sColorPricePercent = GetAttribute(xmlColorGroup, 'priceper');
					this.sColorPriceAdditional = GetAttribute(xmlColorGroup, 'price');					
				}
			}
			if (this.bUseMulticolor)
			{
				this.sColorPricePercent = GetAttribute(xmlItemColors, 'multipriceper');
				this.sColorPriceAdditional = '';
			}
		}
	}
	function CCartItem_Compare(CartItem)
	{
		var bEquals = this.sId == CartItem.sId;
		bEquals &= this.sSizeGroupId == CartItem.sSizeGroupId;
		bEquals &= this.sSizeId == CartItem.sSizeId;
		bEquals &= this.bUseMulticolor == CartItem.bUseMulticolor;
		bEquals &= this.bInstall == CartItem.bInstall;
		bEquals &= this.Colors.length == CartItem.Colors.length;
		if (bEquals)
			for (var nIndex = 0; nIndex < this.Colors.length; nIndex++)
			{
				bEquals &= this.Colors[nIndex].sId == CartItem.Colors[nIndex].sId;
				bEquals &= this.Colors[nIndex].sGroupId == CartItem.Colors[nIndex].sGroupId;
			}
		return bEquals;		
	}
	
////////////////////////////////////
// CCartItemArray

function CCartItemArray()
{
// Variables
	this.CartItems = new Array();

// Methods
	this.GetAsString = CCartItemArray_GetAsString;
	this.Update = CCartItemArray_Update;
	this.UpdateXmlData = CCartItemArray_UpdateXmlData;
	this.Apply = CCartItemArray_Apply;
	this.Find = CCartItemArray_Find;
	this.Add = CCartItemArray_Add;
	this.Remove = CCartItemArray_Remove;
	this.RemoveAll = CCartItemArray_RemoveAll;
	this.GetTotalPrice = CCartItemArray_GetTotalPrice;
}
// Implementation
	function CCartItemArray_GetAsString() 
	{
		var sItems = '';
		for (var nIndex = 0; nIndex < this.CartItems.length; nIndex++)
			sItems += this.CartItems[nIndex].GetAsString();
		return sItems;
	}
	function CCartItemArray_Update()
	{
		this.CartItems = new Array();
		var sItems = GetCookie('items');
		if (sItems && sItems.length > 0)
		{
			var Items = sItems.split(':');
			for (var nIndex = 0; nIndex < Items.length; nIndex++)
			{
				if (Items[nIndex].length <= 0)
					continue;
				var CartItem = new CCartItem();
				CartItem.LoadFromString(Items[nIndex]);
				this.CartItems[this.CartItems.length] = CartItem;
			}
		}
	}
	function CCartItemArray_Length(array)
	{
		return (array && array.length) ? array.length : 0;
	}
	function CCartItemArray_Test(xmlDoc)
	{	
		var xmlColors = GetChildNodesByTagName(xmlDoc, 'colors');
		var xmlItems = GetChildNodesByTagName(xmlDoc, 'items');
		var xmlAdvertisement = GetChildNodesByTagName(xmlDoc, 'advertisement');
		var xmlCategories = GetChildNodesByTagName(xmlDoc, 'categories');
		alert(
			"xmlColors: " + xmlColors + " (" + CCartItemArray_Length(xmlColors) + ")\n" + 
			"xmlItems: " + xmlItems + " (" + CCartItemArray_Length(xmlItems) + ")\n" + 
			"xmlAdvertisement: " + xmlAdvertisement + " (" + CCartItemArray_Length(xmlAdvertisement) + ")\n" +
			"xmlCategories: " + xmlCategories + " (" + CCartItemArray_Length(xmlCategories) + ")\n"
			);
		xmlColors = xmlDoc.getElementsByTagName('colors');
		xmlItems = xmlDoc.getElementsByTagName('items');
		xmlAdvertisement = xmlDoc.getElementsByTagName('advertisement');
		xmlCategories = xmlDoc.getElementsByTagName('categories');
		alert(
			"xmlColors: " + xmlColors + " (" + CCartItemArray_Length(xmlColors) + ")\n" + 
			"xmlItems: " + xmlItems + " (" + CCartItemArray_Length(xmlItems) + ")\n" + 
			"xmlAdvertisement: " + xmlAdvertisement + " (" + CCartItemArray_Length(xmlAdvertisement) + ")\n" +
			"xmlCategories: " + xmlCategories + " (" + CCartItemArray_Length(xmlCategories) + ")\n"
			);
	}
	function CCartItemArray_UpdateXmlData(xmlDoc)
	{
		//CCartItemArray_Test(xmlDoc);
		var xmlColors = GetChildNodesByTagName(GetChildNodesByTagName(xmlDoc, 'colors')[0], 'color');
		var xmlItems = GetChildNodesByTagName(GetChildNodesByTagName(xmlDoc, 'items')[0], 'item');
		for (var nIndex = 0; nIndex < this.CartItems.length; nIndex++)
			this.CartItems[nIndex].UpdateXmlData(xmlColors, xmlItems);
	}
	function CCartItemArray_Apply()		
	{
		SetCookie('items', this.GetAsString());
	}
	function CCartItemArray_Find(CartItem)
	{
		for (var nIndex = 0; nIndex < this.CartItems.length; nIndex++)
			if (this.CartItems[nIndex].Compare(CartItem))
			{
				var Result = new Array;
				Result[0] = nIndex;
				Result[1] = this.CartItems[nIndex];
				return Result;
			}
		return null;			
	}
	function CCartItemArray_Add(sId, sSizeGroupId, sSizeId, Colors, bUseMulticolor, bInstall)
	{
		var CartItem = new CCartItem(sId, sSizeGroupId, sSizeId, Colors, bUseMulticolor, bInstall);
		var FindResult = this.Find(CartItem);
		if (FindResult)
		{
			FindResult[1].nCount++;
			return;
		}
		this.CartItems[this.CartItems.length] = CartItem;
	}
	function CCartItemArray_Remove(CartItem)
	{
		var FindResult = this.Find(CartItem);
		if (!FindResult)
		{
			alert('Unable to remove item.');
			return;
		}
		this.CartItems.splice(FindResult[0], 1);	
	}
	function CCartItemArray_RemoveAll()
	{
		this.CartItems = new Array();
	}
	function CCartItemArray_GetTotalPrice()
	{
		var fPrice = 0.0;
		for (var nIndex = 0; nIndex < this.CartItems.length; nIndex++)
			fPrice += this.CartItems[nIndex].GetTotalPrice();
		return RoundFloat(fPrice);
	}
	
var g_CartItemArray = new CCartItemArray();
g_CartItemArray.Update();

function UpdateTopCartPrice()
{
	var PriceElement = document.getElementById('topcartprice');
	PriceElement.innerHTML = '';
	if (g_CartItemArray.CartItems.length)
		PriceElement.innerHTML = g_CartItemArray.GetTotalPrice() + ' ' + GetCurrencyString();
}

////////////////////////////////////
// HTML

function GetElementById(ItemElement, sId)
{
	if (ItemElement.id == sId)
		return ItemElement;
	for (var nIndex = 0; nIndex < ItemElement.childNodes.length; nIndex++)
	{
		var Element = GetElementById(ItemElement.childNodes[nIndex], sId);
		if (Element)
			return Element;
	}
	return null;
}

function CalculateCartTotalPrice()
{
	var fPrice = 0.0;
	for (var nIndex = 0; nIndex < g_CartItemArray.CartItems.length; nIndex++)
		fPrice += g_CartItemArray.CartItems[nIndex].GetTotalPrice();
	var TotalPriceElement = document.getElementById('totalprice');
	TotalPriceElement.innerHTML = fPrice.toFixed(2) + ' ' + GetCurrencyString();
}

function AddCartItemImage(RootElement, CartItem)
{
	var Element = document.createElement('td');
	SetElementClass(Element, 'korzina_photo');
	var AElement = document.createElement('a');
	AElement.setAttribute('href', GetZoomImageHref(CartItem.sImageBig));
	var ResizedImage = new CResizedImage(g_HiddenImagesElement, AElement, 50, 90, CartItem.sImageThumbnail, null);
	Element.appendChild(AElement);
	RootElement.appendChild(Element);
}

function GetDescriptionPrice(sPricePercent, sPriceAdditional)
{
	var sSize = '';
	if (sPricePercent.length)
		sSize += ' +' + sPricePercent + '%';
	if (sPriceAdditional.length)
	{
		if (sPricePercent.length)
			sSize += ',';
		sSize += ' +' + sPriceAdditional + ' ' + GetCurrencyString();
	}
	return sSize;
}

function AddCartItemDescription(RootElement, CartItem)
{
	var Element = document.createElement('td');
	SetElementClass(Element, 'korzina_nazv');
	// Title
	var sTitle = CartItem.sTitle;
	var TitleAElement = document.createElement('a');
	TitleAElement.setAttribute('href', GetItemHref(CartItem.sId));
	var TitleBElement = document.createElement('b');
	if (CartItem.sPrice)
		sTitle += ' ' + CartItem.sPrice + ' ' + GetCurrencyString();
	AddHtmlFormatedText(TitleBElement, sTitle);
	//TitleBElement.appendChild(document.createTextNode(sTitle));		
	TitleAElement.appendChild(TitleBElement);
	Element.appendChild(TitleAElement);
	Element.appendChild(document.createElement('br'));
	// Size
	if (CartItem.sSizeGroupTitle.length) 
	{		
		var sSize = CartItem.sSizeGroupTitle;
		if (CartItem.sSizeTitle.length)
			sSize += ', ' + CartItem.sSizeTitle;
		sSize += GetDescriptionPrice(CartItem.sSizePricePercent, CartItem.sSizePriceAdditional);
		Element.appendChild(document.createTextNode(sSize));
		Element.appendChild(document.createElement('br'));
	}
	// Color
	if (CartItem.Colors.length)
	{
		Element.appendChild(document.createTextNode(GetColorString()));
		for (var nIndex = 0; nIndex < CartItem.Colors.length; nIndex++)
		{
			var ColorAElement = document.createElement('a');
			ColorAElement.setAttribute('href', GetZoomImageHref(CartItem.Colors[nIndex].sImageBig));
			var ColorUElement = document.createElement('u');
			ColorUElement.appendChild(document.createTextNode(CartItem.Colors[nIndex].sTitle));
			ColorAElement.appendChild(ColorUElement);
			Element.appendChild(ColorAElement);
			if (nIndex < CartItem.Colors.length - 1)
				Element.appendChild(document.createTextNode(', '));
		}
		Element.appendChild(document.createTextNode(GetDescriptionPrice(CartItem.sColorPricePercent, CartItem.sColorPriceAdditional)));
		Element.appendChild(document.createElement('br'));
	}
	// Install
	if (CartItem.sInstallPrice)
		Element.appendChild(document.createTextNode(GetInstallString() + ' +' + CartItem.sInstallPrice + ' ' + GetCurrencyString()));
	RootElement.appendChild(Element);
}

function AddCartItemPrice(RootElement, CartItem)
{
	var Element = document.createElement('td');
	SetElementClass(Element, 'korzina_cena');
	Element.appendChild(document.createTextNode(CartItem.GetItemPrice().toFixed(2) + ' ' + GetCurrencyString()));
	RootElement.appendChild(Element);
}

var sNumber = '0123456789';
function Quantity_KeyDown(event)
{
	var nCharCode = -1;
	if (event && event.which) 
	{
		// Firefox, Opera
		nCharCode = event.which
     } else
     { 
		// Internet Explorer
		if (window && window.event && window.event.keyCode)
			nCharCode = window.event.keyCode;
     }
     // FIX: Convert numpade keys to numbers in firefox and internet explorer
     if (nCharCode >= 96 && nCharCode <= 106)
		nCharCode = nCharCode - 96 + 48;
     if (nCharCode < 0)
		return false;
	var sCharCode = String.fromCharCode(nCharCode);
	if (nCharCode != 8 && sNumber.search(sCharCode) < 0)
		return false;
}

function Quantity_KeyUp()
{
	var sCount = this.value;
	if (sCount.length <= 0)
		sCount = '0';
	this.CartItem.nCount = parseInt(sCount);
	this.TotalElement.innerHTML = this.CartItem.GetTotalPrice().toFixed(2) + ' ' + GetCurrencyString();
	CalculateCartTotalPrice();
	g_CartItemArray.Apply();
}

// NOTE: This function is blank, and used only to prevent current location change when selecting href
function RemoveFunction()
{
}

function RemoveElement(ElementToRemove)
{
	if (ElementToRemove.removeNode)
	{
		// Internet Explorer
		ElementToRemove.removeNode(true);
		return;
	}
	// Firefox
	while (ElementToRemove.hasChildNodes())
		RemoveElement(ElementToRemove.lastChild)
	ElementToRemove.parentNode.removeChild(ElementToRemove);
}

function OnRemoveClicked()
{
	RemoveElement(this.RootElement);
	g_CartItemArray.Remove(this.CartItem);
	g_CartItemArray.Apply();
	CalculateCartTotalPrice();	
}

function RemoveAll()
{
	g_CartItemArray.RemoveAll();
	g_CartItemArray.Apply();
	ContinueShopping();
}

function AddCartQuantityAndTotalPrice(RootElement, CartItem, bAllowCountChanging)
{
	var TotalElement = document.createElement('td');
	SetElementClass(TotalElement, 'korzina_sum');
	TotalElement.innerHTML = CartItem.GetTotalPrice().toFixed(2) + ' ' + GetCurrencyString();
	var QuantityElement = document.createElement('td');
	SetElementClass(QuantityElement, 'korzina_kol');
	if (bAllowCountChanging)
	{
		// <input type=text size=3 maxlength=2 name="QUANTITY" value="1" class="quan"><br />
		var InputElement = document.createElement('input');
		InputElement.setAttribute('type', 'text');
		InputElement.setAttribute('size', '3');
		InputElement.setAttribute('maxlength', '3');
		InputElement.setAttribute('value', CartItem.nCount);
		SetElementClass(InputElement, 'quan');
		InputElement.CartItem = CartItem;
		InputElement.TotalElement = TotalElement;
		InputElement.onkeydown = Quantity_KeyDown;
		InputElement.onkeyup = Quantity_KeyUp;
		QuantityElement.appendChild(InputElement);
		QuantityElement.appendChild(document.createElement('br'));
		// <a href="">dzēst</a>
		var ARemoveElement = document.createElement('a');
		ARemoveElement.appendChild(document.createTextNode(GetRemoveString()));
		ARemoveElement.setAttribute('href', 'javascript:RemoveFunction()');
		ARemoveElement.RootElement = RootElement;
		ARemoveElement.CartItem = CartItem;
		ARemoveElement.onclick = OnRemoveClicked;
		QuantityElement.appendChild(ARemoveElement);
	} else
	{
		var CountBElement = document.createElement('b');
		CountBElement.appendChild(document.createTextNode(CartItem.nCount));
		QuantityElement.appendChild(CountBElement);
	}	
	RootElement.appendChild(QuantityElement);
	RootElement.appendChild(TotalElement);
}

function CreateCartItemElement(CartItem, bAllowCountChanging)
{
	var ItemElement = document.createElement("tr");
	AddCartItemImage(ItemElement, CartItem);
	AddCartItemDescription(ItemElement, CartItem);
	AddCartItemPrice(ItemElement, CartItem);
	AddCartQuantityAndTotalPrice(ItemElement, CartItem, bAllowCountChanging);
	return ItemElement;
}

function FillCartTable(bAllowCountChanging)
{
	var RootElement = document.getElementById('cartitems');
	var ElementToInsertBefore = document.getElementById('ElementToInsertBefore');
	for (var nIndex = 0; nIndex < g_CartItemArray.CartItems.length; nIndex++)
	{
		var CartItem = g_CartItemArray.CartItems[nIndex];
		RootElement.insertBefore(CreateCartItemElement(CartItem, bAllowCountChanging), ElementToInsertBefore);
	}
	CalculateCartTotalPrice();
}

function ContinueShopping()
{
	var MapItemArray = GetMapItemArray(g_categoriesXmlDoc, g_itemsXmlDoc);
	var sHref = 'index.html';
	for (var nIndex = MapItemArray.length - 1; nIndex >= 0; nIndex--)
	{
		if (!MapItemArray[nIndex].bCanBack)
			continue;
		sHref = MapItemArray[nIndex].sHref;
		break;
	}
	window.location.href = sHref;
}
