
	// If site_url was not set externally via the header html - use the js variable (rtather than the php variable)
   if (typeof SITE_URL == "undefined") { SITE_URL = "http://"+ document.location.host + "/"; }

	// ------------------------------------------------------------------------

	/**
	* General all purpose scripts for each page
	*/

		/*
	   *	Used on main search boxes in the interface
	   */
		function focusSearchBox(box) {
			if (box.defaultText==undefined) {
				box.defaultText = box.value;
			}
			if (box.defaultText == box.value) box.value = '';
		}

		function blurSearchBox(box) {
			if (box.defaultText!=undefined && box.value=='') {
			box.value = box.defaultText;
			}
		}

		/*
		 * Old style use to open a popup page
		 */

		function openwin(newUrl, w, h) {
			if (window.name != 'Window') {
				if (w==undefined) w = 970;
				if (h==undefined) h = 400;
				window.open(newUrl,'Window',config='toolbar=no,location=no,directories=no,status=yes,menubar=yes,width='+w+',height='+h+',left=50,top=50,scrollbars=yes,resizable=yes');
			} else {
				//If already open - just change location (like for printer friendly of popups
				if (location.href.indexOf('spectronicsinoz') > 0) rootPath = "www.spectronicsinoz.com";
				else rootPath = "marketing";
				location = 'http://' + rootPath + '/' + newUrl;
			}
		}

		// Simple function to open a popup (used through catalogue and articles)
		function popup() {
			var a = popup.arguments;
			switch (a.length) {
			   // A url with an anchor
				case 2:
					var anchor = (a.length > 1) ? '#'+a[1] : '';
					openwin('/product/'+ a[0] + '/popup' + anchor);
					break;
				// Open winwith custom x, y co-ordinates
				case 3:
					openwin('/product/'+ a[0] + '/popup', a[1], a[2]);
					break;
				// A normal popup url
				default:
				   openwin('/product/'+ a[0] + '/popup');
			}
		}

      // Simple function to open a popup (used through catalogue and articles) - though in a different style
		function popupMinimal() {
			var a = popup.arguments;
			switch (a.length) {
			   // A url with an anchor
				case 2:
					var anchor = (a.length > 1) ? '#'+a[1] : '';
					openwin('/product/'+ a[0] + '/none/' + anchor);
					break;
				// Open winwith custom x, y co-ordinates
				case 3:
					openwin('/product/'+ a[0] + '/none', a[1], a[2]);
					break;
				// A normal popup url
				default:
				   openwin('/product/'+ a[0] + '/none');
			}
		}


		/*
		 * Goes to the log out url - sending the current page as a return url
		 */
		function staffLogout()
		{
		   var url = "http://" + location.host + "/?path=/staff/logout&return="+ this.location.href.replace("http://" + location.host + "/", "");
		   location=url;
		}



		/*
		 * Main document ready call for use on all pages
		 */
      jQuery(document).ready(function() {

         // Fix #links named links which don't work with our easy urls
         jQuery("a").each(function() {
            var url = jQuery(this).attr('href');
            if (url!=undefined)
            {
	            if (url.indexOf('#')==0 && jQuery(this).attr('rel') != 'ignore')
	            {
						url = CURRENT_URL + url;
	               jQuery(this).attr({ href: url });
	            }
				}
         });


			// Show external links with an icon
			jQuery('a').each(function () {
				var href = jQuery(this).attr('href');
				if (href==undefined) return;

				// If has 'http' and doesn' thave SITE_URL (set via header.php) - show the external image
				// External links
				if (href.indexOf('http')==0 && href.indexOf(SITE_URL)==-1 && jQuery(this).attr('class').indexOf('no-external-icon')==-1)
				{
				   // Don't add it if there's already an image in th elink (cause it will look crumy)
				   var images = jQuery(this).find("img");
				   if (images.length==0)
				   {
			   		jQuery(this).append(' <img style="margin:0;padding:0;float:none;display:inline;" src="/topsight/website/assets/images/external-link.gif" alt="This is an external link" />');
			  	 	}
				}
				// Internal links
				else
				{
					// This is an internal image - make sure it prevserves the 'popup' display if we're showing that
	            if (CURRENT_DISPLAY_MODE=='popup')
	            {
	               // Dont' do this for valid files to download
	               // Don't do this if popup is already in the link href
	               // Don't do thus for staff links (which are often in popups)
	               // Don't do this if target has been set for ita
	               if (
	                  (href.indexOf('.pdf')==-1 && href.indexOf('.doc')==-1 && href.indexOf('.zip')==-1 && href.indexOf('.jpg')==-1 && href.indexOf('.jpeg')==-1 && href.indexOf('.gif')==-1) &&
                     href.indexOf('/popup')==-1 &&
                     href.indexOf('/staff')==-1 &&
                     jQuery(this).attr('target')=='')
	               {
                     // Put popup within the url - either replacing a # symbol - or just at the end of the url
                     if (href.indexOf('#')==-1 && href.indexOf('/staff') > -1)
                     {
                        jQuery(this).attr({'href':href+'/popup'});
                     }
                     else
                     {
                     	jQuery(this).attr({'href':href.replace('#', '/popup#')});
                     }
                  }
	            }

				}
			});


         // Make items with class 'glow' fade from yellow
         jQuery(".glow").each(function() {
            var bgcolor = jQuery(this).css('background-color');
            jQuery(this).css({'background-color':'#FFFFE0'});
				jQuery(this).animate({
					backgroundColor: bgcolor
				}, 2400 );
         });

         jQuery(".glowgreen").each(function() {
            var bgcolor = jQuery(this).css('background-color');
            jQuery(this).css({'background-color':'#F1FFDB'});
				jQuery(this).animate({
					backgroundColor: bgcolor
				}, 2400 );
         });

			/*
			 * Handles the automatic selecting of checkboxes for each input field in the advanced search
			 */
			if (jQuery("#advancedSearchTable"))
			{
			   // The function to select the checkbox representing the input field
			   var selectTheCheckbox = function () {
	               var rowCells = jQuery(this).parent().parent().children()
	               var firstCell = jQuery(rowCells[0]);
	               var firstCellChildren = firstCell.children();
	               var checkbox = jQuery(firstCellChildren[0]);
	            	checkbox.attr({ checked: true });
					}

			   // Select it on keypress for text fields
	         jQuery("#advancedSearchTable .textinput").each(function() {
	            jQuery(this).keydown(selectTheCheckbox);
	         });

	         // And on click for dropdowns
	         jQuery("#advancedSearchTable .dropdown").each(function() {
	            jQuery(this).click(selectTheCheckbox);
	         });
			}
      });

	// ------------------------------------------------------------------------

	/**
	* Product page scripts
	*/

      jQuery(document).ready(function() {

         // Clicking product img toggles the checkbox (and the image src)
			jQuery(".add img").click(function () {
			   var input = jQuery(this).next();
			   var checked = input.attr('checked');
			   input.attr({ checked: !checked });
			   setAddShoppingImg(jQuery(this).next(), jQuery(this));
			});

			// This checks the page and sets the checked image (for when they hit back etc
			jQuery(".add img").each(function () {
            setAddShoppingImg(jQuery(this).next(), jQuery(this));
			});

			// Clicking the product checkbox toggles the img src
			jQuery(".add input").click(function () {
            setAddShoppingImg(jQuery(this), jQuery(this).prev());
			});

      });

		// Get the 'checked' attribute and set
		function setAddShoppingImg(input, img) {
		   var checked = jQuery(input).attr('checked');
			var src = jQuery(img).attr('src');
			src = src.replace('_on.gif', '.gif');
			src = (!checked) ? src.replace('_on.gif', '.gif') : src.replace('.gif', '_on.gif');
         jQuery(img).attr({ src: src });
		}

		/*
		 * Called by the add button to select all items
		 */
		function selectAllProductItems(submitAfter)
		{
		   jQuery(".add input").each(function () {
		      //var checked = jQuery(this).attr('checked');
            jQuery(this).attr({ checked: true });
            setAddShoppingImg(jQuery(this), jQuery(this).prev());
			});
			if (submitAfter) addSelectedProductItemsToList();
		}

		/*
		 * Submits
		 */
		function addSelectedProductItemsToList()
		{
			var hasSelectedItems = false;
			jQuery(".add input").each(function ()
			{
			   var checked = jQuery(this).attr('checked');
			   if (checked)
			   {
			      hasSelectedItems = true;
			   }
			});
			if (hasSelectedItems)
			{
			   jQuery("#productlistForm").submit();
			}
			else
			{
			   jQuery("#addErrorMessage span").text("Please tick the ckeckbox next to the item(s) you wish to add to your list").show().fadeTo(5000, 1).fadeOut(3000);
			}
		}

	// ------------------------------------------------------------------------

	/**
	* Online order scripts
	*/

		/*
		 * Attach click events to each "fill" link on the form
		 */

		jQuery(document).ready(function() {
		   var orderAutoFillFields = ['title', 'fname', 'lname', 'email', 'cemail', 'phone', 'orgname', 'fax', 'address1', 'address2', 'address3', 'postcode', 'country'];
		   jQuery("#fillBillFromContactDetails").click(function (e) {
            e.preventDefault();
		      autoFillFields(orderAutoFillFields, '', 'bill_', jQuery(this));
			});
			jQuery("#fillShipFromContactDetails").click(function (e) {
			   e.preventDefault();
		      autoFillFields(orderAutoFillFields, '', 'ship_', jQuery(this));
			});
			jQuery("#fillShipFromBillDetails").click(function (e) {
            e.preventDefault();
		      autoFillFields(orderAutoFillFields, 'bill_', 'ship_', jQuery(this));
			});
		});

		function autoFillFields(fields, fromFieldKey, toFieldKey, $object) {
	      if (jQuery('#id_linkclicked').length > 0)
	      {
            jQuery('#id_linkclicked').val($object.attr('id'));
	      }

		   jQuery.each(fields, function() {
		      var fromField 	= jQuery("#id_" + fromFieldKey + this);
		      var toField 	= jQuery("#id_" + toFieldKey   + this);

		      if ( jQuery(fromField) && jQuery(toField) && typeof(fromField.attr('name')) != "undefined"  && typeof(toField.attr('name')) != "undefined") {
		         toField.attr({value:fromField.attr('value')})
		      }
		    });
		}


	// ------------------------------------------------------------------------

	/**
	* Search function to browse below items
	*/

	jQuery(document).ready(function() {
	   jQuery(".itemBrowseBelow").each(function () {

		});

		initBrowseBelowButtons();
	});

	function initBrowseBelowButtons()
	{
	   jQuery(".addItemLink").click(function () {

	      if (jQuery(this).attr('isLoading')=='Y')
			{
			   return;
			}
         jQuery(this).attr({'isLoading': 'Y'});

	   	var id = jQuery(this).attr('id')
	   	id = id.replace('addItemLink', '');
	      var elem = jQuery(this);

	      elem.text('One moment...');

			$.get("/shoppinglist/add/"+id, { name: "John", time: "2pm" },
				function(data){
				   elem.parent().fadeTo(200, 0, function()
						{
						   elem.parent().fadeTo(200, 1);
							elem.replaceWith('<span class="addItemLinkDone glowgreen">This item has been added to <a href="/shoppinglist">your shopping list</a></span>');
						}
					);

					// Add this label if it's not there already (ie their first item)
	      		//if (jQuery("#shoppingListCountLabel").id==undefined)
					//{
					//   jQuery(".menuShoppinglist a").append('<span id="shoppingListCountLabel"></span>');
					//}

					jQuery("#shoppingListCountLabel").text(data);
					jQuery("#shoppingListCountLabel").parent().addClass('shoppingListLinkHasItems');     // Make it appear as full

				}
			);
	   });

	   jQuery(".itemBrowseBelow").each(function () {

			// Make sure we don't add the event listeners to the same object again
			if (jQuery(this).attr('hasMyEvents')=='Y')
			{
			   return;
			}
         jQuery(this).attr({'hasMyEvents': 'Y'});

         // Add the event listeners
			jQuery(this).click(function (e) {
            e.preventDefault();

            if (jQuery(this).attr('isLoading')=='dfY')
				{
				   alert('here');
					jQuery(this).text('I know already!');
				   return;
				}

				// Get main variables
			   var id = jQuery(this).attr('id');
	         id = id.replace('listItem', '');

	         var tagId = 'itemBelow'+ id;
	         id = id.substr(0, id.indexOf('_')); // Remove the key part at the end

            var parentContainer = jQuery(this).parent();
            var linkItem = jQuery(this);

            // This is called when we're toggling the search results
			   if (jQuery('#'+ tagId).attr('id')!=undefined)
				{
					jQuery('#'+ tagId).toggle();
					var display = jQuery('#'+ tagId).css('display');

					if (display=='none') jQuery(this).text('Show item\'s below this item');
					else jQuery(this).text('Hide item\'s below this item');

				   var src = 'url(/topsight/website/assets/images/'+ ((display=='none') ? 'expand.gif' : 'collapse.gif') + ')';
				   jQuery(this).css({'background-image': src});
					return;
			   }

				jQuery(this).css({'background-image': 'url(/topsight/website/assets/images/loading-tiny.gif)'});
				jQuery(this).css({'padding-left': '22px'});
				jQuery(this).text('One moment...');


				jQuery(this).attr({'isLoading': 'Y'});

	         $.post("/search_lookbelow/"+id, { isRowOne: parentContainer.hasClass('row1'), current_url: CURRENT_URL },
					function(data){

					   linkItem.css({'padding-left': '18px'});
					   if (data!='' && data.indexOf('<!--OK-->')>=0)
					   {
					      linkItem.text('Hide item\'s below this item');
						parentContainer.append('<div id="'+ tagId +'" class="nestedItems">'+ data +'</div>');
						linkItem.css({'background-image': 'url(/topsight/website/assets/images/collapse.gif)'});
							initBrowseBelowButtons();  // Re-init the buttons because they'll need it when they're dynamically loaded
						}
						else if (data.indexOf('<!--NO CHILDREN-->')>=0)
						{
						   linkItem.replaceWith('<span style="font-size:11px;" class="asdfasdf">There are no items below this item</span>');
						   parentContainer.find(".asdfasdf").fadeTo(2000, 0);
						}
						else
						{
						   linkItem.replaceWith('<span style="font-size:11px;">Ths items below this item could not be loaded</span>');
						}


					}
				);

			})
      });
	}
	// ------------------------------------------------------------------------

	/**
	* print functionality for any page
	*/

	jQuery(document).ready(function() {
     if (location.href.indexOf("print-this-page") >= 0)
     {
        window.print();
     }
	});

	// ------------------------------------------------------------------------

	/**
	* Conference registration scripts
	*/

		/*
		 * Attach click events to each "fill" link on the form
		 */

		jQuery(document).ready(function() {

         // does a visual toggle of the state field
		   jQuery('#id_org_country, #id_country').live('change', function()
         {
            // set it's state field to manipulate
            state_fld = (jQuery(this).attr('id') == 'id_country' ? 'id_state' : 'id_org_state');

            // check the value of the dropdown field
            if (jQuery(this).val() == 'New Zealand')
            {
               // change the state field
               jQuery("#"+state_fld)[0].selectedIndex = 0;
               jQuery('#'+state_fld).trigger('change');
               color = '#d4e3e2';
               label = 'State';
            } else {
               // check if any fields have a red border
               color = '#d4e3e2';
               jQuery('input[type="text"]').each(function(){
                  if (jQuery(this).css("border-color") != '' && jQuery(this).attr('disabled') === false)
                  {
                     color = '#f96363';
                     return;
                  }
               });
               label = 'State <span title="This field is required">*</span>';
            }

            // change the label & border color
            jQuery('label[for="'+state_fld+'"]').html(label);
            jQuery('#'+state_fld).css('border-color', color);

         });

		   var registerAutoFillFields = ['title', 'firstname', 'surname', 'address1', 'address2', 'address3', 'suburb', 'state', 'other_state', 'postcode', 'country', 'email', 'mobile', 'phone'];


         jQuery("#fillInvoiceFromPersonalDetails").click(function () {
		      autoFillFields(registerAutoFillFields, '', 'invoice_', jQuery(this));
			});

         jQuery("#fillInvoiceFromOrgDetails").click(function () {
		      autoFillFields(registerAutoFillFields, 'org_', 'invoice_', jQuery(this));

		      // copy firstname and surname from 'Your Details' page to 'Invoice Section'
		      if (jQuery('#id_firstname').length > 0 && jQuery('#id_invoice_firstname').length > 0)
		      {
               jQuery('#id_invoice_title').val(jQuery('#id_title').val());
   		      jQuery('#id_invoice_firstname').val(jQuery('#id_firstname').val());
   		      jQuery('#id_invoice_surname').val(jQuery('#id_surname').val());
            }

            if (jQuery('#id_invoice_org').length > 0 && jQuery('#id_org_not_applicable').attr('checked') === false)
            {
               jQuery('#id_invoice_org').val(jQuery('#id_organisation').val());
            }
			});

         jQuery("#fillOrgFromPersonalDetails").click(function () {
		      autoFillFields(registerAutoFillFields, '', 'org_', jQuery(this));
			});

         jQuery("#fillPersonalFromOrgDetails").click(function () {
		      autoFillFields(registerAutoFillFields, 'org_', '', jQuery(this));
			});

         jQuery("#fillPersonalFromInvoiceDetails").click(function () {
		      autoFillFields(registerAutoFillFields, 'invoice_', '', jQuery(this));
			});

         jQuery("#fillBillingFromOrgDetails").click(function () {
		      autoFillFields(registerAutoFillFields, 'org_', 'billing_', jQuery(this));
			});

         jQuery("#fillBillingFromHomeDetails").click(function () {
		      autoFillFields(registerAutoFillFields, '', 'billing_', jQuery(this));
			});

			jQuery('#id_org_not_applicable').click(function(){
			  check_org_applicable_field();
			});

			jQuery('#id_billing_not_applicable').click(function(){
			  check_billing_applicable_field();
			});

			// ---- extra call is done for things like a page being submitted
			if ( jQuery("#id_org_not_applicable").length > 0 ) {
   			check_org_applicable_field();
   		}

   		if ( jQuery("#id_home_preferable").length > 0 ) {
			   check_home_preferred_mailing_field();
			}

			jQuery('#id_home_preferable').click(function(){
            check_home_preferred_mailing_field();
			});
		});

   function check_home_preferred_mailing_field()
   {
	   if (jQuery('#id_home_preferable').is(':checked'))
	   {
	      enable_home_fields();
	   } else {
         disable_home_fields();
         if (jQuery('#id_org_not_applicable').is(':checked'))
         {
            jQuery('#id_org_not_applicable').attr("checked", false);
            check_org_applicable_field();
         }
	   }
   }

   function enable_billing_fields()
   {
      enable_field('id_billing_title', 'Title <span title="This field is required">*</span>');
      enable_field('id_billing_firstname', 'First Name <span title="This field is required">*</span>');
      enable_field('id_billing_surname', 'Surname <span title="This field is required">*</span>');
      enable_field('id_billing_address1', 'Address 1 <span title="This field is required">*</span>');
      enable_field('id_billing_address2', 'Address 2');
      enable_field('id_billing_address3', 'Address 3');
      enable_field('id_billing_suburb', 'City/Suburb <span title="This field is required">*</span>');
      enable_field('id_billing_state', 'State <span title="This field is required">*</span>');
      enable_field('id_billing_other_state', 'Other <span title="This field is required">*</span>');
      enable_field('id_billing_postcode', 'Postcode <span title="This field is required">*</span>');
      enable_field('id_billing_country', 'Country <span title="This field is required">*</span>');
	}

   function disable_billing_fields()
   {
      disable_field('id_billing_title', 'Title');
      disable_field('id_billing_firstname', 'First Name');
      disable_field('id_billing_surname', 'Surname');
      disable_field('id_billing_address1', 'Address 1');
      disable_field('id_billing_address2', 'Address 2');
      disable_field('id_billing_address3', 'Address 3');
      disable_field('id_billing_suburb', 'City/Suburb');
      disable_field('id_billing_state', 'State');
      disable_field('id_billing_other_state', 'Other');
      disable_field('id_billing_postcode', 'Postcode');
      disable_field('id_billing_country', 'Country');
	}

   function check_billing_applicable_field()
   {
      if (jQuery('#id_billing_not_applicable').is(':checked'))
		{
	      disable_billing_fields();

		} else {
         enable_billing_fields();
      }
   }

   function check_org_applicable_field()
   {
      if (jQuery('#id_org_not_applicable').is(':checked'))
		{
	      disable_field('id_organisation', 'School/Organisation Name');
	      //disable_field('id_organisation_2', 'Organisation 2');
	      disable_field('id_org_address1', 'Address 1');
	      disable_field('id_org_address2', 'Address 2');
	      disable_field('id_org_address3', 'Address 3');
	      disable_field('id_org_suburb', 'Suburb');
	      disable_field('id_org_state', 'State');
	      disable_field('id_org_other_state', 'Other');
	      disable_field('id_org_postcode', 'Postcode');
	      disable_field('id_org_country', 'Country');
	      disable_field('id_org_timezones', 'Timezone');
	      disable_field('id_org_contact', 'Contact Name');
	      disable_field('id_org_phone', 'Phone (Daytime)');
	      disable_field('id_org_mobile', 'Mobile');
	      disable_field('id_org_fax', 'Fax');
	      disable_field('id_org_purchase_no', 'Purchase Order No');


	      //disable_field('id_org_email', 'Email');
	      //disable_field('id_org_confirm_email', 'Confirm Email');
	      jQuery('#id_home_preferable').attr("checked", true);
	      enable_home_fields();
		} else {
         enable_field('id_organisation', 'School/Organisation Name <span title="This field is required">*</span>');
         //enable_field('id_organisation_2', 'Organisation 2');
         enable_field('id_org_address1', 'Address 1 <span title="This field is required">*</span>');
         enable_field('id_org_address2', 'Address 2');
         enable_field('id_org_address3', 'Address 3');
         enable_field('id_org_suburb', 'Suburb <span title="This field is required">*</span>');
         enable_field('id_org_state', 'State <span title="This field is required">*</span>');
         enable_field('id_org_other_state', 'Other <span title="This field is required">*</span>');
         enable_field('id_org_postcode', 'Postcode <span title="This field is required">*</span>');
         enable_field('id_org_country', 'Country <span title="This field is required">*</span>');
         enable_field('id_org_timezones', 'Timezone <span title="This field is required">*</span>');
         enable_field('id_org_contact', 'Contact Name <span title="This field is required">*</span>');
         enable_field('id_org_phone', 'Phone (Daytime) <span title="This field is required">*</span>');
         enable_field('id_org_mobile', 'Mobile');
         enable_field('id_org_fax', 'Fax');
         enable_field('id_org_purchase_no', 'Purchase Order No');
         //enable_field('id_org_email', 'Email <span title="This field is required">*</span>');
         //enable_field('id_org_confirm_email', 'Confirm Email <span title="This field is required">*</span>');
      }
   }

   function enable_home_fields()
   {
      enable_field('id_address1', 'Address 1 <span title="This field is required">*</span>');
      enable_field('id_address2', 'Address 2');
      enable_field('id_address3', 'Address 3');
      enable_field('id_suburb', 'Suburb <span title="This field is required">*</span>');
      enable_field('id_state', 'State <span title="This field is required">*</span>');
      enable_field('id_other_state', 'Other <span title="This field is required">*</span>');
      enable_field('id_postcode', 'Postcode <span title="This field is required">*</span>');
      enable_field('id_country', 'Country <span title="This field is required">*</span>');
      enable_field('id_timezones', 'Timezones <span title="This field is required">*</span>');
      enable_field('id_name', 'Contact Name <span title="This field is required">*</span>');
      enable_field('id_phone', 'Phone (Daytime) <span title="This field is required">*</span>');
      enable_field('id_mobile', 'Mobile');

   }

   function disable_home_fields()
   {
      disable_field('id_address1', 'Address 1');
      disable_field('id_address2', 'Address 2');
      disable_field('id_address3', 'Address 3');
      disable_field('id_suburb', 'Suburb');
      disable_field('id_state', 'State');
      disable_field('id_other_state', 'Other');
      disable_field('id_postcode', 'Postcode');
      disable_field('id_country', 'Country');
      disable_field('id_timezones', 'Timezone');
      disable_field('id_name', 'Contact Name');
      disable_field('id_phone', 'Phone (Daytime)');
      disable_field('id_mobile', 'Mobile');
   }

   function enable_field(field, label)
   {
      if (jQuery('#'+field).length > 0)
      {
         jQuery('#'+field).removeAttr("disabled");
         jQuery('label[for="'+field+'"]').html(label);
         if (jQuery('#'+field).parent().hasClass('error'))
         {
            jQuery('#'+field).css('border-color', '#f96363');
         }
         jQuery('#'+field).css('background-color', '#FFFFFF');
      }
   }


   function disable_field(field, label)
   {
      if (jQuery('#'+field).length > 0)
      {
         jQuery('#'+field).attr("disabled", true);
         jQuery('label[for="'+field+'"]').html(label);
         jQuery('#'+field).css('background-color', '#f4f4f4');
         jQuery('#'+field).css('border-color', '#D4E3E2');
         jQuery('#'+field).parent().removeClass('error');
      }
   }

	// ------------------------------------------------------------------------

	/**
	* Homepage carousel registration scripts
	*/

   jQuery(document).ready(
		function(){
         if (typeof(SHOW_IMAGE_CAROUSEL) != "undefined")
         {
   			jQuery('#fade').innerfade({
   				speed: 'slow',
   				timeout: 4000,
   				type: 'sequence',
   				containerheight: '390px'
   			});
   		}
	});



// ------------------------------------------------------------------------

	/**
	* Conference: register form radio button functionality
	*/

	 var $session_selection = '';
    jQuery(document).ready(
		function(){
		   if (jQuery("#regcomplete").length > 0)
		   {
		      $session_selection = jQuery("#session_selection");

            // check if the regcustom checkbox is checked on load and if so, set the css
		      if (jQuery('#regcustom').is(':checked'))
		      {
               ipad_borrow_state(false);
		         untick_preconference();
               set_custom_option_box_css();
		      }

		      // ---- complete registration
		jQuery("#regcomplete").click(function(){
		   ipad_borrow_state('enabled');
               jQuery("#option1regbox").addClass("regtypeSelected");
               jQuery("#option2regbox").removeClass("regtypeSelected");
               jQuery("#id_P, #id_D1, #id_D2, #id_D3, #id_ALL, #id_M").attr("checked","");

               _load_timetable_choices();
 		});

          // ---- custom registration
          jQuery("#regcustom").click(function(){
               ipad_borrow_state('disabled');
               untick_preconference();
               set_custom_option_box_css();
               _load_timetable_choices();
      		});

		jQuery("#id_P, #id_D1, #id_D2, #id_D3").click(function(){
			if (jQuery('#id_P').is(':checked') === true && 
				jQuery('#id_D1').is(':checked') === true && 
				jQuery('#id_D2').is(':checked') === true && 
				jQuery('#id_D3').is(':checked') === true)
			{
				re_select_all_option();
			}
			else if (jQuery('#id_D1').is(':checked') === true && 
				jQuery('#id_D2').is(':checked') === true && 
				jQuery('#id_D3').is(':checked') === true)
			{
				re_select_full_option();
			} else {
				ipad_borrow_state('disabled');
               untick_preconference();
               jQuery("#id_ALL").attr("checked","");
               select_custom_option_box();
           }
		});

 		jQuery("#id_ALL").click(function(){
 		   ipad_borrow_state('disabled');
 		   untick_preconference();
 		   jQuery("#id_P, #id_D1, #id_D2, #id_D3").attr("checked","");
               select_custom_option_box();
      		});

		jQuery("#id_ALL, #id_M").click(function(){

               ipad_borrow_state('disabled');
               untick_preconference();
               select_custom_option_box();

		});
	}
	});

 	function re_select_all_option()
 	{
 	 	jQuery("#id_P, #id_D1, #id_D2, #id_D3, #id_ALL, #id_M").attr("checked","");
 	 	
 	 	jQuery("#regcomplete").attr("checked","checked");
 	 	jQuery("#option1regbox").addClass("regtypeSelected");
 	 	jQuery("#option2regbox").removeClass("regtypeSelected");

 	 	ipad_borrow_state('enabled');

        jQuery.colorbox({ inline:false, width: "580px", height: "500px",  scrolling: true, html:jQuery('#registration_notice_all').html()}).click();

	}

	function re_select_full_option()
	{
		jQuery("#id_D1, #id_D2, #id_D3").attr("checked","");
		jQuery("#id_ALL").attr("checked","checked");

		jQuery.colorbox({ inline:false, width: "580px", height: "500px",  scrolling: true, html:jQuery('#registration_notice_full').html()}).click();
	}

   function ipad_borrow_state(state)
   {
      if (jQuery('li.radio_use_ipad').length > 0)
      {
         var visibility= (state == 'enabled' ? 'show' : 'hide');
         jQuery('li.radio_use_ipad').animate({opacity: visibility, height:visibility}, 'slow').prev().animate({opacity: visibility, height:visibility}, 'slow');
      }
   }

   function untick_preconference()
   {
      jQuery("#P1, #P2, #P3, #P4, #P5, #P6, #P7").attr("checked","");
      pre_selection = '';
   }

	function select_custom_option_box()
	{
	    _load_timetable_choices();
      jQuery("#regcustom").attr("checked","checked");
      jQuery("#regcomplete").attr("checked","");
      set_custom_option_box_css();
	}

	function set_custom_option_box_css()
	{
      jQuery("#option1regbox").removeClass("regtypeSelected");
      jQuery("#option2regbox").addClass("regtypeSelected");
	}


// ------------------------------------------------------------------------

	/**
	* Advanced search results
	*/
	function process_click()
	{
	   self.name = "searchresults";
      document.getElementById("exportForm").action = document.getElementById("area").options[document.getElementById("area").selectedIndex].value;
      if (document.getElementById("area").selectedIndex > 0)
      {
         document.getElementById("exportForm").target = '_new';
         document.getElementById("exportForm").submit();
      } else {
         url = '/topsight/cms/load/search/'+document.getElementById("cat").value;
         var myWin = window.open(url,'cms');
      }

	}


// ------------------------------------------------------------------------

	/**
	* EOI Form - Prevent cut and paste of email addresses into the confirm field.
	*/
	   jQuery(document).ready(
      function(){
         if (typeof(isLoggedIn) === 'undefined')
         {
            // check for cut and paste in input fields
            jQuery("input").focus(function () {
               attribute = jQuery(this).attr('nopaste');

               if (typeof(attribute) != 'undefined')
               {
                  jQuery(this).bind('cut copy paste', function(e) {
                  	e.preventDefault();
                  });
               }

     		  });

     		  // check for cut and paste in text areas
     		  jQuery("textarea").focus(function () {
               attribute = jQuery(this).attr('nopaste');

               if (typeof(attribute) != 'undefined')
               {
                  jQuery(this).bind('cut copy paste', function(e) {
                  	e.preventDefault();
                  });
               }

     		  });
       }
   });

// ------------------------------------------------------------------------

	/**
	* Cooliris Object
	*/

   jQuery(document).ready(
		function(){
		   // check if the flashobject div exists
		   if (jQuery("#flashobject").length > 0)
		   {
		      // check if we passed in a #
		      var location = document.location.toString();

		      if (location.match('#'))
		      {
   		      var anchor = location.split('#')[1];
               load_cool_iris('http://www.spectronicsinoz.com/cooliris/Rest of the World');
		      } else {
               load_cool_iris('http://www.spectronicsinoz.com/cooliris');
            }

		     	jQuery('#cooliris-selector a').live('click',function(){
		     	  jQuery("#flashobject").html(''); // clears the div so multiple swf objects aren't appended
         		jQuery('#cooliris-selector span.thumb a').removeClass('active');
         		jQuery(this).addClass('active').addClass('visited');
         		var $href = jQuery(this).attr('href');
               load_cool_iris($href);
         		return false;
         	});

      	}
	});

	function load_cool_iris(href)
	{
	  jQuery('#flashobject').flash({
         swf: 'http://apps.cooliris.com/embed/cooliris.swf',
         width: 760,
         height:450,
         wmode: 'transparent', // allows menus to appear over the cooliris wall
         flashvars: {
          style: 'white',
            feed: href
         }
      });
	}

// ------------------------------------------------------------------------

	/**
	* RSS Video Guides
	*/

   jQuery(document).ready(
		function(){
		   // check if the flashobject div exists
		   if (jQuery("#firefox3-guide").length > 0)
		   {
             load_guide('firefox3-guide', 'Firefox3_RSS_Feed/Firefox3_RSS_Feed.swf');
      	}

      	if (jQuery("#google-guide").length > 0)
		   {
             load_guide('google-guide', 'Google_Reader/Google_Reader.swf');
      	}

         if (jQuery("#ie8-guide").length > 0)
		   {
             load_guide('ie8-guide', 'IE8_RSS_Feed/IE8_RSS_Feed.swf');
      	}
	});

	function load_guide(div, url)
	{
		var so = new SWFObject('/topsight/website/assets/swf/guides/'+url, "Captivate", "791", "413", "9", "#CCCCCC");
		so.addParam("quality", "high");
		so.addParam("name", "Captivate");
		so.addParam("id", "Captivate");
		so.addParam("wmode", "opaque");
		so.addParam("bgcolor","#ffffff");
		so.addParam("menu", "false");
		so.setAttribute("redirectUrl", "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash");
		so.write(div);
	}

// ------------------------------------------------------------------------

	/**
	* Workshop Registration forms
	*/

   jQuery(document).ready(
		function(){
         if (jQuery(".radio_texthelp2011 ul li input").length > 0)
         {
   		 register_sub_options();
         }

		   if (jQuery("#id_preferred_workshop").length > 0 || jQuery("#id_preferred_workshop_alt").length > 0 || jQuery('input[rel=workshop]').length > 0)
		   {
            // find what type of form this is
            var rego = _find_rego();
            jQuery('ul.checkboxes input, ul.radio input, input[rel=workshop]').click(function()
            {
               if (jQuery(this).is(':checked') && jQuery(this).attr('name') == "preferred_workshop[]" || jQuery(this).attr('rel').length > 0)
               {
                  _set_matrix_rego_checkboxes(this, rego);
               }
            });
      	}

      	// code to ensure that any checkboxes with the single_selection classname will select only 1 option
      	jQuery('.checkboxes_single_selection ul li input.checkbox').change(function(e){

         	jQuery('.checkboxes_single_selection ul li input.checkbox').attr('checked', false);
         	jQuery(this).attr('checked', true);

      	});
	});

   function register_sub_options()
   {
      jQuery(".radio_texthelp2011 ul li input").each(function(){
         jQuery(this).click(function(){

            if ($(this).is(":checked") && $(this).attr('id') == 'id_preferred_workshop1')
            {
               if (!$('.radio_texthelp2011Mac').is(":visible"))
               {
                  $('.radio_texthelp2011Win').fadeOut(400);
                  t = setTimeout(function(){
                     $('.radio_texthelp2011Mac').fadeIn(400);
                  }, 405);
               }
            } else if ($(this).is(":checked") && $(this).attr('id') != 'id_preferred_workshop1') {
               if (!$('.radio_texthelp2011Win').is(":visible"))
               {
                  $('.radio_texthelp2011Mac').fadeOut(400);
                  t = setTimeout(function(){
                     $('.radio_texthelp2011Win').fadeIn(400);
                  }, 405);
               }
            } else {
               $('.radio_texthelp2011Mac').fadeOut(400);
               $('.radio_texthelp2011Win').fadeOut(400);
            }
         });
      });
   }

   // ------------------------------------------------------------------------

	/**
	 * Works on a matrix of checkboxes. Good examples are:
	 *
	 * http://localhost/register/workshop/hamiltonnov09form
	 * http://localhost/register/workshop/centralqldworkshopsform
	 *
	 * @author  Adrian Diente
	 * @created  26/08/2009 9:09:41 AM
	 *
	 * @access 	public
	 * @param	object string
	 * @return	unset
	 */
   function _set_matrix_rego_checkboxes(object, rego)
   {
      var checkbox_per_col = 0;
      var checkbox_label = 'id_preferred_workshop';
      var affect_only_current_row =false;
      var custom_rows = new Array();

      switch(rego)
      {
         case 'dynavoxworkshopswaform':  only_one_checked = false;affect_only_current_row = true; checkbox_per_col = 3; total_checkboxes = 3; break;
         case 'waggawaggaworkshopform':  only_one_checked = false;affect_only_current_row = true; checkbox_per_col = 4; total_checkboxes = 4; break;
         case 'centralqldworkshopsform': only_one_checked = false;affect_only_current_row = false; checkbox_per_col = 4; total_checkboxes = 12; break;
         case 'hamiltonnov09form':       only_one_checked = false;affect_only_current_row = true; checkbox_per_col = 4; total_checkboxes = 8; break;
         case 'singaporeoct21':       		only_one_checked = false;affect_only_current_row = true; checkbox_per_col = 4; total_checkboxes = 4; break;
         case 'wellingtonoct09form':      only_one_checked = false; affect_only_current_row = true; checkbox_per_col = 4; total_checkboxes = 4;break;
         case 'newzealand':               only_one_checked = false; affect_only_current_row = true; checkbox_per_col = 3; total_checkboxes = 3;break;
         case 'hamilton':                 only_one_checked = true; affect_only_current_row = true; checkbox_per_col = 3; total_checkboxes = 3;break;
         case 'texthelp':            return; break;
         case 'spectronics':  only_one_checked = false; affect_only_current_row = true; checkbox_per_col = 2; total_checkboxes = 12;break;
         case 'auckland':
            // left hand assignment affects right hand assignment in terms of checkboxes
            custom_rows = _init_array(2,2);
            custom_rows['id_preferred_workshop0'] = new Array('id_preferred_workshop1');
            custom_rows['id_preferred_workshop1'] = new Array('id_preferred_workshop0');
            list_to_affect = 'checkboxes_auckland';

            break;

         case 'christchurch':
            // left hand assignment affects right hand assignment in terms of checkboxes
            custom_rows = _init_array(2,3);
            custom_rows['id_preferred_workshop0'] = new Array('id_preferred_workshop1');
            custom_rows['id_preferred_workshop1'] = new Array('id_preferred_workshop0');
            custom_rows['id_preferred_workshop2'] = new Array('id_preferred_workshop4');
            custom_rows['id_preferred_workshop3'] = new Array('id_preferred_workshop4');
            custom_rows['id_preferred_workshop4'] = new Array('id_preferred_workshop2', 'id_preferred_workshop3');
            list_to_affect = 'checkboxes_christchurch';
            break;
      }

      if (affect_only_current_row)
      {
	      // determine which are the end checkboxes
	      data = new Array();
	      data['only_one_checked'] = only_one_checked;
	      data['affect_only_current_row'] = affect_only_current_row;
	      data['current_object_id'] = jQuery(object).attr('id');
	      data['checkbox_label'] = checkbox_label;

	      data['checkbox_per_col'] = checkbox_per_col;
	      data['total_checkboxes'] = total_checkboxes;

	      data['start_end_checkboxes'] = _build_end_checkbox_array(data);
	      _uncheck_checkboxes(data);
		} else if (custom_rows.length > 0){
         // because we have a custom layout, we need to validate it differently
          jQuery("li."+list_to_affect+" ul li input").each(function(){
               jQuery(this).click(function(){
                  if (jQuery(this).attr('checked') === true)
                  {
                     id = jQuery(this).attr('id');
                     if (typeof custom_rows[id] != 'undefined')
                     {
                        checkboxes = custom_rows[id];
                        for (var i in checkboxes)
                        {
                           jQuery('#'+checkboxes[i]).attr('checked', false);
                        }
                     }
                  }
               });
          });
      }
   }

   // ------------------------------------------------------------------------

	/**
	 * initializes a multidimentional array
	 *
	 * @author  Adrian Diente
	 * @created  8/4/2010 10:26:16 AM
	 *
	 * @access 	public
	 * @param	integer
	 * @param	integer
	 * @return	array
	 */
   function _init_array(rows, cols)
   {
      the_array = new Array(rows);
      for (i = 0; i < the_array.length; ++ i)
	     the_array [i] = new Array(cols);

    return the_array;

   }


   // ------------------------------------------------------------------------

	/**
	 * Dyamically determine which checkboxes this current_object_id affects
	 *
	 * @author  Adrian Diente
	 * @created  25/08/2009 11:32:01 AM
	 *
	 * @access 	public
	 * @param	boolean string string array integer
	 * @return	array
	 */
   function _uncheck_checkboxes(data)
   {
      data['start_end_checkboxes'] = _find_start_and_end_checkbox(data);

      // if we clicked on the end checkbox of the row
      if (data['affect_only_current_row'])
      {
         // if we click on one of the non-end checkboxes, untick the end checkbox for that row
         if (data['current_object_id'] != data['start_end_checkboxes'][1])
         {
               if (data['only_one_checked'] === true)
               {
                  _toggle_checkbox(data);
               } else {
                  jQuery('#'+data['start_end_checkboxes'][1]).attr("checked", "");
               }
         } else {
            _toggle_checkbox(data);
         }
      } else {
         _toggle_checkbox(data);
      }

   }

   // ------------------------------------------------------------------------

	/**
	 * Dyamically checks and unchecks the checkboxes depending if we affect the current
	 * row only
	 *
	 * @author  Adrian Diente
	 * @created  25/08/2009 4:47:24 PM
	 *
	 * @access 	public
	 * @param	array
	 * @return	array
	 */
   function _toggle_checkbox(data)
   {
      var checkboxids = data['total_checkboxes'] - 2;
      var counter = 0;
      var first_run = true;
      var alter_checkbox = (!data['affect_only_current_row'] ? true : false);

      // otherwise if we click on the end checkbox, uncheck all the items in this row
      while (counter <= checkboxids)
      {
         if (first_run)
         {
            checkbox = data['checkbox_label'];
            first_run = false;
         } else {
            checkbox = data['checkbox_label']+""+counter;
            counter++;
         }

         // if we click on one of the end checkboxes, untick the all other checkboxes
         if ((data['current_object_id'] == data['start_end_checkboxes'][1]) && (!data['affect_only_current_row']))
         {
            if (checkbox != data['start_end_checkboxes'][1])
            {
               jQuery('#'+checkbox).attr("checked", "");
            }
         } else {
            if (data['only_one_checked'] === true)
            {
               alter_checkbox = (data['current_object_id'] != checkbox ? true : false);
            } else {
               // check if the checkbox is the same as the first checkbox in the row
               if (checkbox == data['start_end_checkboxes'][0])
               {
                  alter_checkbox = (data['affect_only_current_row'] ? true : false);
               }
               // check if the checkbox is the same as the last checkbox in the row
               else if (checkbox == data['start_end_checkboxes'][1])
               {
                  alter_checkbox = (data['affect_only_current_row'] ? false : true);
               }
            }

            if (alter_checkbox)
            {
               jQuery('#'+checkbox).attr("checked", "");
            }
         }
      }
   }

   // ------------------------------------------------------------------------

	/**
	 * Find the start and end checkbox that sits on this particular row
	 *
	 * @author  Adrian Diente
	 * @created  25/08/2009 11:33:56 AM
	 *
	 * @access 	public
	 * @param	string array string integer
	 * @return	array
	 */
   function _find_start_and_end_checkbox(data)
   {
      var len = data['start_end_checkboxes'].length;
      var current_id = data['current_object_id'].split(data['checkbox_label']);
         current_id = parseInt(current_id[1]);

         // check if current_id is numeric
         if (current_id != parseInt(current_id))
         {
            current_id = 0;
         }
      var end_checkbox = '';
      var start_checkbox = '';
      var counter = 0;
      data['start_end_checkboxes'] = data['start_end_checkboxes'].reverse();

      while(counter < len)
      {
//      alert(counter + "-"+data['start_end_checkboxes'][counter]);
         result = data['start_end_checkboxes'][counter].split(data['checkbox_label']);
         result = parseInt(result[1]);

         if (current_id <= result)
         {
            end_checkbox = data['checkbox_label']+""+result;

            temp_counter = counter - 1;
            if (temp_counter < 0)
            {
               start_checkbox = data['checkbox_label'];
            } else {
               result = data['start_end_checkboxes'][temp_counter].split(data['checkbox_label'])
               result = parseInt(result[1]) + 1;
               start_checkbox = data['checkbox_label']+""+result;
            }
            counter = len;
         }

         counter++;
      }

      return new Array(start_checkbox, end_checkbox);
   }

   // ------------------------------------------------------------------------

	/**
	 * Dyamically figure out the checkboxes at the end of each row
	 *
	 * @author  Adrian Diente
	 * @created  25/08/2009 11:14:00 AM
	 *
	 * @access 	public
	 * @param	integer integer
	 * @return	array
	 */
   function _build_end_checkbox_array(data)
   {
      var temp_array = new Array();
      var rows = (data['checkbox_per_col'] == 1 ? data['checkbox_per_col'] : (data['total_checkboxes'] / data['checkbox_per_col']));

      // General rule is remove 2 from the total then minus total_checkboxes to determine end checkboxes
      // We remove 2 from total because the first checkbox has no number attached to the id and the
      // 2nd checkboxes starts at zero.
      counter = 0;
      startid = data['total_checkboxes'] - 2;

      while (counter < rows)
      {
         // check if we've hit the first checkbox in the list
         if (startid < 0) {
            startid = '';
            counter = rows;
         }

         temp_array[counter] = data['checkbox_label']+""+startid;
         startid = startid - data['checkbox_per_col'];
         counter++;
      }

      return temp_array;
   }

	/*
	 * parses the url to return the last option
	 *
	 * @access 	public
	 * @param	unset
	 * @return	string
	 */
   function _find_rego()
   {
      var location_str = location.href;
      location_str = location_str.split('/');
      return location_str[5];
   }


// ------------------------------------------------------------------------

	/**
	* Facebook Fans
	*/

	/*jQuery(document).ready(
		function(){
   	   if (DISABLE_FB === false && (jQuery("#fbdiv").length > 0) && (typeof(FB) !='undefined'))
   	   {
            FB.init("966d7293c34a1aa387b0d63589096045");
            jQuery('#facebook a').live('click',function (){
               _load_facebook_fans();
            });

            // close the div
            jQuery('#close_facebox').live('click',function (){
             jQuery(document).trigger('close.facebox');
            });

      	}
	});


   function _load_facebook_fans()
   {
      var viewportwidth;
      var viewportheight;

      // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

      if (typeof window.innerWidth != 'undefined')
      {
         viewportwidth = window.innerWidth,
         viewportheight = window.innerHeight
      }

      // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
      else if (typeof document.documentElement != 'undefined'
        && typeof document.documentElement.clientWidth !=
        'undefined' && document.documentElement.clientWidth != 0)
      {
          viewportwidth = document.documentElement.clientWidth,
          viewportheight = document.documentElement.clientHeight
      }

      // older versions of IE

      else
      {
          viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
          viewportheight = document.getElementsByTagName('body')[0].clientHeight
      }


	   // figured 1 cols = roughly 8 pixels
	   width_padding = 200;
	   width = (viewportwidth - width_padding) / 8;

	   // figured 1 row = roughly 18 pixels
      height_padding = 0;
	   height = (viewportheight - height_padding) / 18;

      div_data = '<div>';
      div_data += jQuery('#fbdiv').html();
      div_data += '</div>';
      jQuery.facebox(''+div_data+'');
   }
*/

// ------------------------------------------------------------------------

	/**
	* Funding Application form
	*/
	jQuery(document).ready(
		function(){
   	   if (jQuery("#id_funding_form").length > 0)
   	   {
   	      jQuery("li.textarea.error").each(function(){
               jQuery(this).css("background","none");
            })

      	}
	});

// ------------------------------------------------------------------------

	/**
	* Wellington registration forms
	*/
	jQuery(document).ready(
		function(){
		    // wellington oct 2009
   	   if (jQuery(".checkboxes_wellington_oct_prefs").length > 0)
   	   {
   	      jQuery("#id_preferred_workshop").click(function()
            {
               // if Monday 5th October is unticked
               if (!jQuery("#id_preferred_workshop").attr("checked"))
               {
                  jQuery("#id_extra_option").attr("checked", false);
                  jQuery("#id_extra_option0").attr("checked", false);
                  jQuery("#id_extra_option1").attr("checked", false);
                  jQuery("#id_extra_option2").attr("checked", false);
               } else {
                  jQuery("#id_extra_option").attr("checked", true);
               }
            });

            jQuery("#id_preferred_workshop_alt2").click(function()
            {
               // if we choose all three tuesday workshops option
               if (jQuery("#id_preferred_workshop_alt2").attr("checked"))
               {
                  jQuery("#id_preferred_workshop_alt").attr("checked", false);
                  jQuery("#id_preferred_workshop_alt0").attr("checked", false);
                  jQuery("#id_preferred_workshop_alt1").attr("checked", false);
               }
            });


            jQuery("input.checkbox").each(function(){
               jQuery(this).click(function()
               {
                  if ((jQuery(this).attr('id') == "id_preferred_workshop_alt") ||
                  (jQuery(this).attr('id') == "id_preferred_workshop_alt0") ||
                  (jQuery(this).attr('id') == "id_preferred_workshop_alt1"))
                  {
                     jQuery("#id_preferred_workshop_alt2").attr("checked", false);
                  }
               });

            });

            _check_parent_selected('id_preferred_workshop');
      	}

      	// wellington sept 2009
      	if (jQuery(".checkboxes_wellington_sept_prefs").length > 0)
   	   {
   	      // Disabled
   	      return;
   	      _check_wellington_sept_set('');
   	      jQuery("#id_preferred_workshop0").click(function()
            {
               _check_wellington_sept_set('clicked');
            });

            _check_parent_selected('id_preferred_workshop0');
      	}
	});

function _check_wellington_sept_set(action)
{
   // if Tuesday 22nd Septober is unticked
   if (!jQuery("#id_preferred_workshop0").attr("checked"))
   {
      jQuery("#id_extra_option").attr("checked", false);
      jQuery("#id_extra_option0").attr("checked", false);
      jQuery("#id_extra_option1").attr("checked", false);
      jQuery("#id_extra_option2").attr("checked", false);
   } else {
      if (action == 'clicked')
      {
         jQuery("#id_extra_option").attr("checked", true);
      }
   }
}

// ------------------------------------------------------------------------

/**
* checks if the parent checkbox/radio button is ticked before allowing a child
* radio button to be selected
*
* @author  Adrian Diente
* @created  11/08/2009 2:39:17 PM
*
* @access  public
* @param   string
* @return  unset
*/
function _check_parent_selected(parent)
{
   jQuery("input.radio").each(function(){
      jQuery(this).click(function()
      {
         if ((jQuery(this).attr('id') == "id_extra_option") ||
         (jQuery(this).attr('id') == "id_extra_option0") ||
         (jQuery(this).attr('id') == "id_extra_option1") ||
         (jQuery(this).attr('id') == "id_extra_option2"))
         {
            if (!jQuery("#"+parent).attr("checked"))
            {
               jQuery(this).attr('checked', false);
            }
         }
      });

   });
}


// ------------------------------------------------------------------------

/**
* Conference Timetable generation
*/
jQuery(document).ready(
		function(){

   	   if (jQuery("#session_selection").length > 0)
   	   {
   	      _load_timetable_choices();
       }
	});

var pre_selection = '';
/*
 ensures that only 1 pre-conference is selected
*/

function check_selections(checkbox)
{
  if (jQuery(checkbox).is(":checked"))
  {
    if (pre_selection && pre_selection != jQuery(checkbox).val())
    {
      jQuery(checkbox).attr("checked", false);
      alert('You cannot select this session as you have already selected a session for this timeslot');
    } else {
      pre_selection = jQuery(checkbox).val();
    }
  } else {
    // if the checkbox we untick is the original checkbox, clear the pre_selection variable
    if (pre_selection == jQuery(checkbox).val())
    {
      pre_selection = '';
    }
  }
}

var session_showing = false;
var current_year = 2012;
function _load_timetable_choices()
{
  /* need this delay so if they choose a custom registration type
    from the complete package, code will get it's time to untick
    the 'complete' package radio button
  */

  t = setTimeout(function(){
    if (jQuery('#regcomplete').is(':checked') === true || (jQuery('#id_P').is(':checked') === true && jQuery('#regcomplete').is(':checked') !== true))
    {
      if (session_showing === false)
      {
         session_showing = true;
         ltc_options = 'Pre';
         if (typeof timetable_options != 'undefined')
         {
           /* this is done because the posted values are not passed back
            to the ajax query so we need to manually pass it in the
            ajax call
            */
           pre_selection = timetable_options;
         }

         if (typeof timetable_options == "undefined")
         {
           timetable_options = '';

         }

         /* setTimeout added so that when old contents dissappear,
         new contents won't appear until the fade out animation is completed */
         $session_selection.animate({opacity: 'hide', height: 'hide'}, 'slow', function(){
           t = setTimeout(function(){
             // post the data to the loadTimetable function

              jQuery.post("conference/loadTimetable/"+current_year, 'options='+ltc_options+"&timetable_options="+timetable_options, function(data){
              	
               $session_selection.html(data).animate({opacity: 'show', height: 'show'}, 'slow');
               $session_selection.prev().animate({opacity: 'show', height: 'show'}, 'slow');
               check_session_selection();
             });
           }, 200);
         });
      } else {
         $session_selection.prev().animate({opacity: 'show', height: 'show'}, 'slow');
      }
    } else  {
      session_showing = false;
      $session_selection.animate({opacity: 'hide', height: 'hide'}, 'slow');
      $session_selection.prev().animate({opacity: 'hide', height: 'hide'}, 'slow');
    }
  }, 100);
}

function _set_checkbox_options()
{
  options = '';
    // check which options the user selected
    if (jQuery('#id_P').is(':checked'))
    {
      options += 'Pre';
      seperater = ',';
    }

    return options;
}

// ------------------------------------------------------------------------

/**
* Show / hide Other Profession Field
*/
jQuery(document).ready(
		function(){
       show_hide_other_field('id_org_title', 'id_other_field');
       show_hide_other_field('id_org_state', 'id_org_other_state');
       show_hide_other_field('id_state', 'id_other_state');
       show_hide_other_field('id_org_state_fa', 'id_org_other_state_fa');
       show_hide_other_field('id_org_state_sa', 'id_org_other_state_sa');
       show_hide_other_field('id_invoice_state', 'id_invoice_other_state');
       show_hide_other_field('id_billing_state', 'id_billing_other_state');
       show_hide_other_field('id_profession', 'id_other_field');
       show_hide_other_field('id_stream', 'id_other_stream');
	});

/**
 * function figures out who the parent row is before passing
 * execution to the process_other_field function.
 *
 * function also sets up the change handler
 */
function show_hide_other_field(parent, child)
{
   if (jQuery("#"+child).length > 0)
   {
      var other_field_parent = jQuery('#'+child);
      other_field_parent = other_field_parent.parent();
      jQuery(other_field_parent).hide('fast');
      _process_other_field("#"+parent, other_field_parent, child);

      jQuery("#"+parent).change(function()
      {
          _process_other_field(this, other_field_parent, child);
      });
   }
}
/**
 * function executes jquery animation to show or hide the 'other' field as appropriate
 */
function _process_other_field(object, other_field_parent, other_field)
{
  if (jQuery(object).val() == 'Other')
  {

    if (jQuery("#"+other_field).val().toLowerCase() == 'ignore')
    {
      jQuery("#"+other_field).val('');
    }
    jQuery(other_field_parent).animate({opacity: 'show', height: 'show'}, 'slow');
  } else {

    jQuery(other_field_parent).animate({opacity: 'hide', height: 'hide'}, 'slow', function(){
      /*t = setTimeout(function(){
        jQuery("#"+other_field).val("ignore");
      }, 200);*/
    });
  }

}

// ------------------------------------------------------------------------

/**
* disable submit by making fields readonly
*/
jQuery(document).ready(
	function(){
		if (typeof disable_submit != 'undefined' && disable_submit === true)
	    {
		    jQuery('input[type=text]').attr('disabled', 'disabled');
		    jQuery('input[type=checkbox]').attr('disabled', 'disabled');
		    jQuery('input[type=radio]').attr('disabled', 'disabled');
	        jQuery('#id_email').removeAttr('disabled');
		    jQuery('textarea').attr('disabled', 'disabled');
		    jQuery('select').attr('disabled', 'disabled');

		    if (jQuery("#regcomplete").length > 0)
		    {
				jQuery('#regcomplete, #regcustom, #id_ALL, #id_P, #id_D1, #id_D2, #id_D3, #id_M').attr('disabled', '');
		    }
        }

	});


// ------------------------------------------------------------------------

/**
* sgd competition
*/
jQuery(document).ready(
	function(){
	   if (jQuery('#device_selection_label').length > 0)
	   {
         jQuery('#id_device_selection').change(function()
         {
            set_device_label();
         });
         set_device_label();
	   }
});

function set_device_label()
{
   dropdown_selection = jQuery('#id_device_selection').find('option').filter(':selected').text();

   text_label = "Tell us about your situation and how you would benefit from winning the <span id='device_selection_label'>" +
      dropdown_selection +
       "</span>?<span>*</span>";

   // if this field errors, set the appropriate label in the error message
   jQuery('#device_selection_label').text(dropdown_selection);

   // set the entire label next to textarea
   jQuery('#label_situation').html(text_label);

}




// ------------------------------------------------------------------------

	/**
	* Timezone controls
	*/

	jQuery(document).ready(function() {
      jQuery("#id_state").change(function(){
         set_timezone('id_state', 'id_timezones');
      });

      jQuery("#id_org_state").change(function(){
         set_timezone('id_org_state', 'id_org_timezones');
      });
	});

   function set_timezone(state_dropdown, timezone)
   {
      if (jQuery('#'+timezone).length > 0)
      {
         index = 0;
         switch (jQuery('#'+state_dropdown+" option:selected").val())
         {
            case 'ACT':
            case 'TAS':
            case 'VIC':
            case 'NSW': index = 4; break;
            case 'NT':  index = 1; break;
            case 'QLD': index = 2; break;
            case 'SA':  index = 3; break;
            case 'WA':  index = 0; break;
         }
         jQuery("#"+timezone)[0].selectedIndex = index;
      }
   }

/*
* ************************************************************************
*
* Widgets/zebra Styles : Last modified September 23, 2010, 9:53am
*
* ************************************************************************
*/

function applyZebraRows()
{
   var rowi = 1;
   $('table.zebra tr').each(function(){
   	if ($(this).attr('class') == 'heading')
   	{
   		rowi = 2;
   	}
   	else
   	{
   		$(this).addClass('row' + rowi);
   		rowi = (rowi==1) ? 2 : 1;
   	}
   });
}


$(document).ready(function() {

   applyZebraRows();

});

/*
* ************************************************************************
*
* staff control panel
*
* ************************************************************************
*/

jQuery(document).ready(function() {
   if (jQuery('#updateKeywords').length > 0)
   {
      jQuery('#updateKeywords').click(function(e){
         e.preventDefault();

         // load the keywords
         $.post('/staff/keywords/retrieve', {id:$(this).attr('itemid')}, function(data){
            $('#keywordsDiv').slideDown(250);
            $('#staff_keywords').val(data);
         });
      });

      jQuery('#saveKeywords').click(function(e){
         // save the keywords
         $.post('/staff/keywords/save', {id:$('#updateKeywords').attr('itemid'), staff_keywords:$('#staff_keywords').val()}, function(data){
            $('#staff_keywords_success').fadeIn(500).delay(2000).fadeOut(500);

         });
      });

      jQuery('#staff_close_keywords').click(function(e){
         // hide the keywords panel
         $('#keywordsDiv').slideUp(250);
      });


   }
});

/*
* ************************************************************************
*
* credit card input mask
*
* ************************************************************************
*/
jQuery(document).ready(function() {
   if (jQuery('#id_card_number').length > 0)
   {
      jQuery('#id_card_number').mask('9999 9999 9999 9999');
   }
});


/*
* ************************************************************************
*
* Online Training
*
* ************************************************************************
*/
jQuery(document).ready(function() {
   if (jQuery('#ot_container').length > 0)
   {

		
      div_width = (screen.width <= 1024 || screen.height <= 768 ? "99%" : "70%");
      div_height = (screen.width <= 1024 || screen.height <= 768 ? "99%" : "80%");
      object = null;

      jQuery('a[rel=colorbox-popup], a[rel=colorbox-popup-scroll]').click(function(e){

         e.preventDefault();
         jQuery('#cboxClose').click();
         $('#cboxOverlay, #colorbox').remove();
         var key = jQuery(this).attr('href');
         var rel = jQuery(this).attr('rel');

         jQuery.post('/colorbox_popup/', {key: key}, function(ot_data){

            $.fn.colorbox.init();
            jQuery.colorbox({width:div_width, inline:false, height: div_height,  scrolling: true, html:'<div id="training_data" style="height:100%; width:100%; overflow:hidden; text-align:left; position:relative">'+ot_data+'</div>'}).click();

            if (rel == 'colorbox-popup-scroll')
            {
               // odd issue in colorbox that doesn't allow me to set the style on #cboxLoadedContent directly
               jQuery('#training_data').attr('style'," width:100%; overflow:auto; text-align:left;  position:relative").attr('style'," width:100%; overflow:hidden; text-align:left;  position:relative");
            }
         });
      });
      
		var sessionid=document.URL.split('#')[1];
		if (typeof sessionid != 'undefined')
		{
			jQuery('#cboxClose').click();
			jQuery('#'+sessionid).click();
		}

      // this code prevents the parent document from scrolling when colorbox is open
      jQuery(document).bind('cbox_open', function(){ jQuery('html').css({overflow:'hidden'});
         }).bind('cbox_closed', function(){ jQuery('html').css({overflow:'auto'});
      });
   }

   jQuery('a[rel=iframe-link]').live('click', function(e){
      e.preventDefault();

      // show the scrollbar once this is loaded
      jQuery('#training_data').attr('style',"height:100%; width:100%; overflow:auto; text-align:left;  position:relative");

      url_split = jQuery(this).attr('href').split('/');
      jQuery('#popup-frame').attr('src', "https://www3.gotomeeting.com/register/"+url_split[url_split.length - 1]);

   });


   jQuery('#timezone').live('change', function(e){

      jQuery.post('/onlinetraining/set_local_timezone', {offset:jQuery(this).val(), session:jQuery(this).attr('rel')},                 function(sessions) {
         for (i =0; i < sessions.length; i++)
         {
            var session = sessions[i].split('--');
            jQuery('#' + session[0]+'_date').empty().html(session[1]);
            jQuery('#' + session[0]+'_time').empty().html(session[2]);
         }

      }, 'json');
   });
});

/*
* ************************************************************************
*
* Update Prices List
*
* ************************************************************************
*/
jQuery(document).ready(function() {
   if (jQuery('#pricelist').length > 0)
   {
      var updated_fields = new Array();
      jQuery('input[rel=price_field]').focusin(function(e){
         // check if a value is set
         if (typeof jQuery(this).data('price') == 'undefined')
         {
            jQuery(this).data('price', jQuery(this).val());
         }
      }).focusout(function(e){
         // check if a value is changed
         if (typeof jQuery(this).data('price') != 'undefined')
         {
            if (jQuery(this).data('price') != jQuery(this).val().trim())
            {
               updated_fields.push(jQuery(this).attr('id'));
            }
         }
      });

      $("#pricelist_form").submit( function () {
         jQuery('#updated_fields').val(updated_fields.join(','));

         return true;
      });
   }
});

/*
* ************************************************************************
*
* preview pane colorbox for webinars
*
* ************************************************************************
*/
jQuery(document).ready(function() {
   var orig_url = '';
   var orig_obj = null;
   jQuery('a[rel=preview-pane]').live('click', function(e){
      e.preventDefault();

         orig_url = jQuery('a[rel=preview-pane]').attr('href');
         jQuery.post(orig_url+'/ajax', function(url){

               // change to a view_webinar link
               jQuery('a[rel=preview-pane]').attr('href', url).attr('rel', 'view_webinar');

               div_width = (screen.width <= 1024 || screen.height <= 768 ? "99%" : "90%");
               div_height = (screen.width <= 1024 || screen.height <= 768 ? "99%" : "90%");

               // open colorbox
               jQuery('a[rel=view_webinar]').colorbox({iframe:true, innerWidth:div_width, innerHeight:div_height,  scrolling: false}).click();
         });
   });

   // this code prevents the parent document from scrolling when colorbox is open
   jQuery(document).bind('cbox_open', function(){ jQuery('html').css({overflow:'hidden'});
      }).bind('cbox_closed', function(){ jQuery('html').css({overflow:'scroll'});
      if (orig_url.length > 0)
      {
         // revert orignal url
         jQuery('a[rel=view_webinar]').attr('href', orig_url).attr('rel', 'preview-pane');
      }
   });
});

/*
* ************************************************************************
*
* preview pane colorbox for any document url that is unencrypted
*
* ************************************************************************
*/
jQuery(document).ready(function() {
   var orig_url = '';
   var orig_obj = null;
   jQuery('a[rel=view-document]').live('click', function(e){
      e.preventDefault();

      div_width = (screen.width <= 1024 || screen.height <= 768 ? "99%" : "90%");
      div_height = (screen.width <= 1024 || screen.height <= 768 ? "99%" : "90%");

      // open colorbox
      jQuery('a[rel=view-document]').colorbox({iframe:true, innerWidth:div_width, innerHeight:div_height,  scrolling: false});

   });

   // this code prevents the parent document from scrolling when colorbox is open
   jQuery(document).bind('cbox_open', function(){ jQuery('html').css({overflow:'hidden'});
      if (jQuery.browser.msie ) {
         jQuery("body").css('text-align', 'left');
      }
      }).bind('cbox_closed', function(){ jQuery('html').css({overflow:'scroll'});
      if (jQuery.browser.msie ) {
         jQuery("body").css('text-align', 'center');
      }
   });
});

/*
* ************************************************************************
*
* load youtube videos
*
* ************************************************************************
*/
jQuery(document).ready(function() {
   jQuery('a[class=video-link]').click(function(e){
      e.preventDefault();

      $me = jQuery(this);
      href = jQuery(this).attr('href');
      youtubeID = href.substring(31, jQuery(this).attr('href').length);

      // check if the link is a youtube link
      if (href.toLowerCase().indexOf("youtube") >= 0)
      {

         // need the callback=? portion to avoid IE complaining about security
         jQuery.getJSON('http://gdata.youtube.com/feeds/api/videos/'+youtubeID+'?callback=?&enablejsapi=1&v=2&alt=jsonc', function(d) {

            if (d)
            {

               div = '<div id="loaded_video" style="position:absolute;height:100%; width:100%; overflow:hidden"><div id="video"><object width="640" height="470"><param name="movie" value="http://www.youtube.com/v/'+youtubeID+'&rel=1"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/'+youtubeID+'&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="640" height="470"></embed></object></div>';

               div += '<div id="title"><h3 class="coloured">'+d.data.title+'</h3></div>';
               div += '<div id="description">'+d.data.description.replace(/(http:\/\/\S+)/g, "<a href='$1' target='_new'>$1</a>")+'</div></div>';
//alert(div);
               jQuery("#video-pane").empty().html(div).show().colorbox({width:682, height:'80%', inline:true, href:"#loaded_video"}).click();

            }
         });
      } else {
         window.open( $me.attr('href') ); // open weird video links like moletv.org.uk in a new window
      }
   });

});

/*
* ************************************************************************
*
* create a jquery tabbed item
*
* ************************************************************************
*/
jQuery(document).ready(function() {
/*
var myGallery = new gallery(jQuery('.jcGallery'), {
            timed: false
            });

   jQuery('#active-tabs-navigation').attr('style', 'display:block');
    $("#active-tabs").tabs();*/



});

/*
* ************************************************************************
*
* toc scrolling
*
* ************************************************************************
*/
jQuery(document).ready(function()
{
   jQuery("#toc li a, #toc-js li a").live('click', function(e){
      e.preventDefault();
      toc_scroll(jQuery(this));
   });
});
      
function toc_scroll($object)
{

	//get the full url - like mysitecom/index.htm#home
	//split the url by # and get the anchor target name - home in mysitecom/index.htm#home
	var parts = $object.attr('href').split("#");
	var trgt = parts[1];

	//get the top offset of the target anchor
	var target_offset = jQuery("#"+trgt).offset();
	var target_top = target_offset.top;

   // timeout used to prevent a yoyo effect; can't figure out why it happens
   t = setTimeout(function(){
	  //goto that anchor by setting the body scroll top to anchor top
	  jQuery('html, body').animate({scrollTop:target_top}, 500);
   }, 200);
}

/*
* ************************************************************************
*
* Badges
*
* ************************************************************************
*/


jQuery(document).ready(function()
{
	if (jQuery("#badges li ul li input").length > 0)
	{
		var val = (CURRENT_URL == 'conference/2012/badges/delegates' ? 'delegates/Badges-01.jpg' : 'presenters/Badges-01.jpg' );
		_set_badge(val);
		jQuery("#badges li ul li input").click(function(e){
			var val = jQuery(this).attr('value');
			if (val != '')
			{
				_set_badge(val);
			} else {
				e.preventDefault();
			}
		});
	}
});

function _set_badge(val)
{
	jQuery('#banner_image').attr('src', '/topsight/website/assets/images/badges/'+val);
	jQuery('#id_web_embed_code').attr('value', '<a href="http://www.spectronics.com.au/conference" target="_new"><img src="/topsight/website/assets/images/badges/'+val+'" border="0" /></a>');
	jQuery('#id_gmail_embed_code').attr('value', 'http://www.spectronics.com.au/topsight/website/assets/images/badges/'+val);
	
}

function _show_message(message, timing)
{
   // show a message to say it's done.
   $('#message').html(message).slideDown('fast', function(){
      t = setTimeout(function(){
         $('#message').slideUp('fast');
      }, timing);
   });
}
