/*
 *  This code is largely for all parts of the ordering process.
 */


/*
 * Jump to one of the ordering pages
 */
HandMadeBasin.jumpTo = function(whichOne) {
	
	if (!whichOne) return;
	
	var form = gebi('pageForm');
	var np   = gebi('form_nextPage');
	
	// also alter the cookies
	HandMadeBasin.formToCookies();
	
	np.value = whichOne;
	form.submit();
	return null;
}


/*
 *  Code to use when choosing an item
 *
 *	@param itemPath  full path of item in product tree
 *	@param min   minimum number of choices of items in this category
 *	@param max   maximum number of choices of items in this category
 *	@param total maximum number of this type of choice that can be added to a 
 *		product
 */
HandMadeBasin.choose = function(itemPath, min, max, total, obj) {
	
	// get the characteristics of the basin being defined
	var basinSpec = HandMadeBasin.getOrderSpec();
	
	// chop the itemPath into pieces
	var itemPathParts = itemPath.split(/\//);
	
	// get the current contents of the field
	// strip off product group prependage from itemPath
	var group = itemPathParts.shift();
	var groupChoices = basinSpec[group];
	if (!groupChoices) {
		throw (itemPath + ' is an unknown product group');
	}
	itemPath = itemPathParts.join('/');
	
	// if item is already in list, remove it
	var
			switchedOff = false, // whether we've removed an option from the list
			p,                   // utility variable
			tmp = new Array()    // storage for the filtered options
	;
	while (groupChoices.length > 0) {
		p = groupChoices.shift();
		if (p != itemPath) {
			tmp.push(p);
			HandMadeBasin.markChosen(group + '/' + p, true);
		} else {
			// we removed an existing item from the list...
			switchedOff = true;
			HandMadeBasin.markChosen(group + '/' + p, false);
		}
	}
	groupChoices = tmp;
	
	// if the option was removed, then store the changed option list and exit
	if (switchedOff) {
		basinSpec[group] = groupChoices;
		HandMadeBasin.putOrderSpec(basinSpec);
		return;
	}
	
	// drop end off if limit reached
	while (groupChoices.length >= max) {
		p = groupChoices.shift();
		HandMadeBasin.markChosen(group + '/' + p, false);
	}
	
	// add new item
	groupChoices.push(itemPath);
	HandMadeBasin.markChosen(group + '/' + itemPath, true);
	
	// restore the field value
	basinSpec[group] = groupChoices;
	HandMadeBasin.putOrderSpec(basinSpec);

}/**/


/*
 *  Put the values from a specification object  (as returned from
 *	getOrderSpec())into the page's fields.
 *
 *	@param spec the specification to load into the page's fields
 */
HandMadeBasin.putOrderSpec = function(spec) {
	var specVal, field, sinkParts = HandMadeBasin.sinkParts;
	for (var i = 0; i < sinkParts.length; i++) {
		specVal = spec[sinkParts[i]];
		field = gebi(HandMadeBasin.formOrderPrefix + sinkParts[i]);
		if (specVal && field) {
			field.value = specVal.join(';');
		}
	}
}


/*
 *	
 *	@return the characteristics of the current basin as a hash of arrays.
 */
HandMadeBasin.getOrderSpec = function() {
	var obj = {}, definition, id;
	for (var i = 0; i < HandMadeBasin.sinkParts.length; i++) {
		
		// get the id
		id =
				(HandMadeBasin.formOrderPrefix +
				HandMadeBasin.sinkParts[i]).replace(/\//g, '_')
		;
		
		// get the field value for the part (e.g. unit)
		definition = gebi(id);
		if (!definition) throw ("Unknown field '" + id + "'");
		definition = definition.value;
		if (definition && definition != '')
			definition = definition.split(/;/);
		else
			definition = [];
		obj[HandMadeBasin.sinkParts[i]] = definition;
	}
	return obj;
}


/**
 *	Remove an item from the cart
 */
HandMadeBasin.removeCartItem = function(itemIndex) {
	
	// get the cart spec as an array of cart item specs (strings)
	
	if (!confirm("Really remove this item from the cart?")) return;
	var cart = gebi('cartContents');
	var cartSpec = cart.value.split(/#/);
	
	var newSpec = [];
	
	for (var i = 0; i < cartSpec.length; i++)
		if (i != itemIndex) newSpec.push(cartSpec[i]);
	
	cart.value = newSpec.join('#');
	
	HandMadeBasin.jumpTo('viewCart');
}


/**
 * For the named characteristic, highlight the chosen options.
 */
HandMadeBasin.outlineChosen = function(charc) {
	
	// ch is an object holding the characteristics of the current basin
	var ch = HandMadeBasin.getOrderSpec();
	
	if (ch) {
		// get the parts making up the characteristic
		var components = ch[charc];
		if (components && components.length > 0)
			for (var i = 0; i < components.length; i++)
				HandMadeBasin.markChosen(charc + '_' + components[i], true);
	} else {
		throw('getting basin characteristic\'' + charc + '\' failed');
	}
}


HandMadeBasin.markChosen = function(path, status) {
	
	path = path.replace(/\//g, '_');
	path = path.replace(/:.*$/, '');
	var o = gebi(HandMadeBasin.choiceItemPrefix + path);
	if (!o) {throw 'Don\'t know item ' + path;}
	o = o.style;
	if (status) {
		o.backgroundColor = '#bbccff';
		o.borderColor     = '#0000ff';
	} else {
		o.backgroundColor = 'transparent';
		o.borderColor     = '#ffffff';
	}
	
}


HandMadeBasin.generateBasinSpecHtml = function(sections, choices, docroot) {
	var
			// caches to HTML to write out to the page
			output = [],
			
			// max amount of current spec item allowed, as dictated by previous one
			macks
	;
	
	output.push("<h2>Basin Specification</h2>\n");
	
	for (var i = 0; i < HandMadeBasin.sinkParts.length; i++) {
	
		// display heading for section
		output.push("\n<h3>", HandMadeBasin.sinkParts[i], '</h3>');
		
		/*
		 * do section choices
		 */
		
		// no choice made for this section
		if (choices[i].length == 0) {
			output.push("<p><em>No selection made</em></p>");
			continue;
		}
		
		// go through each choice in turn
		for (var j = 0; j < choices[i].length; j++) {
			
			output.push(
				
				// table init
				"<table class='selection'><tr>",
				
				// component image
				"<td class='img' rowspan='2'>",
				"<img src='", docroot, "images/Products/",
				choices[i][j].picFile,
				"' alt='", choices[i][j].textshort , "'></td>",
				
				// description
				"<td class='desc'>", choices[i][j].textlong, "</td>",
				
				// Quantity
				"</tr><tr><td class='qty'>Quantity "
			);
			
			/*
			 * quantity field
			 */
			var
					tot = sections[i]     ,
					min = tot.minChoices  , // minimum amount of this kind of component
					max = tot.maxChoices  , // maximum amount of this kind of component
					tot = tot.totalChoices  // maximum number of candidates for choices
																	//   of this component
			;
			
			// start field HTML
			output.push(
					"<input type='text' ",
					"name='", HandMadeBasin.sinkParts[i], "_", j, "' ",
					"id='",   HandMadeBasin.sinkParts[i], "_", j, "' ",
					"size='2'"
			);
			
			// if min == max, user *must* have this number
			if (min == max) {
				output.push("value='", min, "' disabled");
			} else {
				// QUESTION: does default amount want to be 1 or min? 1
				output.push("value='", 1, "' ");
			}
			
			// end of table
			output.push("></td></tr></table>");
		}
	}
	
	return output.join('');
}


HandMadeBasin.order = function() {
	var frm = gebi('doTheOrder');
	if (frm) frm.submit();
	return true;
}


HandMadeBasin.getCartContents = function() {
	
	var contents = [];
	
	// get cart as individual items
	var cart = gebi('cartContents').value;
	if (cart == '') return '';
	cart = cart.split(/#/);
	
	// do each item
	for (var i = 0; i < cart.length; i++) {
		
		// get cart item as parts
		var cartItem = cart[i];
		var name;
		var ci = {};
		
		// turn string into name/value pairs
		cartItem = cartItem.split(/[=;]/);
		while (name = cartItem.shift()) {
			ci[name] = cartItem.shift();
			if (!ci[name]) { // handle IE5 lameness <rolls eyes>
				ci[name] = '';
				break;
			} else {
				ci[name] = ci[name].replace(/,/g, ', ');
			}
		}
		
		if (name = gebi('price'    + i)) ci['price'   ] = name.value;
		if (name = gebi('delivery' + i)) ci['delivery'] = name.value;
		
		contents[i] = ci;
	}
	
	return contents;
}


// these are the required details in emails
HandMadeBasin.emailDetails = [
		{
				'id'  : 'givenName',
				'text': 'Given Name',
				'regx': '.+',
				'type': 'input'
		},
		
		{
				'id'  : 'familyName',
				'text': 'Family Name',
				'regx': '.+',
				'type': 'input'
		},
		
		{
				'id'  : 'street',
				'text': 'First line of address',
				'regx': '.+',
				'type': 'input'
		},
		
		{
				'id'  : 'city',
				'text': 'City (or nearest city/town)',
				'regx' : '.+',
				'type': 'input'
		},
		
		{
				'id'  : 'postcode',
				'text': 'Post code',
				'regx': '^[a-zA-Z]{1,2}\\\\d{1,2}\\\\s*([a-zA-Z]{1,2}\\\\d{1,2})?$',
				'type': 'input'
		},
		
		{
				'id'  : 'email',
				'text': 'Your email address',
				'regx': '^[a-zA-Z][\\\\w\\\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\\\w\\\\.-]*[a-zA-Z0-9]\\\\.[a-zA-Z][a-zA-Z\\\\.]*[a-zA-Z]$',
				'type': 'input'
		},
		
		{
				'id'  : 'comment',
				'text': 'Comments',
				'regx': '.*',
				'type': 'area'
		}
];


HandMadeBasin.getDetailsHtml = function(cartContents) {
	
	var output = [];
	
	for (var i = 0; i < HandMadeBasin.emailDetails.length; i++) {
		
		// heading of detail
		output.push('<tr><th>', HandMadeBasin.emailDetails[i].text, '</th><td>');
		
		// form control of detail
		if (HandMadeBasin.emailDetails[i].type == 'input') {
			output.push(
					'<input type="text" onblur=\'HandMadeBasin.validateRe(this, "', 
					HandMadeBasin.emailDetails[i].regx,
					'")\' ', 
					'name="email_',
					HandMadeBasin.emailDetails[i].id,
					'" id="email_', 
					HandMadeBasin.emailDetails[i].id,
					'">'
			);
		} else if (HandMadeBasin.emailDetails[i].type == 'area') {
			output.push(
					'<textarea onblur=\'HandMadeBasin.validateRe(this, "', 
					HandMadeBasin.emailDetails[i].regx,
					'")\' ', 
					'name="email_',
					HandMadeBasin.emailDetails[i].id,
					'" id="email_', 
					HandMadeBasin.emailDetails[i].id,
					'"></textarea>'
			);
		}
		
		// end of table row
		output.push('</td></tr>');
	}
	
	// invisible stuff
	var inner = [];
	for (var i = 0; i < cartContents.length; i++) {
		output.push('<input type="hidden" name="basin_', i, '" value="');
		
		for (var j = 0; j < HandMadeBasin.sinkParts.length; j++) {
			inner.push(cartContents[i][HandMadeBasin.sinkParts[j]]);
		}
		output.push(inner.join(','));
		
		output.push('">');
	}
	
	return output.join('');
}


HandMadeBasin.validateRe = function(obj, regexString) {
	var re = regexString;
	// if (!confirm(re)) throw 'STOPPED';
	re = new RegExp(re);
	if (re.test(obj.value)) {
		obj.style.backgroundColor = '#ffffff';
		return true;
	} else {
		obj.style.backgroundColor = '#ffcccc';
		return false;
	}
}


HandMadeBasin.createPaypalForm = function(cartContents) {
	
	var output = [];
	
	// LIVE:    https://www.paypal.com/cgi-bin/webscr
	// SANDBOX: https://www.sandbox.paypal.com/cgi-bin/webscr
	output.push(
			'<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="doTheOrder">',
			'<input type="hidden" name="cmd" value="_cart">',
			'<input type="hidden" name="business" value="order@handmadebasin.co.uk">',
			'<input type="hidden" name="currency_code" value="GBP">',
			'<input type="hidden" name="return" value="http://www.handmadebasin.co.uk/cgi-bin/pageserve.pl?page=order1">',
			'<input type="hidden" name="cancel_return" value="http://www.handmadebasin.co.uk/cgi-bin/pageserve.pl?page=viewCart">',
			'<input type="hidden" name="upload" value="1">'
	);
	
	// do each item
	for (var i = 0; i < cartContents.length; i++) {
		var ppIndex = i + 1;
		
		output.push(
				'<input type="hidden" name="item_name_', ppIndex, '" value="'          , cartContents[i]['unit']    , '">',
				'<input type="hidden" name="amount_'   , ppIndex, '" value="'          , gebi('price_' + i).value   , '">',
				'<input type="hidden" name="shipping_' , ppIndex, '" value="'          , gebi('delivery_' + i).value, '">',
				'<input type="hidden" name="on0_'      , ppIndex, '" value="Glaze">'                                      ,
				'<input type="hidden" name="os0_'      , ppIndex, '" value="'          , cartContents[i]['glaze']   , '">',
				'<input type="hidden" name="on1_'      , ppIndex, '" value="Stencils">'                                   ,
				'<input type="hidden" name="os1_'      , ppIndex, '" value="'          , cartContents[i]['stencil'] , '">'
		);
	}
	
	output.push('</form>');
	
	return output.join('');
}

/* SIMPLE:
	output.push(
			'<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="doTheOrder">',
			'<input type="hidden" name="cmd" value="_xclick">',
			'<input type="hidden" name="business" value="order@handmadebasin.co.uk">',
			'<input type="hidden" name="currency_code" value="GBP">',
			'<input type="hidden" name="item_name" value="', gebi('cartContents').value, '">',
			'<input type="hidden" name="amount" value="', gebi('cartPrice').value, '">',
			'</form>'
	);
*/

