// this file contains general officeworks javascript code which may
// apply to any (and or every) printworks page
//

// ----------------------------------------------------------------------------
// Store locator functionality
var lastPostcode = '';
var storeInfo = {};
var storeJsonUrl = 'ow/stores-by-postcode.php?postcode=POSTCODE';

function storeSelected() {
   // figure out which store was picked... we subtract one for the "select your store" option
   var indx = $('#store-delivery-dropdown').attr("selectedIndex") - 1;
   var store = storeInfo[indx];

   $('#JT_DeliveryAddress_del_Name').val(store.name);
   $('#JT_DeliveryAddress_del_AddressOne').val(store.address1 + ' ' + store.address2);
   $('#JT_DeliveryAddress_del_AddressTwo').val(store.name);
   $('#JT_DeliveryAddress_del_Memo').val('-Pickup from Store-');
   $('#JT_DeliveryAddress_del_City').val('-Store Delivery-');
   $('#JT_DeliveryAddress_del_Country').val('Australia');

   try {
//      var storePostcode = store.address2.trim().replace(/.* /,'');
	  //trim() is not a string function in javascript. use jquery trim instead
      var storePostcode = $.trim(store.address2).replace(/.* /,'');
      $('#JT_DeliveryAddress_del_Zip').val(storePostcode);
   } catch (err) {
      // bummer
      $('#JT_DeliveryAddress_del_Zip').val('0000');
   }
}

function setupStoreLocator() {

   if($('legend:contains(Delivery Address)').length && $('input[name=JT_DeliveryAddress_del_AddressOne]').length) {
           
      // guard against doing this twice
      if( $('fieldset:eq(1) tbody.store-locator').length > 0) {
          return;
      }
           
      // note down that the existing fields are NOT for store delivery
      $('fieldset:eq(1)').find('tr').addClass('not-store-delivery-row');

      // NOTE: this bit is temporary until steve updates the code
      // shove a radio selector in 
      $('fieldset:eq(1)').find('tbody').addClass('store-locator').prepend(''
         + ' <tr>      '
         + ' <td colspan="3">      '
         + ' <div class="deliv-options">    '
         + ' <div class="left">    '
         + ' <h1>Select your Delivery Option</h1>    '
         + ' Please choose either Delivery or In Store Pickup from the options on the right.      '
         + ' </div>    '
         + ' <div class="right">      '
         + ' <img src="/ow/css/images/delivery_button_on.png" class="deliv-selection" alt="Delivery"/>    '
         + ' <img src="/ow/css/images/collect_button_off.png" class="pickup-selection" alt="Pickup from Store"/>      '
         + ' </div>    '
         + ' <div class="clear"/>     '
         + '     '
         + ' <input class="checkbox" type="checkbox" id="store-delivery" checked>     '
         + '     '
         + ' </div>    '
         + ' </td>     '
         + ' </tr>     '
         + '');  
//      + '<tr><td>&nbsp;</td></tr>');  


      // add a bunch of fields to be shown for store delivery 
      $('fieldset:eq(1)').find('tbody').append('<tr class="store-delivery-row"><td class="label">Closest Postcode:</td><td class="data-entry"><input type="text" id="store-postcode" name="store-postcode" maxlength="4"/><img src="/ow/css/images/small-ajax.gif" id="ajax-load"/></td></tr>');
      $('#store-postcode').addClass('fontFamily_normalText fontSize_normalText fontColor_normalText borderColor_inputField borderWidth_inputField borderStyle_inputField backgroundColor_inputField');

      var hideUnused = true; // more for dev testing than anything else

      // update the checkbox selection based on image selection
      $('.deliv-selection').click(function() {
         $('#store-delivery').attr('checked',true);
         $('.deliv-selection').attr('src','/ow/css/images/delivery_button_on.png');
         $('.pickup-selection').attr('src','/ow/css/images/collect_button_off.png');

          $('.store-delivery-row').hide();
         if (hideUnused) {
          $('.not-store-delivery-row').show();
         }
      });
      $('.pickup-selection').click(function() {
         $('#store-delivery').attr('checked',false);
         $('.deliv-selection').attr('src','/ow/css/images/delivery_button_off.png');
         $('.pickup-selection').attr('src','/ow/css/images/collect_button_on.png');

          $('.store-delivery-row').show();
         if (hideUnused) {
          $('.not-store-delivery-row').hide();
         }
      });
      


     try { parent.c_OnSetIFrameHeight($('#DivHeightDetection').outerHeight() + 150); } catch (err) {}

   }

  // watch the postcode field for changes and look up stores if necessary
  $('#store-postcode').bind('keyup change', function() {
    var postcode = $('#store-postcode').val();
    if (postcode.length == 4 && !(postcode == lastPostcode)) {
      lastPostcode = postcode;

      // remove any existing store delivery dropdowns
      $('#store-dropdown-row').remove();

      var storesUrl = storeJsonUrl.replace(/POSTCODE/,postcode);

      $('#ajax-load').show();

      // kick off ajax to retrieve the closest stores
      $.ajax({
            url: storesUrl,
            dataType: 'text',
            data: {},
            success: function(realData) {
            $('body').append('<div class="json">' + data + '</data>');
               var data = JSON.parse(realData);
                
               // select pickup just in case somebody changed screens on us
               $('.pickup-selection').click(); 

               // remove again.. just in case multiples were kicked off
               $('#store-dropdown-row').remove();

               var dropDown = $('<select id="store-delivery-dropdown" name="store-delivery-dropdown"/>');
               var stores = data['stores'];
               storeInfo = stores;

               dropDown.append('<option value="">-Select a Store-</option>');

               for (i=0;i<10;i++) {
                 dropDown.append('<option value="' + stores[i].name + '">' + stores[i].name + '</option>');
               }


               $('fieldset:eq(1)').find('tbody').append( ''
                  + '<tr id="store-dropdown-row" class="store-delivery-row">'
                  + ' <td>Store:</td>'
                  + ' <td id="store-delivery-dropdown-holder"></td></tr>');

               
               // add the new dropdown
               $('#store-delivery-dropdown-holder').append(dropDown);
         
               // add all the helix classes to the store dropdown
               $('#store-delivery-dropdown').addClass('fontFamily_normalText fontSize_normalText fontColor_normalText borderColor_inputField borderWidth_inputField borderStyle_inputField backgroundColor_inputField');
               $('.store-delivery-row').show();
         
               // focus the store list dropdown
               $('#store-delivery-dropdown').focus();

               $('#store-delivery-dropdown').change(storeSelected); 

               $('#ajax-load').hide();
            },
beforeSend: function(x) {
  if(x && x.overrideMimeType) {
   x.overrideMimeType("application/j-son;charset=UTF-8");
  }
 },
            
error: function(XMLHttpRequest, textStatus, errorThrown) {
                 alert('err ' + textStatus + '\nerror was ' + errorThrown.message);
         }
      });


     }
  });
}

function addDeliveryHover() {
   if($('legend:contains(Delivery Address)').length && $('input[name=JT_DeliveryAddress_del_AddressOne]').length) {
      // guard against multiple runs
      if ($('#delivery-policy-link.js-done').length) {
        return;
      }
      $('#delivery-policy-link').addClass('js-done').prepend(''
         + '<div class="free-deliv-box">'
         + ' Free delivery for orders over $55 - <img src="ow/css/images/questionmark_icon.png" id="questionMarkImage" />'
         + ' <div class="deliv-popup-holder">'
         + '  <div id="freeDeliveryInfo-popup" class="freeDeliveryInfo-popup"> '
         + '   <div class="freeDeliveryInfo-container"> '
         + '    <h1> FREE Delivery for orders over $55* </h1> <p class="i1"> Also applies when you chose to have your order<br/> '
         + '     delivered to store.  </p> '
         + '   </div> '
         + '  </div>'
         + ' </div>'
         + '</div>'
         ).append( ''
         + '<div class="clear"></div>'
         );

      $("#questionMarkImage").hover(
         function() { $('#freeDeliveryInfo-popup').show(); },
         function() { $('#freeDeliveryInfo-popup').hide(); }
      );
      
   }
}

// ----------------------------------------------------------------------------
// colour count popup
function checkColourCount() {

try {
   // make sure we only display this on the page with colour selection
   if ($('#JT_PrinterOptions_DIF_Color').length == 0) {
    return;
   }

   var colourText = $('#Order_PageInfo').val();

   // grab everything before the slash as colour page count
//   var colourPages = colourText.replace(/\/.*$/,'').trim();
	  //trim() is not a string function in javascript. use jquery trim instead
   var colourPages = $.trim(colourText.replace(/\/.*$/,''));

   // grab everything after the slash as bw page count
//   var bwPages = colourText.replace(/^.*?\//,'').trim();
	  //trim() is not a string function in javascript. use jquery trim instead
   var bwPages = $.trim(colourText.replace(/^.*?\//,''));

   if (colourPages != bwPages && bwPages != 0) {
    $.modal(''
        + '<div class="ow-modal">'
        + '<h1>Officeworks Top-Tip:</h1>'
        + '<div class="tip-text">'
        + ' We\'ve noticed your document contains some black and white pages as well as some colour ones!<br/><br/>'
        + ' If you\'d like to print this document in black and white please select "Only B/W" from the "Colour Print" selection box before you continue.<p/>'
        + '</div>'
            + '</div>'
        ,
        {position:['80px','15px'],minHeight:300,opacity:80}
    );
    $('.ow-modal').corner();
	//scroll the modal to top, position specified in the modal above only sets inside the iframe
    $(window.parent.document).scrollTop($('div.ow-modal').position().top);
   }
 }
 catch (err) {}
}


//----------------------------------------------------------------------------
//page size warning - tell the user the page size they upload is the page size used for printing.
var fileUploadSelector = '#Upload_UserFile';
//function waitToOpenFileChooser() {
//	$(fileUploadSelector).each(function(i, value) {alert(i + " : " + value);});
//
//	$(fileUploadSelector).click();
//}

function pageSizeWarning() {
	if (window.parent.OPS_pageSizeWarningShown == undefined) window.parent.OPS_pageSizeWarningShown = false;

	$(fileUploadSelector).click(function(e) {
		displayModal(e);
	});

	function displayModal(e) {
//		alert('start: ' + e.isDefaultPrevented());

		if (window.parent.OPS_pageSizeWarningShown != true) {
//			e.preventDefault();
			window.parent.OPS_pageSizeWarningShown = true; 

			$.modal(''
					+ '<div class="ow-modal">'
					+ '<h1>Officeworks Top-Tip:</h1>'
					+ '<div class="tip-text">'
					+ ' The document page sizes you upload will be the page sizes used for printing your order.<br/><br/>'
					+ '</div>'
					+ '</div>'
					,
					{position:['80px','15px'],minHeight:300,opacity:80,onClose:function(dialog) {this.close();}}
//					{position:['80px','15px'],minHeight:300,opacity:80,onClose:function(dialog) {setTimeout("waitToOpenFileChooser()", 1000); this.close();}}
			);
			$('.ow-modal').corner();
			//scroll the modal to top, position specified in the modal above only sets inside the iframe
		    try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }
		}

		return;
	}
}

//----------------------------------------------------------------------------
//delivery information table 
function addDeliveryInformationTable() {
   if($('legend:contains(Delivery Address)').length && $('input[name=JT_DeliveryAddress_del_AddressOne]').length) {
		if ($('body.deliv-table-done').length) {
			return;
		}
		$('body').addClass('deliv-table-done');

		var fieldsets = $('fieldset:contains(Delivery Address):eq(0), fieldset:contains(General Job Settings):eq(0)');
		if (fieldsets.size() == 0) return;

		// now setup the deliver information table.
		//$(fieldsets).eq(0).wrap('<div class="checkoutAddress_fieldsetDiv"></div>');
		$(fieldsets).css('width', '55%');
		$(fieldsets).eq(1).css('display', 'inline');
		
		var theDiv = $('#checkoutAddress_fieldsetDiv');
		var theTable = '' 
			+ '<table id="checkoutAddress_DeliveryInfoTable" border="1" cellspacing="0">'
			+     '<tr>'
			+         '<td></td><td>SA / WA / NSW / VIC</td><td>TAS / NT / QLD</td>'
			+     '</tr>'
			+     '<tr>'
			+         '<td>Delivery Address</td>'
			+         '<td>2 - 5 Business Days<br/><br/><span class="smalltext">*Above timeframe includes production time</span><br/>&nbsp;</td>'
			+         '<td>4 - 7 Business Days<br/><br/><span class="smalltext">*Above timeframe includes production time</span><br/>&nbsp;</td>'
			+     '</tr>'
			+     '<tr>'
			+         '<td>In Store Pick Up</td>'
			+         '<td colspan="2">Within 48 hours<br/><br/><span class="smalltext">*If the timeframe above (based on your requirements) cannot be met your selected store will contact you</span><br/>&nbsp;</td>'
			+     '</tr>'
			+ '</table>'; 
		theDiv.append(theTable);
   }
}


// ----------------------------------------------------------------------------
// delivery policy links
function addDeliveryPolicyLinks() {

   if($('legend:contains(Delivery Address)').length && $('input[name=JT_DeliveryAddress_del_AddressOne]').length) {
      if ($('body.deliv-policy-done').length) {
        return;
      }
      $('body').addClass('deliv-policy-done');

    // find the delivery input section and add the policy link after
    $('fieldset:contains(Delivery Address):eq(0)').parent().eq(0).after(''  
        + '<div id="delivery-policy-link" class="fontColor_normaltext fontSize_normalText fontFamily_normalText">'
        + ' <a href="/ow/delivery-policy.php"'
        + '    rel="defaultPopup" class="popupwindow" >'
        + '     Delivery Policy</a>'
        + '</div>'

        + '<div id="delivery-policy-note" class="fontColor_normaltext fontSize_normalText fontFamily_normalText">'
        + '     * If you require urgent delivery please visit one of our many '
        + '<a href="http://www.officeworks.com.au/retail/b2c/init.do?forward=storeSearchNoBanners" rel="storePopup" class="popupwindow">stores<a/>'
        + ' who can organise speedy printing for you.'
        + '</div>'

        + '<div id="delivery-policy-note" class="fontColor_normaltext fontSize_normalText fontFamily_normalText">'
        + '      ** Please note that any address details you enter here are only saved for this order. '
        + '  To save delivery address changes, please update your profile at: User Info > Addresses'
        + '</div>'
    );


    // because we've fked with the height of this page so much the inbuilt functions no longer work. 
    // ensure that whenever the billing address stuff is checked we change the size to make room for it
    $('#useInvoiceAddress').change(function() {
        try { parent.c_OnSetIFrameHeight($('#DivHeightDetection').outerHeight() + 50); } catch (err) {}
    }); 
    //readjust the height during checkout mode
    $(document).ready(function() {
    	$("#GlobalMiddle #GlobalData", window.parent.document).css('height', '717px');
    });
   }
}

function cornerMiddleSection() {
   $('.WSPageTitleText').not('.cornered').each(function() {
      $(this).addClass('cornered');                   
      $(this).wrap('<div class="ow-light-round-div"/>'); 
      $(this).parents('body:eq(0)').addClass('with-cornered-heading');
   });


  var options = {tl: { radius: 8 },
	  tr: { radius: 8 },
	  bl: { radius: 0 },
	  br: { radius: 0 }};

  $('.ow-light-round-div').corner(options);
}

function addExternalJobProfiles() {

    // don't add them more than once
    if ($('#jobprofilelist .external-profile').length > 0) {
        return;
    }

    $('#jobprofilelist').append(''
        + '<div class="external-profile">'
        + '  <div class="profile-image-box">'
        + '   <img width="70" height="50" alt="" src="ow/css/images/jobTickets/OPS_canvas_art.png">'
        + '  </div>'
        + '  <div class="profile-text-box">'
        + '   Canvas Art'
        + '  </div>'
        + '  <div class="profile-link-box">'
        + '   <input class="canvas-link" value="Start" title="Create Canvas Art"/>'
        + '  </div>'
        + '</div>'
    );

    $('#jobprofilelist').append(''
        + '<div class="external-profile">'
        + '  <div class="profile-image-box">'
        + '   <img width="70" height="50" alt="" src="ow/css/images/jobTickets/OPS_photobooks.png">'
        + '  </div>'
        + '  <div class="profile-text-box">'
        + '   Photobooks'
        + '  </div>'
        + '  <div class="profile-link-box">'
        + '   <input class="photo-books-link" value="Start" title="Create Photo Books"/>'
        + '  </div>'
        + '</div>'
    );

   // add the standard helix classes to our link box
   $('.profile-link-box input').addClass("WSButtonInput1 backgroundColor_button borderColor_button borderWidth_button borderStyle_button fontColor_buttonText fontSize_buttonText fontFamily_buttonText");

   // link back to websites
   $('.canvas-link').click(function(e) {
        e.preventDefault();
        top.location.href = 'http://www.canvasart.officeworks.com.au/RtOrder/Order.aspx';
   });
   $('.photo-books-link').click(function(e) {
        e.preventDefault();
        top.location.href = 'http://www.officeworks.com.au/retail/promo/photobooksintro';
   });

}

function pdfPreviewWarning() {
   // if we're on the pdf preview page then bind our warnings and functions
   if ($('input[name=Order_PDFCheck]').length > 0) {
	   
	   if ($('input[name=Order_PDFCheck]:checked').length <= 0 && !$('#Order_NextButton').attr('disabled')) {
		   $('#Order_NextButton').attr('disabled', true);
		   $('#Order_NextButton').hide();
		   $('#Order_NextButton').parent().hide();
		   $('#Order_NextButton').parent().parent().hide();
	   } 
	   
	   $('input[name=Order_PDFCheck]').click(function(){
		   if($('input[name=Order_PDFCheck]:checked').length > 0 ) {
			   	$('#Order_NextButton').attr('disabled', false);
			   	$('#Order_NextButton').show();
			   $('#Order_NextButton').parent().show();
			   $('#Order_NextButton').parent().parent().show();
		   } else {
			   $('#Order_NextButton').attr('disabled', true);
			   $('#Order_NextButton').hide();
			   $('#Order_NextButton').parent().hide();
			   $('#Order_NextButton').parent().parent().hide();
		   }
	   });
	   
	   if ($('.datalist a').length <= 0) {
           $('input[name=Order_PDFCheck]').hide();
		   $.modal(''
                   + '<div class="ow-modal">'
                   + '<h1>Check document present</h1>'
                   + '<div class="tip-text">'
                   + ' It appears that an error has occured while finding the preview of your document.<br/><br/>'
                   + ' Please click the \'Back\' button and try again.'
                   + '</div>'
                         + '</div>'
                   ,
                   {position:['80px','15px'],minHeight:300,opacity:80}
                );
            $('.ow-modal').corner();
     	 }
	   
      // update all the pdf preview links to automatically check the box on run
      $('.datalist a').each(function() {
         // take note of what this link used to do and cancel it
         var oldFunction = $(this).attr('onclick');
         $(this).attr('onclick','');

         // bind our shizz in place
         $(this).click(function(e) {
            e.preventDefault();
            $('input[name=Order_PDFCheck]').attr('checked','checked');
		   	$('#Order_NextButton').attr('disabled', false);
		   	$('#Order_NextButton').show();
		   $('#Order_NextButton').parent().show();
		   $('#Order_NextButton').parent().parent().show();
           // call the old function now that we're done
            oldFunction();
         });
      });

      // fix up the next button so that it displays our warning about pdf previews
      // THEN does it's other checks
      var nextFunction = $('#Order_NextButton').attr('onclick');
      $('#Order_NextButton').attr('onclick','');
      $('#Order_NextButton').click(function(e) {
         e.preventDefault();

         if ($('input[name=Order_PDFCheck]:checked').length <= 0) {
            // user clicked the next button without previewing.. show msg

            $.modal(''
               + '<div class="ow-modal">'
               + '<h1>Please check the preview before continuing</h1>'
               + '<div class="tip-text">'
               + ' To ensure the best possible output for your job please click one of the pdf icons '
               + ' (<img border="0" class="imgPdfSmall" src="./images/1px.gif">)'
               + ' and review the job preview.<br/><br/>'
               + ' This helps ensure quality and makes sure all your images and fonts have been converted correctly.'
               + '</div>'
                     + '</div>'
               ,
               {position:['80px','15px'],minHeight:300,opacity:80}
            );
            $('.ow-modal').corner();
         } else {
            // let helix continue on with it's checks
            if (nextFunction) {
              nextFunction();
            }
         }
      });

   }
}


// ----------------------------------------------------------------------------
// rounded corners yo
function cornerDatShizz() {

   // jquery foo
   $('.WSSideBox').each(function() {
        if ( ! $(this).hasClass('ow-rounded') ) {
            // make a note that this one has already been rounded... so have
            // all it's ugly little rat children
            $(this).addClass('ow-rounded');
            $(this).find('.WSSideBox').addClass('ow-rounded');

            var headingContainer = $(this).find('.WSSideBoxHeader');
            var container = $(this);
            container.wrap('<div class="ow-round-div"/>');
            container.before('<h1>' + headingContainer.text() + '</h1>');
            container.wrap('<div class="ow-round-div-inside"/>');

            // remove the old table heading
            headingContainer.remove();
        }
   }); 

   // if you can get this to look right without using jquery you're doing better than i :(
   // ... seriously... css properties for this seem to get ignored.. *sigh*
   if($.browser.msie){
     $('#LoginForm .ow-round-div h1').css('padding-top','10px');
   }
   
   $('.ow-round-div').corner();

   // fix up the height of this frame
   $('iframe#iframeLoginWindow').attr('height','320px');
}

function cornerButtons() {
	//dont make the Order_AddButton cornered because it overlap when the label change to remove
	   $('input.WSButtonInput1').not('#btnFilter').not('#Order_AddButton').not('.cornered').each(function() {
	   if ($(this).css('display') == 'none') {
		   return;
	   }

	   if ($(this).attr("style") != "display: none;") {
	      $(this).addClass('cornered');
	      if ($(this).attr('id') == 'Order_UploadButton' ) {
		      $(this).wrap('<div class="button-order-upload" style="margin-left: 255px"/>').wrap('<div class="button-left"/>').wrap('<div class="button-right"/>');
	      } else if ($(this).attr('id') == 'Upload_SendButton') {
		      $(this).wrap('<div class="button-order-upload" style="margin-left: 420px"/>').wrap('<div class="button-left"/>').wrap('<div class="button-right"/>');
	      }
	      else {
		      $(this).wrap('<div class="button-left"/>').wrap('<div class="button-right"/>');
	      }
   		}
   });
}

function cornerButtons2() {
   $('input.WSButtonInput1').not('.cornered').each(function() {
	   if ($(this).css('display') == 'none') {
		   return;
	   }

	   if ($(this).attr("style") != "display: none;") {
		  $(this).addClass('cornered');
		  $(this).wrap('<div class="button-left" style="margin-top: 0px;"/>').wrap('<div class="button-right"/>');
	   }
   });
}

function lightBlueCornerButtons() {
   $('input.WSButtonInputLightBlue').not('#btnFilter').not('.cornered').each(function() {
	   if ($(this).attr("style") != "display: none;") {
	      $(this).addClass('cornered');
	      $(this).wrap('<div class="button-left-lightblue"/>').wrap('<div class="button-right-lightblue"/>');
	   }
   });
}

function addWarningForMultipleItemsInCart() {

   // check if there's a bunch of items in the cart and if so... display a warning
   if ($('tr.editLabel td:contains(Items in the Shopping Cart)').length > 0
                  && $('img.imgJTSmall').length > 1 
                   ) {

      // add info message
      $('#DivHeightDetection td.backgroundColor_contentBoxFooter').parent().before(''
         + '<tr><td>'
         + '<div class="alertheader">'
         + '<img src="/ow/css/images/upside-down-tick.gif" class="right-tick"/>'
         + '<div class="box">'
         + '<div class="title">We\'ve noticed multiple items in your order</div>'
         + '<div class="normal">Please be aware that items in your order will be sent in a single delivery, if you\'d prefer to receive'
        + '       individually please place seperate orders.</div>'
         + '</div></div>'
         + '</td><tr>'
      ); 

      // bring the top table a little closer
      $('form').addClass('sit-on-top-real-close-like');  
      $('.alertheader').addClass('shift-upwards');  
      $('.alertheader').addClass('smaller-alert-font');
      //stretch the width to occupy the whole GlobalData
      $('.alertheader .box').css('width', '950px');
   }

   $('.box').corner();

   // fix box oddities in ie
   if($.browser.msie){
    $('.box .title').parent().css('width','450px');
    $('.alertheader').css('padding-top','30px');
   }

   // resize the iframe to make room for our warning which padded things down
   if ($('.box').length > 0) {c_OnSetAjaxIframeHeight();}
}

function setupPopupWindows() {
    // setup options on our popup
	var popupProfiles =
	{
		defaultPopup:
		{
			height:600,
			width:800,
			status:1,
            resizable:1,
            location:0,
            toolbar:0,
            scrollbars:1
		},
		storePopup:
		{
			height:560,
			width:600,
			status:0,
            resizable:1,
            location:0,
            toolbar:0,
            scrollbars:1,
            center: 1,
            menubar: 0
		}
	};

    // bind jquery to do the popup on click
	$(".popupwindow").popupwindow(popupProfiles);
}

// Realise nav tabs.  Use an overlay div to hide the messy table columns
function realiseNavTabs(strTargetURL) {
	$('#fakeColumn').remove();
	$('.navTabHack').css('display', 'none');

	var iFrameInfo = {'ourStores.php':{'height':725}, 'corporateResponsibility.php':{'height':650}, 'aboutUs.php':{'height':590}};
	if (strTargetURL in iFrameInfo) {
		var cur = iFrameInfo[strTargetURL];
		var col1Width = $('#GlobalMiddle').parent().outerWidth(true);
		var col2Width = $('#GlobalRight').parent().outerWidth(true);
		var colWidth = col1Width + col2Width;

		var offset = $('#GlobalMiddle').parent().offset();

		$('#GlobalMiddle').parent().css('height', cur.height + 'px');
		$('#GlobalMiddle #GlobalData').css('height', cur.height + 'px');

		$('body').append('<div id="fakeColumn" style="background-color:#FFFFFF;z-index:99999;position:absolute; width:' + colWidth + 'px;height:' + cur.height + 'px;top:' + offset.top + 'px;left:' + offset.left + 'px">&nbsp;</div>');
	}
	$('#GlobalMiddle').css('height', null);
	$('#GlobalMiddle #GlobalData').css('height', null);
}

// display the upload spinner animated gif
function displayUploadSpinner() {
	$(document).ready(function() {
		var imageSize = 96;
		var spinnerTop = ($(window.parent).height()) / 2 - (imageSize / 2);
		var spinnerLeft = ($(window.parent).width()) / 2 - (imageSize / 2);

		// ensure the user has entered something into the file upload box before displaying the spinner.
		if ($('#Upload_UserFile').attr('value') == "") {
			return;
		}

		if ($.browser.msie && new Number($.browser.version) <  8) {
			$('body:first', window.parent.document).append('<div id="uploadSpinner" style="position: absolute; left:' + spinnerLeft + 'px; top:' + spinnerTop + 'px; z-index:99999;"><img src="/ow/css/images/spinner.gif" width="' + imageSize + 'px;" height="' + imageSize + 'px;"/></div>');
			$(window.parent.document).scroll(function() {
			$('#uploadSpinner', window.parent.document).css('top', $(this).scrollTop() + spinnerTop + "px");
		});
		} else {
			$('body:first', window.parent.document).append('<div id="uploadSpinner" style="position: fixed; left:' + spinnerLeft + 'px; top:' + spinnerTop + 'px; z-index:99999;"><img src="/ow/css/images/spinner.gif" width="' + imageSize + 'px;" height="' + imageSize + 'px;"/></div>');
		}
	});
}

// undisplay the spinner gif.
// Do this each time this file is loaded just in case the user has clicked through, instead of waiting for the upload to finish
function undisplayUploadSpinner() {
	$(document).ready(function() {
		$('#uploadSpinner', window.parent.document).remove();
	});
}

/* Link certain Job Profiles to items in the catalog navigation table. */
/*
function linkPsuedoJobProfiles() {
	$(document).ready(function() {
		var psuedoJobProfiles = ['Business Stationery', 'Marketing Materials', 'Personalised Products'];

		for (var i in psuedoJobProfiles) {
			var currentPsuedoJobProfile = psuedoJobProfiles[i];

			// find the element in the table matching the psuedo job profile
			$("#jobprofilelist td.editLabel:contains('" + currentPsuedoJobProfile + "')").each(function(j, jobLabel) {
				var currentJob = currentPsuedoJobProfile;	// lexical scoping has its downsides.
				// find the id of the input element in the same row of the job profiles table
				$(jobLabel).parents('tbody').eq(1).each(function(tbodyNumber, tbody) {
					$('input', tbody).each(function(inputNumber, input) {
						// replace the click behaviour and redirect it to the correct marketing catalog item
						$('input#' + input.id).attr('onclick', '');
						$('input#' + input.id).click(function (e) {
							$("table#archive span:contains('" + currentJob + "')", window.parent.document).click();
						});

					});
				});
			});
		}
	});
}
*/

function setupCheckoutAddressDateTime(allowedDate) {
	$(document).ready(function() {
		var old_c_GoNextToPaymentSelection = c_GoNextToPaymentSelection;
		c_GoNextToPaymentSelection = function() {old_c_GoNextToPaymentSelection.call();};

		// don't use jquery on the hour and minute drop down, hide using css instead
		//$('#JT_GeneralOptions_DeliveryDateHour').css('display', 'none');
		//$('#JT_GeneralOptions_DeliveryDateMinute').css('display', 'none');

		// nodeType 3 corresponds to text nodes, so remove the : and * characters from the text surrounding the drop down options
		$('#JT_GeneralOptions_DeliveryDateHour').parent().contents().filter(function() {
			  return this.nodeType == 3;
		}).remove();
		
		// set the delivery date automatically
		var dateFieldSet = $('fieldset:contains(General Job Settings):eq(0)');
		dateFieldSet.css('display', 'none');

//		var time = new Date().getTime() + 1296000000;			// 15 * 24 * 60 * 60 * 1000 (add 15 days)
//		var newDate = new Date(time);
//
//		// delivery not possible on weekends, so ensure it moved to Monday
//		var newDayOfWeek = newDate.getDay();
//		if (newDayOfWeek == 6 || newDayOfWeek == 0) {
//			var oneDay = 86400000;
//			if (newDayOfWeek == 6) time += (oneDay * 2);		// Saturday, so add 48 hours.
//			if (newDayOfWeek == 0) time += oneDay;		// Sunday, so add 24 hours.
//			newDate = new Date(time);
//		}
//
//		//alert(newDate.getDate() + " : " + (newDate.getMonth() + 1) + " : " + newDate.getFullYear());
//		$('#JT_GeneralOptions_DeliveryDateDay').attr('value', newDate.getDate());
//		$('#JT_GeneralOptions_DeliveryDateMonth').attr('value', newDate.getMonth() + 1);
//		$('#JT_GeneralOptions_DeliveryDateYear').attr('value', newDate.getFullYear());

		var timeParts = allowedDate.split('-');
		$('#JT_GeneralOptions_DeliveryDateDay').val(new Number(timeParts[2]));
		$('#JT_GeneralOptions_DeliveryDateMonth').val(new Number(timeParts[1]));
		$('#JT_GeneralOptions_DeliveryDateYear').val(new Number(timeParts[0]));
		$('#JT_GeneralOptions_DeliveryDateHour').val(12);
		$('#JT_GeneralOptions_DeliveryDateMinute').val(0);
		//alert(allowedDate);

		// now override the date checking function in helix so it always returns true (its possible
		// this function is buggy as we've noticed it occasionaly doesn't pass when it should).
		c_CheckDateValidity = function() {return '';};
	});
}

function redirectToOfficeworksOnLogout() {
    $('input[name=logout]').click(function(e) {
    	  e.preventDefault();
    	  var successUrl = 'http://www.officeworks.com.au/retail/content/Home';
    	  
    	  $.get('/officeworks/logout.php', function(data) {
    		  top.location.href = successUrl;
    		});

    	});
}

// VERY CAREFUL TOUCHING THIS.
// Changing this field to disabled results in complete loss of order number. 
// ye have been fore-warned.
function makeOrderNameReadOnly() {
//	$('input#Order_Name').attr('disabled', 'disabled');
	$('input#Order_Name').attr('readonly', 'readonly');
	$('input#Order_Name').focus(function(e) {
		this.blur();
	});
}


function updatePaymentScreen() {
    // delayed until future release.
    return;

    // make sure we're on the payment page and don't run twice
    if ($('form[action*=checkoutPaymentSel]').not('.ow-updated').length) {
        $('form[action*=checkoutPaymentSel]').addClass('ow-updated');

        // append our new fields after the invoice one
        $('label[for=invoicePayment]').parents('table:eq(0)').before(''
                        + '<div class="ow-30-info">If you\'re an existing officeworks business customer and you\'d like to pay using your 30 day account please select the 30 Day Account option below '
                        + 'and enter your account number.</div>'
                        + ' <div class="30-day-data" style="display:none;">30 day account number :<input id="30-day-acct" type="text" name="30-day-acct"/><div>'
                        + '</div>'
                        );

        // select the radio box for them if they start typing a bp
        $('input[name=30DayAccountBPNumber]').focus(function() {
           $('#30DayAccount').attr('checked','checked') ;
        });
    }
}

function setupNavBarBehaviour() {
	// Set the 'Home' item to be selected when the user lands on the site.
	if( $('#header ul#nav li.on').size() == 0 ) {
		$('#header ul#nav li.tab-home').addClass('on');
	}

	// hack to fix the broken nav bar in IE - work out why later but use this for now.  Mozilla works just fine.
	if($.browser.msie){
	   $('#header ul#nav li a').each(function(i, item) {
		   $(item).hover(function(e) {
			   $(this).css('background-position', 'top left');
		   }, function(e) {
			   $(this).css('background-position', 'bottom left');
		   }
		   );
	   });
	}

	// If the user clicks on functionality existing outside of the context of a nav items purpose, 
	// then highlight 'Home'. 
	$('.WSMainLeftColumn, .WSMainRightColumn').each(function(i, item) {
		$(item).click(function(e) {
			$('#header ul#nav li').removeClass('on');
			$('#header ul#nav li.tab-home').addClass('on');
		});
	});

	// Ensure the right column is displayed whenever a menu item is chosen.
	$('.WSMainLeftColumn').each(function(i, item) {
		$(item).click(function(e) {
			$('#GlobalRight', window.top.document).css('display', 'block');
		});
	});

	// When the user clicks on a nav bar item, the item should stay highlighted.
	$('#header ul#nav li').each(function(i, item) {
		$(item).click(function(e) {
			$('#header ul#nav li').removeClass('on');
			$(this).addClass('on');
		});
	});
}

function removeEmptyCartFromCheckout() {
	$(".WSMainMiddleArea iframe#iframeMainWindow[src^=checkout]", window.parent.document).each(function(i, iframe) {
		if ($("input[value^=Back to Shopping]").size() == 0) {
			$("input[value^=Empty Cart]").css('display', 'none');
		}
	});
}

function hideRightAndLeftNavigation() {
	$("input[value=Check Out]").click(function() {
		$("#GlobalLeft").css('display', 'none');
		$("#GlobalLeft").parent("td").css('display', 'none');
		$("#GlobalRight").css('display', 'none');
  	  	$("#GlobalMiddle #GlobalData").css('width', '995px');
  	});
}
function showRightAndLeftNavigation() {
	$(document).ready(function() {
		$("input[value=Back to Shopping]").click(function() {
			$("#GlobalLeft", window.parent.document).parent("td").css('display', 'block');
			$("#GlobalLeft", window.parent.document).css('display', 'block');
			$("#GlobalRight", window.parent.document).css('display', 'block');
			$("#GlobalMiddle #GlobalData", window.parent.document).css('width', '100%');
		});
	});	
}

function safeResize() {
        try { parent.c_OnSetIFrameHeight($('#DivHeightDetection').outerHeight() + 80); } catch (err) {}
}


// collapse all the option divs because there's a lot of info there, this way they can be expanded one at a time 
// as needed by the user
function collapseSectionDivs() {
    // only do this once
    if ( $('body.collapsed-divs').length == 0 )    {


        // collapse all but the first one
        $('td[onclick*=c_OnToggle]').not(':eq(0)').click();

        var sectionNum = 1;
        $('td[onclick*=c_OnToggle]').each(function() {
            var txtTab = $(this).parents('tr:eq(0)').find('td:eq(0)');
            txtTab.prepend(' ' + sectionNum + '. ').addClass('section-with-number');
            sectionNum = sectionNum + 1;

            // bind on the text so that clicking expands/closes
            var togButton = $(this);
            txtTab.click(function(){togButton.click();safeResize();});
        });

        $('body').addClass('collapsed-divs');

        // workaround for helix bug which prevents resizing from working properly
        $('td[onclick*=c_OnToggle]').click(function() {
           safeResize();
        });
        

        if ($('td[onclick*=c_OnToggle]').length > 0) {
          safeResize();
        }
    }
}

function hideHelixUserManual() {
	$('td a:contains(User Manual)').css('display', 'none');
}

function adjustFrameHeight() {

  // pages using other styles
  var calcHeight = 0;
  if ($('#DivHeightDetection2').length) {
   var tmpHeight = $('#DivHeightDetection2').outerHeight();
   if (tmpHeight > calcHeight) {
    calcHeight = tmpHeight;
   }
  }
  if ($('#DivHeightDetectionFirst').length) {
   var tmpHeight = $('#DivHeightDetectionFirst').outerHeight();
   if (tmpHeight > calcHeight) {
    calcHeight = tmpHeight;
   }
  }
  if ($('#DivHeightDetection').length) {
   var tmpHeight = $('#DivHeightDetection').outerHeight();
   if (tmpHeight > calcHeight) {
    calcHeight = tmpHeight;
   }
  }
  
  // finally set height
  if (calcHeight > 100) {
   try { top.c_OnSetIFrameHeight(calcHeight + 50,1); } catch (err) { }
  }
}

var superSizerRunning = false;

function startFrameSizer() {

 if (!superSizerRunning) {
  superSizerRunning = true;
  setTimeout('adjustFrameHeight()',1000);
 }
}

function miscelanousInternetExplorerRenderingIssues() {

   if($.browser.msie){
    // page navigation pushes buttons off the right of screen... re-align the widths
    $('#pageNavi').parent().attr('width','85%');
    $('#pageNavi').parent().next().attr('width','50%');
   }
}

function isNumber(sText){
   var validChars = "0123456789";
   var isNumber=true;
   var Char; 
   for (i = 0; i < sText.length && isNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (validChars.indexOf(Char) == -1) {
         isNumber = false;
      }
   }
   return isNumber;
}

//function validateTabAndSeparatorNumber(){
//	var mySearch = 'Number of Separators';
//    var mySearchVal = $('table tbody tr td:contains("' + mySearch + '")');
//    if(mySearchVal.length > 0) {
//	    var val = $("#JT_TabsSeparators_NumberofSeparators").val();
//    	if(!isNumber(val)){
//    		alert('Number of Separators must be numeric.');
//    		$("#JT_TabsSeparators_NumberofSeparators").focus();
//    		return false;
//    	}
//    }
//}

function replacePrinterOptionsText(){
	
	$('#JT_PrinterOptions_DIF_Color option').each(function() { 
	    this.text = this.text.replace('Automatically', 'Automatic as per document' );
	    this.text = this.text.replace('Only B/W', 'Black & White' );
	    this.text = this.text.replace('Only Colour', 'Colour' );
	});

	var mySearch = 'Colour Print:';
	var mySearchVal = $('#PrinterOptions td table tbody tr td:contains("' + mySearch + '")');
	if(mySearchVal.length > 0) {
		mySearchVal.text(mySearchVal.text().replace('Colour Print:', 'Black & White or Colour:'));
	}
	var mySearchFile = 'File';
	var mySearchFileVal = $('#PrinterOptions td table td table tbody tr td:contains("' + mySearchFile + '")');
	if(mySearchFileVal.length > 0) {
		mySearchFileVal.text(mySearchFileVal.text().replace('File', 'Document Information'));
	}
	var mySearchPaperType = 'Paper Type';
	var mySearchPaperTypeVal = $('#PrinterOptions td table td table tbody tr td:contains("' + mySearchPaperType + '")');
	if(mySearchPaperTypeVal.length > 0) {
		mySearchPaperTypeVal.text(mySearchPaperTypeVal.text().replace(mySearchPaperTypeVal.text(), 'Paper Size'));
	}
	
	$('#PrinterOptions td table td table tbody td:nth-child(3)').hide();
	$('#PrinterOptions td table td table tbody td:nth-child(2)').css('border-right','1px #0858A8 solid');
}

function loginAccountMessage() {
    $('input[name=username]').unbind('focus');
    $('input[name=username]').bind('focus',function(e){
       if ($('#login-popup').length == 0) { 
         $('#LoginForm').after(''
                 + '<div class="login-account-message">'
                 + '<img src="/ow/css/images/upside-down-tick.gif" class="right-tick"/>'
                 + '<div id="login-popup" class="ow-pop-msg" style=""><div class="inside">'
                 + '<strong>Note: </strong>If this is your first time using Officeworks Print you\'ll need to register an account rather than use your online shopping account.</div></div></div>'); 
         $('#login-popup').corner('4px');
       }
    });
    $('input[name=username]').bind('blur',function(e){
         setTimeout("$('.login-account-message').fadeOut()",8000);
    });
}

// toggle a quantity input field when it's corresponding 'controller' changes value.
function controllerFieldToggleInputField(inputQuantityFieldID, inputFieldControllerID) {
	var controllerInputField = $('#' + inputFieldControllerID);
	var quantityInputField = $('#' + inputQuantityFieldID);

	// ensure this parent setup function executes just once
	var markerClass = 'validate_' + inputFieldControllerID;
	if (controllerInputField.size() == 0 || controllerInputField.hasClass(markerClass) ) {
		return;
	}
	controllerInputField.addClass(markerClass);

	// remove the onchange event, keep a pointer to it so we can choose if/when to execute it.  
	var inputFieldController = controllerInputField.get(0);
	var originalControllerOnchange = inputFieldController.onchange;
	inputFieldController.onchange = null;

	// set the input field when the page first loads.
	var inputField = quantityInputField.get(0);
	setInputField(inputField, inputFieldController);

	// set the input field when the value of the controller changes.
	$(inputFieldController).change(function() {
		setInputField(inputField, inputFieldController);
		//originalOnchange.call(this);  // controller JT type will always be $0 and not displayed, so don't bother recalculating it. 
	});

	// Setup the quantity field to be blank and read only if the controller field is set to 'none'.
	// Call the keypress function on the quantity field to recalculate the price.
	function setInputField(inputField, inputFieldController) {
		if ($('option:selected:not(:first-child)', inputFieldController).size() == 0) {
			inputField.value = '';
			$(inputField).attr('readonly', 'true');
		} else {
			$(inputField).removeAttr('readonly');
		}
		$(inputField).keypress();
	}
}

// validate the padding field.  Ensure it's only ever a positive integer.
function validateQuantityInputField(inputQuantityFieldID, maxQuantityAllowed) {
	var paddingInput = $('#' + inputQuantityFieldID);
	var markerClass = 'validate_' + inputQuantityFieldID;
	var timeout = null;

	// only execute the function once for a given inputQuantityField
	if (paddingInput.size() == 0 || paddingInput.hasClass(markerClass)) {
		return;
	}
	paddingInput.addClass(markerClass);

	// ensure the default onchange event doesn't execute.  However store it for use later when we choose to.
	var paddingInput = paddingInput.get(0);
	var _onChange = paddingInput.onchange;
	paddingInput.onchange = null;

	// called by a timer event to recalculate the price
	function onChangeFunctionCall() {
		var element = $('.' + markerClass).get(0);
		//alert(_onChange);
		//alert($('.' + markerClass).size() + " : " + '.' + markerClass + " : " + element.id + " : " + element.value);
		_onChange.call($('.' + markerClass).get(0));
	}

	// nasty keydown cludge needed because IE and webkit don't send backspace to keypress.
	$(paddingInput).keydown(function(ev) {
		clearTimeout(timeout);
		timeout = setTimeout(onChangeFunctionCall, 500);
	});

	// intercept keypresses and work out if allowing the key will form a valid numeric.
	// e.g. 5, 12, 0 (but no leading zero's e.g. 01).
	$(paddingInput).keypress(function(ev) {
		var keyPressed = String.fromCharCode(ev.which);
		var allowedSpecialKeyCodes = {8:'', 35:'', 36:'', 37:'', 39:'', 46:''};		// backspace, home, end, left cursor, right cursor, delete.
		var isAllowed = ( ((ev.which) && (ev.which in allowedSpecialKeyCodes)) || (ev.keyCode && (ev.keyCode in allowedSpecialKeyCodes)) );
		//alert(ev.which + " : " + isAllowed + " : " + ev.charCode + " : " + ev.keyCode);

		// if this keypress event has been triggered by the controller field for this input then just recalc price.
		if (ev.which == undefined && ev.keyCode == undefined) {
			clearTimeout(timeout);
			timeout = setTimeout(onChangeFunctionCall, 500);
			return false;
		}

		// Only allow the input if the input is a number, or if it's another special key (e.g. backspace).
		if (!isAllowed && isNaN(parseInt(keyPressed))) {
			return false;
		}

		// leading zero's are not allowed.
		var range = $(paddingInput).caret();			// caret jquery plugin to get current cursor position in the input
		var start = (range.start == undefined) ? 0 : range.start;
		var end = (range.end == undefined) ? this.value.length : range.end;

		//alert(this.value.length + " : " + end);
		//alert(start + " : " + this.value.length + " : " + keyPressed);
		if ( (start == 1 && this.value == '0') || (start == 0 && this.value.length > 0 && keyPressed == '0')) {
			if (keyPressed == '0') {
				return false;
			}
			else {
				this.value = '';
			}
		}

		var newValue = this.value.substring(0, start) + keyPressed + this.value.substring(start, this.value.length);
		//alert(newValue + " : " + parseInt(newValue));
		if (parseInt(newValue) > maxQuantityAllowed) {
			this.value = maxQuantityAllowed;
			clearTimeout(timeout);
			timeout = setTimeout(onChangeFunctionCall, 500);
			return false;
		}

		clearTimeout(timeout);
		timeout = setTimeout(onChangeFunctionCall, 500);
	});

//	$(paddingInput).change(function() {
//		if ( (this.value != '') && (isNaN(this.value) || (this.value < 0)) ) {
//			this.value = this.value.replace(/\D*/g,'');  
//		    $.modal(''
//	            + '<div class="ow-modal">'
//	            + '<h1>Officeworks Top-Tip:</h1>'
//	            + '<div class="tip-text">'
//	            + ' You must enter a positive number!<br/>'
//	            + ' e.g. 11'
//	            + '</div>'
//	            + '</div>'
//	            ,
//	            {position:['80px','15px'],minHeight:300,opacity:80}
//	        );
//	        $('.ow-modal').corner();
//		}
//		originalOnChange.call(this);
//	});
}

function replaceColorPrintText(){
	$('#JT_PrinterOptions_DIF_Color option').each(function() { 
	    this.text = this.text.replace('Automatically', 'Automatic as per document' );
	    this.text = this.text.replace('Only B/W', 'Black & White' );
	    this.text = this.text.replace('Only Colour', 'Colour' );
	});

	var mySearch = 'Colour Print:';
	var mySearchVal = $('#PrinterOptions td table tbody tr td:contains("' + mySearch + '")');
	if(mySearchVal.length > 0) {
		mySearchVal.text(mySearchVal.text().replace('Colour Print:', 'Black & White or Colour:'));
	}
}

function moveCopyCount() {
//	var initialSelector = '#Content_PrinterOptions div';

	// ensure we only do this function once per page.
	if ($('.CopyCountMoved').size() > 0) {
		return;
	} else if ( ($('#CopyCount #JT_CopyCount').size() == 0) ) {
		return;
	}
	// marker to indicate this function has already been called.
	$('#JT_CopyCount').addClass('CopyCountMoved');

	// find the new anchor point for the existing copy count input column.
	var firstSectionContentRowTable = $('select').first().closest('table');
	// if a new anchoring point can't be found, then ensure the CopyCount lives on in its current location.
	if (firstSectionContentRowTable.size() == 0) {
		return;
	}

	var originalCellSpacing = firstSectionContentRowTable.attr('cellspacing');
	// width can vary depending on the job ticket, so use the width of the next table in the section.
	var originalFirstArticleColumn = $('tr td', firstSectionContentRowTable).first();
	var width = originalFirstArticleColumn.attr('width');
	width = new Number(width.substring(0, width.length - 1));
	//alert(width + " : " + (100 - width));

	// swap the copyCount with a td of the same width
	var copyCount = $('#CopyCount').replaceWith('<td style="width:5%;"><!-- --></td>');

	$(firstSectionContentRowTable).parent().prepend('<table id="CopyCount" width="100%" cellspacing="' + originalCellSpacing + '" cellpadding="0" border="0"><tbody><tr id="copyCountTR"></tr></tbody></table>');
	$('#copyCountTR').append('<td width="' + width + '%" valign="center" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText">Copy Count:</td>');
	$('#copyCountTR').append('<td id ="copyCountTD" width="' + (100 - width) + '%" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText"></td>');
	$('#copyCountTD').append($('#JT_CopyCount', copyCount));
	$('#JT_CopyCount').css('display', 'inline');
	
}

function addNumericSpinnerToCopyCount() {
	// ensure this only happens once.
	if ($("#CopyCount input#JT_CopyCount").hasClass('ui-spinner-box') ) {
		return;
	}
	$("#CopyCount input#JT_CopyCount").spinner({min: 1});

	// Handle the spinner changes - spinchange is buggy so use spinup and spindown which are more reliable.
	$('#CopyCount input#JT_CopyCount').bind('spinup spindown', function(event, ui) {
		if (document.owOps_CopyCountTimer == undefined) {
			clearTimeout(document.owOps_CopyCountTimer);
			document.owOps_CopyCountTimer = undefined;
		}
		document.owOps_CopyCountTimer = setTimeout("$('#CopyCount input#JT_CopyCount').keyup();", 500);
	});
}

/* 
 * Add Site Intelligence tracking calls whenever the user performs page navigations.
 * At present this function just sets calls up for 'My Menu' and 'Catalogue' clicks.
*/ 
function addSiteIntelligenceTriggers() {
	var selector = '';
	selector += '#GlobalLeft .Catalogue #archive span[onclick*=c_OnSelect(]';
	selector += ', ' + '#GlobalLeft .Catalogue #archive span[onclick*=c_OnSelectJobProfiles(]';
	var catalogueClicks = $(selector);

	// The Left Nav MyMenu should do same (but not for the top 'box'.  Also, no nested items.
	var myMenuClicks = $('#GlobalLeft .MyMenu .MyMenuItem a[onclick*=c_OnNext(]');

	replaceClicks(catalogueClicks, '/catalogue.html');
	replaceClicks(myMenuClicks, '/mymenu.html');

	// proxy each click and add an SI tag call each time.
	function replaceClicks(selector, category) {
		var selection = $(selector);
		$(selection).each(function (i, item) {
//			alert(item + " : " + item.id);
			var vanillaClickFunction = item.onclick;
			item.onclick = null;

			$(item).click(function(event) {
				var pageToLoad = this.innerHTML.replace(/^\s*/g,'').replace(/\s*$/g,'');		// remove start and end whitespace.
				var url = category + '?selection=' + pageToLoad;
				var oid = this.id.replace(/.*_/g,'');
				if (oid != '' && category == '/catalogue.html') {
					url += '&ooid=' + oid;
					url += '&noid=' + oid;
				}

//				alert(url);

				vanillaClickFunction.call(this);
				SiTrackPage(url);
			});
		});
	}

}

// require the user to select a basic paper type.
// executed by enforceOrderCreationCriteria
function validate_EnsureUserToSelectsABasicPaperType() {
	var theSelect = $('#JT_PrinterOptions_DIF_MediaType');
	var hiddenParent = $('#JT_PrinterOptions_DIF_MediaType').closest(':hidden');
//	alert(hiddenParent.size());

	if ( (theSelect.size() == 0) || hiddenParent.size() > 0) {
		return true;
	}
	else {
		return displayPaperRequiredWarning();
	}

	function displayPaperRequiredWarning() {
//		alert(theSelect);
		if (theSelect.size() == 0) {
			return true;
		}

		var selectAmount = $("option:selected:not(:first-child)", theSelect).size();
		if (selectAmount > 0) {
			return true;
		}
		//alert('first child not selected: ' + selectAmount);

		var modalText = ''
		    + '<div class="ow-modal">'
		    + '<h1>Officeworks Top-Tip:</h1>'
		    + '<div class="tip-text">'
		    + ' You must select a Paper Size before continuing.<br/>'
		    + '</div></div>';
	
		$.modal(modalText, {position:['80px','15px'],minHeight:300,opacity:80});
		$('.ow-modal').corner();
		//scroll the modal to top, position specified in the modal above only sets inside the iframe
		try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }
		
		return false;
	}
}

/*function validate_LimitPaperTypesToTwo() {
	var selectBoxSelector = '#PrinterOptions select';
	//var selectBoxSelector = '#Content_PaperTypes select';
	
	// ensure this function works just once for each frame.
	if ($('.SingleOptionSelect').size() > 0) {
		return;
	}
	$(selectBoxSelector).addClass('SingleOptionSelect');
	
	
	$(selectBoxSelector).each(function(i, selectBox) {
		var func = $(selectBox).attr('onchange');
		$(selectBox).attr('onchange', null);
	//	alert("select: " + selectBox.id);
	
		$(selectBox).change(function() {
			var currentlySelected = $('.SingleOptionSelect_Selected').get(0);
			var originalFunc = func;
	
			// all the select boxes should reset to the first option, except 'this'.
	
			$('.SingleOptionSelect option:first-child').not($(":first-child", this).get(0)).attr('selected', 'selected');
	
			$('.SingleOptionSelect_Selected').removeClass('.SingleOptionSelect_Selected');
			if(currentlySelected != undefined) {
	//			alert('here0');
				originalFunc.call(currentlySelected);
			}
	//alert('here1');
			$(this).addClass('SingleOptionSelect_Selected');
			originalFunc.call(this);
		});
	});
}
*/

function validate_LimitPaperTypesToTwo() {
	var selectBoxes = '#Content_PaperTypes select';
	// if there are no paper type select boxes then the function passes by default
	if( $(selectBoxes).size() == 0) { 
		return true;
	}
	
	// ensure setup is executed just once.
	if ($('.validate_LimitPaperTypesToTwo').size() ==  0) {
		$(selectBoxes).addClass('validate_LimitPaperTypesToTwo');
		initialSetup();
	}
	
	function initialSetup() {
		// how many items are already selected when the page loads.
		var quantity = $(" option:first-child[selected=false]", selectBoxes).size();
	
		$(selectBoxes).each(function(i, item) {
			var usualFunc = item.onchange;
			item.onchange = null;
	
			$(item).change(function() {
				usualFunc.call(this);
				var newQuantity = $(" option:first-child[selected=false]", selectBoxes).size();
	//			alert(quantity + " : " + newQuantity);
	//			if (newQuantity >= quantity) {
					var displayedWarning = displayQuantityWarning();
	//			}
				quantity = newQuantity;
				return displayedWarning;
			});
		});
	}
	
	return displayQuantityWarning();
	function displayQuantityWarning() {
		var currentOptions = $("option:selected:not(:first-child)", selectBoxes);
		var quantitySelected = $(currentOptions).size();
		var totalSelects = $(selectBoxes).size();
	//	alert(quantitySelected + " : " + totalSelects);
	
		if (quantitySelected > 1) {
			var modalText = ''
			    + '<div class="ow-modal">'
			    + '<h1>Officeworks Top-Tip:</h1>'
			    + '<div class="tip-text">'
			    + ' We\'ve noticed you\'ve chosen more than one type of paper.<br/>'
			    + ' It\'s only possible for us to print your order using a single paper type.<br/><br/>';
	
				if (quantitySelected > 0) {
					modalText += ' You currently have the following paper types selected.<br/><br/>';
					modalText += '<div>';
					var leftText = '<div style="float:left">';
					var rightText = '<div style="float:left">';
	
				    $(currentOptions).each(function(i, item) {
				    	var labelText = $(item).closest('td').first().siblings().get(0).innerHTML;
				    	leftText += '<div>' + labelText + '</div>';
				    	rightText += '<div style="font-style:italic">&nbsp;' + item.innerHTML + '</div>';
				    });
	
					leftText += '</div>';
					rightText += '</div>';
				    modalText += leftText + rightText + '</div><div style="clear:both"><!-- --></div>';
				    modalText += '<br/>Please deselect ' + (quantitySelected - 1) + ' of the above paper types before continuing.<br/><br/>';
				}
	
			    modalText += '</div>'
		        + '</div>';
	
			$.modal(modalText, {position:['80px','15px'],minHeight:300,opacity:80}
			);
			$('.ow-modal').corner();
	//		$('option', this).first().attr('selected', 'selected');
			//scroll the modal to top, position specified in the modal above only sets inside the iframe
		    try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }
			return false;
		}
		return true;
	}
}

function validation_EnsureUserSelectsExactlyOneOption(requiredIfID, excludeIDs, text) {
	var requiredElement = $('#' + requiredIfID);

	if (requiredElement.size() == 0) {
		return true;
	}

	var excludeSelector = '';
	var excludedOptions = $();
	for (i in excludeIDs) {
		excludeSelector += (excludeSelector.length > 0 ? ', ' : '') + '#' + excludeIDs[i];
		excludedOptions = $('option', excludeSelector);
		//alert(excludedOptions.size());
	}

	var currentOptions = $('option:selected:not(:first-child)').not(excludedOptions);
	var quantitySelected = currentOptions.size();
	//alert(quantitySelected);

	if (quantitySelected != 1) {
		var modalText = ''
		    + '<div class="ow-modal">'
		    + '<h1>Officeworks Top-Tip:</h1>'
		    + '<div class="tip-text">'
		    + 'You currently have ' + (quantitySelected == 0 ? 'no' : quantitySelected) + ' ' + text + 's selected.<br/><br/>';

		    if (quantitySelected > 0) {
				modalText += '<div>';
				var leftText = '<div style="float:left">';

			    $(currentOptions).each(function(i, item) {
			    	var labelText = $(item).get(0).innerHTML;
			    	leftText += '<div style="font-style:italic">' + labelText + '</div>';
			    });

				leftText += '</div>';
			    modalText += leftText + '</div><div style="clear:both"><!-- --></div>';
			    modalText += '<br/>Please deselect ' + (quantitySelected - 1) + ' of the above ' + text + ' before continuing.<br/><br/>';
		    }
		    else {
		    	modalText += ' You must select a ' + text + ' to create your order.<br/>';
		    	modalText += '</div></div>';
		    }
	
		$.modal(modalText, {position:['80px','15px'],minHeight:300,opacity:80});
		$('.ow-modal').corner();
		//scroll the modal to top, position specified in the modal above only sets inside the iframe
		try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }

		return false;
	}
	return true;
}

function validate_EnsureUserAddsQuantityWhenControllerFieldOn(inputQuantityFieldID, inputFieldControllerID, title, sectionName) {
	var inputFieldController = $('#' + inputFieldControllerID);
	var inputField = $('#' + inputQuantityFieldID);

	if (inputFieldController.size() == 0) {
		return true;
	}

	var firstControllerOption = $('option:first-child', inputFieldController).get(0);
	var currentControllerOption = $('option[selected=true]', inputFieldController).get(0);

	if( $('option:first-child[selected=true]', inputFieldController).size() > 0 ) {
		return true;
	}
	else {
		var fieldValue = inputField.get(0).value;
		if(fieldValue == '') {
			var modalText = ''
			    + '<div class="ow-modal">'
			    + '<h1>Officeworks Top-Tip:</h1>'
			    + '<div class="tip-text">'
			    + 'You have chosen the ' + title.toLowerCase() + ' option \'<span style="font-style:italic">' + currentControllerOption.innerHTML + '\'</span>.<br/><br/>'
			    + 'You must specify the \'Total ' + title + ' Required\', or choose the ' + title.toLowerCase() + ' option \'<span style="font-style:italic">' + firstControllerOption.innerHTML + '\'</span> under ' + sectionName + '.<br/>';

			$.modal(modalText, {position:['80px','15px'],minHeight:300,opacity:80});
			$('.ow-modal').corner();
			//scroll the modal to top, position specified in the modal above only sets inside the iframe
		    try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }

			return false;
		}
	}
	return true;
}

/*
 * Calls various functions to perform validation
 * Each function called should generally...
 * 1.  May need some initialisation before being used - in which case it should recognise this the first time it's run, then exit.
 *     In this sitution, the function should be called once for initialisation when the pages loads - before it is called for validation.
 * 2.  Return true when the item being validated is not on the page.
 * 3.  Return true to indicate successful validation, false otherwise.
 * 4.  May display a message to the user which indicates why validation has failed.
*/
function enforceOrderCreationValidationCriteria() {
	if ( $('body').hasClass('criteriaforced')) {
		return;
	}
	$('body').addClass('criteriaforced');

	$('#Order_NextButton').each(function(i, item) {
		var usualFunc = this.onclick;
		this.onclick = null;

		$(item).click(function () {
			var c1 = validate_EnsureUserToSelectsABasicPaperType();
			var c2 = validate_LimitPaperTypesToTwo();
			var c3 = validation_EnsureUserSelectsExactlyOneOption('JT_SignTypes_AFrames', null, 'Sign Type');
			var c4 = validation_EnsureUserSelectsExactlyOneOption('JT_PostersandPlans_PlanPrints-BlackandWhite', ['JT_PostersandPlans_PosterandPlanLaminating'], 'Poster or Plan');
			var c5 = validate_EnsureUserAddsQuantityWhenControllerFieldOn('JT_Finishing_TotalNumberofPadsDesired', 'JT_Finishing_Padding', 'Padding', 'Finishing Options');
			var c6 = validate_EnsureUserAddsQuantityWhenControllerFieldOn('JT_TabsSeparators_NumberofSeparators', 'JT_TabsSeparators_SeparatorSheetTypes', 'Separators', 'Tabs and Separators');
			var c7 = validate_EnsureUserAddsQuantityWhenControllerFieldOn('OW_JT_TabsSeparators_NumberofSeparators', 'OW_JT_TabsSeparators_SeparatorSheetTypes', 'Separators', 'Tabs and Separators');
			var c8 = validation_EnsureUserSelectsExactlyOneOption('JT_BusinessCards_ColourBusinessCards', ['JT_BusinessCards_BusinessCardLaminating'], 'Business Card');
			var c9 = validate_EnsureNoA5ForBookletPrinting();

			var criteriaPass = c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8 && c9;
//			alert(c1 + " : " + c2 + " : " + c3 + " : " + criteriaPass);

			if (criteriaPass && usualFunc) {
				usualFunc.call(this);
				return true;
			}
			return false;
		});
	});

}
function hideDeleteFileOptions(){
	$(function() {
	    var $radios = $('input:radio[name=Upload_Delete]');
	    $radios.filter('[value=file]').attr('checked', false);
	    $radios.filter('[value=both]').attr('checked', true);
	    $('tr:contains("Choose the File(s):")').hide();
	});
}

function hideDateSettingsInCheckoutSummary() {
	$('fieldset:contains(Date Settings)').css('display', 'none');
}

function addPersonalNote() {
	if($('#PersonalData').length > 0 && $('#personal-note').length == 0){
		$('#PersonalData tr:last').after('<tr><td colspan="2">'
		+ '<div id="personal-note" class="fontColor_normaltext fontSize_normalText fontFamily_normalText">'
        + ' ** Please note that any address details you enter here are only saved for this order. '
        + ' To save personal address changes, please update your profile at: User Info > Addresses'
        + '</div>'
		+ '</td></tr>');
	}
}

function addEncryptedWarningNote(){
	var referenceLoc = $('#tabmain tr table tr table tr:contains("Maximum Allowed Files per Order:")');
	if(referenceLoc.length > 0 && $('#warning-note').length == 0){
		referenceLoc.after('<tr><td colspan="2">'
		+ '<div id="warning-note" class="fontColor_normaltext fontSize_normalText fontFamily_normalText" style="font-style:italic">'
        + ' ** Please note that any encrypted or password protected PDF file can NOT be printed. '
        + '</div>'
		+ '</td></tr>');
	}
}

function businessCardLogic(){
	if(typeof(ow_JobProfileID) != "undefined" && ow_JobProfileID == 'upload your own business card.xml') {
		$('#copyCountTR').css('display', 'none');
	}

	//setup initial enabled/disabledness
	if ($('#JT_BusinessCards_ColourBusinessCards').val() != 'None') {
		$('#JT_BusinessCards_BlackandWhiteBusinessCards').attr('disabled', true);
	}
	else if ($('#JT_BusinessCards_BlackandWhiteBusinessCards').val() != 'None') {
		$('#JT_BusinessCards_ColourBusinessCards').attr('disabled', true);
	}

	// change handlers to enable/disable fields depending on what is selected.
	$('#JT_BusinessCards_ColourBusinessCards').change(function() {
		if($('#JT_BusinessCards_ColourBusinessCards').val() != 'None'){
			$('#JT_BusinessCards_BlackandWhiteBusinessCards').attr('disabled', true);
		}else{
			$('#JT_BusinessCards_BlackandWhiteBusinessCards').attr('disabled', false);
		}
		
	});
	
	$('#JT_BusinessCards_BlackandWhiteBusinessCards').change(function() {
		if($('#JT_BusinessCards_BlackandWhiteBusinessCards').val() != 'None'){
			$('#JT_BusinessCards_ColourBusinessCards').attr('disabled', true);
		}else{
			$('#JT_BusinessCards_ColourBusinessCards').attr('disabled', false);
		}	
	});
	
	var referenceLoc = $('#Content_BusinessCards table tr:contains("Business Card Laminating")');
	if(referenceLoc.length > 0 && $('#business-card-note').length == 0){
		referenceLoc.after('<tr><td colspan="2">'
		+ '<div id="business-card-note" class="fontColor_normaltext fontSize_normalText fontFamily_normalText">'
        + ' ** Business cards will be printed on 300gsm white paper, single sided only. '
        + '</div>'
		+ '</td></tr>');
	}
}

function addNoteToPadding() {
	var table = $('#JT_Finishing_TotalNumberofPadsDesired').closest('table');
	if (table.size() == 0 || table.hasClass('addNoteToPaddingMarker')) {
		//alert('here');
		return;
	}
	table.addClass('addNoteToPaddingMarker');

	var html = '';
	html += '<table width="100%" cellspacing="3" cellpadding="0" border="0">';
	html += '<tbody><tr>';
	html += '<td width="100%" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText">';
	html += 'The total copy count will be divided evenly by the number of pads you have selected.</br>';
	html +=	'E.g. A copy count of 1000 X 10 pads = 100 pages per pad';
	html += '</td>';
	html += '</tr>';
	html += '</tbody></table>';

	table.after(html);
}

function additionalServiceSeparatorSheets() {
	// ensure this function is used just once.
	if( $('table').hasClass('additionalServiceSeparatorSheets')) return;

	// ensure the right section is available before continuing.
	var sectionRows = $('#Sec_TabsSeparators > table > tbody > tr');
	if (sectionRows.size() == 0) {
		//alert('here');
		return;
	}

	// create and append field to contain a list of the special articles.
	var html = '';
	html += '<table width="100%" cellspacing="3" cellpadding="0" border="0" class="additionalServiceSeparatorSheets"><tbody><tr>';
	html += '	<td width="30%" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText">Separator Sheet Types</td>';
	html += '	<td width="70%" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText">';
	html += '		<input type="hidden" name="JT_ArticleManagement_ArtSelect" id="OW_JT_TabsSeparators_SeparatorSheetTypesHidden"/>';
	html += '		<select style="width: 230px;" id="OW_JT_TabsSeparators_SeparatorSheetTypes" name="OW_JT_TabsSeparators_SeparatorSheetTypes" class="validate_JT_TabsSeparators_SeparatorSheetTypes">';
					for (i in ow_SeparatorSheetsInfo) {
						var name = ow_SeparatorSheetsInfo[i].replace(' (Separator)', '');
						html += '<option value="#' + i + '#' + ow_SeparatorSheetsInfo[i] + '"';
						if (ow_CurrentSeparatorSheet != false && ow_CurrentSeparatorSheet.id == i) {
							html += ' selected ';
						}
						html += '>' + name + '</option>';
					}
	html += '		</select>';
	html += '</td></tr></tbody></table>';

	// create and append field to contain the quantity of the selected special article.
	html += '<table width="100%" cellspacing="3" cellpadding="0" border="0">';
	html += '<tbody><tr>';
	html += '	<td width="30%" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText">Number of Separators</td>';
	html += '	<td width="70%" align="left" class="fontSize_normalText fontFamily_normalText fontColor_normalText">';
	html += '		<input type="hidden" name="JT_ArticleManagement_ArtQty" id="OW_JT_TabsSeparators_NumberofSeparatorsHidden"/>';
	html += '		<input type="text" style="width: 230px;" id="OW_JT_TabsSeparators_NumberofSeparators" name="OW_JT_TabsSeparators_NumberofSeparators" class="fontFamily_normalText fontSize_normalText fontColor_normalText borderColor_inputField borderWidth_inputField borderStyle_inputField backgroundColor_inputField"';
					if (ow_CurrentSeparatorSheet != false) {
						html += ' value="' + ow_CurrentSeparatorSheet.quantity + '" ';
					}
	html += '		onchange="ow_c_AddArticlePrice(\'OW_JT_TabsSeparators_SeparatorSheetTypes\', \'OW_JT_TabsSeparators_NumberofSeparators\');">';
	html += '</td></tr></tbody></table>';

	var separatorDescriptionBox = $('td > div #JT_TabsSeparators_DescribeSeparatorPositions', sectionRows.eq(1)).closest('table');
	//alert(separatorDescriptionBox.size());
	separatorDescriptionBox.before(html);

	// setup event handling
	$('#OW_JT_TabsSeparators_SeparatorSheetTypes').change(function() {
		ow_c_AddArticlePrice('OW_JT_TabsSeparators_SeparatorSheetTypes', 'OW_JT_TabsSeparators_NumberofSeparators');
	});
}

// e.g. http://helix-ws/ajaxRequestArticlePrice.php?strOrderGUID={65C1BACE-3369-E168-01C6-A1814E8AC4D5}&iCopyCount=1&iArticleCount=1&strArticleId={8A8EA8E8-07FB-42D1-942D-2E845A8C8F26}&strArticleName=Seps&strFileGUID={00000000-0000-0000-0000-000000000000}&strUserGUID={DC4E336D-061E-E8EC-D275-BDAABDB63832}&sid=0.052231376711057154
function ow_c_AddArticlePrice(controlFieldID, quantityInputFieldID){
	var controlField = document.getElementById(controlFieldID);
	var quantityField = document.getElementById(quantityInputFieldID);
	var controlFieldHidden = $('#' + controlFieldID + 'Hidden');
	var quantityFieldHidden = $('#' + quantityInputFieldID + 'Hidden');

	//var userGUID = '{DC4E336D-061E-E8EC-D275-BDAABDB63832}';
	var userGUID = ow_UserGUID;
	var strOrderGUID = ow_OrderGUID;
	var strArticleId = controlField.value.split("#")[1];
	var strArticleName = controlField.value.split("#")[2];;
	var iArticleCount = quantityField.value;

	// For some reason Helix creates a db entry via ajax, then an additional different one on form submission.
	// So set some hidden fields with with 'JT_ArticleManagement_*' name to trick it into thinking a 
	// real article / quantity submission is happening.
	$(controlFieldHidden).attr('name', 'JT_ArticleManagement_ArtSelect#' + strArticleId);
	$(controlFieldHidden).attr('value', ow_SeparatorSheetsInfo[strArticleId]);
	$(quantityFieldHidden).attr('name', 'JT_ArticleManagement_ArtQty#' + strArticleId);
	$(quantityFieldHidden).attr('value', iArticleCount);
	
 	//alert($(controlFieldHidden).attr('name') + " : " + $(controlFieldHidden).attr('value') + " : " + $(quantityFieldHidden).attr('name') + " : " + $(quantityFieldHidden).attr('value'));
	
	var iCopyCount = document.getElementById("JT_CopyCount").value;
	var fileGUID = '{00000000-0000-0000-0000-000000000000}';
	//alert(userGUID + " : " + strOrderGUID + " : " + strArticleId + " : " + strArticleName + " : " + iArticleCount + " : " + iCopyCount + " : " + controlField.value);
	
	c_OnAjaxCallResponseText('ajaxRequestArticlePrice.php?strOrderGUID=' + strOrderGUID + '&iCopyCount='+iCopyCount+'&iArticleCount='+iArticleCount+'&strArticleId='+strArticleId+'&strArticleName='+strArticleName+'&strFileGUID=' + fileGUID + '&strUserGUID=' + userGUID, 'ajaxPriceRequest');
}

function addAcceptedFileTypesLinkToFileUpload() {
	if ($('#acceptedDocuments').size() > 0) return;

//	var theHTML = '<div id="acceptedDocuments" class="WSPageTitleText fontColor_headerText fontSize_headerText fontFamily_headerText" style="float:right;cursor:pointer !important; text-decoration:underline">Accepted Documents</div><div style="clear:both"/>';
//	var myDocuments = $('form[name=upload] div.WSPageTitleText:contains(My Documents)').first();
//	if (myDocuments.size() == 0) {
//		myDocuments = $('form[name=order] div.WSPageTitleText:contains(File Selection)').first();
//	}
//	myDocuments.css('float', 'left');
//	myDocuments.after(theHTML);
//
//	$('#acceptedDocuments').click(function() {
//		var fileTypesWindow = window.open('ow/supportedFileFormats.html', '_blank');
//	});

	var theHTML = '<a id="acceptedDocuments" onclick="window.open(\'ow/supportedFileFormats.html\', \'_blank\');" href="#">Over 200 File Types Accepted!</a>';
	var searchText1 = 'All native Documents';
	var searchText2 = 'Over 200 File Types Accepted!';
	var textContainer = $('td.fontFamily_normalText:contains(' + searchText1 + '),td.fontFamily_normalText:contains(' + searchText2 + ')');
	textContainer.html(theHTML);
}

function setOWAppTitleBar() {
	if ( $('div.OwAppTitle').find('table').length == 0 ) {//ensure run once
		$('div.OwAppTitle').load('./ow/ow-app-title-bar.php #owAppTitleTable');
	}
}

function hideDocumentFilter() {
	if ( $('table.tableButtonsTopRight').find('div#orderDropdown').length > 0 ) {
		$('table.tableButtonsTopRight').hide();
	}
}

function disableLanguageSelection() {
	if ( $('#frmMain').find('#Config_Language').length > 0 && !$('#Config_Language').attr('disabled') ) {
		$('#Config_Language').attr('disabled', 'disabled');
	}
}

//run this function after other ones which already manipulate the printer options content.
function MovePaperSizeToTopOfPrinterOptionsSection() {
	// ensure function only executes ONCE when on the Upload Your Document job profile.
	try {
		if (typeof(ow_JobProfileID) == 'undefined') return;
		if (ow_JobProfileID != 'upload your document.xml') return;
		if ($('#formatRow1').size() > 0) return; 
	
		var topTable = $('#Content_PrinterOptions > td > div > table > tbody');
		//alert(topTable.size() + " : " + ow_JobProfileID);

		var theHTML = '';
		theHTML += '<tr><td><table>';
		theHTML += '<tr id="formatRow1"><td></td><td id="pictd" rowspan=4></td></tr>';
		theHTML += '<tr id="formatRow2"><td></td></tr>';
		theHTML += '<tr id="formatRow3"><td></td></tr>';
		theHTML += '<tr id="formatRow4"><td></td></tr>';
		theHTML += '<tr><td colspan=2 style="height:13px;"></td></tr>';
		theHTML += '</table></td></tr>';
		topTable.prepend(theHTML);
		//alert('format row: ' + $('#formatRow1').size());
  
		var formatHeaderTD = $('#Content_PrinterOptions #PrinterOptions tbody tr td table tbody tr td table tbody tr td:contains(Document Information)');
		var PaperSizeTD = $('#Content_PrinterOptions #PrinterOptions tbody tr td table tbody tr td table tbody tr td:contains(Paper Size)');
		var formatContentTDRow = formatHeaderTD.parent().siblings();

		$('#formatRow1 td').eq(0).replaceWith(PaperSizeTD);
		$('#formatRow2 td').eq(0).replaceWith($('td', formatContentTDRow).eq(1));
		$('#formatRow3 td').eq(0).replaceWith(formatHeaderTD);
		$('#formatRow4 td').eq(0).replaceWith($('td', formatContentTDRow).eq(0));

		var preview = $('#PagePreview1');
		$('#pictd').append(preview);

		function togglePrintSizePrompt() {
			if($('#JT_PrinterOptions_DIF_MediaType option:first').attr('selected')) {
				$('#PagePreview').prepend('<span id="printSizePrompt">Please choose your print size from the Paper Size drop-down list</span>');
				$('#ImgPreview').attr('src', './images/1px.gif');
			} else {
				$('#printSizePrompt').remove();
			}
		}
		
		// initial page setup, then whenever the drop down changes.
		togglePrintSizePrompt();
		$('#JT_PrinterOptions_DIF_MediaType').change(function() {
			togglePrintSizePrompt();
		});

		//alert('format row: ' + $('#formatRow1').parent().html());

	}
	catch(e) {
		alert(e.message);
	}
}



//require the user to select a basic paper type.
//executed by enforceOrderCreationCriteria
function validate_EnsureNoA5ForBookletPrinting() {
	var theSelect = $('#JT_PrinterOptions_DIF_Booklet');

	if ( (theSelect.size() == 0) ) {
		return true;
	}
	else {
		return displayNoA5ForBookletPrintingWarning();
	}

	function displayNoA5ForBookletPrintingWarning() {
		if (theSelect.size() == 0) {
			return true;
		}
		
		if (theSelect.val() != "activated") {
			return true;
		}
		
		var thePaperSize = $('#JT_PrinterOptions_DIF_MediaType');
		if (thePaperSize.size() == 0) {//no paper selection box
			return true;
		}
	    if (thePaperSize.val().search("^A5") !== 0) {
	    	return true;
	    }

		var modalText = ''
		    + '<div class="ow-modal">'
		    + '<h1>Officeworks Top-Tip:</h1>'
		    + '<div class="tip-text">'
		    + ' Booklet printing is not supported using a paper size of A5.<br/>'
		    + '</div></div>';
	
		$.modal(modalText, {position:['80px','15px'],minHeight:300,opacity:80});
		$('.ow-modal').corner();
		//scroll the modal to top, position specified in the modal above only sets inside the iframe
		try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }
		
		return false;
	}
}


/**
 * disableA5SelectionForBookletPrinting
 * This function check and disable A5 paper selection for booklet printing
 */
function disableA5SelectionForBookletPrinting() {
	var selectBox =  $('#JT_PrinterOptions_DIF_Booklet');

	// if there is no booklet selection box then the function passes by default
	if( $(selectBox).size() == 0) { 
		return true;
	}
	
	$(selectBox).change ( function () {
		  try{				
				if (selectBox.val() == "activated") { //disable all A5 paper selection
					//check paper size selection
					var thePaperSize = $('#JT_PrinterOptions_DIF_MediaType');
					if (thePaperSize.size() > 0 ) {
						if (thePaperSize.val().search("^A5") === 0) {
							var modalText = ''
							    + '<div class="ow-modal">'
							    + '<h1>Officeworks Top-Tip:</h1>'
							    + '<div class="tip-text">'
							    + ' Booklet printing is not supported using a paper size of A5.<br/>';
						    modalText += '</div>'
						        + '</div>';
							$.modal(modalText, {position:['80px','15px'],minHeight:400,opacity:80});
							$('.ow-modal').corner();
							try { $(window.parent.document).scrollTop($('div.ow-modal').position().top);} catch (err) {  }
						}
						$('#JT_PrinterOptions_DIF_MediaType option').each(function(i){
							if ($(this).val().search("^A5") === 0) {
								$(this).attr('disabled', 'disabled');
							}
						});
						$('#JT_Finishing_Laminating option').each(function(j){
							if ($(this).val().search("^A5") === 0) {
								$(this).attr('disabled', 'disabled');
							}
						}); 
				    }
					
					return true;
				} else {
					$('#JT_PrinterOptions_DIF_MediaType option').each(function(i){
						if ($(this).val().search("^A5") === 0) {
							$(this).removeAttr('disabled');
						}
					});
					$('#JT_Finishing_Laminating option').each(function(j){
						if ($(this).val().search("^A5") === 0) {
							$(this).removeAttr('disabled');
						}
					}); 
					return true;
				}
			}
			catch(e){} 
	}

			
	);
	
}


$(document).ready(function() {

try {
   var MAX_PADDING_QUANTITY_ALLOWED = 99;
   var MAX_SEPARATOR_QUANTITY_ALLOWED = 99;

   startFrameSizer();

   addSiteIntelligenceTriggers();

   setupNavBarBehaviour();

   setupStoreLocator();

   checkColourCount();
 
//   pageSizeWarning();
   makeOrderNameReadOnly();
   hideHelixUserManual();
   hideDateSettingsInCheckoutSummary();
   validate_LimitPaperTypesToTwo();

   addDeliveryInformationTable();
   addDeliveryPolicyLinks();
   addDeliveryHover();

   setupPopupWindows();

   //cornerMiddleSection(); 

   addExternalJobProfiles();

   pdfPreviewWarning();

   cornerDatShizz();

   addWarningForMultipleItemsInCart();

   undisplayUploadSpinner();

   redirectToOfficeworksOnLogout();
   
   updatePaymentScreen();

   removeEmptyCartFromCheckout();

   cornerButtons();

   lightBlueCornerButtons();

   hideRightAndLeftNavigation();

   showRightAndLeftNavigation();   

   collapseSectionDivs();
   moveCopyCount();
   addNumericSpinnerToCopyCount();  // relies on moveCopyCount, do not change order.

   miscelanousInternetExplorerRenderingIssues();

   // quick one on load... re-runs periodically to deal with ajax page updates
   adjustFrameHeight();

   // restrict padding input and ensure pricing is recalculated as required.
   controllerFieldToggleInputField('JT_Finishing_TotalNumberofPadsDesired', 'JT_Finishing_Padding');
   validateQuantityInputField('JT_Finishing_TotalNumberofPadsDesired', MAX_PADDING_QUANTITY_ALLOWED);
   addNoteToPadding();

   //validateTabAndSeparatorNumber();
   //restrict separators input and ensure pricing is recalculated as required.
//   controllerFieldToggleInputField('JT_TabsSeparators_NumberofSeparators', 'JT_TabsSeparators_SeparatorSheetTypes');
//   validateQuantityInputField('JT_TabsSeparators_NumberofSeparators', MAX_SEPARATOR_QUANTITY_ALLOWED);

   // turn back on for additional services style separator sheets
//   additionalServiceSeparatorSheets();
//   controllerFieldToggleInputField('OW_JT_TabsSeparators_NumberofSeparators', 'OW_JT_TabsSeparators_SeparatorSheetTypes');
//   validateQuantityInputField('OW_JT_TabsSeparators_NumberofSeparators', MAX_SEPARATOR_QUANTITY_ALLOWED);

   loginAccountMessage();
   
   replacePrinterOptionsText();
   
   enforceOrderCreationValidationCriteria();
   
   hideDeleteFileOptions();
   
   addPersonalNote();
   
   addEncryptedWarningNote();
   
   addAcceptedFileTypesLinkToFileUpload();
   MovePaperSizeToTopOfPrinterOptionsSection();
   
   setOWAppTitleBar();
   
   hideDocumentFilter();
   
   disableLanguageSelection();
   
   disableA5SelectionForBookletPrinting();

   businessCardLogic();
  } catch (err) {
    // make sure we don't break anything important
  }
});

