function trimmed(mystring)
{
	return mystring.replace(/^\s+|\s+$/g,'');
}

function checkform(theform,alertmessage)
{
	var okform = true;
 	var i;
	for (i=0;i<theform.elements.length;++i)
	{
		if (theform.elements[i].name && !checkfield(theform.elements[i]))
		{
			okform = false;
		}

	}
	if (okform && theform.form_checked)
	{
		theform.form_checked.value = 'Yes';
	}
	if (theform.return_url)
	{
		theform.return_url.value = document.location;
	}
	if (alertmessage && !okform)
	{
		alert(alertmessage);
	}
	return okform;  
}


function checkfield(formfield)
{
	var ok = true;

	var formid = document.getElementById(formfield.name.replace(/\[\]/,''));

	var required = false;
	var email = false;
	if (formid)
	{
		var classes = formid.className.split(/\W+/);

		for (i=0;i<classes.length;++i)
		{
			if (classes[i].indexOf('required') == 0)
			{
				var class_original = classes[i];
				required = true; 
			}
			if (classes[i] == 'email' && formfield.type == 'text')
			{
				email = true;
			}
		}
		if (required)
		{
			var class_stem = class_original.substr(0,(class_original+'_').indexOf('_'));
			var class_new = class_original;
//alert(formfield.type);


			if (formfield.name != formid.id || formfield.type == 'radio')
			{
// Multiple fields radio/checkbox only 
				ok = false;

// Loop round to make sure one is checked
				for (i=0;i<formfield.form.elements.length;++i)
				{
					if (formfield.form.elements[i].name == formfield.name && formfield.form.elements[i].checked)
					{
						ok = true;
					}
				}

			} else { 
			if (formfield.type == 'text' || formfield.type == 'textarea')
			{
				if (trimmed(formfield.value) == '')
				{
					ok = false;  
				}
			}
			if (formfield.type == 'checkbox')
			{
				if (!formfield.checked)
				{
					ok = false;
				}
			}

			if (formfield.type == 'select-one')
			{
				if (formfield.options[formfield.selectedIndex].value == '')
				{
					ok = false;
				}
			}
			if (formfield.type == 'select-multiple')
			{
				ok = false;
				for (i=0;i<formfield.options.length;++i)
				{
					if (formfield.options[i].selected && formfield.options[i].value != '')
					{
						ok = true;
						break;
					}
				}
			}

			}
			if (ok)
			{
				class_new = class_stem+'_ok';
			} else {
				class_new = class_stem+'_error';
			}
			if (!email)
			{
			formid.className = formid.className.replace(class_original,class_new);
			}
		}
	}
	if (email && (required || trimmed(formfield.value) != ''))
	{
//alert('checking email');
		ok = emailCheck(formfield.value);
//alert(ok);
		if (required)
		{
			if (ok)
			{
				class_new = class_stem+'_ok';
			} else {
				class_new = class_stem+'_error';
			}
//alert(class_new);
//alert(class_original);
			formid.className = formid.className.replace(class_original,class_new);
//alert(formid.className);
		}
	}
	return ok;
}


function emailCheck (emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or
well-known TLD.  1 means check it, 0 means dont. */

	var checkTLD=1;

/* The following is the list of known TLDs that an e-mail
address must end with. */

	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered
e-mail address fits the user@domain format.  It also is used to separate
the username from the domain. */

	var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching
all special characters.  We dont want to allow special characters in
the address.  These characters include ( ) < > @ , ; : \ " . [ ] */

	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters
allowed in a  username or domainname.  It really states which chars arent
allowed.*/

	var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted
string (in which case, there are no rules about which characters are
allowed and which arent; anything goes).  E.g. "jiminy
cricket"@disney.com is a legal e-mail address. */

	var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP
addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a
legal e-mail address. NOTE: The square brackets are required. */

	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

	var atom=validChars + "+";

/* The following string represents one word in the typical
username. For example, in john.doe@somewhere.com, john and doe are
words. Basically, a word is either an atom or quoted string. */

	var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal
symbolic domain, as opposed to ipDomainPat, shown above. */

	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, lets start trying to figure out if the supplied
address is valid. */

/* Begin with the coarse pattern to simply break up
user@domain into different pieces that are easy to analyze. */

	var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {

/* Too many/few @s or something; basically, this address
doesnt even fit the general mould of a valid e-mail address. */

		alert("Email address "+emailStr+"  seems incorrect (check @ and .s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];

// Start by checking that only basic ASCII characters are in the strings (0-127).

	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Email address "+emailStr+"  seems incorrect (username contains invalid characters).");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Email address "+emailStr+"  seems incorrect (the domain name contains invalid characters).");
			return false;
		}
	}

// See if "user" is valid 

	if (user.match(userPat)==null) {

// user is not valid

		alert("Email address "+emailStr+"  seems incorrect (the username doesn't seem to be valid).");
		return false;
	}

/* if the e-mail address is at an IP address (as opposed to
a symbolic host name) make sure the IP address is valid. */

	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {

// this is an IP address

		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Email address "+emailStr+"  seems incorrect (destination IP address is invalid!)");
				return false;
			}
		}
	}
	return true;
}

sprintfWrapper = {
 
	init : function () {
 
		if (typeof arguments == "undefined") { return null; }
		if (arguments.length < 1) { return null; }
		if (typeof arguments[0] != "string") { return null; }
		if (typeof RegExp == "undefined") { return null; }
 
		var string = arguments[0];
		var exp = new RegExp(/(%([%]|(\-)?(\+|\x20)?(0)?(\d+)?(\.(\d)?)?([bcdfosxX])))/g);
		var matches = new Array();
		var strings = new Array();
		var convCount = 0;
		var stringPosStart = 0;
		var stringPosEnd = 0;
		var matchPosEnd = 0;
		var newString = '';
		var match = null;
 
		while (match = exp.exec(string)) {
			if (match[9]) { convCount += 1; }
 
			stringPosStart = matchPosEnd;
			stringPosEnd = exp.lastIndex - match[0].length;
			strings[strings.length] = string.substring(stringPosStart, stringPosEnd);
 
			matchPosEnd = exp.lastIndex;
			matches[matches.length] = {
				match: match[0],
				left: match[3] ? true : false,
				sign: match[4] || '',
				pad: match[5] || ' ',
				min: match[6] || 0,
				precision: match[8],
				code: match[9] || '%',
				negative: parseInt(arguments[convCount]) < 0 ? true : false,
				argument: String(arguments[convCount])
			};
		}
		strings[strings.length] = string.substring(matchPosEnd);
 
		if (matches.length == 0) { return string; }
		if ((arguments.length - 1) < convCount) { return null; }
 
		var code = null;
		var match = null;
		var i = null;
 
		for (i=0; i<matches.length; i++) {
 
			if (matches[i].code == '%') { substitution = '%' }
			else if (matches[i].code == 'b') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(2));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'c') {
				matches[i].argument = String(String.fromCharCode(parseInt(Math.abs(parseInt(matches[i].argument)))));
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'd') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'f') {
				matches[i].argument = String(Math.abs(parseFloat(matches[i].argument)).toFixed(matches[i].precision ? matches[i].precision : 6));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'o') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(8));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 's') {
				matches[i].argument = matches[i].argument.substring(0, matches[i].precision ? matches[i].precision : matches[i].argument.length)
				substitution = sprintfWrapper.convert(matches[i], true);
			}
			else if (matches[i].code == 'x') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]);
			}
			else if (matches[i].code == 'X') {
				matches[i].argument = String(Math.abs(parseInt(matches[i].argument)).toString(16));
				substitution = sprintfWrapper.convert(matches[i]).toUpperCase();
			}
			else {
				substitution = matches[i].match;
			}
 
			newString += strings[i];
			newString += substitution;
 
		}
		newString += strings[i];
 
		return newString;
 
	},
 
	convert : function(match, nosign){
		if (nosign) {
			match.sign = '';
		} else {
			match.sign = match.negative ? '-' : match.sign;
		}
		var l = match.min - match.argument.length + 1 - match.sign.length;
		var pad = new Array(l < 0 ? 0 : l).join(match.pad);
		if (!match.left) {
			if (match.pad == "0" || nosign) {
				return match.sign + pad + match.argument;
			} else {
				return pad + match.sign + match.argument;
			}
		} else {
			if (match.pad == "0" || nosign) {
				return match.sign + match.argument + pad.replace(/0/g, ' ');
			} else {
				return match.sign + match.argument + pad;
			}
		}
	}
}
 
sprintf = sprintfWrapper.init;

// PACKAGE FUNCTIONS - JUNE 2010
function bundle_show_total(thisform)
{
 var total_product_price = 0;
 var total_product_price_reduction = 0;
 var total_product_price_unbundled = 0;
 var total_vat = 0;
 var total_vat_reduction = 0;
 var total_vat_unbundled = 0;
 var total_product_rrp = 0;

 for (i=0;eachradio = thisform['member_prod_id_'+i];++i)
 {

  if (eachradio.length)
  {
	var thisradio = eachradio;
  } else { 
	var thisradio = new Array(eachradio);
  }
  for (j=0;j< thisradio.length;++j)
  {
  if (thisradio[j].checked)
  {
   total_product_price = sprintf("%0.2f",(1*total_product_price) + (1*thisform['member_product_price_'+i+'_'+j].value));
   total_product_price_reduction = sprintf("%0.2f",(1*total_product_price_reduction) + (1 * thisform['member_product_price_reduction_'+i+'_'+j].value));
   total_product_price_unbundled = sprintf("%0.2f",(1*total_product_price_unbundled) +  ( 1 * thisform['member_product_price_'+i+'_'+j].value) + (1*thisform['member_product_price_reduction_'+i+'_'+j].value));
   try {
   total_product_rrp =  sprintf("%0.2f",(1*total_product_rrp + (1 * thisform['member_product_rrp_'+i+'_'+j].value)));
   } catch (e) {}
   total_vat = sprintf("%0.2f",(1*total_vat) + (1*thisform['member_vat_'+i+'_'+j].value));
   total_vat_reduction = sprintf("%0.2f",(1*total_vat_reduction) + (1 * thisform['member_vat_reduction_'+i+'_'+j].value));
   total_vat_unbundled = sprintf("%0.2f",(1*total_vat) +  ( 1 * thisform['member_vat_'+i+'_'+j].value) + (1 * thisform['member_vat_reduction_'+i+'_'+j].value));
  }
 }
 }
 if (document.getElementById('total_product_price'))
 {
  document.getElementById('total_product_price').innerHTML = total_product_price;
 }
 if (document.getElementById('total_vat'))
 {
  document.getElementById('total_vat').innerHTML = total_vat;
 }
 if (document.getElementById('total_product_price_unbundled'))
 {
  document.getElementById('total_product_price_unbundled').innerHTML = total_product_price_unbundled;
 }
 if (document.getElementById('total_vat_unbundled'))
 {
  document.getElementById('total_vat_unbundled').innerHTML = total_vat_unbundled;
 }
 if (document.getElementById('total_product_price_reduction'))
 {
  document.getElementById('total_product_price_reduction').innerHTML = total_product_price_reduction;
 }
 if (document.getElementById('total_vat_reduction'))
 {
  document.getElementById('total_vat_reduction').innerHTML = total_vat_reduction;
 } 
 if (document.getElementById('total_product_rrp'))
 {
  document.getElementById('total_product_rrp').innerHTML = total_product_rrp;
 }
 if (document.getElementById('total_product_rrp_reduction'))
{
 document.getElementById('total_product_rrp_reduction').innerHTML = sprintf("%0.2f",total_product_rrp - total_product_price);
}

}

function clBundleMember(thisfield,bundle_index)
{
 thisform = thisfield.form;
 thisstore = thisform['product_bundle_not_required_store_'+bundle_index];
 if (thisstore)
 {
  if (thisstore.value == thisfield.value)
  {
   thisfield.checked = false;
   thisstore.value = 0;
  } else {
   thisstore.value = thisfield.value;
  }
 }
 bundle_show_total(thisform);
 return thisfield.checked;
}

function bundle_check_product(thisform,checkoptions)
{
 var missing_bundle_names = '';

 for (i=0;eachradio = thisform['member_prod_id_'+i];++i)
 {

  if (eachradio.length)
  {
        var thisradio = eachradio;
  } else { 
        var thisradio = new Array(eachradio);
  }
  var ischecked = false;
  for (j=0;j< thisradio.length;++j)
  {
   if (thisradio[j].checked)
   {
    ischecked = true;
    var temp_prod_id = thisradio[j].value;
    if (checkoptions != 'no' && thisform['option_count_'+i+'_'+temp_prod_id])
    {
// Check the order options/user text
     for (k=0;k < thisform['option_count_'+i+'_'+temp_prod_id].value;++k)
     {
      optionvalue = thisform['option_value_'+i+'_'+temp_prod_id+'_'+k];

      if (optionvalue && optionvalue.options[optionvalue.selectedIndex].value == '')
      {
       alert('Please select an option for '+thisform['option_display_name_'+i+'_'+temp_prod_id+'_'+k].value+' '+thisform['product_name_'+i+'_'+j].value);
       return false;
      } 
     }
    }
   }
  }
  if ((!thisform['product_bundle_not_required_store_'+i]) && !ischecked)
  {
   missing_bundle_names = missing_bundle_names + ' "' + thisform['product_bundle_name_'+i].value+'"';
  }
 }
 if (missing_bundle_names != '')
 {
  alert('You must make a selection for '+missing_bundle_names);
  return(false);
 } else {
  return(true);
 }
}


