
/* 
 * salmon.js
 */
if (typeof salmon != "object") { var salmon = {}; }

/*************************************************************************
* Extensions
*************************************************************************/

Array.prototype.exists = function (x) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == x) return true;
    }
    return false;
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

getElementsByClassName = function(node, classname){
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for(var i=0,j=els.length; i<j; i++)
        if(re.test(els[i].className))a.push(els[i]);
    return a;
}

/*************************************************************************
* CMS
*************************************************************************/

salmon.cms = {
	init:function(){
		// if you need to kick things off, stick it here.
	},
	newId:0,
	placeholderIds:[],
	getNewId:function(){// increments and returns an ID
		do {
			++this.newId;
	    } while (this.placeholderIds.exists(this.newId));
	    this.placeholderIds.push(this.newId);
	    return this.newId;
	}
};

/*************************************************************************
* Common
*************************************************************************/

salmon.common = {
	init:function(){},
	showConsoleLog : true, // default set to false, need to set to true in when needed
	logIt:function(logWhat){
		if(this.showConsoleLog){
			if(jQuery.browser.mozilla){
				console.log(logWhat);
			} else {
				if(document.getElementById("logIt") == null){
					$("body").append("<div id=\"logIt\" title=\"console.log\"><div>"+logWhat+"<br/></div></div>");
					var doDialog = false;
					if(typeof $.ui == "object"){
						if(typeof $.ui.dialog == "function"){
							doDialog = true;
						}
					}
					if(doDialog) { 
						$("#logIt").dialog();
						$(".ui-dialog").css({
							top:"250px",
							left:"700px",
							height:"340px"
						});
						$("#logIt h1").css({
							backgroundColor:"#666",
							color:"#eee",
							padding:"2px 3px",
							fontSize:"14px"
						});
					} else {
						$("#logIt").css({
							width:"240px",
							height:"600px",
							position:"absolute",
							border:"inset 3px #666",
							backgroundColor:"#eee",
							right:"25px",
							top:"25px",
							textAlign:"left",
							overflow:"auto",
							zIndex:"32000"
							
						});
					}
					$("#logIt").css({
						height:"311px",
						margin:"0",
						overflowY:"auto"
					});
					$("#logIt div").css({
						padding:"0 10px"
					});
				} else {
					$("#logIt div").append(logWhat+"<br/>");
					var objDiv = document.getElementById("logIt");
					objDiv.scrollTop = objDiv.scrollHeight;				
				}
			}
		}
	}, 
	// shows a message in the corner of the screen that will display for
	// for 1 second if no display time is set
	// needs an empty span in the page with an id of "ajaxStatus"
	doMsg:function(msg, displayTime, displayBgColor, displayFgColor){
		// checks for a time parsed through and if none sets it to one second.
		// if there is no span for the message, create one.
		displayBgColor = (displayBgColor) ? displayBgColor : "ffff00";
		displayFgColor = (displayFgColor) ? displayFgColor : "000000";
		if((document.getElementById("ajaxStatus") == null)){
			// logIt("no span, making one.");
			$("body").append("<span id=\"ajaxStatus\"></span>");
		}
		$("#ajaxStatus").css({
			backgroundColor:"#"+displayBgColor,
			color:"#"+displayFgColor
		});
		if(displayTime !=0){
			displayTime = (displayTime>0) ? displayTime : 1000;
		}
		$("#ajaxStatus").empty().fadeIn(100, function(){
			$("#ajaxStatus").append(msg);
			if(displayTime != 0){
				$("#ajaxStatus").fadeOut(displayTime);
			}
		});
	},
	blocker:function(doWhat){// TODO: AO - this is a bit rubbish and i will rewrite it.
		if(doWhat == "show"){
			$("body").append("<div id=\"blocker\"></div>");
			$("#blocker").css({
				 position:"absolute",
				 top:0,
				 left:0,
				 backgroundColor:"#000",
				 width:"100%",
				 height:"100%",
				 opacity:0.66,
				 zIndex:32000
			});
		} else if (doWhat == "hide") {
			$("#blocker").remove();
		} else if (doWhat == "adjust") {
		}
	},
	getHTMLFirstChild: function(html) {
        var root = document.createElement("div");
        root.innerHTML = html;
        return root.firstChild;
	}
}

/*************************************************************************
* Forms
*************************************************************************/

salmon.forms = {
	prePopulate: function(){
		$("input,textarea").each(function(){
			if($(this).attr("title") !== undefined){
				$(this).attr({
					value:$(this).attr("title")
				});
				$(this).focus(function(){
					if($(this).attr("title") == $(this).val()){
						$(this).val("");
					}
				});
				$(this).blur(function(){
					if($(this).val() == ""){
						$(this).val($(this).attr("title"));
					}
				});
			}
		});
	}
};

/*************************************************************************
* More or less
*************************************************************************/

salmon.moreOrLess = {
	fullClassList:"",
	splitClasses:{},
	moreText:"more...",
	lessText:"less...",
	init: function(){
		$(".moreOrLess").each(function(){
			this.fullClassList = $(this).attr("class");
			this.splitClasses = this.fullClassList.split(" ");
			for(var i = 0; i<this.splitClasses.length; i++){	
				if(this.splitClasses[i].indexOf("limit") >= 0){
					var itemLimit =  this.splitClasses[i].split("limit")[1];
				}
			}
			salmon.moreOrLess.hideItems(this,itemLimit);
		});
	},
	hideItems:function(what,itemLimit){
		if($(what).find("li").length <= itemLimit) {
			return;
		}	
		var counter = 0;
		$(what).find("li").each(function(){
			if(counter>= itemLimit){
				$(this).hide();
			}
			counter++;
		});
		$(what).find(".hideThem").remove();
		$(what).append("<li class=\"showThem\"><a href=\"#\">"+this.moreText+"</a></li>");
		$(what).find(".showThem").click(function (){
			salmon.moreOrLess.showItems($(this).parent(),itemLimit); 
			return false;
		});
	},
	showItems:function(what,itemLimit){
		if($(what).find("li").length <= itemLimit) {
			return;
		}	
		$(what).find("li").each(function(){
			$(this).show();
		});
		$(what).find(".showThem").remove();
		$(what).append("<li class=\"hideThem\"><a href=\"#\">"+this.lessText+"</a></li>");
		$(what).find(".hideThem").click(function (){
			salmon.moreOrLess.hideItems($(this).parent(),itemLimit);
			return false;
		});
	}
};

/*************************************************************************
* Name space
*************************************************************************/

if (typeof salmon.namespace != "object") {
	salmon.namespace = {
		addNamespace: function(namespace) {
			var parts = namespace.split(".");
			var root = window;
			for(var i=0;i<parts.length;i++) {
				if(typeof root[parts[i]] != "object") {
					root[parts[i]] = {};
				}
				root = root[parts[i]];
			}
		}
	}
}
/*************************************************************************
* QueryString
*************************************************************************/

salmon.QueryString = new ( function() {
	var queryString = null;
	this.get = function(key) {
		if (key == null || key === "") return null;
		if (queryString == null) {
			queryString = {};
			var qs = location.search.slice(1).split("&"), qsElements;
			for (var i = 0, j = qs.length; i<j; i++) {
				qsElements = qs[i].split("=");
				if (queryString[qsElements[0]]) {
					if (queryString[qsElements[0]] instanceof Array) {
						queryString[qsElements[0]].push(qsElements[1] || "")
					} else {
						queryString[qsElements[0]] = [queryString[qsElements[0]], qsElements[1]];
					}
				} else {
					queryString[qsElements[0]] = qsElements[1] || "";
				}
			}
		}
		return queryString[key];
	};
} )();

/*************************************************************************
* salmon popup window
*************************************************************************/


salmon.popupwindow = {
	init:function(){
			$(".popup").each(function(){
				$(this).click(function(){
					var myHref = this.href;
					var myHeight = 500;
					var myWidth = 500;
					var myTop = 20;
					var myLeft = 20;
					var myToolbar = "no";
					var myLocation = "no";
					var myScrollbars = "no";
					var myVars = myHref.substring(myHref.indexOf("?")+1,myHref.length).split("&");
					for(var i = 0; i < myVars.length; i++) {
				        var pos = myVars[i].indexOf('=');
				        if (pos == -1) continue;
				        if(myVars[i].substring(0,pos) == "width"){
					        myWidth = myVars[i].substring(pos+1);
				        } else if(myVars[i].substring(0,pos) == "height"){
					        myHeight = myVars[i].substring(pos+1);
				        } else if(myVars[i].substring(0,pos) == "top"){
					        myTop = myVars[i].substring(pos+1);
				        } else if(myVars[i].substring(0,pos) == "left"){
					        myLeft = myVars[i].substring(pos+1);
				        } else if(myVars[i].substring(0,pos) == "toolbar"){
					        myToolbar = myVars[i].substring(pos+1);
				        } else if(myVars[i].substring(0,pos) == "location"){
					        myLocation = myVars[i].substring(pos+1);
				        } else if(myVars[i].substring(0,pos) == "scrollbars"){
					        myScrollbars = myVars[i].substring(pos+1);
				        }
				    }
					tools = "resizable,toolbar="+myToolbar+",location="+myLocation+",scrollbars="+myScrollbars+",width="+myWidth+",height="+myHeight+",left="+myLeft+",top="+myTop;
					newWindow = window.open(myHref, 'newPopup', tools);
					newWindow.focus();
					return false;
				});
			});
	}
}




/* 
 * boots.common.js
 */
salmon.namespace.addNamespace("boots.common");

if(typeof boots.common.siteConfig != "object"){
	boots.common.siteConfig = {
		imageDirectoryURL: ""
	}
}

boots.common.cookie = {
	Collection: null,
	init: function() {
		this.Collection = {};
		var cookies = document.cookie.split(";");
		var cookie;
		for( var i = cookies.length-1; i >= 0 ;i--) {
			cookie = cookies[i].split("=");
			var cookieName = cookie[0].replace(/ /g,"");
			if (cookie.length >= 2) {
				this.Collection[cookieName] = cookie[1];
			}
		}
		this.init = function(){	};
	},
	setCookie: function(name,value,days) {
		this.init();
		var expires = "";
		if (days) {
			var date = new Date();
			date.setDate(date.getDate() + days);
			expires = "expires=" + date.toGMTString();
		}
		var cookie = name + "=" + value + ";" + expires + ";path=/";
		document.cookie = cookie;
		this.Collection[name] = value;
	},
	getCookie: function(name) {
		this.init();
		return this.Collection[name];
	},
	removeCookie: function(name) {
		this.init();
		this.setCookie(name,"",-1);
		delete this.Collection[name];
	}
}


boots.common.print = {
	/*
		@param object literal with the following properties
			1. href
			2. className
			3. image
			4. alt
		@return printButton as DOM Node
	*/
	createPrintButton: function() {
		var buttonDetails = {
			href: "#print",
			className: "printButton",
			image: "btn_print.gif",
			alt: "Print this page"
		};
		
		/* allow the passing in of an object literal */
		if (typeof arguments[0] == "object") {
			buttonDetails.href = arguments[0].href || buttonDetails.href;
			buttonDetails.className = arguments[0].className || buttonDetails.className;
			buttonDetails.image = arguments[0].image || buttonDetails.image;
			buttonDetails.alt = arguments[0].alt || buttonDetails.alt;
		}
	
		var activator = document.createElement("a");
		activator.href = buttonDetails.href;
		activator.className = buttonDetails.className;
		$(activator).bind("click", boots.common.print.activate);	
		var img = document.createElement("img");
		img.src = boots.common.siteConfig.imageDirectoryURL + buttonDetails.image;
		img.alt = buttonDetails.alt;
		activator.appendChild(img);
		return activator;
	},
	activate: function() {
		window.print();
		return false;
	}	
}

$(document).ready(function(){
	// error if no methods listed, so if no methods, don't show the doc.ready
	salmon.popupwindow.init();
	
	//remove as nick request
	//$("a[href='#']").click(function(){
		//alert("DEV: this link not done.");
		//return false;
	//});
	
});

/* 
 * boots.forms.validation.js
 */
salmon.namespace.addNamespace("boots.forms");
boots.forms.validation = {
	FORM_ELEMENTS: {
		PASSWORD: "password"
	},
	formsSelector: "form.validate",
	validateAllClass: "validateAll",
	errorContainerID: "formErrorContainer",
	lastFiredButton: null,
	formsCollection: [],
	messages: {},
	
	/*
	 * Create instances of forms to be validated
	 */
	init: function(formID){
		boots.forms.validation.prepareServersideErrors();
		if(formID != null) {
			var form = document.getElementById(formID);
			if(form == null) {
				return;
			}
			
			// before instantiating, delete instance and remove from array
			var formsCollection = boots.forms.validation.formsCollection;
			for (var i=0;i<formsCollection.length;i++) {
				if(formsCollection[i].validationform == form) {
					delete formsCollection[i];
					formsCollection.remove(i);
					break;
				}
			}
		
			var form = new boots.forms.validation.Form(form);
			boots.forms.validation.formsCollection.push(form);
		}
		else {
			var forms = $(this.formsSelector);
			for( var i=0; i<forms.length; i++ ) {
				var form = new boots.forms.validation.Form(forms[i]);
				boots.forms.validation.formsCollection.push(form);
			}
		}
	},
	prepareServersideErrors: function(){
		var errorContainer = document.getElementById(boots.forms.validation.errorContainerID);
		if(errorContainer == null) {
			return;	
		}
		var errors = $("a.error",errorContainer);
		for(var i=0; i<errors.length;i++) {
			errors[i].onclick = boots.forms.validation.error_onClick;
		}
	},
	error_onClick:function() {
		var field = document.getElementById(this.hash.slice(1));
		if(field === null) {
			return;
		}
		var tag = field.tagName.toUpperCase();
		if (tag == "INPUT" || tag == "TEXTAREA" || tag == "SELECT") {
			field.focus();
			return false;
		}
		return true;
	}	
}


/*
 * Validation form Class:
 * @param form as DOM reference
 * @return "this" as Object Reference
 */
salmon.namespace.addNamespace("boots.forms.validation");
boots.forms.validation.Form = function(form) {
	var me = this;
	this.validationform = form;
	this.validators = [];
	this.errorContainer = document.getElementById(boots.forms.validation.errorContainerID);
	
	/*
	 * Constructor function
	 */
	var Form = (function() {
		prepareFormElements();
		addValidators();
		prepareSubmitButtons();
		me.validationform.onsubmit = form_onSubmit;
	})();
	
	
	/*
	 * Setup events for handling field highlighting
	 */
	function prepareFormElements() {
		var fields = me.validationform.elements;
		for( var i=0; i<fields.length; i++ ) {
			var field = fields[i];
			var tagName = field.tagName.toUpperCase();
			
			var isInput = 
				tagName == "INPUT" && ( field.type == "text" || field.type == "checkbox" || field.type == "radio" || field.type == "password" ) ||
				/*tagName == "SELECT" || commented out as IE returns false based on addClass JQuery Function*/
				tagName == "TEXTAREA";
				
				
			if ( isInput ) {
				field.onfocus = field_onFocus;
				field.onblur = field_onBlur;
			}
		}
	}

	/*
	 * When field receives focus
	 */
	function field_onFocus() {
		$(this).addClass("highlight");
	}
	
	/*
	 * When field loses focus 
	 */
	function field_onBlur() {
		$(this).removeClass("highlight");
	}	
	
	/*
	 * This will find all fields in the form that require validation
	 * and add an instance of the validator class to the validators collection
	 */
	function addValidators() {
		if (!boots.forms.validation.routines) {
			return;
		}
		
		var fields = me.validationform.elements;
		for( var i=0; i<fields.length; i++ ) {
			
			var field = fields[i];
			if(field.tagName.toUpperCase() == "FIELDSET") {
				continue;
			}
			
			var fieldID = fields[i].id || null;
			var fieldLabel = $(fields[i]).parents("div.field").children("div").children("label")[0] || $(fields[i]).next("label")[0] || $(fields[i]).prev("label")[0] ||  null;

			if (field.type.toUpperCase() == "RADIO") {
				fieldLabel = $(fields[i]).parents("div.field").children("div").children("span.label")[0];
			}

			addValidatorsByClassNames(field, fieldID, fieldLabel);
			addValidatorsByCustomRoutines(field, fieldID, fieldLabel);
		}
	}		
	
	/*
	 * @param field as DOM reference
	 * @param fieldID as string
	 * @param fieldLabel as DOM reference
	 */
	function addValidatorsByClassNames(field, fieldID, fieldLabel) {
		var field = field;
		var type = "";
		var method = null;
		var message = "";
		var routine = null;
		var classNames = field.className.split(" ");
		for( var j=0; j < classNames.length; j++ ) {
			type = classNames[j];
			var routine = getValidatorRoutine(boots.forms.validation.routines[type]);
			if (!routine) continue;
			method = getValidatorMethod(routine);
			
			message = getValidatorMessage(fieldID, fieldLabel, routine, type);

			if (!validatorExists(field, type)) {
				var validator = new boots.forms.validation.Validator(field, method, message, type);
				me.validators.push(validator);
			}
		}			
	}
	
	/*
	 * @param field as DOM reference
	 * @param fieldID as string
	 * @param fieldLabel as DOM reference
	 * @return nothing is returned
	 */	
	function addValidatorsByCustomRoutines(field, fieldID, fieldLabel) {
		var field = field;
		var type = "";
		var method = null;
		var message = "";
		var routine = null;
		for (var customRules in boots.forms.validation.customroutines[fieldID]) {
			type = customRules;
			routine = getValidatorRoutine(boots.forms.validation.customroutines[fieldID][type]);
			if (!routine) continue;
			method = getValidatorMethod(routine);
			message = getValidatorMessage(fieldID, fieldLabel, routine, type);
			
			if (!validatorExists(field, type)) {
				var validator = new boots.forms.validation.Validator(field, method, message, type);
				me.validators.push(validator);
			}
		}			
	}		
	
	/*
	 * @param validationRoutine as object reference
	 * @return validatorRoutine as object, otherwise null
	 */
	function getValidatorRoutine(validatorRoutine) {
		var routine = validatorRoutine || null;
		if (routine && typeof routine.method == "function" && typeof routine.message == "string") {
			return routine;
		}
		else {
			return null;
		}
	}		

	/*
	 * @param validationRoutine as object reference
	 * @return reference to function otherwise null
	 */
	function getValidatorMethod(validatorRoutine) {
		return validatorRoutine.method || null;
	}

	/*
	 * @param fieldID
	 * @param fieldLabel
	 * @param validatorRoutine
	 * @param validatorType
	 * @return message
	 */
	function getValidatorMessage(fieldID, fieldLabel, validatorRoutine, validatorType) {
		var message = "No message available";
		var customMessage = boots.forms.validation.messages[fieldID] || null;
		if(fieldLabel==null) {
			labelMessage = "Label";
		}
		else {
			labelMessage = $(fieldLabel).text();
		}
		var defaultMessage = validatorRoutine.message;
		
		if(customMessage && typeof customMessage[validatorType] == "string") {
			message = customMessage[validatorType];
		}
		else if(labelMessage != null && defaultMessage) {
			message = labelMessage + ": " + defaultMessage;
		}
		else if(defaultMessage) {
			message = defaultMessage;
		}
				
		return message;				
	}

	/*
	 * @param validatorField as DOM reference
	 * @param validatorType as string
	 * @return true if instance exists, otherwise false
	 */
	function validatorExists(validatorField, validatorType) {
		var exists = false;
		for(var validators in me.validators) {
			if(me.validators[validators].field == validatorField && me.validators[validators].type == validatorType) {
				exists = true;
				break;
			}
		}
		return exists;
	}
	
	/*
	 * Nasty patch to capture the last button to be clicked
	 */
	function prepareSubmitButtons() {
		var submits = $("input[type='submit'], input[type='image'], input[type='button'], button[type='submit']", me.form);
		for( var i=0; i<submits.length; i++ ) {
			submits[i].onclick = function() {
				boots.forms.validation.lastFiredButton = this;
			}
		}
	}
	
	/*
	 * @return true if form is valid, false otherwise
	 */
	function form_onSubmit(){
		clearErrors();
		clearSuccessMessage();
		var valid = true;
		
		// Validate all fields
		if ($(boots.forms.validation.lastFiredButton).hasClass(boots.forms.validation.validateAllClass)) {			
			valid = validateFields(me.validators);
		}
		
		// Validate contextual fields
		for(var buttons in boots.forms.validation.contextualbuttons) {
			var button = document.getElementById(buttons);
			if(boots.forms.validation.lastFiredButton == button ) {
				var contextualCollection = [];
				for(var names in me.validators) {
					var validator = me.validators[names]; //object
					var fieldID = validator["fieldID"]; //string
					
					var requiredFields = boots.forms.validation.contextualbuttons[buttons];
					for(var i = 0; i < requiredFields.length; i++) {
						// if there is a validator for the required field then add to collection
						if(requiredFields[i] == fieldID) {
							contextualCollection.push(validator);
						}
					}
				}
				valid = validateFields(contextualCollection);
			}
		}
		return valid;
	}
	
	/*
	 * Clear existing errors
	 */
	function clearErrors() {
		clearErrorContainer();
		clearFieldErrors();
	}
	
	/*
	 * If the success message is showing and the user submits the form, 
	 * then clear success message.
	 */
	function clearSuccessMessage() {
		var successMessage = document.getElementById("formSuccessContainer");
		if(successMessage == null) {
			return;
		}
		$(successMessage).remove();		
	}
	
	function clearErrorContainer() {
		var errorListContainer = me.errorContainer;
		if (errorListContainer == null) {
			return;
		}
		$(errorListContainer).addClass("hide");
		
		if(errorListContainer.getElementsByTagName("div")[0].getElementsByTagName("ul").length > 0) {
			var errorList = errorListContainer.getElementsByTagName("div")[0].getElementsByTagName("ul")[0];
			errorList.innerHTML = "";
		}
	}
	
	function clearFieldErrors() {
		var formsCollection = boots.forms.validation.formsCollection;
		for(var i=0; i<formsCollection.length;i++) {
			var validators = formsCollection[i].validators;
			for (var property in validators) {
				$(validators[property].fieldIndicator).removeClass("error");
			}
		}	
	}
	
	/*
	 * @param collection in array format
	 * @return true if no errors, false otherwise
	 */
	function validateFields(collection) {
		var errorCollection = [];
		for(var i=0; i<collection.length; i++) {
			if(!collection[i].validate()) {
				errorCollection.push(collection[i]);
			}
		}
		if (errorCollection.length > 0) {
			showErrors(errorCollection);
		}	
		return (errorCollection.length == 0)
	}
	
	function getHTMLFirstChild(html) {
        var root = document.createElement("div");
        root.innerHTML = html;
        return root.firstChild;
	}
	
	/*
	 * @param errorCollection in array format
	 */
	function showErrors(errorCollection) {
		var errorListContainer = me.errorContainer;
		if (errorListContainer == null) {
			alert("The form has errors.");
			return;
		} else {
			$(document).scrollTop(150);
		}
		
		if(errorListContainer.getElementsByTagName("div")[0].getElementsByTagName("ul").length == 0) {
			$("div.messageerrorInner div.container", errorListContainer).append("<ul></ul>");
		}
		
		var errorList = errorListContainer.getElementsByTagName("div")[0].getElementsByTagName("ul")[0];
		for(var i=0;i<errorCollection.length;i++) {
			var li = salmon.common.getHTMLFirstChild(createErrorItem(errorCollection[i].fieldID, errorCollection[i].message));
			var a = li.getElementsByTagName("a")[0];
			a.className="error";
			a.onclick = boots.forms.validation.error_onClick;
			errorList.appendChild(li);
			$(errorCollection[i].fieldIndicator).addClass("error");		
		}
		$(errorListContainer).removeClass("hide");
		$("a#errors").focus();
	}
	
	/*
	 * @param fieldID
	 * @param message
	 * @returns HTML snippet
	 */
	function createErrorItem(fieldID, message) {
		var listItem = '';
		listItem += '<li>';
		listItem +=		'<a href="#'+ fieldID + '">' + message + '</a>';
		listItem += '</li>';
		return listItem;
	}	
}


/*
 * Validator Class:
 * @param field as DOM reference
 * @param routine as reference to function
 * @param message as string
 * @param type as string
 * @return "this" as Object Reference
 */

boots.forms.validation.Validator = function(field, routine, message, type) {
	var me = this;
	this.field = field;
	this.fieldID = field.id;
	this.type = type;
	this.routine = routine;
	this.message = message;
	this.isValid = false;
	this.label = getLabel();
	this.fieldIndicator = getFieldIndicator();
	this.fieldContainer = getFieldContainer();
	
	/*
	 * @return DOM reference to label
	 */	
	function getLabel() {
		return $(me.field).parents("div.field").children("div").children("label")[0] || $(me.field).next("label")[0] || $(me.field).prev("label")[0] ||  null;
	}
	
	/*
	 * @return DOM reference to indicator
	 */		
	function getFieldIndicator() {
		return $(me.field).parents("div.field").children("div").children("span.label")[0] || $(me.field).parents("div.field").children("div").children("label")[0] || null;
	}
	
	/*
	 * @return DOM reference to field container
	 */	
	function getFieldContainer() {
		return $(me.field).parents("div.field")[0] || null;
	}	
}

boots.forms.validation.Validator.prototype = {
	/*
	 * @return true if valid, otherwise false
	 */
	validate: function() {
		this.isValid = this.routine.call(this);
		return this.isValid;
	}
}

$(document).ready(function(){ boots.forms.validation.init(); });

salmon.namespace.addNamespace("boots.forms.validation.routines");
boots.forms.validation.routines = {
	eVoucherDateRequired: {
		method: function() {
			var result = false;
			var field = this.field;
			var value = $.trim(field.value);
			
			var specificDate = document.getElementById("sendOption1");
			if(specificDate == null) {
				return true;
			}
			
			if(specificDate.checked) {
				result = (value.length > 0);
			}
			else {
				result = true;
			}

			return result;
		},
		message: "The date is required for eVoucher."
	},
	addressRequiredBFPO: {
		method: function() {
			var result = false;
			var field = this.field;
			var value = $.trim(field.value);
			var tagName = field.tagName.toUpperCase();
			
			var prefix="";
			var indexI = field.name.indexOf("_");
			if (indexI!=-1) {
				prefix = field.name.substring(0, indexI+1);
			}

			var postcode = document.getElementById(prefix+"zipCode");
			var regex = new RegExp("^(B|b)(F|f)(P|p)(O|o)[ ]?[0-9]{1,3}$");
			if (postcode && regex.test(postcode.value)) {
				return true;
			}

			switch(tagName) {
				case "INPUT":
					switch (field.type) {
						case "text":
							// trimmed version
							result = value.length > 0;
							break;
						case "password":
							// non trimmed version
							result = field.value.length > 0;
							break;							
						case "checkbox":
							result = field.checked;
							break;
						case "radio":
							var radios = $($(this.field).parent().parent()[0]).find("input");
							for(var i=0;i<radios.length;i++) {
								if(radios[i].checked) {
									result = true;
									break;
								}
							}
							break;							
					}
					break;
				case "SELECT":
					result = value.length > 0;
					break;
				case "TEXTAREA":
					result = value.length > 0;
					break;
				default:
					result = true;
			}
			return result;
		},
		message: "This field is required."
	},
	required: {
		method: function() {
			var result = false;
			var field = this.field;
			var value = $.trim(field.value);
			var tagName = field.tagName.toUpperCase();
			switch(tagName) {
				case "INPUT":
					switch (field.type) {
						case "text":
							// trimmed version
							result = value.length > 0;
							break;
						case "password":
							// non trimmed version
							result = field.value.length > 0;
							break;							
						case "checkbox":
							result = field.checked;
							break;
						case "radio":
							var radios = $($(this.field).parent().parent()[0]).find("input");
							for(var i=0;i<radios.length;i++) {
								if(radios[i].checked) {
									result = true;
									break;
								}
							}
							break;							
					}
					break;
				case "SELECT":
					result = value.length > 0;
					break;
				case "TEXTAREA":
					result = value.length > 0;
					break;
				default:
					result = true;
			}
			return result;
		},
		message: "This field is required."
	},
	email: {
		method: function() {
			var field = this.field;
			var value = field.value;
			
			//build the regex
            var SP        = "\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~";
            var ATEXT     = "[a-zA-Z0-9" + SP + "]";
            var ATOM      = ATEXT + "+";
            var DOTATOM   = "\\." + ATOM;
            var LOCALPART = ATOM + "(" + DOTATOM + ")*";
            //RFC 1035 tokens for domain names:
            var LETTER    = "[a-zA-Z]";
            var LETDIG    = "[a-zA-Z0-9]";
            var LETDIGHYP = "[a-zA-Z0-9-]";
            var RFCLABEL  = LETDIG + "(" + LETDIGHYP + "{0,61}" + LETDIG + ")?";
            var DOMAIN    = RFCLABEL + "(\\." + RFCLABEL + ")*\\." + LETTER + "{2,6}";
            //Combined together, these form the allowed email regexp allowed by RFC 2822:
            var ADDRSPEC  = "^" + LOCALPART + "@" + DOMAIN + "$";

			//var regex = new RegExp("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$|^$");
			var regex = new RegExp(ADDRSPEC+"|^$");
			return regex.test(value);
		},
		message: "Invalid email address."
	},
	namecharacters: {
		method: function() {
			var field = this.field;
			var regex = new RegExp("^([a-zA-Z0-9- '`])+$|^$");
			var value = field.value;
			return regex.test(value);
		},
		message: "Invalid name characters. 2 or more characters. Only letters, numbers, spaces, hyphens and apostrophes will be accepted."
	},
	phonenumber: {
		method: function() {
			var field = this.field;
			var regex = new RegExp("^[+]?[0-9 ]*\\({1}[0-9]+\\){1}[0-9 ]+$|^[+]?[0-9 ]+$|^$");
			var value = field.value;
			return regex.test(value);
		},
		message: "Invalid phone number."
	},
	password: {
		method: function(){
			var field = this.field;
			var regex = new RegExp("(^[A-Za-z0-9]{6,12}$)|(^$)");
			var value = field.value;
			return regex.test(value);
		},
		message: "Invalid password. The password can be alphanumeric and has to be between 6 and 12 characters in length."
	},
	alphadigitsspecialfullstop: {
		method: function(){
			var field = this.field;
			var regex = new RegExp("^([a-zA-Z0-9- '`.])+$|^$");
			var value = field.value;
			return regex.test(value);
		},
		message: "Invalid characters. Only letters, numbers, spaces and special characters (hyphen, apostrophe and full stop) are allowed."
	},
	number: {
		method: function(){
			var field = this.field;
			var regex = new RegExp("^([0-9])+$|^$");
			var value = field.value;
			return regex.test(value);
		},
		message: "Invalid characters. Only numbers are allowed."
	}
}

salmon.namespace.addNamespace("boots.forms.validation.customroutines");
boots.forms.validation.customroutines = {
	question2a: {
		isDependantFlomaxQuestion1Yes: {
			method: function() {
				var returnValue = true;
				if(document.getElementById("question1-yes").checked) {
					returnValue = boots.forms.validation.routines.required.method.call(this);
				}
				return returnValue;
			},
			message: "How long have you been taking Flomax Relief?"
		}
	},
	"Flomax14question19-yes": {
		isDependantFlomaxQuestion1Yes: {
			method: function() {
				var returnValue = true;
				if(document.getElementById("question1-yes").checked) {
					returnValue = boots.forms.validation.routines.required.method.call(this);
				}
				return returnValue;
			},
			message: "Have your symptoms improved since you began taking Flomax Relief?"
		}
	},
	"Flomax14question20-yes": {
		isDependantFlomaxQuestion1Yes: {
			method: function() {
				var returnValue = true;
				if(document.getElementById("question1-yes").checked) {
					returnValue = boots.forms.validation.routines.required.method.call(this);
				}
				return returnValue;
			},
			message: "Have your symptoms worsened?"
		}
	},
	"Flomax14question21-yes": {
		isDependantFlomaxQuestion1Yes: {
			method: function() {
				var returnValue = true;
				if(document.getElementById("question1-yes").checked) {
					returnValue = boots.forms.validation.routines.required.method.call(this);
				}
				return returnValue;
			},
			message: "Have you experienced side effects whilst taking Flomax Relief?"
		}
	},
	"Flomax14question22-yes": {
		isDependantFlomaxQuestion1Yes: {
			method: function() {
				var returnValue = true;
				if(document.getElementById("question1-yes").checked) {
					returnValue = boots.forms.validation.routines.required.method.call(this);
				}
				return returnValue;
			},
			message: "Have you seen your doctor to confirm a diagnosis?"
		}
	},
	flomax14question6group: {
		areAllQuestion6Answered: {
			method: function() {
				if(this.field.value === "yes") {
					return true;
				}
				else {
					return false;
				}
			},
			message: "Do you suffer from any urinary symptoms?"
		}
	},
	flomax14question16group: {
		areAllQuestion16Answered: {
			method: function() {
				if(document.getElementById("question1-no").checked) {
					if(this.field.value === "yes") {
						return true;
					}
					else {
						return false;
					}
				} else {
					return true;
				}
			},
			message: "How often do you experience the following symptoms?"
		}
	},
	"Flomax14question17": {
		isDependantFlomaxQuestion1No: {
			method: function() {
				var returnValue = true;
				if(document.getElementById("question1-no").checked) {
					returnValue = boots.forms.validation.routines.required.method.call(this);
				}
				return returnValue;
			},
			message: "How long have you had these symptoms?"
		}
	},
	flomax14question18group: {
		areAllQuestion18Answered: {
			method: function() {
				if(document.getElementById("question1-no").checked) {
					if(this.field.value === "yes") {
						return true;
					}
					else {
						return false;
					}
				} else {
					return true;
				}
			},
			message: "If you were to spend the rest of your life with your urinary (peeing) condition the way it is now, how would you feel about that?"
		}
	},
	flomax28question10group: {
		areAllQuestion10Answered: {
			method: function() {
				if(this.field.value === "yes") {
					return true;
				}
				else {
					return false;
				}
			},
			message: "Do you suffer from any of the conditions mentioned below?"
		}
	},
	reglogonPasswordVerify: {
		matches: {
			method: function() {
				var valid = true;
				var field = this.field;
				var password = document.getElementById("reglogonPassword");
				if (password != null) {
					 if(field.value != password.value) {
					 	valid = false;
					 }
				}
				return valid;
			},
			message: "The field does not match"
		}
	},
	confirmRecipientEmail: {
		matches: {
			method: function() {
				var valid = true;
				var field = this.field;
				var email = document.getElementById("recipientEmail");
				if (email != null) {
					 if(field.value != email.value) {
					 	valid = false;
					 }
				}
				return valid;
			},
			message: "The email does not match the reciever email address"
		}
	},
	youngPersonMonth: {
		required: {
			method: function() {
				var valid = true;
				var field = this.field;				
				var month_value = $.trim(field.value);
				var youngPersonYear = document.getElementById("youngPersonYear");
				if(month_value.length == 0) {
					if (youngPersonYear != null) {
						if ($.trim(youngPersonYear.value).length == 0) {
							valid = false;
						}
					}
				}
				return valid;
			},
			message: "Please enter the age of the youngest patient. Either or Both Month,Year"
		}
	},
	oldestPersonMonth: {
		required: {
			method: function() {
				var valid = true;
				var field = this.field;				
				var month_value = $.trim(field.value);
				var oldestPersonYear = document.getElementById("oldestPersonYear");
				if(month_value.length == 0) {
					if (oldestPersonYear != null) {
						if ($.trim(oldestPersonYear.value).length == 0) {
							valid = false;
						}
					}
				}
				return valid;
			},
			message: "Please enter the age of the oldest patient. Either or Both Month,Year"
		}
	},
	conTelephone: {
		required: {
			method: function() {
				var valid = true;
				var field = this.field;		
				var value = $.trim(field.value);
				var preference = document.getElementById("conPreference");
				if(preference != null && preference.value == "Phone") {
					valid = value.length > 0;
				}
				return valid;
			},
			message: "Please enter a telephone number."
		}
	},
	petPiqQuestion5a: {
		isDependantQuestionNo: {
			method: function() {		
				var returnVal = true;
				var no = document.getElementById("petPiqQuestion5-no");
				if(!no) return returnVal;
				
				if(no.checked && this.field.value.length === 0) {
					returnVal = false;
				}
				return returnVal;
			},
			message: "Please enter a reason why the animal is unwell"
		}
	},
	
	petPiqQuestion6: {
		matches: {
			method: function() {
				var valid = true;
				if(document.getElementById("petPiqQuestion4a-yes").checked) {
					valid = this.field.checked;
				}
				return valid;
			},
			message: "Please confirm that your pet is not pregnant"
		}
	}
}

salmon.namespace.addNamespace("boots.forms.validation.contextualbuttons");
boots.forms.validation.contextualbuttons = {
	dispatch_addressSearch: ["zipCode"],
	PCSValidateCustomerDetails: ["firstName", "lastName", "telphPrimary", "telphSecondary", "telphMobile", "email"],
	PCSValidatePatientDetails: ["patientFirstName", "patientLastName", "patientDOB"]	
}

/* 
 * boots.forms.validation.maxchars.js
 */
salmon.namespace.addNamespace("boots.forms.validation.maxchars");

boots.forms.validation.maxchars = {
	maxcharsEntries:{},
	init:function(){
		this.getAllMaxEntryIds();
	},
	getAllMaxEntryIds:function(){
		$("label").each(function(){
			if($(this).hasClass("maxChars")){
				boots.forms.validation.maxchars.maxcharsEntries[$(this).attr("for")] = $("label[for='"+$(this).attr("for")+"'] .maxChars span").text();
			}
		});
		var howManyItems = 0;
		for(allItems in boots.forms.validation.maxchars.maxcharsEntries){
			howManyItems++;
		}
		if(howManyItems>0){
			this.assignClasses();
		}
	},
	assignClasses:function(){
		var temp = boots.forms.validation.maxchars.maxcharsEntries;
		for(allItems in temp){
			// first run through. check if there is text already in the field and adjust label accordingly
			if($("#"+allItems).attr("value") !== undefined){
				if($("#"+allItems).attr("value").length>boots.forms.validation.maxchars.maxcharsEntries[allItems]){
					var tempString = $("#"+allItems).attr("value");
					$("#"+allItems).attr("value",tempString.slice(0,boots.forms.validation.maxchars.maxcharsEntries[allItems]));
				}
				var charsRemaining = (boots.forms.validation.maxchars.maxcharsEntries[allItems]-$("#"+allItems).attr("value").length);
				if(charsRemaining == 0){
					$("label[for='"+allItems+"'] .maxChars").addClass("charsMax").html(charsRemaining+ " characters remaining");
				} else {
					$("label[for='"+allItems+"'] .maxChars").removeClass("charsMax").html(charsRemaining+ " characters remaining");
				}
			} else {
				$("label[for='"+allItems+"'] .maxChars").removeClass("charsMax").html(boots.forms.validation.maxchars.maxcharsEntries[allItems]+ " characters maximum");
			}
			// add events to the field and check field on key up
			$("#"+allItems).keyup(function(){
				thisId = $(this).attr("id");
				if($(this).attr("value") !== undefined){
					if($(this).attr("value").length>boots.forms.validation.maxchars.maxcharsEntries[thisId]){
						var tempString = $(this).attr("value");
						$(this).attr("value",tempString.slice(0,boots.forms.validation.maxchars.maxcharsEntries[thisId]));
					}
					var charsRemaining = (boots.forms.validation.maxchars.maxcharsEntries[thisId]-$(this).attr("value").length);
					if(charsRemaining == 0){
						$("label[for='"+thisId+"'] .maxChars").addClass("charsMax").html(charsRemaining+ " characters remaining");
					} else {
						$("label[for='"+thisId+"'] .maxChars").removeClass("charsMax").html(charsRemaining+ " characters remaining");
					}
				} else {
					$("label[for='"+thisId+"'] .maxChars").removeClass("charsMax").html(boots.forms.validation.maxchars.maxcharsEntries[thisId]+ " characters maximum");
				}
			});
		}
	}
}

$(document).ready(function(){ boots.forms.validation.maxchars.init() });

/* 
 * boots.forms.prefill.js
 */
salmon.namespace.addNamespace("boots.forms.prefill");
boots.forms.prefill = {
	init:function(){
		$(".prefill").each(function(){
			if($(this).attr("value")==""){
				$(this).attr({value:$(this).attr("title")});
			}
			$(this).focus(function(){
				if($(this).attr("value")==$(this).attr("title")){
					$(this).attr({value:""});
				}
			}).blur(function(){
				if($(this).attr("value")==""){
					$(this).attr({value:$(this).attr("title")});
				}
			});
			$(this.form).submit(function(){
				$(this).find(".prefill").each(function(){
					if($(this).attr("value")==$(this).attr("title")){
						$(this).attr({value:""});
					}
				});
			});
		});
	}
}
$(document).ready(function(){ boots.forms.prefill.init(); });

/* 
 * boots.navigation.js
 */
salmon.namespace.addNamespace("boots.navigation");
boots.navigation = {
	currentWidth:0,
	currentHeight:0,
	currentTop:0,
	currentLeft:0,
	mouseoverCategory:false,
	mouseoverMenu:false,
	isIe6:$.browser.msie,
	init: function() {
			$("ul.jd_menu ul").prepend("<li class=\"top\"><span></span></li>");
			$("ul.jd_menu li.top").each(function(){
				$(this).find("span").css({
					width:$(this).parent().parent().find("a:first").width()+"px"
				});
			});
			if(this.isIe6){
			this.isIe6 = (parseInt($.browser.version)<=6);
		}
		if(this.isIe6){
			$("body").append("<iframe id=\"dropDownBoxIframe\" src=\"/wcsstore/ConsumerDirectStorefrontAssetStore/en_US/i/blank.htm\" scrolling=\"no\" frameborder=\"no\"></iframe>");
			$("#dropDownBoxIframe").css({
				height:"1px",
				position:"absolute",
				top:"0px",
				left:"0px",	
				width:"174px",
				filter:"alpha(opacity=0)"
			});
		}
		$("body").append("<div id=\"dropDownBox\"></div>");
		$("#dropDownBox").css({
			textAlign:"left",
			position:"absolute",
			top:0,
			left:0,
			width:"174px",
			zIndex:"9999"
		});
		$("ul.jd_menu > li > a").mouseover(function(){
			boots.navigation.mouseoverCategory = true;
			boots.navigation.currentWidth = $(this).width();
			boots.navigation.currentHeight = $(this).height();
			boots.navigation.currentTop = $(this).offset().top;
			boots.navigation.currentLeft = $(this).offset().left;
			if(boots.navigation.isIe6){
				$("#dropDownBoxIframe").css({
					top:(parseInt(boots.navigation.currentTop)+parseInt(boots.navigation.currentHeight))+"px",
					left:boots.navigation.currentLeft+"px"
				});
			}
			
			$("#dropDownBox").css({
				top:(parseInt(boots.navigation.currentTop)+parseInt(boots.navigation.currentHeight))+"px",
				left:boots.navigation.currentLeft+"px"
			}).empty();
	
			$(this).parent().find("ul").clone().appendTo("#dropDownBox");
			$("#dropDownBox ul").css({display:"block"});
			
			if(boots.navigation.isIe6){
				$("#dropDownBoxIframe").css({
					height:parseInt($("#dropDownBox").height())+"px"
				});
			}
		});
	
		$("ul.jd_menu > li > a").mouseout(function(){
			boots.navigation.mouseoverCategory = false;
			window.setTimeout(boots.navigation.showMenu,500);
		});
		$("#dropDownBox").mouseover(function(){
			boots.navigation.mouseoverMenu = true;
		});
		$("#dropDownBox").mouseout(function(){
			boots.navigation.mouseoverMenu = false;
			window.setTimeout(boots.navigation.showMenu,500);
		});
	
	},
	
	showMenu:function (){
		if(!boots.navigation.mouseoverCategory){
			if(!boots.navigation.mouseoverMenu){
				if(boots.navigation.isIe6){
					$("#dropDownBoxIframe").css({
						height:"1px",
						top:0,
						left:0
					});
				}
				$("#dropDownBox").css({
					height:"1px",
					top:0,
					left:0
				}).empty();
			}
		}
	}
	
};

$(document).ready(function(){boots.navigation.init();});


/* 
 * boots.tabs.js
 */
salmon.namespace.addNamespace("boots.TabSetCollection");
boots.TabSetCollection = {
	init: function() {
		$("ul.tabNavigation").show();
		$(".tab .tabTitles").hide();
		var tabsets = $(".tabset");
		for(var i = 0;i<tabsets.length;i++) {
			boots.TabSetCollection.tabSet = new boots.TabSetCollection.TabSet(tabsets[i]);
		}
	},
	TabSet: function(tabset) {
		var tabActivators = "";
		var tabActivatorCssClass = "selected";
		var tabCssClass = "unselected";
		init();
		function init() {
			var selectedTab = "";
			tabActivators = $("a.tabActivator",tabset);
			for (var i=0; i < tabActivators.length; i++) {
				tabActivators[i].relatedTab = document.getElementById(tabActivators[i].hash.slice(1));
				tabActivators[i].onclick = tabClicked;
				if ( $(tabActivators[i]).hasClass(tabActivatorCssClass) ) {
					selectedTab = tabActivators[i].relatedTab;
				}			
			}
			hideAllTabs(selectedTab);
			hideEmptyTabs();
		}
		function hideAllTabs(nodeToIgnore) {
			for ( var i = tabActivators.length-1; i >= 0; i--) {
				if (tabActivators[i].relatedTab != nodeToIgnore) {
					$(tabActivators[i]).removeClass(tabActivatorCssClass);
					$(tabActivators[i].relatedTab).addClass(tabCssClass);
				}
			}
		}
		function tabClicked() {
			hideAllTabs(this.relatedTab);
			$(this).addClass(tabActivatorCssClass);
			$(this.relatedTab).removeClass(tabCssClass);
			$(this).blur();
			return false;
		}
		function hideEmptyTabs(){
			var isFirst = false;
			for (var i=0; i < tabActivators.length; i++) {
				var tabName = $(tabActivators[i]).attr("href");
				if($(tabName + " .tabDetails").length>0){
					var tabText = $(tabName + " .tabDetails").text();
					tabText = tabText.replace(/ /g,"");
					tabText = tabText.replace(/\n/g,""); 
					tabText = tabText.replace(/\t/g,"");
					if(tabText.length == 0){
						if($(tabName + " .tabDetails img").length>0){
							if(!isFirst){
								isFirst = true
								$(tabActivators[i]).addClass("selected");
								$(tabName).removeClass("unselected");
								$(tabActivators[i],tabName).parent().addClass("first");
							}
						} else {
							$(tabActivators[i],tabName).css({display:"none"});
							$(tabName).addClass("unselected");
						}
					} else {
						if(!isFirst){
							isFirst = true
							$(tabActivators[i]).addClass("selected");
							$(tabName).removeClass("unselected");
							$(tabActivators[i],tabName).parent().addClass("first");
						}
					}
				}
			}
		}
	}
}

$(document).ready(function(){ boots.TabSetCollection.init(); });

/* 
 * boots.colourPalette.js
 */
salmon.namespace.addNamespace("boots.colourPalette");
var sizeVariants=[];
boots.colourPalette = {
	currentOver:"",
    listerVariants:[],
	isMouseOver:false,
    init: function(){
        var colourPalettes  = $(".colourPalette");
        var inPageSizeVariants = $("#OrderItemAddForm #size_x");
        var inListerSizeVariants = $(".productItem .size select");
        if($("#quickViewColourScript").length > 0){
        	eval($("#quickViewColourScript").text());
        }
        if($("#quickViewSizeScript").length > 0){
        	eval($("#quickViewSizeScript").text());
        }
        for(var i = colourPalettes.length-1; i>=0;i--) {
                    boots.colourPalette.colourPalette = new boots.colourPalette.ColourPalette(colourPalettes[i]);
        }
        if(inPageSizeVariants.length>0){
	        $(".size #size_x").add(".selectASize #size_x").add(".pl_sizeVariant #size_x").add(".qv_sizeVariant #size_x").change(function(){
				boots.colourPalette.SizeVariantSelector();
	        });
	        boots.colourPalette.SizeVariantSelector();
        }
        if(inListerSizeVariants.length>0){
        	$(inListerSizeVariants).each(function(){
        		var thisId = $(this).attr("id");
        		for(var i=0; i<sizeVariants.length; i++){
        			if(sizeVariants[i].sizeVariantId == thisId){
        				boots.colourPalette.listerVariants[thisId] = sizeVariants[i];
        			}
        		}
        		$(this).change(function(){
	        		var myId = $(this).attr("id");
	        		var mySize = $(this).attr("value");
	        		var myParent = $(this).parent();
	        		for(var i=0; i<2; i++){
	        			if($(myParent).hasClass("details")){
	        				i=2;
	        			} else {
		        			myParent = $(myParent).parent();
	        				--i;
	        			}
	        		}
	        		myParent.find(".productNumber").text(boots.colourPalette.listerVariants[myId].variants[mySize].productCode);
	        		var myAddToBasketString  = myParent.find(".addToBasket a").attr("href");
	        		var myBegin = myAddToBasketString.substring(0,myAddToBasketString.indexOf("(")+1);
	        		var myEnd = myAddToBasketString.substring(myAddToBasketString.indexOf(","),myAddToBasketString.length);
	        		var myVariantId = boots.colourPalette.listerVariants[myId].variants[mySize].variantId;
	        		var myNewHref = myBegin + myVariantId + myEnd;
	        		myParent.find(".addToBasket a").attr({href:myNewHref});
        		});
        	});
        }
    },
    SizeVariantSelector:function(){
        var currentItem = $("#size_x").attr("value");
        $("form#OrderItemAddForm #OrderItemAddForm_catEntryId").attr({value:sizeVariant.variants[currentItem].variantId});
        /* for old pages */
        $("#productInformation .priceInformation .oldPrice").text(sizeVariant.boots_oldText +" "+ sizeVariant.variants[currentItem].currentPrice);
        $("#productInformation .priceInformation .save").text(sizeVariant.boots_saveText +" "+ sizeVariant.variants[currentItem].saving);
        $("#productInformation .price").text(sizeVariant.variants[currentItem].nowPrice);
        $("#productInformation .sizeInformation .pricePerSize").text(sizeVariant.variants[currentItem].ppu);
        $("#productInformation .productCode").text(sizeVariant.boots_productCodeText +" "+ sizeVariant.variants[currentItem].productCode);
        $("#productInformation .collectPoints").text(sizeVariant.variants[currentItem].points);
        /* for new pages */
        if($(".page_productDetails").length > 0){
			$(".page_productDetails .pd_addToBasketSection .oldPrice").text(sizeVariant.boots_oldText +" "+ tempCurrentPrice);
			$(".page_productDetails .pd_addToBasketSection .save").text(sizeVariant.boots_saveText +" "+ tempSaving);
			$(".page_productDetails .pd_addToBasketSection .price").text(tempNowPrice);
			$(".page_productDetails .pd_addToBasketSection .sizeInformation .pricePerSize").text(sizeVariant.variants[currentItem].ppu);
			$(".page_productDetails .pd_productName h2 span.pd_productVariant").text(sizeVariant.variants[currentItem].productCode);
			$(".page_productDetails .pd_addToBasketSection .collectPoints").text(sizeVariant.variants[currentItem].points);
		} else if($("#productDetailsQuickView").length > 0) {
			$("#productDetailsQuickView .pd_addToBasketSection .oldPrice").text(sizeVariant.boots_oldText +" "+ sizeVariant.variants[currentItem].currentPrice);
			$("#productDetailsQuickView .pd_addToBasketSection .save").text(sizeVariant.boots_saveText +" "+ sizeVariant.variants[currentItem].saving);
			$("#productDetailsQuickView .pd_addToBasketSection .price").text(sizeVariant.variants[currentItem].nowPrice);
			$("#productDetailsQuickView .pd_addToBasketSection .sizeInformation .pricePerSize").text(sizeVariant.variants[currentItem].ppu);
			$("#productDetailsQuickView .pd_productName h2 span").text(sizeVariant.boots_productCodeText +" "+ sizeVariant.variants[currentItem].productCode);
			$("#productDetailsQuickView .pd_addToBasketSection .collectPoints").text(sizeVariant.variants[currentItem].points);
		}
    },

	ColourPalette:function(colourPalette){
		$(colourPalette).append("<div class=\"toolTip clearfix\"><div class=\"left\">&nbsp;</div><div class=\"middle\">&nbsp;</div><div class=\"right\">&nbsp;</div></div>");
		$(colourPalette).find(".actions,label span").hide();
		$(colourPalette).find(".toolTip").css({left: "-99999em"});
		$(colourPalette).find(".selectedColour").show();
		$(colourPalette).find("fieldset").css({
			width:"auto"
		});
		if($(colourPalette).find("fieldset").attr("class") == "chanelColourPalette"){
			$(colourPalette).find("fieldset div").css({
				float:"left",
				height:"24px",
				width:"48px",
				margin:"0 1px 1px 1px",
				position:"relative"
			});
			$(colourPalette).find("fieldset div img").css({
				height:"24px",
				width:"48px"
			});
			$(colourPalette).find("fieldset div img").attr({
				height:"24",			
				width:"48"
			});
			$(colourPalette).find(".selectedColour img").css({
				height:"50px",
				width:"100px"
			});
			$(colourPalette).find(".selectedColour img").attr({
				height:"50",
				width:"100"
			});
		} else {
			$(colourPalette).find("fieldset div").css({
				float:"left",
				height:"24px",
				width:"24px",
				margin:"0 1px 1px 0",
				position:"relative"
			});
		}
		$(colourPalette).find("fieldset label").css({
			position:"absolute",
			top:"0",
			left:"0"
		});
		$(colourPalette).find("label").click(function(){
			var currentItem = $(this).attr("for");
			$(colourPalette).find(".selectedColour img").attr({
				src:boots.currentProduct.variants[currentItem].bigImage,
				alt:$(this).text()
			});
			if($(".page_productDetails").length > 0){
				// new product details page
				$(colourPalette).find("h2").html("Click to change colour or fragrance. <strong><span>"+$(this).text()+"</span> selected</strong>");
			} else if($("#productDetailsQuickView").length > 0) {
				$(colourPalette).find("h2").html("Click to change colour or fragrance. <strong><span>"+$(this).text()+"</span> selected</strong>");
			} else {
				// old product details page
				$(colourPalette).find(".selectedColour p").text($(this).text());
			}			

			$("form#OrderItemAddForm #OrderItemAddForm_catEntryId").attr({value:boots.currentProduct.variants[currentItem].variantId});
			
			var tempCurrentPrice = boots.currentProduct.variants[currentItem].currentPrice;
			var tempSaving = boots.currentProduct.variants[currentItem].saving;
			var tempNowPrice = boots.currentProduct.variants[currentItem].nowPrice;
						
			tempCurrentPrice = tempCurrentPrice.replace(/&#163;/g,"\u00A3");
			tempSaving = tempSaving.replace(/&#163;/g,"\u00A3");
			tempNowPrice = tempNowPrice.replace(/&#163;/g,"\u00A3");
	
			/* for old pages */		
			$("#productInformation .priceInformation .oldPrice").text(boots.currentProduct.boots_oldText +" "+ tempCurrentPrice);
			$("#productInformation .priceInformation .save").text(boots.currentProduct.boots_saveText +" "+ tempSaving);
			$("#productInformation .price").text(tempNowPrice);
			$("#productInformation .sizeInformation .pricePerSize").text(boots.currentProduct.variants[currentItem].ppu);
			$("#productInformation .productCode").text(boots.currentProduct.boots_productCodeText +" "+ boots.currentProduct.variants[currentItem].productCode);
			$("#productInformation .collectPoints").text(boots.currentProduct.variants[currentItem].points);

	        /* for new pages */
	        if($(".page_productDetails").length > 0){
				$(".page_productDetails .pd_addToBasketSection .oldPrice").text(boots.currentProduct.boots_oldText +" "+ tempCurrentPrice);
				$(".page_productDetails .pd_addToBasketSection .save").text(boots.currentProduct.boots_saveText +" "+ tempSaving);
				$(".page_productDetails .pd_addToBasketSection .price").text(tempNowPrice);
				$(".page_productDetails .pd_addToBasketSection .sizeInformation .pricePerSize").text(boots.currentProduct.variants[currentItem].ppu);
				$(".page_productDetails .pd_productName h2 span.pd_productVariant").text(boots.currentProduct.variants[currentItem].productCode);
				$(".page_productDetails .pd_addToBasketSection .collectPoints").text(boots.currentProduct.variants[currentItem].points);
			} else if($("#productDetailsQuickView").length > 0) {
				$("#productDetailsQuickView .pd_addToBasketSection .oldPrice").text(boots.currentProduct.boots_oldText +" "+ tempCurrentPrice);
				$("#productDetailsQuickView .pd_addToBasketSection .save").text(boots.currentProduct.boots_saveText +" "+ tempSaving);
				$("#productDetailsQuickView .pd_addToBasketSection .price").text(tempNowPrice);
				$("#productDetailsQuickView .pd_addToBasketSection .sizeInformation .pricePerSize").text(boots.currentProduct.variants[currentItem].ppu);
				$("#productDetailsQuickView .pd_productName h2 span").text(boots.currentProduct.variants[currentItem].productCode);
				$("#productDetailsQuickView .pd_addToBasketSection .collectPoints").text(boots.currentProduct.variants[currentItem].points);
			}
		});
		$(colourPalette).find("label").mouseover(function(){
			var currentItem = $(this).attr("for");
			if((boots.colourPalette.currentOver != currentItem) || (!boots.colourPalette.isMouseOver)){
				boots.colourPalette.showToolTip($(this).text(),this,colourPalette);
				boots.colourPalette.isMouseOver = true;
				boots.colourPalette.currentOver = currentItem;
			}
		});
		$(colourPalette).find("label").mouseout(function(){
			var currentItem = $(this).attr("for");
			$(colourPalette).find(".toolTip").unbind("click");
			$(colourPalette).find(".toolTip").css({left: "-99999em"});
			boots.colourPalette.isMouseOver = false;
		});
	},
	showToolTip: function(whatText,whatItem,colourPalette){
		/*
		 * it is important that to calculate the widths of what the tooltip parts need to be that
		 * we first set the text inside the panel and then reset the widths to auto to start from 
		 * level. Then begin calculating offsets and setting them.
		 */
		var tooltip = $(colourPalette).find(".toolTip")[0];
		var tooltipMiddlePane = $("div.middle",tooltip)[0];
		$(tooltipMiddlePane).text(whatText);
		$(tooltip).css({width: "auto"});
		$(tooltipMiddlePane).css({width: "auto"});		
		var tooltipMiddlePaneWidth = $(tooltipMiddlePane).width();
		if($(".page_productDetails").length > 0){
			var itemOffset = $(whatItem).offset();
			var itemOffsetProductDetails = $("#detailedInformation").offset();
			var leftOffset = itemOffset.left-Math.floor($(tooltip).width()/2)+($(colourPalette).find("fieldset div img").width()/2);
			var topOffset = itemOffset.top-38;
		} else {
			$(colourPalette).find(".toolTip").css({position: "absolute"});
			var itemOffset = $(whatItem).offset();
			var itemOffsetProductDetails = $("#productDetails").offset();
			var leftOffset = itemOffset.left-$("#chooseColour").offset().left-Math.floor($(tooltip).width()/2)+($(colourPalette).find("fieldset div img").width()/2);
			var topOffset = -24;
		}
		$(tooltip).css({
			left:leftOffset,
			height:"46px",
			overflow:"hidden",
			top:topOffset,
			width: tooltipMiddlePaneWidth+28 //padding
		});
		$(tooltipMiddlePane).css({width: tooltipMiddlePaneWidth});
	}
};
$(document).ready(function(){boots.colourPalette.init();});


/* 
 * boots.brandviewer.js
 */
salmon.namespace.addNamespace("boots.BrandViewerCollection");
boots.BrandViewerCollection = {
	init: function() {
		var brandViewers = $("div.brandViewer");
		for(var i = brandViewers.length-1; i>=0;i--) {
			boots.BrandViewerCollection.brandViewer = new boots.BrandViewerCollection.BrandViewer(brandViewers[i]);
		}
	},
	BrandViewer: function(BrandViewer) {
		var brandViewerID = BrandViewer.id;
		var moveCount = 1;
		var liTagWidth = 0;
		var itemsToShow = 4;
		var clippingArea = null;
		var animationInProgress = false;
		var rolloverImageCollection = {};
		
		var init = (function() {
			prepareRollovers();
			setLiTagWidth();
			setClippingArea();
			if(!checkIfAnimateable()) {
				return false;
			}
			setItemsToShow();
			prepareControls();
		})();
		
		function prepareRollovers() {
			var rolloverCollection = boots.BrandViewerCollection[brandViewerID];
			if(rolloverCollection == null) {
				return;
			}
			var brandLinks = $("a",BrandViewer);
			for(var i = 0; i<brandLinks.length; i++) {
				var currentLink = brandLinks[i];
				currentLink.image = $(currentLink).find("img")[0];
				currentLink.baseImage = $(currentLink).find("img").attr("src");
				if(rolloverCollection[currentLink.baseImage] == null) {
					continue;
				}
				currentLink.rolloverImage = rolloverCollection[currentLink.baseImage];
				currentLink.onmouseover = brandLinks_over;
				currentLink.onmouseout = brandLinks_out;
			}
		}
		
		function brandLinks_over() {
			this.image.src = this.rolloverImage;
		}
		
		function brandLinks_out() {
			this.image.src = this.baseImage;
		}		
		
		function setLiTagWidth() {
			if($("li", BrandViewer).length == 0) { return };
			liTagWidth = parseInt($("li", BrandViewer).css("width").split("px")[0]);
		}
		
		function setItemsToShow() {
			var classes = BrandViewer.className.split(" ");
			for(var i = classes.length-1; i>=0;i-- ) {
				if(classes[i].indexOf("size") != -1) {
					itemsToShow = classes[i].split("size")[1];
					break;
				}
			}

			// TO DO:
			// check if we have enough "extra <li> tags" for the scroll amount before setting "moveCount above 1"
			// and actually do the movement by that many
			
		}
		
		function checkIfAnimateable() {
			var isAnimateable = true;
			var brandViewerWidth = parseInt(getElementWidth(BrandViewer));
			var clippingAreaWidth = parseInt(getElementWidth(clippingArea));
			if(clippingAreaWidth < brandViewerWidth) {
				isAnimateable = false;
			}
			return isAnimateable;
		}
		
		function getElementWidth(element) {
			var elementWidth = 0;
			elementWidth = $(element).css("width");
			if(elementWidth == "auto") { elementWidth = "0px"}
			elementWidth = elementWidth.split("px")[0];
			return elementWidth;
		}
		
		function setClippingArea() {
			var width = getClippingWidth();
			clippingArea = $("ul", BrandViewer)[0];
			$(clippingArea).css({width: width});
		}
		
		function getClippingWidth() {
			var width = 0;
			var listElements = $("li", BrandViewer);
			for(var i=0;i<listElements.length;i++) {
				width += $(listElements[i]).width();
			}
			return width;
		}
		
		function prepareControls() {
			var backLink = document.createElement("span");
			var backImage = document.createElement("img");
			backImage.src = boots.common.siteConfig.imageDirectoryURL+"btn_back01.png";
			backImage.alt = "Backwards";
			backLink.className = "back";
			backLink.onclick = back_onClick;
			backLink.appendChild(backImage);
			BrandViewer.appendChild(backLink);
			
			$(backLink).pngFix(); 
			
			var forwardLink = document.createElement("span");
			var forwardImage = document.createElement("img");
			forwardImage.src = boots.common.siteConfig.imageDirectoryURL+"btn_forward01.png";
			forwardImage.alt = "Forwards";
			forwardLink.className = "forward";
			forwardLink.onclick = forward_onClick;
			forwardLink.appendChild(forwardImage);
			BrandViewer.appendChild(forwardLink);
			
			$(forwardLink).pngFix(); 
		}
		
		function back_onClick() {
			if(animationInProgress) {
				return false;
			}
			
			var value = 0;
			value = (getClippingAreaCssLeft() - liTagWidth) + "px";
			animationInProgress = true;
			animate(value, animateBack_onComplete);
			this.blur();
			return false;
		}
		
		function animate(value, functionReference) {
			$(clippingArea).animate( { left: value } , {duration: 1000, complete: functionReference} );		
		}
		
		function animateBack_onComplete() {
			animationInProgress = false;
			$("li:first",clippingArea).appendTo(clippingArea);
			$(clippingArea).css({left: "0px"});
		}
		
		function animateForward_onComplete() {
			animationInProgress = false;
		}		
		
		function forward_onClick() {
			if(animationInProgress) {
				return false;
			}
			
			$("li:last",clippingArea).prependTo(clippingArea);
			var leftValue = (getClippingAreaCssLeft()-liTagWidth)+"px";
			$(clippingArea).css({left: leftValue});
		
			var value = 0;
			value = (getClippingAreaCssLeft() + liTagWidth) + "px";
			animationInProgress = true;
			animate(value, animateForward_onComplete);
			this.blur();
			return false;
		}
		
		function getClippingAreaCssLeft() {
			var value = $(clippingArea).css("left");
			if(value == "auto") { value = "0px"; }
			value = parseInt(value.split("px")[0]);
			return value;
		}
		
	}
}

$(document).ready(function(){ boots.BrandViewerCollection.init(); });

/* 
 * boots.askandanswer.js
 */
salmon.namespace.addNamespace("boots.AskAndAnswer");
boots.AskAndAnswer = {
	init: function() {
		var togglers = $("div.askAndAnswerPanel div.question h3");
		for(var i = togglers.length-1; i>=0;i--) {
			$(togglers[i]).addClass("toggleEnhance");
			togglers[i].answersArea = $(togglers[i]).parent().parent().find("div.collapseable")[0]
			togglers[i].onclick = boots.AskAndAnswer.toggleAnswersArea;
			$(togglers[i].answersArea).hide();
		}
	},
	toggleAnswersArea: function() {
		$(this.answersArea).toggle();
	}
}
$(document).ready(function(){ boots.AskAndAnswer.init(); });

/* 
 * boots.showmoreorless.js
 */
salmon.namespace.addNamespace("boots.ShowMoreLess");
boots.ShowMoreLess = {
	selector: "div.showMoreLessText",
	characterClass: "char",
	togglerMoreText:"show more...",
	togglerLessText:"...show less",
	init: function() {
		var showMoreLessComponents = $(boots.ShowMoreLess.selector);
		for(var i = showMoreLessComponents.length-1; i>=0;i--) {
			boots.ShowMoreLess.instance = new boots.ShowMoreLess.ShowMoreLessComponent(showMoreLessComponents[i],boots.ShowMoreLess.getCharacterLimit(showMoreLessComponents[i]));
		}
	},
	getCharacterLimit: function(container) {
		var characterLimit = 0;
		if(container == null) {
			return;
		}
		var classes = container.className.split(" ");
		for(var i = classes.length-1; i>=0;i-- ) {
			if(classes[i].indexOf(boots.ShowMoreLess.characterClass) != -1) {
				characterLimit = classes[i].split(boots.ShowMoreLess.characterClass)[1];
				break;
			}
		}
		return characterLimit;
	},
	ShowMoreLessComponent: function(container, characterLimit) {
		var fullText = "" + container.innerHTML + " ";
		var reducedText = "";
		var toggler = null;
		var showingMinimisedText = false;
		var init = (function() {
			setReducedText();
			if(reducedText == "") {
				return;
			}
			prepareToggler();
			toggleText();
		})();
		
		function setReducedText() {
			if(fullText.length < characterLimit) {
				return;
			}
			for(var i = 0; i<characterLimit; i++) {
				reducedText += fullText.charAt(i);
			}
			reducedText += " ";
		}		
		
		function prepareToggler() {
			toggler = document.createElement("a");
			toggler.href="#togglemore";
			toggler.innerHTML = "hello";
			toggler.onclick = toggleText;
			container.appendChild(toggler);
		}
		
		function toggleText() {
			if(showingMinimisedText) {
				$(container).text(fullText);
				toggler.innerHTML = boots.ShowMoreLess.togglerLessText;
				container.appendChild(toggler);
				showingMinimisedText = false;
			}
			else {
				$(container).text(reducedText);
				toggler.innerHTML = boots.ShowMoreLess.togglerMoreText;
				container.appendChild(toggler);
				showingMinimisedText = true;
			}
			return false;
		}
		
	}
}


$(document).ready(function(){ boots.ShowMoreLess.init(); });

/* 
 * boots.promotion.js
 */
salmon.namespace.addNamespace("boots.promotion");
boots.promotion = {
	init:function(){
		var themedPromos = $("div.banner_main");
		var themedCarousels = $("div.themedPromotionCarousel");
		for(var i = themedPromos.length-1; i>=0;i--) {
			boots.promotion.themedPromo = new boots.promotion.ThemedPromo(themedPromos[i],false);
		}
		for(var i = themedCarousels.length-1; i>=0;i--) {
			boots.promotion.themedCarousel = new boots.promotion.ThemedPromo(themedCarousels[i],true);
			//boots.promotion.themedCarousel = new boots.promotion.ThemedCarousel(themedCarousels[i]);
		}
	},
	ThemedPromo:function(ThemedPromo,paused){
		var isPlaying = false;
		var isAnimating = false;
		var isDirect = false;
		var currentItem = 1;
		var nextItem = 2;
		var maxItems = 8;
		var pauseTimer = 2000;
		var animateTimer = 2000;
		var highestZindex = 0;
		var inicatorPositions =["0","5px","31px","58px","84px" ,"109px" ,"136px" ,"161px" ,"187px" ,"196px" ];
		var init = (function(){
			var promotionHolder = ThemedPromo;
			var promotionHolders = $(ThemedPromo).find(".banner_inner ul li");
			maxItems = (promotionHolders.length<maxItems)?promotionHolders.length:maxItems;
			if((promotionHolder == null) || (maxItems <= 1)){
				return;
			} else if (maxItems == 8){
				$(ThemedPromo).addClass("twoItems");
			}
			$(promotionHolder).prepend("<div class=\"banner_nav\"></div>");
			$(ThemedPromo).find(".banner_nav").append("<div class=\"indicator\">&nbsp;</div>");
			$(ThemedPromo).find(".banner_nav").append("<ul></ul>");
			var count = 1;
			$(promotionHolders).each(function(){
				if(count<=maxItems){
					$(ThemedPromo).find(".banner_nav ul").append("<li><a href=\"#"+count+"\""
						+((count==1)?" class=\"current\"":"")
						+">"+count+"</a></li>");
					$(this).css({
						 position:"absolute",
						 top:0,
						 left:0,
						 display:((count==1)?"block":"none"),
						 zIndex:count++
					});
				} else {
					$(this).remove();
				}
			});
			$(ThemedPromo).find(".banner_nav").append("<div class=\"pausePlay Pause\"><strong>Pause</strong><span>&#160;</span></div>");
			$(ThemedPromo).find(".pausePlay").click(pausePlay);
			if(jQuery.browser.opera){
				$(ThemedPromo).find(".pausePlay").css({top:"-18px"});
			}
			if(maxItems==3){
				$(ThemedPromo).find(".pausePlay").css({left:"97px"});
			}
			$(ThemedPromo).find(".banner_nav li a").click(tp_gothere);
			if(paused){
				$(ThemedPromo).find(".pausePlay").removeClass("Pause").addClass("Play").find("strong").text("Play");
			} else {
				isPlaying = true;
			}
			wait();
		})();
		function pausePlay(){
			var whatAction = $(this).find("strong").text();
			if(whatAction == "Pause"){
				$(this).removeClass("Pause").addClass("Play");
				$(this).find("strong").text("Play");
				pause();
			} else {
				$(this).removeClass("Play").addClass("Pause");
				$(this).find("strong").text("Pause");
				play();
			}
			$(this).blur();
		}
		function play(){
			isPlaying = true;
			animate();
		}
		function pause(){
			isPlaying = false;
		}
		function tp_gothere(){
			var goWhere = $(this).text();
			$(ThemedPromo).find(".pausePlay").removeClass("Pause").addClass("Play");
			$(ThemedPromo).find(".pausePlay").find("strong").text("Play");
			isPlaying = false;
			window.clearTimeout();
			$(ThemedPromo).find(".banner_inner ul li").stop();
			$(ThemedPromo).find(".banner_inner ul li").css({opacity:""});
			$(ThemedPromo).find(".indicator").stop();
			nextItem = $(this).text();
			isDirect = true;
			animate();
			$(this).blur();
			return false;
		}
		function animate(){
			if(!isDirect){
				if(isAnimating || !isPlaying){
					return;
				}
			}
			isDirect = false;
			isAnimating = true;
			$(ThemedPromo).find(".banner_nav ul li a").removeClass("current");
			$(ThemedPromo).find(".banner_inner ul li").each(function(){
				highestZindex = ($(this).css("zIndex")>highestZindex) ? $(this).css("zIndex") : highestZindex;
			});
			var count = 1;
			$(ThemedPromo).find(".banner_inner ul li").each(function(){
				if(count++ == nextItem){
					$(this).css({
						zIndex:++highestZindex
					}).fadeIn(animateTimer,function(){
						$(ThemedPromo).find(".banner_inner ul li").each(function(){
							if($(this).css("zIndex") != highestZindex){
								$(this).css({display:"none"});
							}
						});						
						$(ThemedPromo).find(".banner_nav ul li a").each(function(){
							if($(this).text() == nextItem){
								$(this).addClass("current");
							}
						});
						nextItem = ((nextItem+1)>maxItems)?1:++nextItem;
						isAnimating = false;
						if(isPlaying){
							wait();
						}
					});
					$(ThemedPromo).find(".indicator").animate({left:inicatorPositions[nextItem]},animateTimer);
				}
			});
		}
		function wait(){
			window.setTimeout(animate, pauseTimer);
		}
	},
	ThemedCarousel:function(ThemedCarousel){
		var isAnimating = false;
		var currentItem = 1;
		var maxItems = 8;
		var animateTimer = 3000;
		var highestZindex = 0;
		$(ThemedCarousel).prepend("<div class=\"themedPromotionCarouselControls\"></div>");
		$(ThemedCarousel).find(".themedPromotionCarouselControls").append("<ul><li class=\"back\"><a href=\"#back\"><img src=\""+boots.common.siteConfig.imageDirectoryURL+"btn_back01.png\" width=\"23\" height=\"42\" alt=\"back\" /></a></li><li class=\"forward\"><a href=\"#forward\"><img src=\""+boots.common.siteConfig.imageDirectoryURL+"btn_forward01.png\" width=\"23\" height=\"42\" alt=\"forward\" /></a></li></ul>");
		$(ThemedCarousel).find(".back a").click(goBack);
		$(ThemedCarousel).find(".forward a").click(goForward);
		var count = 1;
		$(ThemedCarousel).find(".banner_inner ul li").each(function(){
			if(count<=maxItems){
				$(this).css({
					 position:"absolute",
					 top:0,
					 left:0,
					 display:((count==1)?"block":"none"),
					 zIndex:count++
				});
			} else {
				$(this).remove();
			}
		});
		
		$(document).pngFix();
		
		function goBack(){
			if(!isAnimating){
				currentItem = (currentItem==1) ? maxItems : currentItem-1;
				fadeNewItem();
			}
			return false;
		}
		function goForward(){
			if(!isAnimating){
				currentItem = (currentItem==maxItems) ? 1 : currentItem+1;
				fadeNewItem();
			}
			return false;
		}
		function fadeNewItem(){
			if(!isAnimating){
				isAnimating = true;
				$(ThemedCarousel).find(".banner_inner ul li").each(function(){
					highestZindex = ($(this).css("zIndex")>highestZindex) ? $(this).css("zIndex") : highestZindex;
				});
				var count = 1;
				$(ThemedCarousel).find(".banner_inner ul li").each(function(){
					if(count++ == currentItem){
						$(this).css({
							zIndex:++highestZindex
						}).fadeIn(animateTimer,function(){
							$(ThemedCarousel).find(".banner_inner ul li").each(function(){
								if($(this).css("zIndex") != highestZindex){
									$(this).css({display:"none"});
								}
							});						
							isAnimating = false;
						});
					}
				});
			}
			$(ThemedCarousel).find("a").blur();
		}
	}
};
$(document).ready(function(){
	boots.promotion.init();
});


/* 
 * boots.header.js
 */
/*
	Authors: Adam Silver, Adam Osborne
	Cookie is: bdccookie_bsktSumm
		Cookie values are:
			coNumItems
			coTotal
			coAdcPts
	Notes:	currency escape char	currency: "\u00A3"
*/
salmon.namespace.addNamespace("boots.shoppingtrolley");
$(document).ready(function(){ 
	boots.shoppingtrolley = new (function() {
		
		/*
		 * 	bi = basket items
		 * 	bt = basket total
		 * 	bp = basket points
		 * 	pi = prescription items
		 *	pp = prescription points
		 */
		
		var cookieKeys = {bi: "bi",bt: "bt",bp: "bp",pi: "pi",pp: "pp"}
		
		var cookie = {};
		var cookieRawString = unescape(boots.common.cookie.getCookie("_bdccookie_bsktSumm"));
		cookieRawString = cookieRawString.replace("{", "");
		cookieRawString = cookieRawString.replace("}", "");
		var cookieArray = cookieRawString.split(",");
		for (var i=0; i<cookieArray.length; i++) {
			var s = cookieArray[i];
			var keyAndValue = s.split(":");
			if (keyAndValue.length>1) {
				cookie[keyAndValue[0]]=keyAndValue[1];
			}
		}
		
		var config = {
			bi: "0",	
			basketItemsText: " items",
			bt: "00.00",
			//bp: "0", 
			//basketPointsText: " points",
			pi: "0",	
			prescriptionBasketItemsText: " prescriptions",
			pp: "0", 
			prescriptionBasketPointsText: " Advantage points"
		}
		
		var fields = {
			bi: document.getElementById("trolleyitems"),
			bt: document.getElementById("trolleyprice"),
			//bp: document.getElementById("trolleypoints"),
			pi: document.getElementById("presTrolleyItems"),
			pp: document.getElementById("presTrolleypoints")
		}
		
		// set values
		config.bi = cookie[cookieKeys.bi] || config.bi;
		config.bt = cookie[cookieKeys.bt] || config.bt;
		//config.bp = cookie[cookieKeys.bp] || config.bp;
		config.pi = cookie[cookieKeys.pi] || config.pi;
		config.pp = cookie[cookieKeys.pp] || config.pp;

		// set dom nodes
		if(fields.bi !== null) { fields.bi.innerHTML = config.bi + config.basketItemsText; }
		if(fields.bt !== null) { fields.bt.innerHTML = config.bt; }
		//if(fields.bp !== null) { fields.bp.innerHTML = config.bp + config.basketPointsText; }
		if(fields.pi !== null) { fields.pi.innerHTML = config.pi + config.prescriptionBasketItemsText; }
		if(fields.pp !== null) { fields.pp.innerHTML = config.pp + config.prescriptionBasketPointsText; }
		
	});
});

salmon.namespace.addNamespace("boots.Header");
$(document).ready(function(){
	boots.Header = new (function() {
		var personalMessage = $("div#userPersonalisation p.welcome")[0];
		if(personalMessage == null) {
			return;
		}
		var config = {
			preText: "Welcome back ",
			firstName: "guest"
		}
		var cookieStr = unescape(boots.common.cookie.getCookie("DISPLAYNAME")) || config.firstName;
		cookieStr = cookieStr.replace(/\+/g, " ");
		config.firstName = cookieStr;
		personalMessage.innerHTML = config.preText + config.firstName;
	});
});

salmon.namespace.addNamespace("boots.signOutLink");
$(document).ready(function(){ 
	boots.signOutLink = new (function(){
		var URLPrefix = "&URL=";
		var link = $("a.signOutLink")[0];
		if(link == null) {
			return;
		}
		var oldUrl = getURL();
		if(oldUrl != "" && oldUrl != null)
		{
			link.href = link.href + URLPrefix + oldUrl;
		}
		
		
	
		function getURL() 
		{
			var homeUrl = "http://" + window.location.host;
			var homeUrlWithSlash = homeUrl + "/";
			var currLoc = window.location;
			var URL = "";

			if(currLoc != homeUrl && currLoc !=  homeUrlWithSlash)
			{
				URL = URL + currLoc;	
			}
			URL = filterUrl(URL,'cm_re');
			URL = filterUrl(URL,'cm_sp');

			URL = encodeURIComponent(URL.substring(URL.indexOf("/webapp"), URL.length));
			return URL;
		}
		function filterUrl(url,param) {
			var newUrl = url;
			var firstParam = false;
			try {
				var startIndex =  url.indexOf('&'+param);
				if (startIndex == -1 ) {
					startIndex =  url.indexOf('?'+param);
					if (startIndex != -1 ) {
						startIndex=startIndex+1;
						firstParam = true;
					}
				}
				if (startIndex != -1 ) { 
							var endIndex =  url.indexOf('&',startIndex+param.length);
							
							if (endIndex != -1 ) {
								if (firstParam) {
									endIndex=endIndex+1;
								}
								newUrl = url.substring(0,startIndex)+url.substring(endIndex,url.length);					
							} else {
								newUrl = url.substring(0,startIndex);
							}
				}
			} catch (err) {}
			return newUrl;		
		}
		
	});
});

/* 
 * boots.BrandRoomHeader.js
 */
salmon.namespace.addNamespace("boots.BrandRoomHeader");
$(document).ready(function(){ 
	boots.BrandRoomHeader = new (function() {
		var brandRoomList = document.getElementById("brandroomheaderlist");
		if(brandRoomList === null) {
			return;
		}
		
		var cookieKeys = {bi: "bi",bt: "bt",bp: "bp",pi: "pi",pp: "pp"}
		
		var cookie = {};
		var cookieRawString = unescape(boots.common.cookie.getCookie("_bdccookie_bsktSumm"));
		cookieRawString = cookieRawString.replace("{", "");
		cookieRawString = cookieRawString.replace("}", "");
		var cookieArray = cookieRawString.split(",");
		for (var i=0; i<cookieArray.length; i++) {
			var s = cookieArray[i];
			var keyAndValue = s.split(":");
			if (keyAndValue.length>1) {
				cookie[keyAndValue[0]]=keyAndValue[1];
			}
		}
		
		var config = {
			bi: "0",	
			basketItemsText: " items",
			bt: "00.00",
			bp: "0", 
			basketPointsText: " points",
			pi: "0",	
			prescriptionBasketItemsText: " prescriptions",
			pp: "0", 
			prescriptionBasketPointsText: " Advantage points"
		}
		
		// set values
		config.bi = cookie[cookieKeys.bi] || config.bi;
		config.bt = cookie[cookieKeys.bt] || config.bt;
		config.bp = cookie[cookieKeys.bp] || config.bp;
		config.pi = cookie[cookieKeys.pi] || config.pi;
		config.pp = cookie[cookieKeys.pp] || config.pp;		

		var paramString = "&bi=";
		paramString += escape(config.bi);
		paramString += "&bt="; 
		paramString += escape(config.bt);
		paramString += "&bp="; 
		paramString += escape(config.bp);
		paramString += "&pi="; 
		paramString += escape(config.pi);
		paramString += "&pp=";
		paramString += escape(config.pp);

		var anchors = brandRoomList.getElementsByTagName("a");
		for(var i=0; i < anchors.length; i++) {
			anchors[i].href += paramString;
		}
		
	});
});
		

/* 
 * boots.multiAddToBasketFormatting.js
 */
boots.multiAddToBasketFormatting = {
	init:function(){
		$("div.featuredProductMulti").each(function(){
			ratingsHeight= 0;
			$(this).find("p.rating").each(function(){
				ratingsHeight += $(this).text().length;
			});
			$(this).find("p.beFirst").each(function(){
				ratingsHeight += $(this).text().length;
			});
			if(ratingsHeight<20){
				$(this).find("p.rating").css({height:"1px",overflow:"hidden"});
                $(this).find("p.beFirst").css({height:"1px",overflow:"hidden"});
			}
			maxHeight = 0;
			$(this).find("div.productItemMiniAddToBasket").each(function(){
				myHeight = $(this).height();
				maxHeight = (myHeight>maxHeight) ? myHeight : maxHeight;
			});
			$(this).find("div.productItemMiniAddToBasket").each(function(){
				myHeight = $(this).height();
				if(myHeight<maxHeight){
					$(this).find(".price").css({marginTop:(maxHeight-myHeight)+"px"});
				}
			});
		});
	}
};
$(document).ready(function(){
	boots.multiAddToBasketFormatting.init();
});

/* 
 * boots.pluck.rewriteurls.js
 */
var rewriteUrlCount = 0;
var amIDoingARequest = false;

if(typeof hasPluckComponent == 'undefined' || hasPluckComponent == null){
	hasPluckComponent = false;
}

function rewriteUrls(){
    var urlAttributes = {}
	var queryString = window.location.search.substring(1);
	var params = queryString.split('&');
	for (var i=0; i<params.length; i++) {
		var position = params[i].indexOf('=');
		if (position > 0) {
			var key = params[i].substring(0,position);
			var val = params[i].substring(position+1);
			if(key=="storeId"){
			    urlAttributes.storeId = val;
			} else if(key=="langId"){
			    urlAttributes.langId = val;
			} else if (key == "catalogId"){
			    urlAttributes.catalogId = val;
			} else if (key == "categoryId"){
			    urlAttributes.categoryId = val;
			} else if (key == "categoryParentId"){
			    urlAttributes.categoryParentId = val;
			} else if (key == "productId"){
			    urlAttributes.productId = val;
			}
		}
	}
	$(".PluckCMS a,.topFivePluck a").each(function(){
		var thisHref = $(this).attr("href");

		if (!(thisHref.indexOf("javascript")<0) || !(thisHref.indexOf("mailto")<0)){
		 // don't update links if in a calendar
		} else	{			
			hasStoreId = false;
		    hasLangId = false;
		    hasCatalogId = false;
		    hasCategoryId = false;
		    hasCategoryParentId = false;
		    hasProductId = false;
		    var linkPath = $(this).attr("href");
		    if(linkPath !== undefined){
				var queryString = linkPath.substring(linkPath.indexOf("?")+1);
				hasQueryString = linkPath.indexOf("?");
				var params = queryString.split('&');
				for (var i=0; i<params.length; i++) {
					var position = params[i].indexOf('=');
					if (position > 0) {
						var key = params[i].substring(0,position);
						var val = params[i].substring(position+1);
						if(key=="storeId"){
						    hasStoreId = true;
						} else if(key=="langId"){
						    hasLangId = true;
						} else if (key == "catalogId"){
						    hasCatalogId = true;
						} else if (key == "categoryId"){
						    hasCategoryId = true;
						} else if (key == "categoryParentId"){
						    hasCategoryParentId = true;
						} else if (key == "productId"){
						    hasProductId = true;
						}
					}
				}
				var isFirst = false;
				function isItFirst(){
				    if(isFirst){
				        isFirst = false;
				    } else {
				        linkPath += "&";
				    }
				}
				if(hasQueryString<0){
				    linkPath += "?";
				    isFirst = true;
				}
				if(!hasStoreId && (urlAttributes.storeId !== undefined)){
				    isItFirst();
				    linkPath += "storeId="+urlAttributes.storeId;
				}
				if(!hasLangId && (urlAttributes.langId !== undefined)){
				    isItFirst();
				    linkPath += "langId="+urlAttributes.langId;
				}
				if(!hasCatalogId && (urlAttributes.catalogId !== undefined)){
				    isItFirst();
				    linkPath += "catalogId="+urlAttributes.catalogId;
				}
				if(!hasCategoryId && (urlAttributes.categoryId !== undefined)){
				    isItFirst();
				    linkPath += "categoryId="+urlAttributes.categoryId;
				}
				if(!hasCategoryParentId && (urlAttributes.categoryParentId !== undefined)){
				    isItFirst();
				    linkPath += "categoryParentId="+urlAttributes.categoryParentId;
				}
				if(!hasProductId && (urlAttributes.productId !== undefined)){
				    isItFirst();
				    linkPath += "productId="+urlAttributes.productId;
				}
				//console.log(linkPath);
				linkPath = linkPath.replace(/\/\/webapp/g,"\/webapp");
				//console.log(linkPath);
				$(this).attr({href:linkPath});
				}
			}
		});
		rewriteUrlCount++;
		if(rewriteUrlCount<15){
			window.setTimeout(isPluckLoaded,1000)
		} else {
			addStyles();
		}
	
}
function trimUserNames(){
	var allUserNames = $(".slComments .slUserInfo .slUserName," + 
		".slGroupDiscussionPosts .slUserInfo .slUserName," + 
		".slGroupBlogPosts .slUserInfo .slUserName");
	
	var maxItems = allUserNames.length;
	for(var i=0; i<maxItems; i++){
		var tempText = allUserNames[i].innerHTML;
		if(tempText.length >16){
			allUserNames[i].innerHTML = tempText.substring(0,16);
		}
	}
}
function addStyles(){
	$(".PersonaHeader_PublicContent a:first").addClass("leaveMe");
	$(".PersonaHeader_PublicContent a:last").addClass("addMe");
}
function isPluckLoaded(){
	var PluckCMSText = $(".PluckCMS").text();
	var pluckText = $("#slGroupLanding").text();
	var pluckPanelText = $(".topFivePluck div ul").text();
	if((pluckText.length+pluckPanelText.length+PluckCMSText.length) <= 0){
		window.setTimeout(isPluckLoaded,1000)
	} else {
		rewriteUrls();
		trimUserNames();
	}
}

if(window['boots.pluck.rewriteurls.loaded'] != true){
	window['boots.pluck.rewriteurls.loaded'] = true;
	$(document).ready(function(){
		if(hasPluckComponent){
			isPluckLoaded();
		}
	});
}


/* 
 * boots.cobrand.js
 */
$(document).ready(function(){ 
		var cookieName = "MDURL";			
		
		var cookieStr = unescape(boots.common.cookie.getCookie(cookieName));

		if ((typeof cookieStr != "undefined") && (cookieStr != "undefined") && (cookieStr != "")){
			$("#webMDHeader").show();
			$("#webMDFooter").show();
			$("#webMDHeaderAnchor").attr("href", cookieStr);
			$("#webMDFooterAnchor").attr("href", cookieStr);
		}
});


/* 
 * boots.coremetrics.js
 */
salmon.namespace.addNamespace("boots.coremetrics");
boots.coremetrics = {
	pageViewTag: function(event){
		if(boots.coremetrics.enabled) {
			cmCreatePageviewTag(boots.coremetrics.pageName + ": " + event, boots.coremetrics.category, null, null, boots.coremetrics.storeId);
		}
	}
}

$(document).ready(function(){ 
		var cookieName = "CM_REG_CONV";	
		
		var cookieStr = unescape(boots.common.cookie.getCookie(cookieName));
		
		if ((typeof cookieStr != "undefined") && (cookieStr != "undefined") && (cookieStr != "")){
			var convParms = cookieStr.split("|");
			
			//replace the '+' symbols with a space
			var strTarget = '+';
			var strSubString = ' '; 
			var strText = convParms[0];
			
			var intIndexOfMatch = strText.indexOf( strTarget );
			  
			// Keep looping while an instance of the target string
			// still exists in the string.
			while (intIndexOfMatch != -1){
				// Relace out the current instance.
				strText = strText.replace( strTarget, strSubString )
			  
				// Get the index of any next matching substring.
				intIndexOfMatch = strText.indexOf( strTarget );
			}
			
			// cmCreateConversionEventTag is defined in cmdatatagutils.js
			// but I can not find any place that referes to cmdatatagutils.js. Maybe this is caused by running cormettrics disabled?
			if(typeof cmCreateConversionEventTag != 'undefined'){
				cmCreateConversionEventTag(strText, convParms[1], convParms[2]);
			}
			
			boots.common.cookie.removeCookie(cookieName);
		}
});

$(document).ready(function(){ 
		var cookieName = "CM_REG";	
		
		var cookieStr = unescape(boots.common.cookie.getCookie(cookieName));
		
		if ((typeof cookieStr != "undefined") && (cookieStr != "undefined") && (cookieStr != "")){
			var convParms = cookieStr.split("|");
			// cmCreateRegistrationTag is defined in cmdatatagutils.js
			// but I can not find any place that referes to cmdatatagutils.js. Maybe this is caused by running cormettrics disabled?
			
			if(typeof cmCreateRegistrationTag != 'undefined'){
				cmCreateRegistrationTag(convParms[0] == "null" ? null : convParms[0], 
					convParms[1] == "null" ? null : convParms[1], 
					convParms[2] == "null" ? null : convParms[2], 
					convParms[3] == "null" ? null : convParms[3], 
					convParms[4] == "null" ? null : convParms[4], 
					convParms[5] == "null" ? null : convParms[5], 
					convParms[6] == "null" ? null : convParms[6], 
					convParms[7] == "null" ? null : convParms[7], 
					convParms[8] == "null" ? null : convParms[8], 
					convParms[9] == "null" ? null : convParms[9], 
					convParms[10] == "null" ? null : convParms[10], 
					convParms[11] == "null" ? null : convParms[11], 
					convParms[12] == "null" ? null : convParms[12], 
					convParms[13] == "null" ? null : convParms[13], 
					convParms[14] == "null" ? null : convParms[14], 
					convParms[15] == "null" ? null : convParms[15], 
					convParms[16] == "null" ? null : convParms[16], 
					convParms[17] == "null" ? null : convParms[17], 
					convParms[18] == "null" ? null : convParms[18], 
					convParms[19] == "null" ? null : convParms[19]);
			}
			
		    boots.common.cookie.removeCookie(cookieName);
		}
});

