/**
						Copyright 2007 Matthew Campbell
							  All rights reserved
		Redistribution and use in source or binary form, with or
		without modification is strictly prohibited
**/

// Site specific variables
var sitename = 'LaTierraBella';	// Name of the cookie to save our cart
var fullname = 'La Tierra Bella';	// Name displayed in PayPal
var siteurl = 'http://www.latierrabella.com'; // My home
var paypalacct = 'tierra.bella@hotmail.com';  // Money target account
var paypalurl = 'https://www.paypal.com/cgi-bin/webscr'; // PayPal target
var imageurl = 'www/images/TierraBellalogoSm.jpg'; // PayPal logo 150x50
var taxrate = 0.075;			// Yavapai county tax rate
var shiprate = 9.00;			// Flat rate shipping and handling fee
var maxproducts = 50;			// Maximum number of products in cart

// General global variables, no need to change these
var num_items = 0;				// Number of products in the cart
var itemlist = new Array(maxproducts);
initProductlist(itemlist);		// product(item, price, desc, quant, url)
var temp_array = new Array(maxproducts);
initProductlist(temp_array);	// product(item, price, desc, quant, url)

function initProductlist(a) {
	for (var i=0; i<maxproducts; i++) {
		a[i] = new product('', 0, '', 0, '')
	}
}

function product(item, price, desc, quant, url) {
	this.item = item;
	this.price = price;
	this.desc = desc;
	this.quant = quant;
	this.url = url;

	return this;
}

function getCookieVal(offset) {
	var endstr = document.cookie.indexOf(";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return decodeURIComponent(document.cookie.substring(offset, endstr));
}

// Fix Mac date bug
function fixCookieDate(date) {
	var base = new Date(0);
	var skew = base.getTime();
	if (skew > 0) date.setTime(date.getTime() - skew);
}

function getCookie(name) {
	var cname = name + "=";
	var nlen = cname.length;
	var cook = document.cookie;
	var clen = cook.length;
	var pos = 0;
	while (pos < clen) {
		var data = pos + nlen;
		if (cook.substring(pos, data) == cname) {
			return getCookieVal(data);
		}
		pos = cook.indexOf(" ", pos) + 1;
		if (pos == 0) break;
	}
	return null;
}

function oneDay() {
	var expires = new Date();
	fixCookieDate(expires);
	expires.setTime(expires.getTime() + (24 * 60 * 60 * 1000));
	return expires;
}

function oneMonth() {
	var expires = new Date();
	fixCookieDate(expires);
	expires.setTime(expires.getTime() + (30 * 24 * 60 * 60 * 1000));
	return expires;
}

function oneYear() {
	var expires = new Date();
	fixCookieDate(expires);
	expires.setTime(expires.getTime() + (365 * 24 * 60 * 60 * 1000));
	return expires;
}

function setCookie(name, value, expires, path, domain, secure) {
	if (!expires) expires = new Date();		// Expire at end of session
	document.cookie = name + "=" + encodeURIComponent(value) +
		"; expires=" + expires.toGMTString() +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure=" + secure : "");
}

function delCookie(name) {		// Expire this cookie immediately
	var expireNow = new Date();
	document.cookie =
		name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/";
}

function padDollar(num) {
	if (! num && num != 0)
		add2Log("Bad argument passed to padDollar(num): '" + num + "'");
	// Strip any leading dollar sign
	a = new String(num);
	if (a.charAt(0) == '$') {
		a = a.substr(1);
		num = a.toString();
	}

	// pad the value with any missing cents
	var dot = a.indexOf('.');
	var len = num.toString().length;
	if (dot < 0) return num + '.00';
	var off = parseInt(len) - parseInt(dot) - 1;
	if (off == 0) return num + '00';
	if (off == 1) return num + '0';
	if (off == 2) return num;

	// round decimals off to two digits
	a = new String(parseFloat(num) + 0.00499);
	return a.substr(0, dot + 3).toString();
}

function totalcost() {
	var order_total = 0;
	if (num_items > 0)
		for (var i=0; i<num_items; i++)
			order_total += eval((itemlist[i].price * itemlist[i].quant));
	return padDollar(order_total);
}

function clearzeros(inputlist) {
	var j=0;
	for (var i=0; i<num_items; i++) {
		if (itemlist[i].quant > 0) temp_array[j++] = itemlist[i];
	}
	itemlist = temp_array;
	num_items = j;
}

function search(item) {
	for (var i=0; i<num_items; i++) {
		if (itemlist[i].item == item) return i;
	}
	return -1;
}

function quantity(item) {
	var loc = search(item);
	if (loc > 0) return itemlist[loc].quant;
	return 0;
}

function additem(item, price, desc, url) {
	loadcart();			// Get our current cart
	loc = search(item);
	if (loc < 0) { 		// Create a new item
		if (num_items == maxproducts) {
			alert("The maximum number of products this cart holds has been exceeded, please check out and start a new cart.");
			return;
		}
		itemlist[num_items] = new product(item, price, desc, 1, url);
		num_items++;
	} else { 			// We're updating an existing item
		// Jewelry items are unique
		if ((itemlist[loc].desc.match(/^Necklace/) ||
				itemlist[loc].desc.match(/^Earring/)) &&
				itemlist[loc].quant > 0) return;
		itemlist[loc].quant++;
	}
	savecart();			// Save our changes
	update_content_screen();
	update_shopping_cart();
}

function clearitem(itemno) {
	loadcart();			// Get our current cart
	if (itemno < 0 || itemno >= num_items) return;

	var j=0;
	for (var i=0; i<num_items; i++) {
		if (i != itemno) temp_array[j++] = itemlist[i];
	}
	itemlist = temp_array;
	num_items--;

	savecart();			// Save our changes
	update_content_screen();
	update_shopping_cart();
}

function decitem(item, price, desc) {
	loadcart();			// Get our current cart
	loc = search(item);
	if (loc >= 0) { 		// We're updating an existing item
		itemlist[loc].quant--;
	}
	//clearzeros(itemlist);
	savecart();			// Save our changes
	update_content_screen();
	update_shopping_cart();
}

function encodeURLspaces(text) { return replace(text, /\s/g, '%20'); }
function encodecommas(text) { return replace(text, /,/g, '&cma;'); }
function decodecommas(text) { return replace(text, /&cma;/g, ','); }

function replace(text, regex, replace) {
	if (typeof text == 'object' && text.constructor == String) {
		return text.replace(regex, replace);
	} else {
		var a = new String(text);
		return a.replace(regex, replace).toString();
	}
}

function clearcart() {
	num_items = 0;
	savecart();			// Save our changes
	update_content_screen();
	update_shopping_cart();
}

function loadcart() { 	// Load in our current cart from the cookie
	var value = getCookie(sitename);
	if (value == null || value == '') {
		num_items = 0;
		return;
	}
	var values = value.split(',');
	num_items = values.length / 5;
	var count=0;
	for (var i=0; i<num_items; i++) {
		itemlist[i] = new product('', 0, '', 0, '')
		itemlist[i].item = decodecommas(values[count++]);
		itemlist[i].price = decodecommas(values[count++]);
		itemlist[i].desc = decodecommas(values[count++]);
		itemlist[i].quant = decodecommas(values[count++]);
		itemlist[i].url = decodecommas(values[count++]);
	}
}

function savecart() { 	// Save our updated cart to the cookie
	// Assume there are no commas in item names or descriptions
	var value = '';
	for (var i=0; i<num_items; i++) {
		if (i > 0) value += ',';
		value += encodecommas(itemlist[i].item) + ',' +
			encodecommas(itemlist[i].price) + ',' +
			encodecommas(itemlist[i].desc) + ',' +
			encodecommas(itemlist[i].quant) + ',' +
			encodecommas(itemlist[i].url);
	}
	//add2Log("Saving " + num_items + " items.");
	setCookie(sitename, value, oneYear());
	//add2Log("cookie set to (" + value + ")");
}

function setText(frame, name, text) {
	var doc = top.frames[frame].document;
	var field = (doc.all) ? doc.all(name) : doc.getElementById(name);
	// if (! (field = top.frames[frame].document.getElementById(name))) {
	if (! field) {
		alert("Error: Field '" + name + "' not found in the document");
		return -1;
	}
	if (field.childNodes.length > 1) {
		alert("Error: Field '" + name + "' has more than one child");
		return -1;
	}
	if (field.firstChild.nodeType != 3) {
		alert("Error: Field '" + name + "' is not a text field");
		return -1;
	}
	field.firstChild.nodeValue = text;
}

function initialize_content_screen() {
	loadcart();			// Get our current cart
	update_content_screen();	// Redraw our dynamic items
}

function swap_array_member(list, num1, num2) {
	var temp = list[num2];
	list[num2] = list[num1];
	list[num1] = temp;
}

function sort_array(list, field, left, right) {
	if (left >= right) return;		// We need at least two items to sort
	for (var i=left+1; i<=right; i++) {
		if (list[i][field].localeCompare(list[left][field]) < 0)
			swap_array_member(list, left, i);
	}
	sort_array(list, field, left+1, right);
}

function discount_framed_pics(list, num) {
	var q = 0;
	for (var i=0; i<num; i++)
		if (list[i].desc.match(/^Flower Pic P\d*$/))
			q += parseInt(list[i].quant);

	for (var i=0; i<num; i++)
		if (list[i].desc.match(/^Flower Pic P\d*$/))
			if (q >= 3) list[i].price = padDollar(25);
			else list[i].price = padDollar(30);
}

function update_content_screen() {
	// Sort the shopping list
	sort_array(itemlist, 'desc', 0, num_items-1);
	// Update total cost widget
	discount_framed_pics(itemlist, num_items);
	setText('contentsFrame', 'listcost', '$' + totalcost());

	// Update shopping list widget
	var text = '';
	for (var i=0; i<num_items; i++) {
		text += itemlist[i].quant + ' ' + itemlist[i].desc + "\n";
	}
	top.contentsFrame.document.list.cart.value = text;
}

// Update the shopping cart screen
function modify_cart(btn, quant, evnt) {
	var item = btn.value;

	if (quant == 'clear') {		// Remove the item
		clearitem(item);
	} else {   					// Modify the item's quantity
		itemlist[item].quant =
			parseInt(itemlist[item].quant) + parseInt(quant);
		if (itemlist[item].quant < 0) itemlist[item].quant = 0;
		// Jewelry items are unique
		if ((itemlist[item].desc.match(/^Necklace/) ||
				itemlist[item].desc.match(/^Earring/))
				&& itemlist[item].quant > 1)
			itemlist[item].quant = 1;
	}
	// Update item prices
	discount_framed_pics(itemlist, num_items);

	// Update the contents pane and cart page
	savecart();			// Save our changes
	update_content_screen();
	update_shopping_cart();
}

// Generate the shopping cart table HTML
function update_shopping_cart() {
	// Change our page header
	loadHeadImage('home');

	// Find our table if it exists
	var doc = top.body.document;
	if (! (table = (doc.all) ? doc.all.shoppingcarttable :
		doc.getElementById('shoppingcarttable'))) return;

	// Clear out all the old table data
	// Deleting the table is easier than trying to modify cells in place.
	var body = table.tBodies[0];
	while (table.rows.length > 1) { table.deleteRow(1); } 
	// doc.getElementById('theshoppingcart').innerHTML = '';

	// Add a horizontal rule as a table divider
	row = table.insertRow(-1);
	row.height = 3;
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));
	cell.colSpan = 4;
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));

	// The bulk of the cart chart
	var row;
	var cell;
	for (var i=0; i<num_items; i++) {
		row = table.insertRow(-1);

		// Clear button
		cell = row.insertCell(row.cells.length);
		var button = doc.createElement('button');
		button.value = i;
		addEvent(button, 'click',
			function(evt) { modify_cart(this, 'clear', evt); } );
		button.appendChild(doc.createTextNode('Clear'));
		cell.appendChild(button);

		// Decrement Quantity button
		cell = row.insertCell(row.cells.length);
		var button = doc.createElement('button');
		button.value = i;
		addEvent(button, 'click',
			function(evt) { modify_cart(this, '-1', evt); } );
		button.appendChild(doc.createTextNode('-'));
		cell.appendChild(button);

		// Increment Quantity button
		cell = row.insertCell(row.cells.length);
		var button = doc.createElement('button');
		button.value = i;
		addEvent(button, 'click',
			function(evt) { modify_cart(this, '1', evt); } );
		button.appendChild(doc.createTextNode('+'));
		cell.appendChild(button);

		// Quantity column
		cell = row.insertCell(row.cells.length);
		cell.appendChild(doc.createTextNode(itemlist[i].quant));
		cell.align = 'right';
		cell.style.paddingRight = '10px';

		// Description column
		cell = row.insertCell(row.cells.length);
		cell.appendChild(doc.createTextNode(itemlist[i].desc));
		cell.style.paddingLeft = '10px';

		// Item Price
		cell = row.insertCell(row.cells.length);
		cell.appendChild(doc.createTextNode('$' + itemlist[i].price));
		cell.align = 'right';
		cell.style.paddingRight = '10px';

		// Item Total
		cell = row.insertCell(row.cells.length);
		cell.appendChild(doc.createTextNode('$' +
			itemlist[i].price * itemlist[i].quant + '.00'));
		cell.align = 'right';
		cell.style.paddingRight = '10px';
	}

	// Add a horizontal rule as a table divider
	row = table.insertRow(-1);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));
	cell.colSpan = 5;
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createElement('hr'));

	// Add the subtotal row
	row = table.insertRow(-1);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('Subtotal:'));
	cell.colSpan = 6;
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	var total = totalcost();
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('$' + total));
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	// Add the tax row
	row = table.insertRow(-1);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('Yavapai County Sales Tax*:'));
	cell.colSpan = 6;
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	var tax = padDollar(total * taxrate);
	total = parseFloat(total) + parseFloat(tax);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('$' + tax));
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	// Add the shipping & Handling row
	row = table.insertRow(-1);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('Shipping and Handling**:'));
	cell.colSpan = 6;
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	total = parseFloat(total) + parseFloat(shiprate);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('$' + padDollar(shiprate)));
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	// Add the total row
	row = table.insertRow(-1);
	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('Total:'));
	cell.colSpan = 6;
	cell.align = 'right';
	cell.style.paddingRight = '10px';

	cell = row.insertCell(row.cells.length);
	cell.appendChild(doc.createTextNode('$' + padDollar(total)));
	cell.align = 'right';
	cell.style.paddingRight = '10px';
}

// Post the shopping cart to PayPal to generate an invoice
function sendcart() {
	// Generate the paypal transaction information:
	var html = '<!DOCTYPE HTML PUBLIC ' +
		'"-//W3C//DTD HTML 4.01 Frameset//EN" ' +
		'"http://www.w3.org/TR/html4/frameset.dtd">\n' +
		'<html>\n' +
		'<head>\n' +
		'<title>La Tierra Bella</title>\n' +
		'</head>\n' +
		'<body>\n' +
		'<br class="vspace50">\n' +
		'<br class="vspace50">\n' +
		'<center>Please Confirm your total and hit the "Submit" button</center>' +
		'<br class="vspace50">\n' +
		'<center>\n' +
		num_items + ' items, $' + (parseInt(totalcost()) + parseFloat(shiprate)) + '\n' +
		'<form method="post" target="paypal" name="paypal_form" ' +
			'action="' + paypalurl + '">\n' +
		'<br class="vspace50">\n' +
		'<button type="submit">Submit Order</button>\n' +
		'<input type="hidden" name="business" ' +
			'value="' + paypalacct + '">\n' +
		'<input type="hidden" name="cmd" value="_cart">\n' +
		'<input type="hidden" name="upload" value="1">\n' +

		'<input type="hidden" name="image_url" ' +
			'value="' + siteurl + '/' + imageurl + '">\n' +
		'<input type="hidden" name="return" ' +
			'value="' + siteurl + '/www/PayPalSuccess">\n' +
		'<input type="hidden" name="cancel_return" ' +
			'value="' + siteurl + '/www/PayPalCancel">\n' +
		'<input type="hidden" name="notify_url" ' +
			'value="' + siteurl + '/www/PayPalNotify">\n' +
		'<input type="hidden" name="rm" value="1">\n' +
		'<input type="hidden" name="cbt" ' +
			'value="Return to ' + fullname + '">\n' +

		'<input type="hidden" name="no_note" value="">\n' +
		'<input type="hidden" name="cn" value="Thanks!">\n' +
		'<input type="hidden" name="cs" value="1">\n' +
		'';

	for (var i=0; i<num_items; i++) {
		var num = parseInt(i) + 1;
		html += '<input type="hidden" name="item_name_' + num + '" ' +
				'value="' + itemlist[i].desc + '">\n' +
			'<input type="hidden" name="quantity_' + num + '" ' +
				'value="' + itemlist[i].quant + '">\n' +
			'<input type="hidden" name="amount_' + num + '" ' +
				'value="' + itemlist[i].price + '">\n';
	}

	html += '<input type="hidden" name="shipping" value="$' + shiprate +
		'">\n' +
	'</form>\n' +
	'</center>\n' +
	'</body>\n' +
	'</html>\n';

	top.body.document.write(html);
}

