// HandPaintedFabrics scripting for sales pages
// mod 1/9/12 cna: add jumbo fabric size, improved pricing display


// 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;
}

// Build pricing info for an available piece size
function listPrice(msg, size, sell, cost, w, h, yards) {
	if (sell > 0) {
		fabWeight(yards);
		for (var n = sell; n > 1; --n) {
            m =  "" + n + " " + size + "s (" + w + "x" + h + " in.) $" + (cost * n).toFixed(2);
            msg.push(m);
			os0.appendChild(makeElement("option", ["value", "" + n + size], m));
			selections.push({ value: "" + n + size, price: cost * n, yardage: n * yards });
		}
		selections.push({ value: size, price: cost, yardage: yards });
        m = size + " (" + w + "x" + h + " in.) $" + cost.toFixed(2);
		os0.appendChild(makeElement("option", ["value", size], m));
        msg.push(m);
	}
}

// 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() {
    if (selections[os0.selectedIndex].yardage > 0)
	    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();
}

// This validates that the user has selected a fabric size, then submits if they have
function validateSubmit() {
    if (selections[os0.selectedIndex].yardage == 0)
    {
        alert('Please select the size of fabric you want, and then click Add To Cart again.');
        return false;
    }
    else
        return true;
}


// 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*([fhqipj]+)(;.*)?/;

	// Default prices for non-irregular pieces
    var priceJumbo = 65.00;
	var priceFull = 34.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 sellJumbo = 0;
		var irregular = false;

		if (fabricPieces.indexOf("i") >= 0) {
			irregular = true;
			sellFull = countOf(fabricPieces, "i");
		} else {
            sellJumbo = countOf(fabricPieces, "j");
            if (sellJumbo > 0) {
                sellFull = 1;
                sellHalves = 1;
                sellQuarters = 1;
            } 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 + ")";
            h2text.parentNode.appendChild(makeElement("span", ["style", "font-style: italic; font-weight: normal"],
                                                      "  - Please scroll down for prices and ordering"));
		}
		
		// 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.";
		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();
        var pricingInfo = makeElement("p", ["align", "center", "style", "font: 12.0px Chalkboard; color: #083233"]);
        frag.appendChild(pricingInfo);
	    var form = frag.appendChild(makeElement("form", ["target", "_self", "name", "buyform",
												 "action", "https://www.paypal.com/cgi-bin/webscr", 
                                                 "onsubmit", "return validateSubmit()",
												 "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();
        selections.push({ value: "Click here to select", price: 0, yardage: 0});
        os0.appendChild(makeElement("option", ["value", "none"], "Click here to select"));
        var info = new Array();
        if (irregular) {
            listPrice(info, "1 piece", 1, priceFull, fabricWidth, fabricHeight, 1);
        } else {
            listPrice(info, "Jumbo piece", sellJumbo, priceJumbo, fabricWidth, fabricHeight, 2);
            if (sellJumbo)
                fabricHeight /= 2;
            listPrice(info, "Large piece", sellFull, priceFull, fabricWidth, fabricHeight, 1);
            listPrice(info, "Medium piece", sellHalves, priceHalf, fabricWidth, fabricHeight/2, .5);
            listPrice(info, "Small piece", sellQuarters, priceQuarter, fabricWidth/2, fabricHeight/2, .25);
		}
        for (var i = info.length - 1; i >= 0; --i) {
            pricingInfo.appendChild(document.createTextNode(info[i]));
            if (i)
                pricingInfo.appendChild(makeElement("br"));
        }
		td.appendChild(os0);
		td = makeElement("td");
		td.appendChild(makeElement("input", ["name", "trysubmit", "type", "image",
											 "src", "https://www.paypal.com/en_US/i/btn/btn_cart_LG.gif",
											 "border", "0",
											 "alt", "(Add to Cart)"]));
		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);
		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));

		//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);
}

