// HandPaintedFabrics scripting for sales pages
//


// Make an html node with some attributes, and possibly a text child.
// Attributed elements in IE-land require flaming hoops due
// to the broken DOM, so deal with that here.
function makeElement(type, attrList, text) {
	var e = null;
	var i = 0;
	var setAttrs = false;
	var html;
	if (attrList != null) {
		html = "<" + type;
		for (var i = 0; i < attrList.length; i += 2) {
			html += " " + attrList[i] + '="' + attrList[i + 1] + '"';
		}
		html += '>';
		try {
			e = document.createElement(html);
		} catch (err) { }
		if (e && e.nodeName == type.toUpperCase()) {
			setAttrs = true;
		}
	}
	if (e == null)
		e = document.createElement(type);
	if (!setAttrs && attrList != null) {
		for (var i = 0; i < attrList.length; i += 2) {
			e.setAttribute(attrList[i], attrList[i + 1]);
		}
	}
	if (text != null) {
		var t = document.createTextNode(text);
		e.appendChild(t);
	}
	return e;
}

// Find the first non-empty text node beneath the specified node
function firstTextNodeUnder(node) {
	for (i = 0; i < node.childNodes.length; ++i) {
		if (node.childNodes[i].nodeType == 3 &&
			node.childNodes[i].nodeValue.length > 0)
			return node.childNodes[i];
		if (node.childNodes[i].hasChildNodes()) {
			var below = firstTextNodeUnder(node.childNodes[i]);
			if (below != null)
				return below;
		}
	}
	return null;
}

// Count the instances of a character in a string
function countOf(s, c) {
	var k = 0;
	es = s.split("");
	for (var i = 0; i < es.length; ++i) {
		if (es[i] == c)
			++k;
	}
	return k;
}

// Weight has to be set by event handlers when selecting from pull-down.
var poundsPerYard = .4375;
var weightElement;
var weightSet = false;
var selections;
var os0;

function fabWeight(n) {
	var weight = poundsPerYard * n;
	var w = weight.toFixed(2);
	if (weight < 1)
		w = "0" + w;
	weightElement.setAttribute("value", w);
	weightSet = true;
}

function fabChoice() {
	fabWeight(selections[os0.selectedIndex].yardage);
}

// This is here so that the raw shopping cart jump page in Sandvox won't go bonkers
function shoppingCart() {
	document.shoppingcart.submit();
}

// Transform a suitably formed caption on the page into the correct content.
function doPricingIfAppropriate() {

	// Look for relevant caption page elements to edit with sales info.

	var mainContent = document.getElementById("main-content");
	var divs = mainContent.getElementsByTagName("div");
	var caption = null;

	for (var i = 0; i < divs.length; ++i) {
		if (divs[i].className == "caption") {
			var caparas = divs[i].getElementsByTagName("p");
			if (caparas.length > 0)
				caption = caparas[0].firstChild;
		}
	}

	// Stop here if page has no appropriate caption
	if (caption == null) {
		//console.log('no caption found');
		return;
	}

	var fabricPattern = /(.+)=\s*(\d+)\s*x\s*(\d+)\s*([fhqip]+)(;.*)?/;

	// Default prices for non-irregular pieces
	var priceFull = 36.00;
	var priceHalf = 18.00;
	var priceQuarter = 9.00;
	var priceIrregSqIn = .0202;

	// For first caption, if it exists and matches magic pattern
	if (caption.nodeValue.match(fabricPattern)) {
		var fabricName = RegExp.$1;
		var fabricWidth = RegExp.$2;
		var fabricHeight = RegExp.$3;
		var fabricPieces = RegExp.$4;
		var fabricMessage = RegExp.$5;

		// Figure out what we are selling
		var sellFull = 0;
		var sellHalves = 0;
		var sellQuarters = 0;
		var irregular = false;
		if (fabricPieces.indexOf("i") >= 0) {
			irregular = true;
			sellFull = countOf(fabricPieces, "i");
		} else {
			sellFull = countOf(fabricPieces, "f");
			if (sellFull > 0) {
				sellHalves = 1;
				sellQuarters = 1;
			} else {
				sellHalves = countOf(fabricPieces, "h");
				if (sellHalves > 0)
					sellQuarters = 1;
				else 
					sellQuarters = countOf(fabricPieces, "q");
			}
		} 
		
		// Make sure the message includes no starting semicolon and is a string
		if (fabricMessage != null && fabricMessage.length > 1)
			fabricMessage = fabricMessage.slice(1);
		else
			fabricMessage = "";

		// Adjust full price if irregular
		if (irregular) {
			var p = fabricWidth * fabricHeight * priceIrregSqIn;
			if (p - Math.floor(p) <= .50)
				priceFull = Math.floor(p) + .50;
			else
				priceFull = Math.ceil(p);
		}

		// Replace title
		document.title = "Fabric for Sale (" + fabricName + ") | HandPaintedFabrics";
		
		// Replace inner page heading. Find h2 in main content area for this.
		var h2s = mainContent.getElementsByTagName("h2");
		if (h2s.length > 0 && h2s[0].firstChild.nodeName == "SPAN") {
			var h2text = firstTextNodeUnder(h2s[0].firstChild);
			h2text.nodeValue = "Fabric for Sale (" + fabricName + ")";
		}
		
		// Create fabric description string
		var fabricDesc = "Please note: This image represents a 12 x 16 inch section. Patterns vary somewhat from section to section with most of the same colors shown here. Please use the pull-down below to see available sizes and quantity.";
		if (fabricPieces.indexOf("p") >= 0)
			fabricDesc = "This piece contains some pearlescent paint. " + fabricDesc;
		
		// Build form with description, pull-down menu, and paypal shopping cart linkage
		var frag = document.createDocumentFragment();
		frag.appendChild(makeElement("p", ["align", "center", "style", "font: 14.0px Chalkboard; color: #083233;"], fabricDesc));
		if (fabricMessage.length > 0)
			frag.appendChild(makeElement("p", ["align", "center", "style", "font: 14.0px Chalkboard; color: #083233;"], fabricMessage));
	    var form = frag.appendChild(makeElement("form", ["target", "_self", "name", "buyform",
												 "action", "https://www.paypal.com/cgi-bin/webscr", 
												 "method", "post"]));
		form = form.appendChild(makeElement("p", ["align", "center"]));
		form.appendChild(makeElement("input", ["name", "cmd", "type", "hidden", "value", "_cart"]));
		form.appendChild(makeElement("input", ["name", "business", "type", "hidden", "value", "paykim@kebrown.com"]));
		form.appendChild(makeElement("input", ["name", "image_url", "type", "hidden", "value", "http://www.handpaintedfabric.com/images/pplogo.jpg"]));
		form.appendChild(makeElement("input", ["name", "lc", "type", "hidden", "value", "US"]));
		form.appendChild(makeElement("input", ["name", "item_name", "type", "hidden", "value", "Fabric " + fabricName]));
		//form.appendChild(makeElement("input", ["name", "item_number", "type", "hidden", "value", "0"]));
		form.appendChild(makeElement("input", ["name", "button_subtype", "type", "hidden", "value", "products"]));
		form.appendChild(makeElement("input", ["name", "currency_code", "type", "hidden", "value", "USD"]));
		form.appendChild(makeElement("input", ["name", "shopping_url", "type", "hidden", "value", location.href]));
		form.appendChild(makeElement("input", ["name", "add", "type", "hidden", "value", "1"]));
		form.appendChild(makeElement("input", ["name", "paymentaction", "type", "hidden", "value", "authorization"]));
		//form.appendChild(makeElement("input", ["name", "undefined_quantity", "type", "hidden", "type", "hidden", "value", "1"]));
		form.appendChild(makeElement("input", ["name", "on0", "type", "hidden", "value", "Quantity and Size"])); 
		weightElement = makeElement("input", ["name", "weight", "type", "hidden", "value", ""]);
		////form.appendChild(weightElement);

		os0 = makeElement("select", [ "name", "os0", "onchange", "fabChoice()" ]);
		var table = makeElement("table");
		var tbody = table.appendChild(makeElement("tbody"));
		var tr = makeElement("tr");
		tbody.appendChild(tr);
		var td = makeElement("td");
		tr.appendChild(td);
		selections = new Array();
		if (sellFull > 0) {
			var size = "Large piece";
			if (irregular)
				size = "1 piece";
			selections.push({ value: size, price: priceFull, yardage: 1 });
			fabWeight(1);
			os0.appendChild(makeElement("option", ["value", size], size + " (" + fabricWidth + "x" + fabricHeight + " in.) $" + priceFull.toFixed(2)));
			for (var n = 2; n <= sellFull; ++n) {
				os0.appendChild(makeElement("option", ["value", "" + n + size], "" + n + " pieces (" + fabricWidth + "x" + fabricHeight + " in.) $" + (priceFull * n).toFixed(2)));
				selections.push({ value: "" + n + size, price: priceFull * n, yardage: n });
			}
		}
		if (sellHalves > 0) {
			selections.push({ value: "Medium", price: priceHalf, yardage: .5 });
			if (!weightSet)
				fabWeight(.5);
			os0.appendChild(makeElement("option", ["value", "Medium"], "Medium piece (" + fabricWidth + "x" + fabricHeight/2 + " in.) $" + priceHalf.toFixed(2)));
			for (var n = 2; n <= sellHalves; ++n) {
				os0.appendChild(makeElement("option", ["value", "" + n + " Medium pieces"], "" + n + " Medium pieces (" + fabricWidth + "x" + fabricHeight/2 + " in.) $" + (priceHalf * n).toFixed(2)));
				selections.push({ value: "" + n + " Medium pieces", price: priceHalf * n, yardage: .5 * n });
			}
		}
		if (sellQuarters > 0) {
			selections.push({ value: "Small piece", price: priceQuarter, yardage: .25 });
			if (!weightSet)
				fabWeight(.25);
			os0.appendChild(makeElement("option", ["value", "Small piece"], "Small piece (" + fabricWidth/2 + "x" + fabricHeight/2 + " in.) $" + priceQuarter.toFixed(2)));
			for (var n = 2; n <= sellQuarters; ++n) {
				os0.appendChild(makeElement("option", ["value", "" + n + " Small pieces"], "" + n + " Small pieces (" + fabricWidth/2 + "x" + fabricHeight/2 + " in.) $" + (priceQuarter * n).toFixed(2)));
				selections.push({ value: "" + n + " Small pieces", price: priceQuarter * n, yardage: .25 * n });
			}
		}
		td.appendChild(os0);
		td = makeElement("td");
		td.appendChild(makeElement("input", ["name", "submit", "type", "image",
											 "src", "https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif",
											 "border", "0",
											 "alt", "PayPal - The safer, easier way to pay online!"]));
		tr.appendChild(td);

		for (var i = 0; i < selections.length; ++i) {
			form.appendChild(makeElement("input", ["name", "option_select" + i, "type", "hidden", "value", selections[i].value]));
			form.appendChild(makeElement("input", ["name", "option_amount" + i, "type", "hidden", "value", selections[i].price]));
		}
		form.appendChild(makeElement("input", ["name", "option_index", "type", "hidden", "value", "0"]));
		form.appendChild(table);
		//alert((new XMLSerializer()).serializeToString(frag));
		//show(frag);
		caption.parentNode.replaceChild(frag, caption);
    } else {
		console.log('no fabric information found');
	}
}

function testform() {
	var p = document.getElementsByTagName('p')[0];
	var frag = document.createDocumentFragment();
	frag.appendChild(makeElement("p", ["align", "center", "style", "font: 14.0px Chalkboard; color: #083233;"], 'Hello'));
	var form = frag.appendChild(makeElement("form", ["target", "_self", 
											 "action", "https://www.paypal.com/cgi-bin/webscr", 
													 "method", "post"]));
	form = form.appendChild(makeElement("p", ["align", "center"]));


	var s = makeElement("select", [ "name", "os0" ]);
	s.appendChild(makeElement("option", ["value", "Small piece"], "small piece"));
	s.appendChild(makeElement("option", ["value", "Big piece"], "big piece"));
	var table = makeElement("table");
	var tr = makeElement("tr");
	table.appendChild(tr);
	var td = makeElement("td", "foo");
	tr.appendChild(td);
	td.appendChild(s);

	form.appendChild(table);
	p.parentNode.replaceChild(frag, p);
}
