function getURLVar(name)
{
get_string = document.location.search;
return_value = '';

do { //This loop is made to catch all instances of any get variable.
name_index = get_string.indexOf(name + '=');

if(name_index != -1)
  {
  get_string = get_string.substr(name_index + name.length + 1, get_string.length - name_index);

  end_of_value = get_string.indexOf('&');
  if(end_of_value != -1)
    value = get_string.substr(0, end_of_value);
  else
    value = get_string;

  if(return_value == '' || value == '')
     return_value += value;
  else
     return_value += ', ' + value;
  }
} while(name_index != -1)

//Restores all the blank spaces.
space = return_value.indexOf('+');
while(space != -1)
  {
  return_value = return_value.substr(0, space) + ' ' +
  return_value.substr(space + 1, return_value.length);

  space = return_value.indexOf('+');
  }

return(return_value);
}

function getCookie() {

        cookieData = new Array();
        cookieVals = window.document.cookie.split( ';' );

        for( idx in cookieVals ) {

            var parts = cookieVals[ idx ].replace( /^\s*([^\s]*)\s*$/, '$1' );
            parts = parts.split( '=' );
            cookieData[ parts[ 0 ] ] = unescape( parts[ 1 ] );
        }

        return cookieData;
    }

function setCookie( n, v, expiryHours ) {

        var today = new Date();

        var expiry = new Date( today.getTime() + 1000 * 60 * 60 * expiryHours );

        if( n && v ) {
            window.document.cookie = n + '=' + escape( v ) + ';path=/;expires=' + expiry.toGMTString();
        }
    }


function iemOutput() {

    this.fldSetup = {
        'Title'     			: { 'req'  : true, 'key'  :'T' },
        'First_Name'            : { 'alias' : 'First Name', 'req'  : true, 'key'  :'F', 'class':'l' },
        'Surname'               : { 'alias' : 'Last Name', 'req':true, 'key':'L', 'class':'l' },
        'Company_Name'          : { 'alias' : 'Company Name', 'key':'Y', 'class':'l' },
        'Address_1'             : { 'alias' : 'House Number (or name)', 'req':true, 'key':'H', 'class':'m' },
        'Street'                : { 'req': true, 'key':'S', 'class':'xl' },
        'Address_2'             : { 'alias' : 'Address 2', 'key':'A', 'class':'xl' },
        'Town'                  : { 'alias' : 'Town (or district)', 'req':true, 'key':'W', 'class':'xl' },
        'County'                : { 'alias' : 'County (or city)', 'req':true, 'key':'C', 'class':'xl' },
        'Postcode'              : { 'req' :true, 'key':'P', 'class':'s' },
        'Country'               : { 'req' :true, 'key':'O' },
        'Telephone'             : { 'alias' : 'Your Phone', 'req' :true, 'key':'N', 'class':'m', 'note' : '<br />Please include your full dialing code' },
        'Mobile'                : { 'key':'m', 'class':'M' },
        'Fax'                   : { 'alias' : 'Other Number', 'key':'R', 'class':'m' },
        'EMail'                 : { 'alias' : 'Your Email', 'req':true, 'key':'E', 'class':'xl' },
        'Comments'              : { 'alias' : 'PERSONALISED INFORMATION', 'key':'B' },
        'Delivery_Title'        : { 'alias' : 'Title', 'req': false, 'key':'T' },
        'Delivery_First_Name'   : { 'alias' : 'First Name', 'req' : false, 'key':'F', 'class':'l' },
        'Delivery_Surname'      : { 'alias' : 'Last Name', 'req':false, 'key':'L', 'class':'l' },
        'Delivery_Company_Name' : { 'alias' : 'Company Name', 'key':'Y', 'class':'l' },
        'Delivery_Address_1'    : { 'alias' : 'House Number (or name)', 'req':false, 'key':'H', 'class':'m' },
        'Delivery_Street'       : { 'alias' : 'Street', 'req':false, 'key':'S', 'class':'xl' },
        'Delivery_Address_2'    : { 'alias' : 'Address 2', 'key':'A', 'class':'xl' },
        'Delivery_Town'         : { 'alias' : 'Town (or district)', 'req':false, 'key':'W', 'class':'xl' },
        'Delivery_County'       : { 'alias' : 'County (or city)', 'req':false, 'key':'C', 'class':'xl' },
        'Delivery_Postcode'     : { 'alias' : 'Postcode', 'req':false, 'key':'P', 'class':'s' },
        'Delivery_Country'      : { 'alias' : 'Country', 'req':false, 'key':'O' },
        'Delivery_Telephone'    : { 'alias' : 'Telephone', 'key':'T', 'class':'m' },
        'Delivery_Notes'        : { 'alias' : 'Delivery Instructions', 'key':'I' },
        'Card_Name'             : { 'alias' : 'Name as it appears on Card', 'req':true, 'key':'N', 'class':'l' },
        'Card_Type'             : { 'alias' : 'Card Type', 'req':true, 'key':'C' },
        'Card_Number'           : { 'alias' : 'Card Number', 'req':true, 'key':'U' },
        'Card_Start'            : { 'alias' : 'Valid From', 'key':'S' },
        'Card_End'              : { 'alias' : 'Expiry Date', 'req':true, 'key':'E' },
        'Card_Issue_Number'     : { 'alias' : 'Issue Number', 'key':'I', 'class':'xs', 'note' : '(switch/solo only)' },
        'Pwd'                   : { 'alias' : 'Password', 'req':true, 'class':'l' },
        'Pwd_Check'             : { 'alias' : 'Password Confirm', 'req':true, 'class':'l' },
        'Mail_Lists'            : { 'alias' : 'Newsletter opt-ins' },
        'Old_Pwd'               : { 'alias' : 'Password', 'req':true, 'class':'l' },
        'New_Pwd'               : { 'alias' : 'New Password', 'class':'l', 'note' : '(complete to change password)' },
        'New_Pwd_Check'         : { 'alias' : 'New Password Confirm', 'class':'l' },
        'Promotional_Codes'     : { 'alias' : 'Promotion Code', 'class':'m' },
        'Gift_Wrapping'         : { 'alias' : 'Gift Wrapping', 'note' : ' Use the Personalised Information box to inform us of the item to be gift-wrapped' },
        'Card_CV2'              : { 'alias' : '3-digit security code', 'req':true, 'note' : '<br />Most users can find this on the back of the card near the signature strip' }
    }

	// fldsetup overwritten for admin section
    if( window.location.pathname.indexOf( 'admin' ) > -1 ) {
    	this.fldSetup[ 'EMail' ][ 'req' ] = false;
    	this.fldSetup[ 'County' ][ 'req' ] = false;
      	this.fldSetup[ 'Promotional_Codes' ][ 'alias' ] = 'Media code';
      	this.fldSetup[ 'Promotional_Codes' ][ 'note' ] = '<br />How did you find out about Sleepover Company.';
   	}

    this.getCookie = function() {

        cookieData = new Array();
        cookieVals = window.document.cookie.split( ';' );

        for( idx in cookieVals ) {

            var parts = cookieVals[ idx ].replace( /^\s*([^\s]*)\s*$/, '$1' );
            parts = parts.split( '=' );
            cookieData[ parts[ 0 ] ] = unescape( parts[ 1 ] );
        }

        return cookieData;
    }

    this.setCookie = function( n, v, expiryHours ) {

        var today = new Date();

        var expiry = new Date( today.getTime() + 1000 * 60 * 60 * expiryHours );

        if( n && v ) {
            window.document.cookie = n + '=' + escape( v ) + ';path=/;expires=' + expiry.toGMTString();
        }
    }

    this.displayCartList = function( cartRows ) {

        var htm = '';
        var rowCount = 0;

        for( var lineID in cartRows ) {

            rowCount++;

            var row = cartRows[ lineID ];

            htm += '<form name="frm' + lineID + '" onsubmit="if(this.productQty.value>0){iem.CartUpdate( \'[LineID] = [' + lineID + ']\', { \'fld' + lineID + '_' + row[ 'Qty' ][ 'index' ] + '\' : this.productQty.value } );iem.CartList( \'[Completed] = [-1]\' );iem.CartSubmit( window.location );}else{alert(\'Please enter a quantity\');}return false;">' +
                '<tr>' +
                ' <td rowspan="2" width="67px" valign="top">' +
                '   <img src="' + ( row[ 'Image_Thumbnail' ][ 'value' ] ? row[ 'Image_Thumbnail' ][ 'value' ] : '/_res/19.gif' ) + '" border="0" alt="' + row[ 'Product_Name' ][ 'value' ] + '" style="border: 1px solid #002C72; width:65px;" />' +
                ' </td>' +
                ' <td colspan="4" valign="top">' +
            '    <strong>' + row[ 'Product_Name' ][ 'value' ] + ' ' + row[ 'Product_Code' ][ 'value' ] + '</strong><br />';

            for( var i = 1; i <= 5; i++ ) {
                htm += ( row[ 'Option_' + i ][ 'value' ] != 0 ? row[ 'Option_' + i ][ 'value' ].replace( '|', ': ' ) + ' ' : '' );
            }
            if( row[ 'Instructions' ][ 'value' ] ) {
                htm += '<br />Personalisation: ' + row[ 'Instructions' ][ 'value' ];
            }
            htm += ' </td>' +
                '</tr>' +
                '<tr>' +
                ' <td>Quantity <input type="text" name="productQty" value="' + row[ 'Qty' ][ 'value' ] + '" size="2" maxlength="3" /></td>' +
                ' <td class="price">(Unit Cost &pound;' + row[ 'Base_Price' ][ 'value' ] + ')</td>' +
                ' <td class="price"><strong>Total &pound;' + row[ 'Sub_Total' ][ 'value' ] + '</strong></td>' +
                ' <td class="price" nowrap="nowrap"><input type="submit" class="button" value="Update" />&nbsp;' +
                '<input type="button" class="button" value="Remove" onclick="iem.CartDelete( \'[LineID] = [' + lineID + ']\' );iem.CartList( \'[Completed] = [-1]\' );iem.CartSubmit();return false;" /></td>' +
                '</tr>' +
                '<tr><td colspan="5"><hr /></td></tr>' +
            '</form>';
        }
        if( ! rowCount ) {
            htm += '<tr><td colspan="5">Your shopping basket is currently empty.<br /><br /></td></tr>';
        }
        document.write( htm );
    }


    this.displayCartPreview = function( cartRows ) {

        var htm = '';

        var tempRows = new Array();

        for( var lineID in cartRows ) {
            tempRows[ tempRows.length ] = cartRows[ lineID ];
        }
        cartRows = tempRows.sort( iem.output.previewSort );

        for( var i in cartRows ) {

            var row = cartRows[ i ];
            var iCol = iCol;
            var lineID = row[ 'LineID' ][ 'value' ];

            if( iCol < 1 ) {
            	var iClass = 'prodOptionPink';
            	var iCol = 1;
            } else {
            	var iClass = 'prodOptionBlue';
            	var iCol = 0;
            }

            htm += '<div class="' + iClass + '">' +

			'<table cellpadding="0" cellspacing="0" border="0" width="100%" style="padding: 5px;">' +
			' <tr>' +
			'  <td><h3>' + row[ 'Product_Name' ][ 'value' ] + '</h3></td>' +
			'  <td><p style="color: #24A2D8; font: bold 12px Verdana,sans-serif;">Product Code: ' + row[ 'Product_Code' ][ 'value' ] + '</p></td>' +
			' </tr>' +
			'</table>' +
			'<hr />';

            /*'<h3>' + row[ 'Product_Name' ][ 'value' ] + '</h3>' +
            '<div class="prodCode">Product Code: ' + row[ 'Product_Code' ][ 'value' ] + '</div>' +
            '<hr />' +
			*/

            htm += '<form name="frm' + lineID + '" onsubmit="iem.CartAdd(\'' + row[ 'Product_ID' ][ 'value' ] + '\', 1, null );iem.CartUpdate( \'\', { \'Country\' : \'UNITED KINGDOM\' } );iem.CartUpdate( \'[LineID] = [' + lineID + ']\', { \'fld' + lineID + '_' + row[ 'Completed' ][ 'index' ] + '\' : \'-1\', \'fld' + lineID + '_' + row[ 'Qty' ][ 'index' ] + '\' : this.productQty.value, \'fld' + lineID + '_' + row[ 'Instructions' ][ 'index' ] + '\' :  ( typeof( this.productMessage ) == \'object\' ? this.productMessage.value : \'\' ) } );iem.CartList( \'[Completed] = [-1]\' );iem.CartSubmit();return false;">' +
            '<a name="' + row[ 'Product_Code' ][ 'value' ] + '"></a><table>';

            for( var i = 1; i <= 5; i++ ) {
                if( row[ 'Option_' + i ][ 'options' ] ) {

                    htm += '<tr>';
                    htm += '<th>' + row[ 'Option_' + i ][ 'optName' ] + '</th>';
                    htm += '<td>';

                    var optCount = 0;
                    for( var idx in row[ 'Option_' + i ][ 'options' ] ) optCount++;

                    if( optCount > 1 ) {
                        htm += '<select name="Option_' + i + '" onchange="iem.CartUpdate( \'[Product_ID] = [' + row[ 'Product_ID' ][ 'value' ] + '] and [Completed] = [0]\', { \'fld' + lineID + '_' + row[ 'Option_' + i ][ 'index' ] + '\' : this[ this.selectedIndex ].value } );iem.CartList( \'[Product_ID] = [' + row[ 'Product_ID' ][ 'value' ] + '] and [Completed] = [0]\' );iem.CartSubmit( \'http://\' + window.location.hostname + window.location.pathname + \'#' + row[ 'Product_Code' ][ 'value' ] + '\' );">';
                		for( var idx in row[ 'Option_' + i ][ 'options' ] ) {
                        	htm += '<option value="' + idx + '"' + ( idx == row[ 'Option_' + i ][ 'value' ] ? ' selected="selected"' : '' ) + '>' + row[ 'Option_' + i ][ 'options' ][ idx ][ 0 ] + '</option>';
                		}
                        htm += '</select>';
                    } else {
                		for( var idx in row[ 'Option_' + i ][ 'options' ] ) {
                        	htm += row[ 'Option_' + i ][ 'options' ][ idx ][ 0 ];
                		}
                    }

                    htm += '</td>';
                    htm += '</tr>';
                }
            }

            htm += '<tr>' +
                '<th>Quantity</th>' +

                '<td><input type="text" name="productQty" value="' + row[ 'Qty' ][ 'value' ] + '" size="2" maxlength="3" class="qty" title="Enter Quantity here..." ';

                if( parseInt( row[ 'Length' ][ 'value' ] ) > 0 ) {
                    htm += 'onkeyup="this.form.productMessage.value=new String(this.form.productMessage.value).substring(0,this.value);" ';
                }

                htm += '/> @ ';

                if( row[ 'RRP' ][ 'value' ] > 0 ) {
                    htm += '<strong style="color: #E52324;">&pound;' + row[ 'Base_Price' ][ 'value' ] + '</strong>';
					htm += ' (RRP &pound;<span style="text-decoration: line-through;">' + row[ 'RRP' ][ 'value' ] + '</span>)';
                } else {
                    htm += '<strong>&pound;' + row[ 'Base_Price' ][ 'value' ] + '</strong>';
                }

			htm += '</td>' +
                '</tr>';

            if( row[ 'Instructions' ][ 'value' ] != '' ) {
                htm += '<tr>' +
                    '<th>Personalisation</th>' +
                    '<td><input type="text" name="productMessage" value="" class="text" title="Enter personalised message here..." ';

                if( parseInt( row[ 'Length' ][ 'value' ] ) > 0 ) {
                    htm += 'onkeyup="this.form.productQty.value=this.value.split( \' \' ).join( \'\' ).length;" ';
                }

                htm += '/></td>' +
                    '</tr>';
            }
            htm += '</table>' +
                '<input type="submit" value="Add to basket" class="button" />' +
                '</form>' +
            '</div>';
        }
        document.write( htm );
    }

    this.displayPromoCode = function( totals ) {

        var htm = '';

        var prods = iem.response.getField( 'CartList' );

            htm += '<form name="frmPromo" onsubmit="if(this.promo_code.value){iem.CartUpdate( \'\', { \'fld37\' : this.promo_code.value } );iem.CartSubmit( window.location );}else{alert(\'Please enter a promotion code\');}return false;">' +
                '<tr>' +
                ' <td colspan="3" align="right"><strong>Promotion Code:</strong></td>' +
                ' <td><input type="text" name="promo_code" value="' + ( prods[ 'Order' ][ 'Promotional_Codes' ] ? prods[ 'Order' ][ 'Promotional_Codes' ] : '' ) + '" size="5" maxlength="6" /></td>' +
                ' <td class="price" nowrap="nowrap"><input type="submit" class="button" value="Update Promotion Code" /></td>' +
                '</tr>' +
                '<tr>' +
                ' <td colspan="4" ><p>Please enter a valid promotion code, then click the "Update Promotion Code" button.</p><p>If you enter an invalid code, it will simply disappear when the button is pressed.</p></td>' +
                ' <td>&nbsp;</td>' +
                '</tr>' +
            	'<tr><td colspan="5"><hr /></td></tr>' +
            '</form>';

    	document.write( htm );
    }

    this.displayCartTotal = function( totals ) {

        var htm = '';

        var prods = iem.response.getField( 'CartList' );

        var orderDiscounts    = prods[ 'Discounts' ][ 'order' ];
        var shippingDiscounts = prods[ 'Discounts' ][ 'shipping' ];

        var billingCountry  = ( prods[ 'Order' ][ 'Country' ] ? prods[ 'Order' ][ 'Country' ] : '' );
        var shippingCountry = ( prods[ 'Order' ][ 'Delivery_Country' ] ? prods[ 'Order' ][ 'Delivery_Country' ] : '' );
        var shippingMethod  = ( prods[ 'Order' ][ 'Delivery_Method' ] ? prods[ 'Order' ][ 'Delivery_Method' ] : '' );

        var lookup = {
            'Product_Total' : 'Total Goods',
            'Options_Totals' : true,
            'Shipping_Total' : 'Delivery',
            'Grand_Total' : 'TOTAL (inc VAT)'
        }

        // discounts affecting whole order
        var discountCount = 0;
        for( var orderDiscount in orderDiscounts ) discountCount++;

        if( discountCount ) {
            htm += '<tr>';
            htm += '<td colspan="3"><strong>';
                for( var orderDiscount in orderDiscounts ) {
                    htm += 'Discount: ' + orderDiscounts[ orderDiscount ][ 'title' ] + '<br />';
                }
            htm += '</strong></td>';
            htm += '<td class="price">-&pound;' + totals[ 'Order_Discount' ] + '</td>';
            htm += '<td>&nbsp;</td>';
            htm += '</tr>';
            htm += '<tr><td colspan="5"><hr /></td></tr>';
        }



        for( var total in lookup ) {

            if( totals[ total ] ) {
                if( total == 'Options_Totals' ) {
                    for( var optionTotal in totals[ total ] ) {
                        if( totals[ total ][ optionTotal ] > 0 ) {
                            htm += '<tr>' +
                                '<td colspan="3"><strong>' + optionTotal.split( '_' ).join( ' ' ) +  '</strong></td>' +
                                '<td class="price">&pound;' + totals[ total ][ optionTotal ] + '</td>' +
                                '<td>&nbsp;</td>' +
                            '</tr>';
                        }
                    }

                } else {

                    if( total == 'Grand_Total' ) {
                        iem.output.setCookie( 'orderTotal', totals[ total ] );
                    }

                    htm += '<tr>' +
                        '<td colspan="3"><strong>' + ( lookup[ total ] ? lookup[ total ] : total ) +  '</strong>';

                    if( total == 'Shipping_Total' ) {
                        htm += '&nbsp;<a href="#" onClick="javascript:window.open('+"'http://www.sleepovercompany.com/customer_service/index_8.html','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no'"+');" title="View delivery information popup">information...</a>';
		    }

		    htm += '</td>' +
                        '<td class="price">&pound;' + totals[ total ] + '</td>' +
                        '<td>&nbsp;</td>' +
                    '</tr>';
                    // shipping options
                    if( total == 'Shipping_Total' ) {

                        if( window.location.protocol == 'http:' ) {
                          if( ! ( window.location.pathname.indexOf( 'admin' ) > -1 ) ) {
                        		htm += '<tr><td colspan="5"><strong>Delivery Options</strong> <a href="/basket/25.html" onclick="iem.CallFunc(\'CartCheckoutFields\');iem.CartSubmit(this.href);" title="Choose a different delivery method">change...</a></td></tr>';
                            htm += '<tr><td colspan="5"><span style="font-size: 10px">' + ( shippingCountry ? shippingCountry : billingCountry ) + ' ' + shippingMethod + '</span></td></tr>';
                          } else {
                        		htm += '<tr><td colspan="5"><strong>Delivery Options</strong> <a href="/basket/25.html" onclick="iem.CallFunc(\'CartCheckoutFields\');iem.CartSubmit(this.href);" title="Choose a different delivery method">change...</a></td></tr>';
                            htm += '<tr><td colspan="5"><span style="font-size: 10px">' + ( shippingCountry ? shippingCountry : billingCountry ) + ' ' + shippingMethod + '</span></td></tr>';

                          }
                            //htm += '<tr><td colspan="5"><span style="font-size: 10px">' + ( shippingCountry ? shippingCountry : billingCountry ) + '</span></td></tr>';
                        }
                        // shipping discounts
                        for( var shippingDiscount in shippingDiscounts ) {
                            htm += '<tr><td colspan="5"><span style="font-size: 10px">Discount: ' + shippingDiscounts[ shippingDiscount ][ 'title' ] + '</span></td></tr>';
                        }
                    }
                }
            }
        }
        document.write( htm );
    }


/*
    this.displayCartTotal = function( totals ) {

        var htm = '';

        var lookup = {
            'Product_Total' : 'Subtotal',
            'Shipping_Total' : 'Shipping',
            'Grand_Total' : 'TOTAL (inc VAT)'
        }

        for( var total in totals ) {
            if( lookup[ total ] ) {
                htm += '<tr>' +
                    '<td colspan="3"><strong>' + ( lookup[ total ] ? lookup[ total ] : total ) +  '</strong></td>' +
                    '<td class="price">&pound;' + totals[ total ] + '</td>' +
                    '<td>&nbsp;</td>' +
                '</tr>';
            }
        }

        document.write( htm );
    }
*/
    this.displayCheckout = function( flds, currPage, frmAction, frmType ) {

        var htm = ''; // html of the form

        // perform a default set of manipulation on fields
        // which are ommitted from the setup array
        for( var fld in flds ) {
            if( ! iem.output.fldSetup[ fld ] ) {
                iem.output.fldSetup[ fld ] = {
                    'alias' : fld.split( '_' ).join( ' ' ),
                    'key'   : false,
                    'class' : false,
                    'note'  : false
                }
            }
        }

        // build the js command to validate required fields
        var reqCmd = '';

        for( var fld in flds ) {
            if( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'req' ] && flds[ fld ][ 'type' ] != 'HIDDEN' ) {
                reqCmd += 'this.fld' + flds[ fld ][ 'idx' ] + '_1,';
            }
        }
        if( reqCmd.length > 0 ) {
            reqCmd = reqCmd.substring( 0, reqCmd.length - 1 );
        }

        htm += '<form name="frmCheckout" method="post" action="' + frmAction + '" onsubmit="return iem.output.validateForm(' + reqCmd + ');" name="checkoutForm" AUTOCOMPLETE="off">';


/*
	cookieData = getCookie();
	if( cookieData['Ref_Code_51'] != "" ){
		//flds[ 'Ref_Code' ][ 'value' ] = cookieData['Ref_Code_51'];
                htm += '<input type="hidden" name="Ref_Code" value="' + cookieData['Ref_Code_51'] + '" />\n';
	}
*/

        // print out all hidden fields
        for( var fld in flds ) {
            if( flds[ fld ][ 'type' ] == 'HIDDEN' ) {
                htm += '<input type="hidden" name="' + fld + '" value="' + flds[ fld ][ 'value' ] + '" />\n';
            }
        }

        var fldOrder = { 'Promotional_Codes' : true, 'EMail' : true, 'Telephone' : true, 'Mobile' : true, 'Fax' : true, 'Title' : true, 'First_Name' : true, 'Surname' : true, 'Company_Name' : true, 'Address_1' : true, 'Street' : true, 'Address_2' : true, 'Town' : true, 'County' : true, 'Postcode' : true, 'Country' : true, 'Delivery_Title' : true, 'Delivery_First_Name' : true, 'Delivery_Surname' : true, 'Delivery_Company_Name' : true, 'Delivery_Address_1' : true, 'Delivery_Street' : true, 'Delivery_Address_2' : true, 'Delivery_Town' : true, 'Delivery_County' : true, 'Delivery_Postcode' : true, 'Delivery_Country' : true, 'Delivery_Telephone' : true, 'Delivery_Notes' : true, 'Comments' : true, 'Card_Name' : true, 'Card_Type' : true, 'Card_Number' : true, 'Card_Start' : true, 'Card_End' : true, 'Card_Issue_Number' : true, 'Card_CV2' : true, 'Mail_Lists' : true, 'Gift_Wrapping' : true, 'Old_Pwd' : true, 'New_Pwd' : true, 'New_Pwd_Check' : true, 'Pwd' : true, 'Pwd_Check' : true }

        // print out input fields
        for( var fld in fldOrder ) {
            if( flds[ fld ] ) {
                if( flds[ fld ][ 'type' ] != 'HIDDEN' ) {

                    var reqMark = '';
                    var fldDesc = fld;

                    if( iem.output.fldSetup[ fld ] ) {
                        if( iem.output.fldSetup[ fld ][ 'alias' ] ) {
                            fldDesc = iem.output.fldSetup[ fld ][ 'alias' ];
                        }
                        if( iem.output.fldSetup[ fld ][ 'req' ] ) {
                            reqMark = ' <span class="red">*</span>';
                        }
                    }

                    var fldDisp = '';

                    var matchedChar = false;
                    var currChar = 0;

                    if( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'key' ] ) {
                        while( ! matchedChar && currChar <= fldDesc.length ) {
                            if( fldDesc.charAt( currChar ).toLowerCase() == iem.output.fldSetup[ fld ][ 'key' ].toLowerCase() ) {
                                fldDisp += '<u>' + fldDesc.charAt( currChar ) + '</u>';
                                matchedChar = true;
                            } else {
                                fldDisp += fldDesc.charAt( currChar );
                            }
                            currChar++;
                        }
                    }

                    fldDisp += fldDesc.substring( currChar ) + reqMark;

                    var fldCode = '';
                    if( iem.output.fldSetup[ fld ] ) {
                        fldCode += ' class="' + ( iem.output.fldSetup[ fld ][ 'class' ] ? iem.output.fldSetup[ fld ][ 'class' ] : 'l' ) + '"' + ( iem.output.fldSetup[ fld ][ 'key' ] ? ' accesskey="' + iem.output.fldSetup[ fld ][ 'key' ] + '"' : '' );
                    }

                    var fldName = 'fld' + flds[ fld ][ 'idx' ] + '_1';

                    switch( fld ) {
                        case 'Country' : {
                            htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">' +
                                '    <input' + fldCode + ' type="text" name="' + fldName + '" value="UNITED KINGDOM" title="' + fldDesc + '" readonly="readonly" />' +
                                '</div>\n';
                            break;
                        }
                        case 'Delivery_Country' : {
                            htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">' +
                                '    <input type="text" name="' + fldName + '" value="UNITED KINGDOM" title="' + fldDesc + '" readonly="readonly" />' +
                                '</div>';
                            break;
                        }
                        case 'Card_Number' : {
                            htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">' +
                                '    <input' + fldCode + ' type="text" name="' + fldName + '" value="" onblur="convert(this);" title="' + fldDesc + '" AUTOCOMPLETE="off"/>' +
                                '</div>';
                            break;
                        }
                        case 'Card_Start' :
                        case 'Card_End' : {
                        	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">';

                            // generate month drop down
                            var months = new Array( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
                            htm += '    <select' + fldCode + ' name="' + fldName + '_mm" onchange="this.form[ \'' + fldName + '\' ].value=this.form[ \'' + fldName + '_mm\' ][ this.form[ \'' + fldName + '_mm\' ].selectedIndex ].value + \'/\' + this.form[ \'' + fldName + '_yyyy\' ][ this.form[ \'' + fldName + '_yyyy\' ].selectedIndex ].value" title="' + fldDesc + '" AUTOCOMPLETE="off">' +
                                '     <option value=""> -- </option>';
                            for( var i = 0; i < 12; i++ ) {
                                htm += '     <option value="' + ( i + 1 ) + '">' + months[ i ] + '</option>';
                            }
                            htm += '    </select>';

                            // generate year drop down
                            var currDate = new Date();
                            var currYear = currDate.getFullYear();
                            var maxAge = 30;

                            htm += '    <select' + fldCode + 'name="' + fldName + '_yyyy" onchange="this.form[ \'' + fldName + '\' ].value=this.form[ \'' + fldName + '_mm\' ][ this.form[ \'' + fldName + '_mm\' ].selectedIndex ].value + \'/\' + this.form[ \'' + fldName + '_yyyy\' ][ this.form[ \'' + fldName + '_yyyy\' ].selectedIndex ].value" title="' + fldDesc + '" AUTOCOMPLETE="off">' +
                                '     <option value=""> -- </option>';
                            if( fld == 'Card_Start' ) {
                                for( var i = currYear; i > currYear - maxAge; i-- ) {
                                    htm += '     <option value="' + i + '">' + i + '</option>';
                                }
                            } else {
                                for( var i = currYear; i < currYear + maxAge; i++ ) {
                                    htm += '     <option value="' + i + '">' + i + '</option>';
                                }
                            }

                            htm += '    </select>' +
                                '    <input type="hidden" name="' + fldName + '" title="' + fldDesc + '">' +
                                '</div>';
                            break;
                        }
                        case 'Mail_Lists' : {
                        	htm += '<div class="formLabelLong">' + fldDisp + ':</div>\n' +
                        	    '<div class="formElementLong">';
                            for( var opt in flds[ fld ][ 'options' ] ) {
                                // horrific way of concatenating checkbox values into a hidden field
                                htm += '    <input class="noborder" type="checkbox" name="' + fld + '_' + opt + '" value="' + flds[ fld ][ 'options' ][ opt ] + '" onclick="this.form.' + fld + '.value=\'\'; for( var i = 0; i < this.form.elements.length; i++ ) { if( this.form.elements[ i ].checked && this.form.elements[ i ].name.indexOf( \'' + fld + '\' ) != -1 ) { this.form.' + fld + '.value += this.form.elements[ i ].value + \',\'; } } this.form.' + fld + '.value=this.form.' + fld + '.value.substring( 0, this.form.' + fld + '.value.length - 1 );" title="' + fldDesc + '" />' + flds[ fld ][ 'options' ][ opt ] + ' ';
                            }
                            htm += '    <input type="hidden" name="' + fld + '" value="" />&nbsp;' +
                                '</div><hr />';
                            break;
                        }
                        case 'Mobile' :
                        case 'Fax' :
                        case 'Delivery_Notes' :
                        case 'Comments' :

                        case 'Delivery_Telephone' :
                        case 'Delivery_Method' :
                        case 'Spare_1' :
                        case 'Promotional_Codes' :
                        case 'Gift_Wrapping' :
                        case 'Pwd_Reminder' : {
                            break;
                        }
                        default : {

                            if( flds[ fld ][ 'options' ] ) {

                                if( fld == 'Title' ) {
                                    htm += '<hr />';
                                    htm += '<div class="formText">';
                                    htm += '<h2>3. Address Details</h2>';
                                    htm += 'Please enter your name and address detals. These must match those registered with your card issuer.';
                                    htm += '</div>';
                                }
                                if( fld == 'Delivery_Title' ) {
                                    htm += '<hr />';
                                    htm += '<div class="formText">Delivery address if different:</div>';
                                }

                            	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                            	    '<div class="formElement">' +
                                    '    <select name="' + fldName + '"' + fldCode + ' title="' + fldDesc + '" AUTOCOMPLETE="off">';
                                for( var opt in flds[ fld ][ 'options' ] ) {
                                    htm += '     <option value="' + flds[ fld ][ 'options' ][ opt ] + '"' + ( flds[ fld ][ 'value' ] == flds[ fld ][ 'options' ][ opt ] ? ' selected="selected"' : '' ) + '>' + flds[ fld ][ 'options' ][ opt ] + '</option>';
                                }
                                htm += '    </select>' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                    '</div>';
                            } else {
                                switch( flds[ fld ][ 'type' ] ) {
                                    case 'LARGE_TEXT' : {

                                        if( fld == 'Notes' && frmType == 'register' ) {
                                            break;
                                        }

                                    	htm += '<div class="formLabelLong">' + fldDisp + ':</div>' +
                                    	    '<div class="formElementLong">' +
                                            '    <textarea name="' + fldName + '"' + fldCode + ' style="width: 475px;" title="' + fldDesc + '">' + flds[ fld ][ 'value' ] + '</textarea>' +
                                            '</div>';
                                        break;
                                    }
                                    case 'BOOL' : {
                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                    	    '<div class="formElement">' +
                                            '    <input' + fldCode + ' type="checkbox" style="border: 0" name="' + fldName + '" title="' + fldDesc + '" AUTOCOMPLETE="off" />' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                            '</div>';
                                        break;
                                    }
                                    case 'PASSWORD' : {
                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                    	    '<div class="formElement">' +
                                            '    <input' + fldCode + ' type="password" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" title="' + fldDesc + '" AUTOCOMPLETE="off" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                            '</div>';
                                        break;
                                    }
                                    default: {
                                        if( fld == 'EMail' ) {
                                            htm += '<hr />';
                                            htm += '<div class="formText">';
                                            htm += '<h2>2. Your Contact Details</h2>';
                                            htm += 'We need your email address to confirm your order, so please type carefully.  We also need a contact number in case we have any problems with your order.';
                                            htm += '<br /><b><a href="http://www.sleepovercompany.com/customer_service/index_12.html" target="_blank">Our privacy policy</a></b>';
                                            htm += '</div>';
                                        }
                                        if( fld == 'Card_Name' ) {
                                            htm += '<hr />';
                                            htm += '<div class="formText">';
                                            htm += '<h2>4. Card Details</h2>';
                                            htm += 'Please enter your credit card details, including the 3-digit code found on the back of your card, near the signature strip.';
                                            htm += '</div>';
                                        }
                                        if( fld == 'EMail' ) {
                                            if( iem.request.getField( 'usr_1' ) ) {
                                                flds[ fld ][ 'value' ] = iem.request.getField( 'usr_1' );
                                            }
                                        }

                                        if( fld == 'Promotional_Codes' ) {
	                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
	                                    	    '<div class="formElement">' +
	                                            '    <input' + fldCode + ' type="text" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" title="' + fldDesc + '" AUTOCOMPLETE="off" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
	                                            '</div>';
                                        } else {
	                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
	                                    	    '<div class="formElement">' +
	                                            '    <input' + fldCode + ' type="text" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" onblur="convert(this);" title="' + fldDesc + '" AUTOCOMPLETE="off" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
	                                            '</div>';
                                        }
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }

    	if( currPage == 1 ) {
    	    htm += '<span class="formLabel"><input type="button" onclick="javascript:history.go(-2)" value="&#171; Back" class="prev" /></span>';
    	} else {
            htm += '<span class="formLabel"><input type="button" onclick="javascript:history.go(-1)" value="&#171; Back" class="prev" /></span>';
        }
    	htm += '<span class="formElement"><input type="submit" value="Continue &#187;" class="next" /></span>';

        htm += '<br style="clear: both;" />'
        htm += '</form>';

        document.write( htm );
    }

    this.displayCartConfirm = function( success, cartError, cartErrNo ) {
        var htm = '';
        if( success ) {
            htm += '<h1>Thank you</h1>'
            htm += '<p>Your order details have been sent successfully and will receive our immediate attention.</p>';
            htm += '<p><strong>Please check your e-mail for a review of the order.</strong></p>';
            htm += '<br/><p><a href="http://www.sleepovercompany.com/">Click Here</a> to return to The Sleepover Company web site.</p>';


            if( iem.response.getField( 'OrderID' ) ) {
                var orderId = iem.response.getField( 'OrderID' );
            } else {
                var orderId = 0;
            }

            var fromCookie = iem.output.getCookie();

            //if( fromCookie[ 'orderTotal' ] ) {
            //    var orderValue = fromCookie[ 'orderTotal' ];
            if( iem.response.getField( 'ordersValue' ) ) {
                var orderValue = iem.response.getField( 'ordersValue' );
            } else {
                var orderValue = 0;
            }

	

            //merchantID = 898
            //payoutCodes = ""
            //offlineCode = ""
            //orderValue = orderValue;
            //orderRef = orderId;
            //CatalinkProcessLead(merchantID, orderValue, orderRef, payoutCodes, offlineCode);



			// Google Code for purchase Conversion Page - clickconsult.co.uk
			// var google_conversion_id = 1054730675;
			// var google_conversion_language = "en_GB";
			// var google_conversion_format = "1";
			// var google_conversion_color = "CC99CC";
			// if (1) {
			// var google_conversion_value = 1;
			// }
			// var google_conversion_label = "purchase";

			htm += unescape("%3Cscript type='text/javascript'%3E"+"var google_conversion_id = 1054730675;var google_conversion_language = 'en_GB';var google_conversion_format = '1';var google_conversion_color = 'CC99CC';var google_conversion_value = 1;var google_conversion_label = 'purchase';"+"%3C/script%3E");
			var secure = (document.location.toString().indexOf("https") == 0);
			if ( secure == true ){
				htm += unescape("%3Cscript src='https://www.googleadservices.com/pagead/conversion.js' type='text/javascript'%3E%3C/script%3E");
			} else {
				htm += unescape("%3Cscript src='http://www.googleadservices.com/pagead/conversion.js' type='text/javascript'%3E%3C/script%3E");
			}


			// affiliatefuture.com - purchase tracking

			var merchantID = 3090;
			var payoutCodes = ''; 
			var offlineCode = '';
			var orderRef = orderId;
			AFProcessSaleV2( merchantID, orderValue, orderRef, payoutCodes, offlineCode );

			//htm += unescape("%3Cscript src='https://scripts.affiliatefuture.com/AFFunctions.js' type='text/javascript'%3E%3C/script%3E");
			//htm += unescape("%3Cscript type='text/javascript'%3E"+"merchantID=3090; payoutCodes=''; offlineCode=''; orderValue='"+orderValue+"'; orderRef='"+orderId+"'; AFProcessSaleV2(merchantID, orderValue, orderRef, payoutCodes, offlineCode); "+"%3C/script%3E");
			//htm += unescape("%3Cscript type='text/javascript'%3E"+"AFProcessSaleV2(3090, "+orderValue+", "+orderId+", '', ''); "+"%3C/script%3E");


        } else {
            htm += '<h1>Error</h1>';

            if( cartError ) {
                if( cartErrNo >= 500 ) {
                    htm += '<p>Error validating email address, please use a different email address or try again later</p>';
                } else {
                  htm += '<p>Sorry, but we are having problems processing your card. Please go back and check that you have entered your details correctly, including your card number, security code, expiry dates and card holder information. Alternatively, please contact our CUSTOMER SERVICE DEPARTMENT ON 0870 300 2011.</p';
                }
                htm += '<p>' + cartErrNo + ' - ' + cartError + '</p>';
            }
            htm += '<p><a href="javascript:window.history.go(-1);">Back</a></p>';
        }
        document.write( htm );
    }

    this.displayCheckoutWin = function( checkoutUrl ) {
        window.location = checkoutUrl;
    }


    this.adminCartPreview = function( cartRows ) {


        var htm = '';

        for( var lineID in cartRows ) {

            var row = cartRows[ lineID ];
            var iCol = iCol;

            if( iCol < 1 ) {
            	var iClass = 'prodOptionPink';
            	var iCol = 1;
            } else {
            	var iClass = 'prodOptionBlue';
            	var iCol = 0;
            }

            htm += '<div class="' + iClass + '">' +
            '<h3>' + row[ 'Product_Name' ][ 'value' ] + '</h3>' +
            '<div class="prodCode">Product Code: ' + row[ 'Product_Code' ][ 'value' ] + '</div>' +
            '<hr />' +
            '<form name="frm' + lineID + '" onsubmit="iem.CartAdd(\'' + row[ 'Product_ID' ][ 'value' ] + '\', 1, null );iem.CartUpdate( \'[LineID] = [' + lineID + ']\', { \'fld' + lineID + '_' + row[ 'Completed' ][ 'index' ] + '\' : \'-1\', \'fld' + lineID + '_' + row[ 'Qty' ][ 'index' ] + '\' : this.productQty.value, \'fld' + lineID + '_' + row[ 'Instructions' ][ 'index' ] + '\' :  ( typeof( this.productMessage ) == \'object\' ? this.productMessage.value : \'\' ) } );iem.CartList( \'[Completed] = [-1]\' );iem.CartSubmit();return false;">' +
            '<a name="' + row[ 'Product_Code' ][ 'value' ] + '"></a><table>';

            for( var i = 1; i <= 5; i++ ) {
                if( row[ 'Option_' + i ][ 'options' ] ) {

                    htm += '<tr>';
                    htm += '<th>' + row[ 'Option_' + i ][ 'optName' ] + '</th>';
                    htm += '<td>';

                    var optCount = 0;
                    for( var idx in row[ 'Option_' + i ][ 'options' ] ) optCount++;

                    if( optCount > 1 ) {
                        htm += '<select name="Option_' + i + '" onchange="iem.CartUpdate( \'[Product_ID] = [' + row[ 'Product_ID' ][ 'value' ] + '] and [Completed] = [0]\', { \'fld' + lineID + '_' + row[ 'Option_' + i ][ 'index' ] + '\' : this[ this.selectedIndex ].value } );iem.CartList( \'[Product_ID] = [' + row[ 'Product_ID' ][ 'value' ] + '] and [Completed] = [0]\' );iem.CartSubmit( window.location );">';
                		for( var idx in row[ 'Option_' + i ][ 'options' ] ) {
                        	htm += '<option value="' + idx + '"' + ( idx == row[ 'Option_' + i ][ 'value' ] ? ' selected="selected"' : '' ) + '>' + row[ 'Option_' + i ][ 'options' ][ idx ][ 0 ] + '</option>';
                		}
                        htm += '</select>';
                    } else {
                		for( var idx in row[ 'Option_' + i ][ 'options' ] ) {
                        	htm += row[ 'Option_' + i ][ 'options' ][ idx ][ 0 ];
                		}
                    }

                    htm += '</td>';
                    htm += '</tr>';
                }
            }

            htm += '<tr>' +
                '<th>Quantity</th>' +
                '<td><input type="text" name="productQty" value="' + row[ 'Qty' ][ 'value' ] + '" size="2" maxlength="3" class="qty" title="Enter Quantity here..." /> @ &pound;' + row[ 'Base_Price' ][ 'value' ] + '</td>' +
              '</tr>';

            if( row[ 'Instructions' ][ 'value' ] != '' ) {
                htm += '<tr>' +
                    '<th>Personalisation</th>' +
                    '<td><input type="text" name="productMessage" value="" class="text" title="Enter personalised message here..." /></td>' +
                    '</tr>';
            }


            htm += '</table>' +
                '<input type="submit" value="Add to order &#187;" class="button" /><br/>' +
                '<input type="button" value="<< Cancel" class="button" onclick="javascript:history.go(-1)"/>' +
            '</form>' +
            '</div>';
        }
        document.write( htm );
    }




    this.adminCheckout = function( flds, currPage, frmAction, frmType ) {

        var htm = ''; // html of the form

        // perform a default set of manipulation on fields
        // which are ommitted from the setup array
        for( var fld in flds ) {
            if( ! iem.output.fldSetup[ fld ] ) {
                iem.output.fldSetup[ fld ] = {
                    'alias' : fld.split( '_' ).join( ' ' ),
                    'key'   : false,
                    'class' : false,
                    'note'  : false
                }
            }
        }

        // build the js command to validate required fields
        var reqCmd = '';

        for( var fld in flds ) {
            if( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'req' ] && flds[ fld ][ 'type' ] != 'HIDDEN' ) {
                reqCmd += 'this.fld' + flds[ fld ][ 'idx' ] + '_1,';
            }
        }
        if( reqCmd.length > 0 ) {
            reqCmd = reqCmd.substring( 0, reqCmd.length - 1 );
        }

        htm += '<form name="frmCheckout" method="post" action="' + frmAction + '" onsubmit="return iem.output.validateForm(' + reqCmd + ');" name="checkoutForm" AUTOCOMPLETE="off">';

        htm += '<div class="formText" style="text-align: left;">';


        // AW
        // print out all hidden fields
        for( var fld in flds ) {
            if( flds[ fld ][ 'type' ] == 'HIDDEN' ) {
                htm += '<input type="hidden" name="' + fld + '" value="' + flds[ fld ][ 'value' ] + '" />\n';
            }

            // field value overwritten for admin section
            if( window.location.pathname.indexOf( 'admin' ) > -1 ) {
              if( fld == 'EMail' && flds[ fld ][ 'value' ] == '' ) {
                flds[ fld ][ 'value' ] = 'unregistered@sleepovercompany.com';
              }
            }
        }


        var fldOrder = { 'Promotional_Codes' : true, 'EMail' : true, 'Telephone' : true, 'Mobile' : true, 'Fax' : true, 'Title' : true, 'First_Name' : true, 'Surname' : true, 'Company_Name' : true, 'Address_1' : true, 'Street' : true, 'Address_2' : true, 'Town' : true, 'County' : true, 'Postcode' : true, 'Country' : true, 'Delivery_Title' : true, 'Delivery_First_Name' : true, 'Delivery_Surname' : true, 'Delivery_Company_Name' : true, 'Delivery_Address_1' : true, 'Delivery_Street' : true, 'Delivery_Address_2' : true, 'Delivery_Town' : true, 'Delivery_County' : true, 'Delivery_Postcode' : true, 'Delivery_Country' : true, 'Delivery_Telephone' : true, 'Delivery_Notes' : true, 'Comments' : true, 'Card_Name' : true, 'Card_Type' : true, 'Card_Number' : true, 'Card_Start' : true, 'Card_End' : true, 'Card_Issue_Number' : true, 'Card_CV2' : true, 'Mail_Lists' : true, 'Gift_Wrapping' : true, 'Old_Pwd' : true, 'New_Pwd' : true, 'New_Pwd_Check' : true, 'Pwd' : true, 'Pwd_Check' : true }

        // print out input fields
        for( var fld in fldOrder ) {
            if( flds[ fld ] ) {
                if( flds[ fld ][ 'type' ] != 'HIDDEN' ) {

                    var reqMark = '';
                    var fldDesc = fld;

                    if( iem.output.fldSetup[ fld ] ) {
                        if( iem.output.fldSetup[ fld ][ 'alias' ] ) {
                            fldDesc = iem.output.fldSetup[ fld ][ 'alias' ];
                        }
                        if( iem.output.fldSetup[ fld ][ 'req' ] ) {
                            reqMark = ' <span class="red">*</span>';
                        }
                    }

                    var fldDisp = '';

                    var matchedChar = false;
                    var currChar = 0;

                    if( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'key' ] ) {
                        while( ! matchedChar && currChar <= fldDesc.length ) {
                            if( fldDesc.charAt( currChar ).toLowerCase() == iem.output.fldSetup[ fld ][ 'key' ].toLowerCase() ) {
                                fldDisp += '<u>' + fldDesc.charAt( currChar ) + '</u>';
                                matchedChar = true;
                            } else {
                                fldDisp += fldDesc.charAt( currChar );
                            }
                            currChar++;
                        }
                    }

                    fldDisp += fldDesc.substring( currChar ) + reqMark;

                    var fldCode = '';
                    if( iem.output.fldSetup[ fld ] ) {
                        fldCode += ' class="' + ( iem.output.fldSetup[ fld ][ 'class' ] ? iem.output.fldSetup[ fld ][ 'class' ] : 'l' ) + '"' + ( iem.output.fldSetup[ fld ][ 'key' ] ? ' accesskey="' + iem.output.fldSetup[ fld ][ 'key' ] + '"' : '' );
                    }

                    var fldName = 'fld' + flds[ fld ][ 'idx' ] + '_1';

                    switch( fld ) {
                        case 'Country' : {
                            htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">' +
                                '    <input' + fldCode + ' type="text" name="' + fldName + '" value="UNITED KINGDOM" title="' + fldDesc + '" readonly="readonly" />' +
                                '</div>\n';
                            break;
                        }
                        case 'Delivery_Country' : {
                            htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">' +
                                '    <input type="text" name="' + fldName + '" value="UNITED KINGDOM" title="' + fldDesc + '" readonly="readonly" />' +
                                '</div>';
                            break;
                        }
                        case 'Card_Number' : {
                            htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">' +
                                '    <input' + fldCode + ' type="text" name="' + fldName + '" value="" onblur="convert(this);" title="' + fldDesc + '" />' +
                                '</div>';
                            break;
                        }
                        case 'Card_Start' :
                        case 'Card_End' : {
                        	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                '<div class="formElement">';

                            // generate month drop down
                            var months = new Array( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
                            htm += '    <select' + fldCode + ' name="' + fldName + '_mm" onchange="this.form[ \'' + fldName + '\' ].value=this.form[ \'' + fldName + '_mm\' ][ this.form[ \'' + fldName + '_mm\' ].selectedIndex ].value + \'/\' + this.form[ \'' + fldName + '_yyyy\' ][ this.form[ \'' + fldName + '_yyyy\' ].selectedIndex ].value" title="' + fldDesc + '">' +
                                '     <option value=""> -- </option>';
                            for( var i = 0; i < 12; i++ ) {
                                htm += '     <option value="' + ( i + 1 ) + '">' + months[ i ] + '</option>';
                            }
                            htm += '    </select>';

                            // generate year drop down
                            var currDate = new Date();
                            var currYear = currDate.getFullYear();
                            var maxAge = 30;

                            htm += '    <select' + fldCode + 'name="' + fldName + '_yyyy" onchange="this.form[ \'' + fldName + '\' ].value=this.form[ \'' + fldName + '_mm\' ][ this.form[ \'' + fldName + '_mm\' ].selectedIndex ].value + \'/\' + this.form[ \'' + fldName + '_yyyy\' ][ this.form[ \'' + fldName + '_yyyy\' ].selectedIndex ].value" title="' + fldDesc + '">' +
                                '     <option value=""> -- </option>';
                            if( fld == 'Card_Start' ) {
                                for( var i = currYear; i > currYear - maxAge; i-- ) {
                                    htm += '     <option value="' + i + '">' + i + '</option>';
                                }
                            } else {
                                for( var i = currYear; i < currYear + maxAge; i++ ) {
                                    htm += '     <option value="' + i + '">' + i + '</option>';
                                }
                            }

                            htm += '    </select>' +
                                '    <input type="hidden" name="' + fldName + '" title="' + fldDesc + '">' +
                                '</div>';
                            break;
                        }
                        case 'Mail_Lists' : {
                        	htm += '<div class="formLabelLong">' + fldDisp + ':</div>\n' +
                        	    '<div class="formElementLong">';
                            for( var opt in flds[ fld ][ 'options' ] ) {
                                // horrific way of concatenating checkbox values into a hidden field
                                htm += '    <input class="noborder" type="checkbox" name="' + fld + '_' + opt + '" value="' + flds[ fld ][ 'options' ][ opt ] + '" onclick="this.form.' + fld + '.value=\'\'; for( var i = 0; i < this.form.elements.length; i++ ) { if( this.form.elements[ i ].checked && this.form.elements[ i ].name.indexOf( \'' + fld + '\' ) != -1 ) { this.form.' + fld + '.value += this.form.elements[ i ].value + \',\'; } } this.form.' + fld + '.value=this.form.' + fld + '.value.substring( 0, this.form.' + fld + '.value.length - 1 );" title="' + fldDesc + '" />' + flds[ fld ][ 'options' ][ opt ] + ' ';
                            }
                            htm += '    <input type="hidden" name="' + fld + '" value="" />&nbsp;' +
                                '</div><hr />';
                            break;
                        }
                        case 'Mobile' :
                        case 'Fax' :
                        case 'Delivery_Notes' :
                        case 'Comments' :

                        case 'Delivery_Telephone' :
                        case 'Delivery_Method' :
                        case 'Spare_1' :
                        case 'Gift_Wrapping' :
                        case 'Pwd_Reminder' : {
                            break;
                        }
                        default : {

                            if( flds[ fld ][ 'options' ] ) {

                                if( fld == 'Title' ) {
                                    htm += '<br />';
                                    htm += '<div class="formText">';
                                    htm += '<h2>3. Address Details</h2>';
                                    htm += 'Please enter your name and address detals. These must match those registered with your card issuer.';
                                    htm += '</div>';
                                }
                                if( fld == 'Delivery_Title' ) {
                                    htm += '<br />';
                                    htm += '<div class="formText">Delivery address if different:</div>';
                                }

                            	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                            	    '<div class="formElement">' +
                                    '    <select name="' + fldName + '"' + fldCode + ' title="' + fldDesc + '">';
                                for( var opt in flds[ fld ][ 'options' ] ) {
                                    htm += '     <option value="' + flds[ fld ][ 'options' ][ opt ] + '"' + ( flds[ fld ][ 'value' ] == flds[ fld ][ 'options' ][ opt ] ? ' selected="selected"' : '' ) + '>' + flds[ fld ][ 'options' ][ opt ] + '</option>';
                                }
                                htm += '    </select>' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                    '</div>';
                            } else {
                                switch( flds[ fld ][ 'type' ] ) {
                                    case 'LARGE_TEXT' : {

                                        if( fld == 'Notes' && frmType == 'register' ) {
                                            break;
                                        }

                                    	htm += '<div class="formLabelLong">' + fldDisp + ':</div>' +
                                    	    '<div class="formElementLong">' +
                                            '    <textarea name="' + fldName + '"' + fldCode + ' style="width: 475px;" title="' + fldDesc + '">' + flds[ fld ][ 'value' ] + '</textarea>' +
                                            '</div>';
                                        break;
                                    }
                                    case 'BOOL' : {
                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                    	    '<div class="formElement">' +
                                            '    <input' + fldCode + ' type="checkbox" style="border: 0" name="' + fldName + '" title="' + fldDesc + '" />' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                            '</div>';
                                        break;
                                    }
                                    case 'PASSWORD' : {
                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                    	    '<div class="formElement">' +
                                            '    <input' + fldCode + ' type="password" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" title="' + fldDesc + '" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                            '</div>';
                                        break;
                                    }
                                    default: {
                                        if( fld == 'EMail' ) {
                                            htm += '<br />';
                                            htm += '<div class="formText">';
                                            htm += '<h2>2. Your Contact Details</h2>';
                                            htm += 'We need a contact number in case we have any problems with your order.';
                                            htm += '<br /><b><a href="http://www.sleepovercompany.com/customer_service/index_12.html" target="_blank">Our privacy policy</a></b>';
                                            htm += '</div>';
                                        }
                                        if( fld == 'Card_Name' ) {
                                            htm += '<br />';
                                            htm += '<div class="formText">';
                                            htm += '<h2>4. Card Details</h2>';
                                            htm += 'Please enter your credit card details, including the 3-digit code found on the back of your card, near the signature strip.';
                                            htm += '</div>';
                                        }
                                        if( fld == 'EMail' ) {
                                            if( iem.request.getField( 'usr_1' ) ) {
                                                flds[ fld ][ 'value' ] = iem.request.getField( 'usr_1' );
                                            }
                                        }
                                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                    	    '<div class="formElement">' +
                                            '    <input' + fldCode + ' type="text" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" onblur="convert(this);" title="' + fldDesc + '" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                            '</div>';
                                        break;
                                    }
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }



        // AW end

        /*        if( iem.response.getField( 'cartErrNo' ) > 0 ) {
            document.write( '<p class="error">Error ' + iem.response.getField( 'cartErrNo' ) + ': <strong>' + iem.response.getField( 'cartError' ) + '</strong></p>' );
        }

        var formHeadings = {
            'checkout' : {
                '1' : 'STEP 2: User Details &amp; Profile',
                '2' : 'STEP 3: Delivery Details',
                '3' : 'STEP 4: Card Information'
            },
            'register' : {
                '1' : 'Your Details'
            }
        }

        //document.title = formHeadings[ frmType ][ currPage ];

    	//htm += '<div class="formText"><h2>' + formHeadings[ frmType ][ currPage ] + '</h2></div>';
    	htm += '</div>';
        htm += '<div class="formText">';

        // print out all hidden fields
        for( var fld in flds ) {
            if( flds[ fld ][ 'type' ] == 'HIDDEN' ) {
                htm += '<input type="hidden" name="' + fld + '" value="' + flds[ fld ][ 'value' ] + '" />\n';
            }
        }

        htm += '</div>' +
    	    '<div id="formDetails">';

        // print out input fields
        for( var fld in flds ) {
            if( flds[ fld ][ 'type' ] != 'HIDDEN' ) {


				// field value overwritten for admin section
			    if( window.location.pathname.indexOf( 'admin' ) > -1 ) {
			    	if( fld == 'EMail' && flds[ fld ][ 'value' ] == '' ) {
						flds[ fld ][ 'value' ] = 'unregistered@sleepovercompany.com';
			    	}
			   	}


                var reqMark = '';
                var fldDesc = fld;

                if( iem.output.fldSetup[ fld ] ) {
                    if( iem.output.fldSetup[ fld ][ 'alias' ] ) {
                        fldDesc = iem.output.fldSetup[ fld ][ 'alias' ];
                    }
                    if( iem.output.fldSetup[ fld ][ 'req' ] ) {
                        reqMark = ' <span class="red">*</span>';
                    }
                }

                var fldDisp = '';

                var matchedChar = false;
                var currChar = 0;

                if( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'key' ] ) {
                    while( ! matchedChar && currChar <= fldDesc.length ) {
                        if( fldDesc.charAt( currChar ).toLowerCase() == iem.output.fldSetup[ fld ][ 'key' ].toLowerCase() ) {
                            fldDisp += '<u>' + fldDesc.charAt( currChar ) + '</u>';
                            matchedChar = true;
                        } else {
                            fldDisp += fldDesc.charAt( currChar );
                        }
                        currChar++;
                    }
                }

                fldDisp += fldDesc.substring( currChar ) + reqMark;

                var fldCode = '';
                if( iem.output.fldSetup[ fld ] ) {
                    fldCode += ' class="' + ( iem.output.fldSetup[ fld ][ 'class' ] ? iem.output.fldSetup[ fld ][ 'class' ] : 'l' ) + '"' + ( iem.output.fldSetup[ fld ][ 'key' ] ? ' accesskey="' + iem.output.fldSetup[ fld ][ 'key' ] + '"' : '' );
                }

                var fldName = 'fld' + flds[ fld ][ 'idx' ] + '_1';

                switch( fld ) {
                    case 'Country' : {
                        htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                            '<div class="formElement">' +
                            '    <input' + fldCode + ' type="text" name="' + fldName + '" value="United Kingdom" title="' + fldDesc + '" />' +
                            '</div>\n';

                        if( frmType == 'checkout' ) {
                            htm +=  '<div class="formLabel">Use this as <u>D</u>elivery Address</div>\n' +
                                '<div class="formElement">' +
                                '    <select name="nextPage" accesskey="d" title="' + fldDesc + '">' +
                                '     <option value="3" selected="selected">Yes</option>' +
                                '     <option value="2">No</option>' +
                                '    </select> If \'No\' you can change this next' +
                                '</div>';
                        }
                        htm += '<hr />';
                        break;
                    }
                    case 'Delivery_Country' : {
                        htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                            '<div class="formElement">' +
                            '    <input type="text" name="' + fldName + '" value="United Kingdom" onblur="" title="' + fldDesc + '" />' +
                            '</div>';
                        break;
                    }
                    case 'Card_Number' : {
                        htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                            '<div class="formElement">' +
                            '    <input' + fldCode + ' type="text" name="' + fldName + '" value="" onblur="convert(this);" title="' + fldDesc + '" />' +
                            '</div>';
                        break;
                    }
                    case 'Card_Start' :
                    case 'Card_End' : {
                    	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                            '<div class="formElement">';

                        // generate month drop down
                        var months = new Array( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' );
                        htm += '    <select' + fldCode + ' name="' + fldName + '_mm" onchange="this.form[ \'' + fldName + '\' ].value=this.form[ \'' + fldName + '_mm\' ][ this.form[ \'' + fldName + '_mm\' ].selectedIndex ].value + \'/\' + this.form[ \'' + fldName + '_yyyy\' ][ this.form[ \'' + fldName + '_yyyy\' ].selectedIndex ].value" title="' + fldDesc + '">' +
                            '     <option value=""> -- </option>';
                        for( var i = 0; i < 12; i++ ) {
                            htm += '     <option value="' + ( i + 1 ) + '">' + months[ i ] + '</option>';
                        }
                        htm += '    </select>';

                        // generate year drop down
                        var currDate = new Date();
                        var currYear = currDate.getFullYear();
                        var maxAge = 10;

                        htm += '    <select' + fldCode + 'name="' + fldName + '_yyyy" onchange="this.form[ \'' + fldName + '\' ].value=this.form[ \'' + fldName + '_mm\' ][ this.form[ \'' + fldName + '_mm\' ].selectedIndex ].value + \'/\' + this.form[ \'' + fldName + '_yyyy\' ][ this.form[ \'' + fldName + '_yyyy\' ].selectedIndex ].value" title="' + fldDesc + '">' +
                            '     <option value=""> -- </option>';
                        if( fld == 'Card_Start' ) {
                            for( var i = currYear; i > currYear - maxAge; i-- ) {
                                htm += '     <option value="' + i + '">' + i + '</option>';
                            }
                        } else {
                            for( var i = currYear; i < currYear + maxAge; i++ ) {
                                htm += '     <option value="' + i + '">' + i + '</option>';
                            }
                        }
                        htm += '    </select>' +
                            '    <input type="hidden" name="' + fldName + '" title="' + fldDesc + '">' +
                            '</div>';
                        break;
                    }
                    case 'Mail_Lists' : {
                    	htm += '<div class="formLabelLong">' + fldDisp + ':</div>\n' +
                    	    '<div class="formElementLong">';
                        for( var opt in flds[ fld ][ 'options' ] ) {
                            // horrific way of concatenating checkbox values into a hidden field
                            htm += '    <input class="noborder" type="checkbox" name="' + fld + '_' + opt + '" value="' + flds[ fld ][ 'options' ][ opt ] + '" onclick="this.form.' + fld + '.value=\'\'; for( var i = 0; i < this.form.elements.length; i++ ) { if( this.form.elements[ i ].checked && this.form.elements[ i ].name.indexOf( \'' + fld + '\' ) != -1 ) { this.form.' + fld + '.value += this.form.elements[ i ].value + \',\'; } } this.form.' + fld + '.value=this.form.' + fld + '.value.substring( 0, this.form.' + fld + '.value.length - 1 );" title="' + fldDesc + '" />' + flds[ fld ][ 'options' ][ opt ] + ' ';
                        }
                        htm += '    <input type="hidden" name="' + fld + '" value="" />&nbsp;' +
                            '</div><hr />';
                        break;
                    }
                    case 'Spare_1' :
                    case 'Pwd_Reminder' : {
                        break;
                    }
                    default : {

                        if( flds[ fld ][ 'options' ] ) {
                        	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                        	    '<div class="formElement">' +
                                '    <select name="' + fldName + '"' + fldCode + ' title="' + fldDesc + '">';
                            for( var opt in flds[ fld ][ 'options' ] ) {
                                htm += '     <option value="' + flds[ fld ][ 'options' ][ opt ] + '"' + ( flds[ fld ][ 'value' ] == flds[ fld ][ 'options' ][ opt ] ? ' selected="selected"' : '' ) + '>' + flds[ fld ][ 'options' ][ opt ] + '</option>';
                            }
                            htm += '    </select>' +
                                '</div>';
                        } else {
                            switch( flds[ fld ][ 'type' ] ) {
                                case 'LARGE_TEXT' : {

                                    if( fld == 'Notes' && frmType == 'register' ) {
                                        break;
                                    }

                                	htm += '<div class="formLabelLong">' + fldDisp + ':</div>' +
                                	    '<div class="formElementLong">' +
                                        '    <textarea name="' + fldName + '"' + fldCode + ' style="width: 475px;" title="' + fldDesc + '">' + flds[ fld ][ 'value' ] + '</textarea>' +
                                        '</div>';
                                    break;
                                }
                                case 'BOOL' : {
                                	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                	    '<div class="formElement">' +
                                        '    <input' + fldCode + ' type="checkbox" style="border: 0" name="' + fldName + '" title="' + fldDesc + '" />' +
                                        '</div>';
                                    break;
                                }
                                case 'PASSWORD' : {
                                	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                	    '<div class="formElement">' +
                                        '    <input' + fldCode + ' type="password" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" title="' + fldDesc + '" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                        '</div>';
                                    break;
                                }
                                default: {
                                    if( fld == 'EMail' ) {
                                        if( iem.request.getField( 'usr_1' ) ) {
                                            flds[ fld ][ 'value' ] = iem.request.getField( 'usr_1' );
                                        }
                                    }
                                	htm += '<div class="formLabel">' + fldDisp + '</div>\n' +
                                	    '<div class="formElement">' +
                                        '    <input' + fldCode + ' type="text" name="' + fldName + '" value="' + flds[ fld ][ 'value' ] + '" onblur="" title="' + fldDesc + '" /> ' + ( iem.output.fldSetup[ fld ] && iem.output.fldSetup[ fld ][ 'note' ] ? iem.output.fldSetup[ fld ][ 'note' ] : '' ) +
                                        '</div>';
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }

        // confirm address details
        if( currPage == 3 ) {
            for( var fld in flds ) {
                if( flds[ fld ][ 'type' ] == 'HIDDEN' ) {
                    if( fld != 'cartId' && fld != 'location' && fld != 'func_1' && fld != 'nextPage' ) {
                        //htm += '<tr><td colspan="2">' + flds[ fld ][ 'value' ] + '</td></tr>\n';
                        //htm += '<tr><th>' + fld.split( '_' ).join( ' ' ) + '</th><td>' + flds[ fld ][ 'value' ] + '</td></tr>\n';
                    }
                }
            }
        }
        */

    	htm += '<span class="formLabel"><input type="button" onclick="javascript:history.go(-1)" value="&#171; Back" class="prev" /> <input type="button" onclick="javascript:iem.CartClear();iem.CartSubmit(\'http://www.sleepovercompany.com/admin/\');" value="Cancel" class="prev" /></span>';
    	htm += '<span class="formElement"><input type="submit" value="Continue &#187;" class="next" /></span>';

        htm += '<br style="clear: both;" />'
        htm += '</form>';
        htm += '</div>';


        document.write( htm );
    }


    //  generic form validation function
    //  pass a list of form field objects, and each will be checked for a value
    //  fields containing 'email' in the name will be checked for an email-format value
    //  tim@saltstonemedia.co.uk

    this.validateForm = function() {

        var flds = iem.output.validateForm.arguments;
        var val = true;
        var err = '';

        var firstFld = null;

        for( var i = 0; i < flds.length; i++ ) {
            if( flds[ i ] ) {
                if( typeof( flds[ i ].type ) != 'undefined' ) {
                    switch( flds[ i ].type ) {
                        case 'select-one' : {
                            if( ! flds[ i ].options[ flds[ i ].selectedIndex ].value ) {
                                val = false;
                                err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must be selected.\n';
                            }
                            break;
                        }
                        case 'checkbox' : {
                            if( ! flds[ i ].checked ) {
                                val = false;
                                err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must be checked.\n';
                            }
                            break;
                        }
                        default : {
                            if( ! flds[ i ].value ) {
                                val = false;
                                err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must be completed.\n';
                            } else {

                                var fldTxt = flds[ i ].name;
                                if( flds[ i ].title ) fldTxt += ' ' + flds[ i ].title;

                                if( fldTxt.toLowerCase().indexOf( 'email' ) != -1 || fldTxt.toLowerCase().indexOf( 'e-mail' ) != -1 ) {
                                    // assume from the field name that this should be an email address

                                    var mailEx = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
                                    if( ! mailEx.test( flds[ i ].value ) ) {
                                        val = false;
                                        err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must contain an e-mail address.\n';
                                    }
                                }

                                if( fldTxt.toLowerCase().indexOf( 'postcode' ) != -1 ) {
                                    // assume from the field name that this should be postcode

                                    if( flds[ i ].value.length < 5 || flds[ i ].value.length > 10 ) {
                                        val = false;
                                        err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must contain a postcode, 5-10 characters long.\n';
                                    }
                                }

                                if( fldTxt.toLowerCase().indexOf( 'issue' ) != -1 ) {
                                    // assume from the field name that this should be issue number
                                    if( parseInt( flds[ i ].value ) > 99 ) {
                                        val = false;
                                        err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must contain an issue number of 1-2 digits.\n';
                                    }
                                }
                            }
                        }
                    }
                } else {
                    var chk = false;
                    for( var btn = 0; btn < flds[ i ].length; btn++ ) {
                        if( flds[ i ][ btn ].type == 'radio' ) {
                            if( flds[ i ][ btn ].checked ) chk = true;
                        }
                    }
                    if( ! chk ) {
                        val = false;
                        err += ( flds[ i ].title ? flds[ i ].title : flds[ i ].name ) + ' must be selected.\n';
                    }
                }
            }
            if( err && ! firstFld ) {
                firstFld = flds[ i ];
            }
        }
        if( ! val ) {
            alert( err );
            if( typeof( firstFld.select ) == 'function' ) {
                firstFld.select();
            } else {
                firstFld.focus();
            }
        }
        return val;
    }

    this.previewSort = function( a, b ) {

        var orderA = a[ 'View_Order' ][ 'value' ];
        var orderB = b[ 'View_Order' ][ 'value' ];

        if( orderB > orderA )
            return -1;
        else if ( orderA == orderB )
            return 0;
        else
            return 1;
    }
}
