//The standard Javascript functions used on most pages
//Options configuration
//Comma seperated list of elements which will activate the basket update function
var basketUpdateTrigger = ".buyButton, .addButton, .addInputButton input";
//The element which will have it's content replaced with the updated basket details
var basketContainer = "#headerBasketContainer";
/*The position of the bottom of the basket button (the top left position of the element plus its height)*/
var basketContainerPosition = 0;
//Checkbox elements associated with hidden fields
var hiddenCheckboxes = "#saveDetails, #delivery";
//Search box placeholder text
var searchPlaceholder = "Search...";

//Set the site root to detect if the test or live site is being used, this is needed for the AJAX requests. The site root is set here to make it a global variable for use in postcodeLookup.js and lightbox.js
var siteRoot = window.location.protocol + "//" + window.location.hostname + "/"
//If the hostname is equal to the test site			
if (window.location.hostname == "www.axisfirst.net") {
	//Add the virtual directory to the end
	siteRoot = siteRoot + "healthyworkstations/";	
}

//Hide all elements that are skinned by uniform, this should stop the originals flashing up before being replaced
$("select, input[type=checkbox], input[type=radio]").hide();

//Run this function when the page loads
$(document).ready(function(){		   
	/********************************************************************************************************/
	/***********************************************Search box***********************************************/
	/********************************************************************************************************/
	//When the search box is clicked
	$("#headerSearch").click(function() {			  
		//If the text input is filled with the placeholder text
		if ($(this).val() == searchPlaceholder) {
			//Clear the placeholder text
			$(this).val("").addClass("headerSearchFocus");
		}
	});
	//When the search box loses focus
	$("#headerSearch").blur(function() {
		//If the length of the value in the input box is 0 then no text has been entered
		if ($(this).val().length == 0) {
			//Show the placeholder text
			$(this).val(searchPlaceholder).removeClass("headerSearchFocus");
		}
	});
	/********************************************************************************************************/
	/**********************************************Basket update*********************************************/
	/********************************************************************************************************/
	//When an "Add to basket", "Add", or recently viewed "Buy now" button is clicked
	$(basketUpdateTrigger).click(function() {
		//Var used to store the url to which the AJAX request is made (with a default value of includes/updateBasket.asp)
		var ajax_url = siteRoot + "includes/updateBasket.asp";
		//Var used to store form values
		var formElements;
		//Store the parent form
		var parentForm = $(this).parents('form');
		//Used to flag if the options selected on the form are valid
		var formValid = true;
		
		//If the validation plugin exists
		if(jQuery().validate) {
			//Check to se if the details entered are valid
			formValid = $(parentForm).valid();
		}

		//If the form has passed validation
		if (formValid) {
			//If we are dealing with a group item
			if ($('input[name=formtype]', parentForm).length > 0) {
				//Change the ajax_url from includes/updateBasket.asp to AddGrpItmBasket.asp
				ajax_url = siteRoot + "AddGrpItmBasket.asp";
	 
				//Store serialised form values, with an ajax flag set to true
				formElements = parentForm.serialize() + "&ajax_request=true";
			}
			else {
				//Get the product reference number
				var productReference = $(this).attr("name");
				//Start the array of the product ID and quantity
				formElements = "productID=" + productReference + "&addMultiple=false";
	
				//If the length of the quantity input is not zero
				if ($("#REF" + productReference).length) {
					//Then a buy button with a quantity input has been clicked, set the quantity to the value of the quantity input
					formElements = formElements + "&REF" + productReference + "=" + $("#REF" + productReference).val();
					//Reset the quantity box to 1
					$("#REF" + productReference).val(1);
				//If the length of the quantity input is zero
				}
				else {
					//Then the a buy button without a quantity input was clicked, set the quantity to 1
					formElements = formElements + "&REF" + productReference + "=1";
				}
				//If the name of the button pressed was "multiple" then more than one product is to be added to the basekt
				if (productReference == "multiple") {
					//Get all the fields in the buttons containing form
					formElements = parentForm.serialize() + "&addMultiple=true";
					//Reset the quantity boxes to 0
					$(this).parents("form:first").find("input[name^=REF]").val(0);
				}
			}
	
			//Call the update basket include page to update with the values entered (formElements)
			$.ajax({ type: "POST", url: ajax_url, data: formElements, success: function(basketContents) {  
				//Update the basket section in the header with the updated basket contents
				$(basketContainer).html(basketContents);
				$(basketContainer).addClass("headerBasketContainerItems");
				/*Call headerBasketScrollPosition to position the header basket popup*/
				headerBasketScrollPosition();
				/*Show the basket popup then hide it after 3 seconds*/
				$("#headerBasketPopup").slideDown().delay(3000).slideUp();
			}}); 
		}
		
		//Return false to stop the button from submitting the form or following the link
		return false;
	});
	
	/********************************************************************************************************/
	/*******************************************Header basket popup******************************************/
	/********************************************************************************************************/
	//When the mouse cursor entered and leaves the header basket container
	$("#headerBasketContainer").live("mouseover", function(event) {
		//If hover intent has not been attached to this element
        if (!$(this).data("init")) {
			//Flag that hover intent has been attached to the element
            $(this).data("init", true);  
			//Attach hover intent to the element to ensure that there is a slight delay when the user hovers over
            $(this).hoverIntent (  
                function() {  
                	//When the basket container is hovered call headerBasketScrollPosition to position the header basket popup
					headerBasketScrollPosition();
					//Show the basket popup
					$("#headerBasketPopup").stop(true, true).slideDown();
                },  
                function() {  
					//When the basket container is not hovered, hide the basket popup
					$("#headerBasketPopup").slideUp(); 
                }  
            );  
			//Trigger the mouse over event
            $(this).trigger("mouseover");  
        } 
    });

	/********************************************************************************************************/
	/******************************************Basket scroll position****************************************/
	/********************************************************************************************************/
	/*Ensures that the basket popup is displayed at the top of the screen if the basket button is not in view and under it if it is*/
	function headerBasketScrollPosition() {
		/*If the position of the popup is set to fixed then the browser supports fixed positioning (not IE6)*/
		if ($("#headerBasketPopup").css("position") == "fixed") {
			/*If the basket container is not on screen*/
			if ($(window).scrollTop() > basketContainerPosition) {
				/*Set the popup to be at the top of the window*/
				$("#headerBasketPopup").css("top", "0");
			/*If the basket container is on screen*/
			} else {
				/*Ensure the popup is positioned below the basket container*/
				$("#headerBasketPopup").css("top", basketContainerPosition - $(window).scrollTop());
			}
			/*The position of the basket when scrolled*/
			$(window).scroll(function () { 
				/*If the basket container is not on screen*/
				if ($(window).scrollTop() > basketContainerPosition) {
					/*Set the popup to be at the top of the window*/
					$("#headerBasketPopup").css("top", "0");
				/*If the basket container is on screen*/
				} else {
					/*Ensure the popup is positioned below the basket container*/
					$("#headerBasketPopup").css("top", basketContainerPosition - $(window).scrollTop());
				}
			});
		//If the popup is using absolute positioning (IE6)
		} else {
			//Ensure the popup is positioned at the top of the window
			$("#headerBasketPopup").css("top", $(window).scrollTop() - 29);
			/*The position of the basket when scrolled*/
			$(window).scroll(function () { 
				//Ensure the popup is positioned at the top of the window
				$("#headerBasketPopup").css("top", $(window).scrollTop() - 29);
			});
		}
	}	
	
	/********************************************************************************************************/
	/*******************************************Hidden area toggles******************************************/
	/********************************************************************************************************/
	//Create an array of all the checkboxes associated with a hidden container
	var hiddenCheckboxesArray = hiddenCheckboxes.split(",");
	//For each checkbox in the array
	for (var checkbox in hiddenCheckboxesArray) {
		//If the checkbox is not checked
		if ($(hiddenCheckboxesArray[checkbox]).attr("checked") === false) {
			//Hide the container by default. This is hidden using JavaScript to enable users with JavaScript disabled to see the container
			$(hiddenCheckboxesArray[checkbox] + "Container").hide();			
		}	
	}
	//When a checkbox associated with a hidden container is clicked
	$(hiddenCheckboxes).click(function() {
		var checkboxName = $(this).attr("id");
		//Toggle the visibility of the associated container
		if ($(this).attr("checked") === true) {
			$("#" + checkboxName + "Container").slideDown();
		} else { 
			$("#" + checkboxName + "Container").slideUp();
		}
	});
	
	/********************************************************************************************************/
	/*****************************************Delivery address autofill**************************************/
	/********************************************************************************************************/
	//The delivery checkbox is hidden by default for users with JavaScript disabled. Show it
	$("#copyAddressContainer").show();
  	//When the checkbox is clicked
    $("#copyAddress").click(function() {
        //If billing address is to be copied
        if ($(this).is(":checked")) {
            //For each delivery address input field
            $("#deliveryContainer input").each(function(i) { 
                //Copy the values from the billing address inputs
                $(this).val($("#billingContainer input").eq(i).val());
             });
            //For each delivery address select field
            $("#deliveryContainer select").each(function(i) { 
				//The name of the current select box
				var deliverySelectName = $(this).attr("id");
				//The value of the billing select box
				var billingSelectValue = $("#billingContainer select").eq(i).val();
                //Copy the values from the billing address selects
				$("#" + deliverySelectName + " option[value=" + billingSelectValue + "]").attr("selected", "selected");
				//Set the text for the uniform span tag
				$("#uniform-" + deliverySelectName + " span").text(billingSelectValue);
            });
        //If billing address is not to be copied      
        } else {
			//For each delivery address input field
			$("#deliveryContainer input").each(function(i) { 
				//If the type of the input in not hidden
				if ($(this).attr("type") != "hidden") {
					//Set it's value to nothing
					$(this).val(""); 
				}
			});
			//For each delivery address select field
			$("#deliveryContainer select").each(function(i) { 
				//The name of the current select box
				var deliverySelectName = $(this).attr("id");
				//Set it to the default option
				$("#" + deliverySelectName + " option:first").attr("selected", "selected");
				//Set the text for the uniform span tag
				$("#uniform-" + deliverySelectName + " span").text($("#" + deliverySelectName).val());
			});
        }
    });
	
	/********************************************************************************************************/
	/*********************************************Quantity update********************************************/
	/********************************************************************************************************/
	//When a plus or minus button is clicked
	$(".addQuantityButton, .minusQuantityButton").click(function() {
		//The quantity input associated with the plus and minus buttons				 
		var quantityInput 
		//If the pressed button is on the basket page
		if ($(this).hasClass("quantityBasketButton")) {
			quantityInput = $(this).parents(".quantityContainer").find(".AXISFieldText");
		//If the pressed button is not on the basket page
		} else {
			quantityInput = $(this).parent().find(".quantityInput"); 
		}
		//The current value in the quantity input
		var quantityAmount = parseInt($(quantityInput).val());
		//If the minus button has been pressed
		if ($(this).hasClass("minusQuantityButton")) {
			//If the quantity is greater than 0
			if (quantityAmount > 0) {
				//Remove one from the value
				$(quantityInput).val(quantityAmount - 1);
			}
		//If the plus button has been pressed
		} else {
			//Add one to the value
			$(quantityInput).val(quantityAmount + 1);
		}				 
		//Return false to stop the button from submitting the form or following the link
		return false;
	});
	//Highlight the quantity box when the user focuses on the element or hovers over the add/minus buttons
	$(".quantityInput, .AXISFieldText").live("focus", function(event){$(this).addClass("active");}).live("blur", function(event){$(this).removeClass("active");});
	$(".addQuantityButton, .minusQuantityButton").live("mouseover", function(event){$(this).parent().find(".quantityInput").addClass("active");}).live("mouseout", function(event){$(this).parent().find("input").removeClass("active");});
	/********************************************************************************************************/
	/****************************************View orders date switcher***************************************/
	/********************************************************************************************************/
	$("#AXISOrdersPeriod").attr("onchange","");
	//When the view orders date drop down is changed
	$("#AXISOrdersPeriod").change(function() {
		//Submit the containing form
		$(this).parents("form:first").submit();
	});
	
	/********************************************************************************************************/
	/**********************************************VAT switcher**********************************************/
	/********************************************************************************************************/
	/*When the VAT switcher radio buttons are clicked*/
	$(".VATSwitchRadio").click(function() {
		/*Submit the VAT switcher form*/
  		$("#VATSwitchForm").submit();
	});
	
	/********************************************************************************************************/
	/************************************************Mega menus**********************************************/
	/********************************************************************************************************/
	/*When the mega menu navigation containers are hovered over*/
	$("#headerNavList li").hoverIntent(
		function() {
			/*Show the popup*/
			$(this).find(".headerNavMenu").stop(true, true).slideDown();
			/*Highlight the button*/
			$(this).find(".headerNavLink").addClass("selected");
		},
  		function () {
			/*Hide the popup*/
			$(this).find(".headerNavMenu").slideUp("slow", function() {
				/*Remove the highlight on the button*/
				$(this).prev("a").removeClass("selected");
			});
  		}
	);	
});


/********************************************************************************************************/
/*********************************************Wizard update**********************************************/
/********************************************************************************************************/
$(".wizardSelect").attr("onchange","");
$(".wizardSelect").live("change",function(){
	//Create an array of the elements within the form
	var formElements = $(this).parents("form").serialize();
	
	//If the wizard select box being changed is not the equip_id box
	if ($(this).attr("id") != "equip_id") {
		//Call the wizard include page to update with the values entered (formElements)
		$.ajax({ type: "POST", data: formElements + "&dynamicUpdate=true", url: siteRoot + "includes/wizard.asp", cache: false, success: function(wizardUpdate){
			//Replace old part finder form with the new part finder form generated by the AJAX request
			$("#wizardForm").replaceWith(wizardUpdate);	
			$(".wizardSelect").attr("onchange","").uniform();		
		}}); 
	}
});

//When the wizard is submitted
$("#wizardForm").live("submit",function(e){	
	var wizardErrorFound, wizardErrorMessage;
	//If the required printer wizard options have not been selected then the manu_id select box will be disabled
	if ($("#manu_id").attr("disabled")) {
		//Add the error message to the form and flag that an error has been found
		wizardErrorMessage = "<div class='errorContainer'>Please choose your cartridge type</div>";	
		wizardErrorFound = true;
	//If the required printer wizard options have not been selected then the equip_id select box will be disabled
	} else if ($("#equip_id").attr("disabled")) {
		//Add the error message to the form and flag that an error has been found
		wizardErrorMessage = "<div class='errorContainer'>Please choose your make of printer</div>";	
		wizardErrorFound = true;
	}
	//If an error was found
	if (wizardErrorFound) {
		if ($(".errorContainer").length == 0) {
			//Add the error message to the form
			$("#wizardForm fieldset").append(wizardErrorMessage);	
		}
		//Stop the button from submitting the form
		e.preventDefault();
	}
});


/********************************************************************************************************/
/***************************************External links new window****************************************/
/********************************************************************************************************/
//When any link with the rel parameter equal to external is clicked
$("a[rel='external']").click(function(){
	//Open the link in a new window
	window.open($(this).attr("href"));
	//Return false to stop the button from submitting the form or following the link
	return false;
});


/********************************************************************************************************/
/*****************************************JavaScript load defer******************************************/
/********************************************************************************************************/
//Functions used to create JavaScript files
function async_load(fileType, fileAddress){
	//The code block being created (e.g. script or link)
	var s = document.createElement(fileType);
	//If the file type is link (stylesheet)
	if (fileType == "link") {
		//Set the type, rel, href and media attributes of the code block
		s.type = "text/css";
		s.rel = "stylesheet";
		s.href = fileAddress;
		s.media = "print";		
	//If the file type is script
	} else if (fileType == "script") {
		//Set the type, async (only supported by HTML5) and src attributes of the code block
		s.type = "text/javascript";
		s.async = true;
		s.src = fileAddress;
	}
	//Finds the tag in the page and places the new code block before it
	var x = document.getElementsByTagName(fileType)[0];
	x.parentNode.insertBefore(s, x);
}

//Functions used to defer loading of the created JavaScript files
function deferScriptLoad(fileType, fileAddress) {
	//If the browser supports attachEvent (e.g. IE)
	if (window.attachEvent) {
		//Set the script to run onload
		window.attachEvent("onload",function(){async_load(fileType, fileAddress);});
	//If the browser does not support attachEvent (e.g. FireFox)
	} else {
		//Set the script to run onload
		window.addEventListener("load",function(){async_load(fileType, fileAddress);},false);
	}
}
//Defer the loading of the print stylesheet
//deferScriptLoad("link", siteRoot + "css/print.min.css");

/********************************************************************************************************/
/********************************************************************************************************/
/*******************************************External Javascript******************************************/
/********************************************************************************************************/
/********************************************************************************************************/
/**
* hoverIntent is similar to jQuery's built-in "hover" function except that
* instead of firing the onMouseOver event immediately, hoverIntent checks
* to see if the user's mouse has slowed down (beneath the sensitivity
* threshold) before firing the onMouseOver event.
* 
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* hoverIntent is currently available for use in all personal or commercial 
* projects under both MIT and GPL licenses. This means that you can choose 
* the license that best suits your project, and use it accordingly.
* 
* // basic usage (just like .hover) receives onMouseOver and onMouseOut functions
* $("ul li").hoverIntent( showNav , hideNav );
* 
* // advanced usage receives configuration object only
* $("ul li").hoverIntent({
*	sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
*	interval: 100,   // number = milliseconds of polling interval
*	over: showNav,  // function = onMouseOver callback (required)
*	timeout: 0,   // number = milliseconds delay before onMouseOut function call
*	out: hideNav    // function = onMouseOut callback (required)
* });
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($) {
	$.fn.hoverIntent = function(f,g) {
		// default configuration options
		var cfg = {
			sensitivity: 8,
			interval: 100,
			timeout: 0
		};
		// override configuration options with user supplied object
		cfg = $.extend(cfg, g ? { over: f, out: g } : f );

		// instantiate variables
		// cX, cY = current X and Y position of mouse, updated by mousemove event
		// pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
		var cX, cY, pX, pY;

		// A private function for getting mouse position
		var track = function(ev) {
			cX = ev.pageX;
			cY = ev.pageY;
		};

		// A private function for comparing current and previous mouse position
		var compare = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			// compare mouse positions to see if they've crossed the threshold
			if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
				$(ob).unbind("mousemove",track);
				// set hoverIntent state to true (so mouseOut can be called)
				ob.hoverIntent_s = 1;
				return cfg.over.apply(ob,[ev]);
			} else {
				// set previous coordinates for next time
				pX = cX; pY = cY;
				// use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
				ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
			}
		};

		// A private function for delaying the mouseOut function
		var delay = function(ev,ob) {
			ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
			ob.hoverIntent_s = 0;
			return cfg.out.apply(ob,[ev]);
		};

		// A private function for handling mouse 'hovering'
		var handleHover = function(e) {
			// copy objects to be passed into t (required for event object to be passed in IE)
			var ev = jQuery.extend({},e);
			var ob = this;

			// cancel hoverIntent timer if it exists
			if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }

			// if e.type == "mouseenter"
			if (e.type == "mouseenter") {
				// set "previous" X and Y position based on initial entry point
				pX = ev.pageX; pY = ev.pageY;
				// update "current" X and Y position based on mousemove
				$(ob).bind("mousemove",track);
				// start polling interval (self-calling timeout) to compare mouse coordinates over time
				if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}

			// else e.type == "mouseleave"
			} else {
				// unbind expensive mousemove event
				$(ob).unbind("mousemove",track);
				// if hoverIntent state is true, then call the mouseOut function after the specified delay
				if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
			}
		};

		// bind the function to the two event listeners
		return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover);
	};
})(jQuery);

/*Uniform v1.5
Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC
http://pixelmatrixdesign.com

Requires jQuery 1.3 or newer

Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this

Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/>
and his noSelect plugin. <http://github.com/mathiasbynens/noSelect-jQuery-Plugin>

Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin

License:
MIT License - http://www.opensource.org/licenses/mit-license.php*/
(function($) {
  $.uniform = {
    options: {
      selectClass:   'uniformSelect',
      radioClass: 'uniformRadio',
      checkboxClass: 'uniformCheckbox',
      fileClass: 'uploader',
      filenameClass: 'filename',
      fileBtnClass: 'action',
      fileDefaultText: 'No file selected',
      fileBtnText: 'Choose File',
      checkedClass: 'checked',
      focusClass: 'focus',
      disabledClass: 'disabled',
      activeClass: 'active',
      hoverClass: 'hover',
      useID: true,
      idPrefix: 'uniform',
      resetSelector: false
    },
    elements: []
  };

  if($.browser.msie && $.browser.version < 7){
    $.support.selectOpacity = false;
  }else{
    $.support.selectOpacity = true;
  }

  $.fn.uniform = function(options) {

    options = $.extend($.uniform.options, options);

    var el = this;
    //code for specifying a reset button
    if(options.resetSelector != false){
      $(options.resetSelector).mouseup(function(){
        function resetThis(){
          $.uniform.update(el);
        }
        setTimeout(resetThis, 10);
      });
    }

    function doSelect(elem){

      var divTag = $('<div />'),
          spanTag = $('<span />');

      divTag.addClass(options.selectClass);
	  /*Added: Inherit the class from the select box, allows different sizes to be easily applied to each item*/
      divTag.addClass(elem.attr("class"));

      if(options.useID){
        divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
      }
      
      var selected = elem.find(":selected:first");
      if(selected.length == 0){
        selected = elem.find("option:first");
      }
      spanTag.html(selected.text());
      
      elem.css('opacity', 0);
      elem.wrap(divTag);
      elem.before(spanTag);

      //redefine variables
      divTag = elem.parent("div");
      spanTag = elem.siblings("span");

      elem.change(function() {
        spanTag.text(elem.find(":selected").text());
        divTag.removeClass(options.activeClass);
      })
      .focus(function() {
        divTag.addClass(options.focusClass);
      })
      .blur(function() {
        divTag.removeClass(options.focusClass);
        divTag.removeClass(options.activeClass);
      })
      .mousedown(function() {
        divTag.addClass(options.activeClass);
      })
      .mouseup(function() {
        divTag.removeClass(options.activeClass);
      })
      .click(function(){
        divTag.removeClass(options.activeClass);
      })
      .hover(function() {
        divTag.addClass(options.hoverClass);
      }, function() {
        divTag.removeClass(options.hoverClass);
      })
      .keyup(function(){
        spanTag.text(elem.find(":selected").text());
      });

      //handle disabled state
      if($(elem).attr("disabled")){
        //box is checked by default, check our box
        divTag.addClass(options.disabledClass);
      }
      $.uniform.noSelect(spanTag);
      
      storeElement(elem);

    }

    function doCheckbox(elem){

      var divTag = $('<div />'),
          spanTag = $('<span />');

      divTag.addClass(options.checkboxClass);
	  /*Added: Inherit the class from the checkbox, allows the replacement to be positioned in the same place*/
      divTag.addClass(elem.attr("class"));

      //assign the id of the element
      if(options.useID){
        divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
      }

      //wrap with the proper elements
      $(elem).wrap(divTag);
      $(elem).wrap(spanTag);

      //redefine variables
      spanTag = elem.parent();
      divTag = spanTag.parent();

      //hide normal input and add focus classes
      $(elem)
      .css("opacity", 0)
      .focus(function(){

        divTag.addClass(options.focusClass);
      })
      .blur(function(){

        divTag.removeClass(options.focusClass);
      })
      .click(function(){

        if(!$(elem).attr("checked")){
          //box was just unchecked, uncheck span
          spanTag.removeClass(options.checkedClass);
        }else{
          //box was just checked, check span.
          spanTag.addClass(options.checkedClass);
        }
      })
      .mousedown(function() {
        divTag.addClass(options.activeClass);
      })
      .mouseup(function() {
        divTag.removeClass(options.activeClass);
      })
      .hover(function() {
        divTag.addClass(options.hoverClass);
      }, function() {
        divTag.removeClass(options.hoverClass);
      });

      //handle defaults
      if($(elem).attr("checked")){
        //box is checked by default, check our box
        spanTag.addClass(options.checkedClass);
      }

      //handle disabled state
      if($(elem).attr("disabled")){
        //box is checked by default, check our box
        divTag.addClass(options.disabledClass);
      }

      storeElement(elem);

    }

    function doRadio(elem){

      var divTag = $('<div />'),
          spanTag = $('<span />');

      divTag.addClass(options.radioClass);
	  /*Added: Inherit the class from the radio button, allows the replacement to be positioned in the same place*/
      divTag.addClass(elem.attr("class"));

      if(options.useID){
        divTag.attr("id", options.idPrefix+"-"+elem.attr("id"));
      }

      //wrap with the proper elements
      $(elem).wrap(divTag);
      $(elem).wrap(spanTag);

      //redefine variables
      spanTag = elem.parent();
      divTag = spanTag.parent();

      //hide normal input and add focus classes
      $(elem)
      .css("opacity", 0)
      .focus(function(){
        divTag.addClass(options.focusClass);
      })
      .blur(function(){
        divTag.removeClass(options.focusClass);
      })
      .click(function(){
        if(!$(elem).attr("checked")){
          //box was just unchecked, uncheck span
          spanTag.removeClass(options.checkedClass);
        }else{
          //box was just checked, check span
          $("."+options.radioClass + " span."+options.checkedClass + ":has([name='" + $(elem).attr('name') + "'])").removeClass(options.checkedClass);
          spanTag.addClass(options.checkedClass);
        }
      })
      .mousedown(function() {
        if(!$(elem).is(":disabled")){
          divTag.addClass(options.activeClass);
        }
      })
      .mouseup(function() {
        divTag.removeClass(options.activeClass);
      })
      .hover(function() {
        divTag.addClass(options.hoverClass);
      }, function() {
        divTag.removeClass(options.hoverClass);
      });

      //handle defaults
      if($(elem).attr("checked")){
        //box is checked by default, check span
        spanTag.addClass(options.checkedClass);
      }
      //handle disabled state
      if($(elem).attr("disabled")){
        //box is checked by default, check our box
        divTag.addClass(options.disabledClass);
      }

      storeElement(elem);

    }

    function doFile(elem){
      //sanitize input
      $el = $(elem);

      var divTag = $('<div />'),
          filenameTag = $('<span>'+options.fileDefaultText+'</span>'),
          btnTag = $('<span>'+options.fileBtnText+'</span>');

      divTag.addClass(options.fileClass);
      filenameTag.addClass(options.filenameClass);
      btnTag.addClass(options.fileBtnClass);

      if(options.useID){
        divTag.attr("id", options.idPrefix+"-"+$el.attr("id"));
      }

      //wrap with the proper elements
      $el.wrap(divTag);
      $el.after(btnTag);
      $el.after(filenameTag);

      //redefine variables
      divTag = $el.closest("div");
      filenameTag = $el.siblings("."+options.filenameClass);
      btnTag = $el.siblings("."+options.fileBtnClass);

      //set the size
      if(!$el.attr("size")){
        var divWidth = divTag.width();
        //$el.css("width", divWidth);
        $el.attr("size", divWidth/10);
      }

      //actions
      $el
      .css("opacity", 0)
      .focus(function(){
        divTag.addClass(options.focusClass);
      })
      .blur(function(){
        divTag.removeClass(options.focusClass);
      })
      .change(function(){
        var filename = $(this).val();
        filename = filename.split(/[\/\\]+/);
        filename = filename[(filename.length-1)];
        filenameTag.text(filename);
      })
      .mousedown(function() {
        if(!$(elem).is(":disabled")){
          divTag.addClass(options.activeClass);
        }
      })
      .mouseup(function() {
        divTag.removeClass(options.activeClass);
      })
      .hover(function() {
        divTag.addClass(options.hoverClass);
      }, function() {
        divTag.removeClass(options.hoverClass);
      });

      //handle defaults
      if($el.attr("disabled")){
        //box is checked by default, check our box
        divTag.addClass(options.disabledClass);
      }
      
      $.uniform.noSelect(filenameTag);
      $.uniform.noSelect(btnTag);
      storeElement(elem);

    }

    function storeElement(elem){
      //store this element in our global array
      elem = $(elem).get();
      if(elem.length > 1){
        $.each(elem, function(i, val){
          $.uniform.elements.push(val);
        });
      }else{
        $.uniform.elements.push(elem);
      }
    }
    
    //noSelect v1.0
    $.uniform.noSelect = function(elem) {
      function f() {
       return false;
      };
      $(elem).each(function() {
       this.onselectstart = this.ondragstart = f; // Webkit & IE
       $(this)
        .mousedown(f) // Webkit & Opera
        .css({ MozUserSelect: 'none' }); // Firefox
      });
     };

    $.uniform.update = function(elem){
      if(elem == undefined){
        elem = $($.uniform.elements);
      }
      //sanitize input
      elem = $(elem);

      elem.each(function(){
        //do to each item in the selector
        //function to reset all classes
        $e = $(this);

        if($e.is("select")){
          //element is a select
          spanTag = $e.siblings("span");
          divTag = $e.parent("div");

          divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);

          //reset current selected text
          spanTag.html($e.find(":selected").text());

          if($e.is(":disabled")){
            divTag.addClass(options.disabledClass);
          }else{
            divTag.removeClass(options.disabledClass);
          }

        }else if($e.is(":checkbox")){
          //element is a checkbox
          spanTag = $e.closest("span");
          divTag = $e.closest("div");

          divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
          spanTag.removeClass(options.checkedClass);

          if($e.is(":checked")){
            spanTag.addClass(options.checkedClass);
          }
          if($e.is(":disabled")){
            divTag.addClass(options.disabledClass);
          }else{
            divTag.removeClass(options.disabledClass);
          }

        }else if($e.is(":radio")){
          //element is a radio
          spanTag = $e.closest("span");
          divTag = $e.closest("div");

          divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);
          spanTag.removeClass(options.checkedClass);

          if($e.is(":checked")){
            spanTag.addClass(options.checkedClass);
          }

          if($e.is(":disabled")){
            divTag.addClass(options.disabledClass);
          }else{
            divTag.removeClass(options.disabledClass);
          }
        }else if($e.is(":file")){
          divTag = $e.parent("div");
          filenameTag = $e.siblings(options.filenameClass);
          btnTag = $e.siblings(options.fileBtnClass);

          divTag.removeClass(options.hoverClass+" "+options.focusClass+" "+options.activeClass);

          filenameTag.text($e.val());

          if($e.is(":disabled")){
            divTag.addClass(options.disabledClass);
          }else{
            divTag.removeClass(options.disabledClass);
          }
        }
      });
    }

    return this.each(function() {
      if($.support.selectOpacity){
        var elem = $(this);

        if(elem.is("select")){
          //element is a select
          if(elem.attr("multiple") != true){
            //element is not a multi-select
            doSelect(elem);
          }
        }else if(elem.is(":checkbox")){
          //element is a checkbox
          doCheckbox(elem);
        }else if(elem.is(":radio")){
          //element is a radio
          doRadio(elem);
        }else if(elem.is(":file")){
          //element is a file upload
          doFile(elem);
        }

      }
    });
  };
})(jQuery);

/********************************************************************************************************/
/*************************************************Popups*************************************************/
/********************************************************************************************************/
//To make sure that the plugin doesn't collide with other libraries that might use the dollar sign, it's best practice to pass jQuery to a self executing function ((function($){})(jQuery);) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution 
(function($) {
	//Set the default options for the plugin, this can be overriden when calling the object (i.e. $(".popupLink").popup({"popupContainerID" : "#anotherContainer"});
	$.popup = {
		options: {
			popupContainerID: "#popupContainer",
			overlayID: "#popupOverlay",
			closeElements: "#popupOverlay, .popupCloseButton",
			includeURL: "includes/popups.asp"
		}
	};
	
	//Add a new function to the jQuery.fn object
	$.fn.popup = function(options) {
		//Using extend allows for the default options to be overridden by any arguments
		options = $.extend($.popup.options, options);

		//When the elements which involked the jQuery object is clicked on
		this.click(function() {
			//Call the popup include page to get the selected popup and display it
			$.ajax({ type: "POST", data: "popupID=" + $(this).attr("name"), url: options.includeURL, cache: false, success: function(popupContent){
				//Add the popup to the page
				$("body").append(popupContent);
				//The width and height of the popup
				var popupWidth = $(options.popupContainerID).width(), popupHeight = $(options.popupContainerID).height();
				//The horizontal and vertical position of the popup, set to be in the center of the screen
				var popupHorizontalPosition = ($(window).width() - popupWidth) / 2+$(window).scrollLeft(), popupVerticalPosition = ($(window).height() - popupHeight) / 2+$(window).scrollTop();
				//Position the popup in the middle of the screen and fade it in
				$(options.popupContainerID).css({top: popupVerticalPosition, left: popupHorizontalPosition, filter: "alpha(opacity = 0)", opacity: "0"}).fadeTo("slow", 1);
				//Set the default opacity to 0 for IE (filter) and other browsers (opacity), as well as the height of the overlay. Fade in the overlay to half opacity
				$(options.overlayID).css({filter: "alpha(opacity = 0)", opacity: "0", height: $(document).height()}).fadeTo("slow", 0.5);
			}}); 
			//Return false to stop the link from following the destination URL
			return false;
		}); 

		//When the popup close button is clicked
		$(options.closeElements).live("click",function(){
			//Fade out the overlay and popup then remove them
			$(options.overlayID + "," + options.popupContainerID).fadeOut("slow").remove();
			//Return false to stop the link from following the destination URL
			return false;
		});
		
		//Return this to maintain chainability (i.e. $(".popupLink").popup().css('color', 'red');)
		return this;
 	};
})(jQuery);
	
/********************************************************************************************************/
/************************************************Tooltips************************************************/
/********************************************************************************************************/
//To make sure that the plugin doesn't collide with other libraries that might use the dollar sign, it's best practice to pass jQuery to a self executing function ((function($){})(jQuery);) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution 
(function($) {
	//Set the default options for the plugin, this can be overriden when calling the object (i.e. $(".tooltipLink").tooltip({"tooltipContainerID" : "#anotherContainer"});
	$.tooltip = {
		options: {
			tooltipContainerID: "#tooltipContainer",
			includeURL: "includes/tooltips.asp"
		}
	};
	
	var displayTimeout = 0;
	
	//Add a new function to the jQuery.fn object
	$.fn.tooltip = function(options) {
		//Using extend allows for the default options to be overridden by any arguments
		options = $.extend($.tooltip.options, options);

		//When the mouse cursor enters and leaves the tooltip element
		this.live("mouseenter", function(event) {	
			//The horizontal and vertical position of the tooltip, set to be at the bottom left of the tooltip element
			var tooltipHorizontalPosition = $(this).offset().left, tooltipVerticalPosition = $(this).offset().top + $(this).outerHeight();
			//The complete width and height (including padding, margin and borders) of the element invoking the tooltip
			var tooltipElementWidth = $(this).outerWidth(), tooltipElementHeight = $(this).outerHeight();
			//Save a reference to 'this' so we can use it in timeout function
			var tooltipLink = this;
			
			//If displayTimeout does not equal 0
			if(displayTimeout != 0) {
				//Clears the timeout set by setTimeout
				clearTimeout(displayTimeout);
			}
			
			//Call the setTimeout function to make the actions occur after the specified delay (in this case 400ms)
			displayTimeout = setTimeout(function() {
				//Reset the timeout variable
				displayTimeout = 0;
				//Call the tooltip include page to get the selected tooltip and display it
				$.ajax({ type: "POST", data: "tooltipID=" + $(tooltipLink).attr("name"), url: options.includeURL, cache: false, success: function(tooltipContent){
					//Add the tooltip to the page
					$("body").append(tooltipContent);
					//If the right edge of the tooltip is off the screen
					if ((tooltipHorizontalPosition + $(options.tooltipContainerID).outerWidth()) > $(window).width()) {
						//Amend the position to be at the right of the element invoking the tooltip
						tooltipHorizontalPosition = tooltipHorizontalPosition - $(options.tooltipContainerID).outerWidth() + tooltipElementWidth;
					}
					//If the bottom edge of the tooltip is off the screen
					if ((tooltipVerticalPosition + $(options.tooltipContainerID).outerHeight()) > $(window).height()) {
						//Amend the position to be at the top of the element invoking the tooltip
						tooltipVerticalPosition = tooltipVerticalPosition - $(options.tooltipContainerID).outerHeight() - tooltipElementHeight;
					}
					//Position the tooltip in the middle of the screen and fade it in
					$(options.tooltipContainerID).css({top: tooltipVerticalPosition, left: tooltipHorizontalPosition, filter: "alpha(opacity = 0)", opacity: "0"}).fadeTo("slow", 1);
				}}); 
			}, 200);
		}).live("mouseleave", function(event) {
			//If displayTimeout does not equal 0
			if(displayTimeout != 0) {
				//Clears the timeout set by setTimeout
				clearTimeout(displayTimeout);
			}
			//When the basket container is not hovered, hide the basket popup
			$(options.tooltipContainerID).fadeOut("slow").remove();
		});
		
		//Return this to maintain chainability (i.e. $(".tooltipLink").tooltip().css('color', 'red');)
		return this;
 	};

/********************************************************************************************************/
/***********************************Enforce textarea character limit*************************************/
/********************************************************************************************************/

//For each text area with a 'maxlength' attribute
$.each(jQuery('textarea[maxlength]'), function(key, value){
	var textarea = jQuery(this); //Store the reference to the current text area object
	var textareaMaxlength = parseInt(textarea.attr('maxlength'), 10); //Get the text area's maximum length

	textarea.val(textarea.val().substr(0, textareaMaxlength)); //Strip any characters over the maximum length

	//Bind keydown event handler
	jQuery(textarea).keydown(function(){
		//If the current length is greater than the maximum length
		if(textarea.val().length > textareaMaxlength){
			textarea.val(textarea.val().substr(0, textareaMaxlength)); //Strip any characters over the maximum length
			return false;
		}
	});
});

})(jQuery);

/********************************************************************************************************/
/***************************************Linked hidden area toggle****************************************/
/********************************************************************************************************/
//To make sure that the plugin doesn't collide with other libraries that might use the dollar sign, it's best practice to pass jQuery to a self executing function ((function($){})(jQuery);) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution 
(function($) {
	//Set the default options for the plugin, this can be overriden when calling the object (i.e. $(".popupLink").popup({"popupContainerID" : "#anotherContainer"});
	$.linkedArea = {
		options: {
			linkIdentifier: "hiddenAreaLink",
			linkSelectedClass: "active",
			hiddenAreaClass: "hiddenArea"
		}
	};
	//Add a new function to the jQuery.fn object
	$.fn.linkedArea = function(options) {
		//Using extend allows for the default options to be overridden by any arguments
		options = $.extend($.linkedArea.options, options);
		var hiddenAreaClass = options.hiddenAreaClass;
		var linkIdentifier = options.linkIdentifier;
		var linkSelectedClass = options.linkSelectedClass;
		
		//Hide all of the hidden areas
		$("." + hiddenAreaClass).hide();
		//Show the first hidden area
		$("." + hiddenAreaClass + ":first").show();

		//When the hidden area link is clicked
		this.live("click",function(){
			//Remove the current class from all the links
			$(linkIdentifier).removeClass(linkSelectedClass);
			//Add the current class to the link clicked
			$(this).addClass(linkSelectedClass)
			//Hide all of the hidden areas
			$("." + hiddenAreaClass).hide();
			//Show the area associated with the link clicked, the name of the link is the same as the ID of the hidden area
			$("#" + $(this).attr("id") + "Container").show();
			//Return false to stop the link from following the destination URL
			return false;
		});
		//Return this to maintain chainability
		return this;
 	};
})(jQuery);
	
$(document).ready(function(){
	//Apply the plugins to the specified elements
	$("select, input[type=checkbox], input[type=radio]").uniform().show();
	$(".uniformSelect").hide().fadeIn();
	$(".popupLink").popup();
	$("#productTabList a").linkedArea({"hiddenAreaClass" : "productDetailsContainer", "linkIdentifier" : "#productTabList a"});
	$("#paymentOptionsList a").linkedArea({"hiddenAreaClass" : "paymentOptionsContainer", "linkIdentifier" : "#paymentOptionsList a"});
});
