/**
 * Product Object
 *
 * @author Chris Sheail
 * @package Zelley
 * @copyright 2005 LBB Internet Limited
 * @version 1.0.0
 */

/**
 * Constructor
 * @access public
 * @param object productData
 * @return object
 */
function Product(productData)
{
	this.base = '/';
	this.allData = productData;
	this.data = new Object();
	this.caratFrom = 0;
	this.caratTo = 0;

	/**
	 * Load the product
	 * @access public
	 * @param string ref
	 * @return bool
	 */
	this.load = function(ref)
	{
		if (!this.allData[ref]) { return false;}

		this.data = this.allData[ref];

		this.setElements();
		this.setPrice();

		return true;
	}

	/**
	 * Set up the page elements for the product
	 * @access private
	 * @return void
	 */
	this.setElements = function()
	{
		// Product text
		//document.getElementById('productRef').firstChild.nodeValue = this.data['ref'];
		document.getElementById('productDetails').firstChild.nodeValue = this.data['details'];
		document.getElementById('productPrice').firstChild.nodeValue = this.data['price'];
		
		// Image
		//var imgBox = document.getElementById('productImage');
		//imgBox.setAttribute('src', this.data['image2']);
		var imgBox = document.getElementById('productImageBox');
		imgBox.style.backgroundImage = 'url("'+this.data['image2']+'")';
		
		
		var thisAlt = 'Zelley - ' + this.data['catname'] + ' - ' + this.data['name'] + ' (' + this.data['ref'] + ')';
		
		imgBox.setAttribute('alt', thisAlt);
		//imgBox.setAttribute('alt', this.data['ref']);		
		
		imgBox.setAttribute('title', thisAlt);
		//imgBox.setAttribute('title', this.data['ref']);
		
		//imgBox.setAttribute('width', '350');
		//imgBox.setAttribute('height', '272');

		// Show certain buttons
		document.getElementById('enlargeButton').style.display = (this.data['image3']) ? '' : 'none';
		document.getElementById('wornButton').style.display = (this.data['image4']) ? '' : 'none';
		document.getElementById('sideButton').style.display = (this.data['image5']) ? '' : 'none';
		document.getElementById('dimensionsButton').style.display = (this.data['dimensions']) ? '' : 'none';

		document.getElementById('certificateButton').style.display = 'none';

		document.getElementById('diamondFilter').style.display = (this.data['cut'] == 'Princess') ? 'none' : '';

		document.getElementById('fingerSizeBox').style.display = (this.data['fingerSize']) ? '' : 'none';

		//removed <input id="moreCharmsButton" ... /> from template 13.08.07 (ab/kb)
		//this.showMoreCharmsButton();

		// Metal Options
		var metalBox = document.getElementById('metalBox');
		metalBox.style.display = 'none';

		if (this.countProps(this.data['metals']) > 0)
		{
			var drop = document.getElementById('metalSelector');
			this.clear(drop);

			for (var i in this.data['metals'])
			{
				var option = document.createElement('option');
				option.setAttribute('value', i);
				var name = document.createTextNode(i);
				option.appendChild(name);
				drop.appendChild(option);
			}

			metalBox.style.display = '';
		}

		// Diamond Options
		var diamondBox = document.getElementById('diamondBox');
		diamondBox.style.display = 'none';
		
		if (this.data['diamond'])
		{
			var drop = document.getElementById('caratSelector');
			this.clear(drop);

			var option = document.createElement('option');
			option.setAttribute('value', '');
			var name = document.createTextNode('(Any)');
			option.appendChild(name);
			drop.appendChild(option);

			// Size Options
			if (this.countProps(this.data['sizes']) > 0)
			{				
				this.caratFrom = 0;
				this.caratTo = 0;
				for (var i in this.data['sizes'])
				{
					if (this.caratFrom == 0)
					{
						this.caratFrom = this.data['sizes'][i]['from'];
					}
					this.caratTo = this.data['sizes'][i]['to'];

					var option = document.createElement('option');
					option.setAttribute('value', i);
					var name = document.createTextNode(this.data['sizes'][i]['name']);
					option.appendChild(name);
					drop.appendChild(option);
				}
			}

			// Colour Options - already on page
			// Clarity Options - already on page

			// Diamond Stock List
			this.getDiamondList();

			diamondBox.style.display = '';
		}

		// Matching products
		this.showMatching(this.data['ref']);

		// Buy With products
		this.showBuyWith(this.data['ref']);

		// Size Option products
		this.showSizeOptions(this.data['ref']);
	}

	/**
	 * Show the matching products
	 * @access public
	 * @param string ref
	 * @return void
	 */
	this.showMatching = function(ref)
	{
		for (var i in this.allData)
		{
			if (related = document.getElementById('relatedProducts'+this.allData[i]['id']))
			{
				related.style.display = 'none';
			}
		}
		if (related = document.getElementById('relatedProducts'+this.allData[ref]['id']))
		{
			related.style.display = '';
		}
	}

	/**
	 * Show the buy with products
	 * @access public
	 * @param string ref
	 * @return void
	 */
	this.showBuyWith = function(ref)
	{
		for (var i in this.allData)
		{
			if (buyWith = document.getElementById('buyWithProducts'+this.allData[i]['id']))
			{
				buyWith.style.display = 'none';
			}
		}
		if (buyWith = document.getElementById('buyWithProducts'+this.allData[ref]['id']))
		{
			buyWith.style.display = '';
		}

		// Reset the selected option
		this.selectDiamond('', '');
	}

	/**
	 * Show the size option products
	 * @access public
	 * @param string ref
	 * @return void
	 */
	this.showSizeOptions = function(ref)
	{
		for (var i in this.allData)
		{
			if (related = document.getElementById('sizeOptionProducts'+this.allData[i]['id']))
			{
				related.style.display = 'none';
			}
		}
		if (related = document.getElementById('sizeOptionProducts'+this.allData[ref]['id']))
		{
			related.style.display = '';
		}
	}

	/**
	 * Get the diamond stock list
	 * @access public
	 * @return void
	 */
	this.getDiamondList = function(refresh)
	{
		if (!this.data['diamond']) { return ;}

		var cut = this.data['cut'];
		var carat = document.getElementById('caratSelector');
		var carat = carat.options[carat.selectedIndex].value;
		var colour = document.getElementById('colourSelector');
		var colour = colour.options[colour.selectedIndex].value;
		var clarity = document.getElementById('claritySelector');
		var clarity = clarity.options[clarity.selectedIndex].value;

		if (!carat)
		{
			carat = this.caratFrom+'-'+this.caratTo;
		}
		else 
		{
			carat = this.data['sizes'][carat]['from']+'-'+this.data['sizes'][carat]['to'];
		}

		// Selected metal
		var met = document.getElementById('metalSelector');
		var metalType = met.options[met.selectedIndex].value;

		var url = this.base+'home/m/DiamondList/cut/'+cut+'/carat/'+carat+'/colour/'+colour+'/clarity/'+clarity+'/id/'+this.data['id']+'/metal/'+metalType+'/';

		if (refresh)
		{
			url += 'refresh/1/';
		}

		frames['diamondSelector'].location.href = url;

		// Reset the selected diamond
		//this.selectDiamond('', '');
	}

	/**
	 * Revise the price
	 * @access private
	 * @return void
	 */
	this.setPrice = function()
	{
		var name = this.data['ref']+' - '+this.data['name'];
		var showName = name;
		var showMetal = '';
		var diamond = '';
		var price = this.data['price'];

		var f = document.getElementById('shopForm');

		// Calculate the price
		if (this.countProps(this.data['metals']) > 0)
		{
			box = document.getElementById('metalSelector');
			selected = box.options[box.selectedIndex].value;

			name = name+' ('+selected+')';
			showMetal = 'You have selected ('+selected+'). To change your metal choice select an alternative in the metal options.';
			price += this.data['metals'][selected];

			metalType = (selected == 'Platinum') ? 'plat' : 'gold';
		}

		if (this.countProps(this.data['sizes']) > 0)
		{
			var carat = f.orderDiamondCarat.value;
			for (var i in this.data['sizes'])
			{
				if (this.data['sizes'][i]['from'] <= carat && this.data['sizes'][i]['to'] >= carat)
				{
					price += this.data['sizes'][i][metalType];
					break;
				}
			}
		}		

		// Is an option (diamond) needed?
		if (this.data['diamond'] || this.data['buyWith'])
		{
			// Is an option (diamond) selected?
			if (!f.orderDiamondPrice.value)
			{
				price = '';
			}
			else
			{
				diamond = f.orderDiamond.value;
				price += Number(f.orderDiamondPrice.value);
			}
		}

		// Clear the retail price
		document.getElementById('retailPrice').firstChild.nodeValue = ' ';

		// Show buy button?
		if (price > 0)
		{
			document.getElementById('buyButton').style.display = '';

			// Set the retail price
			var retail = 0;
			if (this.data['retailPrice'] > 0)
			{
				retail = this.data['retailPrice'];
			}
			else if (this.data['retailPercentage'] > 0)
			{
				retail = price * (1 + (this.data['retailPercentage'] / 100));
				//retail = Math.round(retail * 100) / 100;
				retail = 5 * Math.round(retail / 5);
			}

			if (retail > 0)
			{
				var saving = 0;
				saving = retail - price;

				var nrp = ' (NRP: \u00A3'+formatCurrency(retail);
				if (saving > 0)
				{
					nrp += ', a saving of \u00A3'+formatCurrency(saving);
				}
				nrp += ')';

				document.getElementById('retailPrice').firstChild.nodeValue = nrp;
			}

			price = formatCurrency(price);
		}
		else 
		{
			document.getElementById('buyButton').style.display = 'none';
			price = ' [please select an option below]';
		}

		// Set the hidden form fields
		f.orderRef.value = this.data['ref'];
		f.orderName.value = name;
		f.orderPrice.value = price;

		document.getElementById('certificateButton').style.display = 'none';

		if (diamond)
		{
			f.orderName.value += ' with '+diamond;
			diamond = ' with '+diamond;

			if (f.orderDiamondRef.value && f.orderDiamondRef.value != 'undefined')
			{
				document.getElementById('certificateButton').style.display = '';
			}
		}
		else 
		{
			f.orderDiamond.value = '';
			f.orderDiamondPrice.value = '';

			f.orderDiamondRef.value = '';
		}

		// Display on page
		document.getElementById('productName').firstChild.nodeValue = showName;
		document.getElementById('productMetal').firstChild.nodeValue = showMetal;
		document.getElementById('productDiamondName').firstChild.nodeValue = diamond;
		document.getElementById('productPrice').firstChild.nodeValue = price;
	}

	/**	
	 * Selects a diamond
	 * @access public
	 * @param float price
	 * @param string name
	 * @return void
	 */
	this.selectDiamond = function(price, name, carat, ref)
	{
		// Set the hidden form fields
		var f = document.getElementById('shopForm');
		f.orderDiamond.value = name;
		f.orderDiamondPrice.value = price;
		f.orderDiamondCarat.value = carat;
		f.orderDiamondRef.value = ref;

		// Update the price
		this.setPrice();		
	}

	/**	
	 * Opens the enlarged view window
	 * @access public
	 * @return void
	 */
	this.enlargeImage = function()
	{
		if (!this.data['image3']) {	return false;}

		var href = this.base+'home/m/LargeImage/id/'+this.data['id'];

		newWindow(href, '', this.data['image3']);
	}

	/**	
	 * Opens the being worn view window
	 * @access public
	 * @return void
	 */
	this.wornImage = function()
	{
		if (!this.data['image4']) {	return false;}

		var href = this.base+'home/m/WornImage/id/'+this.data['id'];

		newWindow(href, '', this.data['image4']);
	}

	/**	
	 * Opens the being side view window
	 * @access public
	 * @return void
	 */
	this.sideImage = function()
	{
		if (!this.data['image5']) {	return false;}

		var href = this.base+'home/m/SideImage/id/'+this.data['id'];

		newWindow(href, '', this.data['image5']);
	}

	/**	
	 * Shows the dimensions details
	 * @access public
	 * @return void
	 */
	this.showDimensions = function()
	{
		if (!this.data['dimensions']) {	return false;}

		var href = this.base+'home/m/ShowDimensions/id/'+this.data['id'];

		newWindow(href, '', 'width=250,height=250');
	}

	/**	
	 * Shows the certficate details
	 * @access public
	 * @return void
	 */
	this.showCertificate = function()
	{
		var id = document.getElementById('orderDiamondRef').value;
		if (!id) { return false;}

		var href = this.base+'home/m/ShowCertificate/id/'+id;

		newWindow(href, '', 'width=300,height=300');
	}

	/**	
	 * Add to order
	 * @access public
	 * @return bool
	 */
	this.addToOrder = function()
	{
		var c = new Cookies();
		var ref = document.getElementById('orderRef').value;
		var name = document.getElementById('orderName').value;
		var price = document.getElementById('orderPrice').value;

		if (this.data['fingerSize'])
		{
			var fSize = document.getElementById('fingerSizeSelector');
			name += ' ('+fSize.options[fSize.selectedIndex].value+')';
		}

		var toAdd = (c.data['toAdd']) ? c.data['toAdd'] : '';
		toAdd += '['+ref+'|'+name+'|'+price+']';
		c.set('toAdd', toAdd);

		alert(name+'\nHas been added to your order.\n\nWhen you are ready to complete your purchase please\nclick the \'Your Order\' link in the bar at the top of the page.');

		return false;
	}

	/**	
	 * Shows or hides the more charms button
	 * @access public
	 * @return void
	 */
	this.showMoreCharmsButton = function()
	{
		var butt = document.getElementById('moreCharmsButton');
		var show = false;

		if (catid == 13)
		{
			show = true;
			butt.value = 'Add More Earring Drops';
			butt.style.width = '125px';
		}
		else if (catid == 15)
		{
			show = true;
			butt.value = 'Add More Charms';
			butt.style.width = '100px';
		}

		butt.style.display = (show) ? '' : 'none';
	}

	/**	
	 * Redirects to the charms page
	 * @access public
	 * @return void
	 */
	this.moreCharms = function()
	{
		var url = '';
		if (catid == 13)	
		{
			url = this.base+'home/m/Shop/c/35/';
		}
		else if (catid == 15)
		{
			url = this.base+'home/m/Shop/c/33/';
		}

		if (!url) {	return false;}

		location.href = url;
	}

	/**	
	 * Counts the number of properties in an object
	 * @access private
	 * @param object obj
	 * @return int
	 */
	this.countProps = function(obj)
	{
		var count = 0;
		for (var i in obj)
		{
			count++;
		}
		return count;
	}

	/**	
	 * Clears all child nodes
	 * @access private
	 * @param object obj
	 * @return void
	 */
	this.clear = function(obj)
	{
		while (obj.hasChildNodes()) 
		{
			obj.removeChild(obj.firstChild);
		}		
	}
}


/**
 * Cookies Object
 * Caveats: expiry is the end of session, path is the doc root /
 *
 * @author Chris Sheail
 * @package Zelley
 * @copyright 2005 LBB Internet Limited
 * @version 1.0.0
 */

/**
 * Constructor
 * @access public
 * @return object
 */
function Cookies()
{
	this.data = new Object();

	/**
	 * Load the cookie data
	 * @access public
	 * @return bool
	 */
	var cookieString = '' + document.cookie;
	var cookieArray = cookieString.split('; ');

	for (var i = 0; i < cookieArray.length; ++ i)
	{
		var singleCookie = cookieArray[i].split('=');
		if (singleCookie.length != 2) {	continue;}

		var name  = unescape(singleCookie[0]);
		var value = unescape(singleCookie[1]);
		
		this.data[name] = value;
	}

	/**
	 * Sets a cookie
	 * @access public
	 * @param string $name
	 * @param string $value
	 * @return bool
	 */
	this.set = function(name, value)
	{
		this.data[name] = value;
		document.cookie = escape(name) + '=' + escape(value) + '; path=/';
		return true;
	}

	/**
	 * Removes a cookie
	 * @access public
	 * @param string $name
	 * @return bool
	 */
	this.remove = function(name)
	{
		// Build expiration date string
		var expirationDate = new Date();
		expirationDate.setYear(expirationDate.getYear() - 1);
		expirationDate = expirationDate.toGMTString();

		// Delete the cookie
		document.cookie = escape(name) + '=; expires=' + expirationDate;

		this.data[name] = '';

		return true;
	}

	/**
	 * Removes all cookies
	 * @access public
	 * @return bool
	 */
	this.removeAll = function()
	{
		for (var i in this.data)
		{
			this.remove(i);
		}

		return true;
	}

	/**
	 * Format cookie data into one string
	 * @access public
	 * @return string
	 */
	this.toString = function()
	{
		var str = '';

		for (var i in this.data)
		{
			str += i + '=' + this.data[i] + '\n';
		}

		return str;
	}
}
