/* combine : /javascript/common/responsive/remodal.js*/
/*
 *  Remodal - v1.1.0
 *  Responsive, lightweight, fast, synchronized with CSS animations, fully customizable modal window plugin with declarative configuration and hash tracking.
 *  http://vodkabears.github.io/remodal/
 *
 *  Made by Ilya Makarov
 *  Under MIT License
 */

!(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], function($) {
      return factory(root, $);
    });
  } else if (typeof exports === 'object') {
    factory(root, require('jquery'));
  } else {
    factory(root, root.jQuery || root.Zepto);
  }
})(this, function(global, $) {

  'use strict';

  /**
   * Name of the plugin
   * @private
   * @const
   * @type {String}
   */
  var PLUGIN_NAME = 'remodal';

  /**
   * Namespace for CSS and events
   * @private
   * @const
   * @type {String}
   */
  var NAMESPACE = global.REMODAL_GLOBALS && global.REMODAL_GLOBALS.NAMESPACE || PLUGIN_NAME;

  /**
   * Animationstart event with vendor prefixes
   * @private
   * @const
   * @type {String}
   */
  var ANIMATIONSTART_EVENTS = $.map(
    ['animationstart', 'webkitAnimationStart', 'MSAnimationStart', 'oAnimationStart'],

    function(eventName) {
      return eventName + '.' + NAMESPACE;
    }

  ).join(' ');

  /**
   * Animationend event with vendor prefixes
   * @private
   * @const
   * @type {String}
   */
  var ANIMATIONEND_EVENTS = $.map(
    ['animationend', 'webkitAnimationEnd', 'MSAnimationEnd', 'oAnimationEnd'],

    function(eventName) {
      return eventName + '.' + NAMESPACE;
    }

  ).join(' ');

  /**
   * Default settings
   * @private
   * @const
   * @type {Object}
   */
  var DEFAULTS = $.extend({
    hashTracking: false,
    closeOnConfirm: true,
    closeOnCancel: true,
    closeOnEscape: true,
    closeOnOutsideClick: true,
    modifier: '',
    appendTo: null
  }, global.REMODAL_GLOBALS && global.REMODAL_GLOBALS.DEFAULTS);

  /**
   * States of the Remodal
   * @private
   * @const
   * @enum {String}
   */
  var STATES = {
    CLOSING: 'closing',
    CLOSED: 'closed',
    OPENING: 'opening',
    OPENED: 'opened'
  };

  /**
   * Reasons of the state change.
   * @private
   * @const
   * @enum {String}
   */
  var STATE_CHANGE_REASONS = {
    CONFIRMATION: 'confirmation',
    CANCELLATION: 'cancellation'
  };

  /**
   * Is animation supported?
   * @private
   * @const
   * @type {Boolean}
   */
  var IS_ANIMATION = (function() {
    var style = document.createElement('div').style;

    return style.animationName !== undefined ||
      style.WebkitAnimationName !== undefined ||
      style.MozAnimationName !== undefined ||
      style.msAnimationName !== undefined ||
      style.OAnimationName !== undefined;
  })();

  /**
   * Is iOS?
   * @private
   * @const
   * @type {Boolean}
   */
  var IS_IOS = /iPad|iPhone|iPod/.test(navigator.platform);

  /**
   * Current modal
   * @private
   * @type {Remodal}
   */
  var current;

  /**
   * Scrollbar position
   * @private
   * @type {Number}
   */
  var scrollTop;

  /**
   * Returns an animation duration
   * @private
   * @param {jQuery} $elem
   * @returns {Number}
   */
  function getAnimationDuration($elem) {
    if (
      IS_ANIMATION &&
      $elem.css('animation-name') === 'none' &&
      $elem.css('-webkit-animation-name') === 'none' &&
      $elem.css('-moz-animation-name') === 'none' &&
      $elem.css('-o-animation-name') === 'none' &&
      $elem.css('-ms-animation-name') === 'none'
    ) {
      return 0;
    }

    var duration = $elem.css('animation-duration') ||
      $elem.css('-webkit-animation-duration') ||
      $elem.css('-moz-animation-duration') ||
      $elem.css('-o-animation-duration') ||
      $elem.css('-ms-animation-duration') ||
      '0s';

    var delay = $elem.css('animation-delay') ||
      $elem.css('-webkit-animation-delay') ||
      $elem.css('-moz-animation-delay') ||
      $elem.css('-o-animation-delay') ||
      $elem.css('-ms-animation-delay') ||
      '0s';

    var iterationCount = $elem.css('animation-iteration-count') ||
      $elem.css('-webkit-animation-iteration-count') ||
      $elem.css('-moz-animation-iteration-count') ||
      $elem.css('-o-animation-iteration-count') ||
      $elem.css('-ms-animation-iteration-count') ||
      '1';

    var max;
    var len;
    var num;
    var i;

    duration = duration.split(', ');
    delay = delay.split(', ');
    iterationCount = iterationCount.split(', ');

    // The 'duration' size is the same as the 'delay' size
    for (i = 0, len = duration.length, max = Number.NEGATIVE_INFINITY; i < len; i++) {
      num = parseFloat(duration[i]) * parseInt(iterationCount[i], 10) + parseFloat(delay[i]);

      if (num > max) {
        max = num;
      }
    }

    return max;
  }

  /**
   * Returns a scrollbar width
   * @private
   * @returns {Number}
   */
  function getScrollbarWidth() {
    if ($(document.body).height() <= $(window).height()) {
      return 0;
    }

    var outer = document.createElement('div');
    var inner = document.createElement('div');
    var widthNoScroll;
    var widthWithScroll;

    outer.style.visibility = 'hidden';
    outer.style.width = '100px';
    document.body.appendChild(outer);

    widthNoScroll = outer.offsetWidth;

    // Force scrollbars
    outer.style.overflow = 'scroll';

    // Add inner div
    inner.style.width = '100%';
    outer.appendChild(inner);

    widthWithScroll = inner.offsetWidth;

    // Remove divs
    outer.parentNode.removeChild(outer);

    return widthNoScroll - widthWithScroll;
  }

  /**
   * Locks the screen
   * @private
   */
  function lockScreen() {
    if (IS_IOS) {
      return;
    }

    var $html = $('html');
    var lockedClass = namespacify('is-locked');
    var paddingRight;
    var $body;

    if (!$html.hasClass(lockedClass)) {
      $body = $(document.body);

      // Zepto does not support '-=', '+=' in the `css` method
      paddingRight = parseInt($body.css('padding-right'), 10) + getScrollbarWidth();

      $body.css('padding-right', paddingRight + 'px');
      $html.addClass(lockedClass);
    }
  }

  /**
   * Unlocks the screen
   * @private
   */
  function unlockScreen() {
    if (IS_IOS) {
      return;
    }

    var $html = $('html');
    var lockedClass = namespacify('is-locked');
    var paddingRight;
    var $body;

    if ($html.hasClass(lockedClass)) {
      $body = $(document.body);

      // Zepto does not support '-=', '+=' in the `css` method
      paddingRight = parseInt($body.css('padding-right'), 10) - getScrollbarWidth();

      $body.css('padding-right', paddingRight + 'px');
      $html.removeClass(lockedClass);
    }
  }

  /**
   * Sets a state for an instance
   * @private
   * @param {Remodal} instance
   * @param {STATES} state
   * @param {Boolean} isSilent If true, Remodal does not trigger events
   * @param {String} Reason of a state change.
   */
  function setState(instance, state, isSilent, reason) {

    var newState = namespacify('is', state);
    var allStates = [namespacify('is', STATES.CLOSING),
                     namespacify('is', STATES.OPENING),
                     namespacify('is', STATES.CLOSED),
                     namespacify('is', STATES.OPENED)].join(' ');

    instance.$bg
      .removeClass(allStates)
      .addClass(newState);

    instance.$overlay
      .removeClass(allStates)
      .addClass(newState);

    instance.$wrapper
      .removeClass(allStates)
      .addClass(newState);

    instance.$modal
      .removeClass(allStates)
      .addClass(newState);

    instance.state = state;
    !isSilent && instance.$modal.trigger({
      type: state,
      reason: reason
    }, [{ reason: reason }]);
  }

  /**
   * Synchronizes with the animation
   * @param {Function} doBeforeAnimation
   * @param {Function} doAfterAnimation
   * @param {Remodal} instance
   */
  function syncWithAnimation(doBeforeAnimation, doAfterAnimation, instance) {
    var runningAnimationsCount = 0;

    var handleAnimationStart = function(e) {
      if (e.target !== this) {
        return;
      }

      runningAnimationsCount++;
    };

    var handleAnimationEnd = function(e) {
      if (e.target !== this) {
        return;
      }

      if (--runningAnimationsCount === 0) {

        // Remove event listeners
        $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
          instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS);
        });

        doAfterAnimation();
      }
    };

    $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
      instance[elemName]
        .on(ANIMATIONSTART_EVENTS, handleAnimationStart)
        .on(ANIMATIONEND_EVENTS, handleAnimationEnd);
    });

    doBeforeAnimation();

    // If the animation is not supported by a browser or its duration is 0
    if (
      getAnimationDuration(instance.$bg) === 0 &&
      getAnimationDuration(instance.$overlay) === 0 &&
      getAnimationDuration(instance.$wrapper) === 0 &&
      getAnimationDuration(instance.$modal) === 0
    ) {

      // Remove event listeners
      $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
        instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS);
      });

      doAfterAnimation();
    }
  }

  /**
   * Closes immediately
   * @private
   * @param {Remodal} instance
   */
  function halt(instance) {
    if (instance.state === STATES.CLOSED) {
      return;
    }

    $.each(['$bg', '$overlay', '$wrapper', '$modal'], function(index, elemName) {
      instance[elemName].off(ANIMATIONSTART_EVENTS + ' ' + ANIMATIONEND_EVENTS);
    });

    instance.$bg.removeClass(instance.settings.modifier);
    instance.$overlay.removeClass(instance.settings.modifier).hide();
    instance.$wrapper.hide();
    unlockScreen();
    setState(instance, STATES.CLOSED, true);
  }

  /**
   * Parses a string with options
   * @private
   * @param str
   * @returns {Object}
   */
  function parseOptions(str) {
    var obj = {};
    var arr;
    var len;
    var val;
    var i;

    // Remove spaces before and after delimiters
    str = str.replace(/\s*:\s*/g, ':').replace(/\s*,\s*/g, ',');

    // Parse a string
    arr = str.split(',');
    for (i = 0, len = arr.length; i < len; i++) {
      arr[i] = arr[i].split(':');
      val = arr[i][1];

      // Convert a string value if it is like a boolean
      if (typeof val === 'string' || val instanceof String) {
        val = val === 'true' || (val === 'false' ? false : val);
      }

      // Convert a string value if it is like a number
      if (typeof val === 'string' || val instanceof String) {
        val = !isNaN(val) ? +val : val;
      }

      obj[arr[i][0]] = val;
    }

    return obj;
  }

  /**
   * Generates a string separated by dashes and prefixed with NAMESPACE
   * @private
   * @param {...String}
   * @returns {String}
   */
  function namespacify() {
    var result = NAMESPACE;

    for (var i = 0; i < arguments.length; ++i) {
      result += '-' + arguments[i];
    }

    return result;
  }

  /**
   * Handles the hashchange event
   * @private
   * @listens hashchange
   */
  function handleHashChangeEvent() {
    var id = location.hash.replace('#', '');
    var instance;
    var $elem;

    if (!id) {

      // Check if we have currently opened modal and animation was completed
      if (current && current.state === STATES.OPENED && current.settings.hashTracking) {
        current.close();
      }
    } else {

      // Catch syntax error if your hash is bad
      try {
        $elem = $(
          '[data-' + PLUGIN_NAME + '-id="' + id + '"]'
        );
      } catch (err) {}

      if ($elem && $elem.length) {
        instance = $[PLUGIN_NAME].lookup[$elem.data(PLUGIN_NAME)];

        if (instance && instance.settings.hashTracking) {
          instance.open();
        }
      }

    }
  }

  /**
   * Remodal constructor
   * @constructor
   * @param {jQuery} $modal
   * @param {Object} options
   */
  function Remodal($modal, options) {
    var $body = $(document.body);
    var $appendTo = $body;
    var remodal = this;

    remodal.settings = $.extend({}, DEFAULTS, options);
    remodal.index = $[PLUGIN_NAME].lookup.push(remodal) - 1;
    remodal.state = STATES.CLOSED;

    remodal.$overlay = $('.' + namespacify('overlay'));

    if (remodal.settings.appendTo !== null && remodal.settings.appendTo.length) {
      $appendTo = $(remodal.settings.appendTo);
    }

    if (!remodal.$overlay.length) {
      remodal.$overlay = $('<div>').addClass(namespacify('overlay') + ' ' + namespacify('is', STATES.CLOSED)).hide();
      $appendTo.append(remodal.$overlay);
    }

    remodal.$bg = $('.' + namespacify('bg')).addClass(namespacify('is', STATES.CLOSED));

    remodal.$modal = $modal
      .addClass(
        NAMESPACE + ' ' +
        namespacify('is-initialized') + ' ' +
        remodal.settings.modifier + ' ' +
        namespacify('is', STATES.CLOSED))
      .attr('tabindex', '-1');

    remodal.$wrapper = $('<div>')
      .addClass(
        namespacify('wrapper') + ' ' +
        remodal.settings.modifier + ' ' +
        namespacify('is', STATES.CLOSED))
      .hide()
      .append(remodal.$modal);
    $appendTo.append(remodal.$wrapper);

    // Add the event listener for the close button
    remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="close"]', function(e) {
      e.preventDefault();

      remodal.close();
    });

    // Add the event listener for the cancel button
    remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="cancel"]', function(e) {
      e.preventDefault();

      remodal.$modal.trigger(STATE_CHANGE_REASONS.CANCELLATION);

      if (remodal.settings.closeOnCancel) {
        remodal.close(STATE_CHANGE_REASONS.CANCELLATION);
      }
    });

    // Add the event listener for the confirm button
    remodal.$wrapper.on('click.' + NAMESPACE, '[data-' + PLUGIN_NAME + '-action="confirm"]', function(e) {
      e.preventDefault();

      remodal.$modal.trigger(STATE_CHANGE_REASONS.CONFIRMATION);

      if (remodal.settings.closeOnConfirm) {
        remodal.close(STATE_CHANGE_REASONS.CONFIRMATION);
      }
    });

    // Add the event listener for the overlay
    remodal.$wrapper.on('click.' + NAMESPACE, function(e) {
      var $target = $(e.target);

      if (!$target.hasClass(namespacify('wrapper'))) {
        return;
      }

      if (remodal.settings.closeOnOutsideClick) {
        remodal.close();
      }
    });
  }

  /**
   * Opens a modal window
   * @public
   */
  Remodal.prototype.open = function() {
    var remodal = this;
    var id;

    // Check if the animation was completed
    if (remodal.state === STATES.OPENING || remodal.state === STATES.CLOSING) {
      return;
    }

    id = remodal.$modal.attr('data-' + PLUGIN_NAME + '-id');

    if (id && remodal.settings.hashTracking) {
      scrollTop = $(window).scrollTop();
      location.hash = id;
    }

    if (current && current !== remodal) {
      halt(current);
    }

    current = remodal;
    lockScreen();
    remodal.$bg.addClass(remodal.settings.modifier);
    remodal.$overlay.addClass(remodal.settings.modifier).show();
    remodal.$wrapper.show().scrollTop(0);
    remodal.$modal.focus();

    syncWithAnimation(
      function() {
        setState(remodal, STATES.OPENING);
      },

      function() {
        setState(remodal, STATES.OPENED);
      },

      remodal);
  };

  /**
   * Closes a modal window
   * @public
   * @param {String} reason
   */
  Remodal.prototype.close = function(reason) {
    var remodal = this;

    // Check if the animation was completed
    if (remodal.state === STATES.OPENING || remodal.state === STATES.CLOSING) {
      return;
    }

    if (
      remodal.settings.hashTracking &&
      remodal.$modal.attr('data-' + PLUGIN_NAME + '-id') === location.hash.substr(1)
    ) {
      location.hash = '';
      $(window).scrollTop(scrollTop);
    }

    syncWithAnimation(
      function() {
        setState(remodal, STATES.CLOSING, false, reason);
      },

      function() {
        remodal.$bg.removeClass(remodal.settings.modifier);
        remodal.$overlay.removeClass(remodal.settings.modifier).hide();
        remodal.$wrapper.hide();
        unlockScreen();

        setState(remodal, STATES.CLOSED, false, reason);
      },

      remodal);
  };

  /**
   * Returns a current state of a modal
   * @public
   * @returns {STATES}
   */
  Remodal.prototype.getState = function() {
    return this.state;
  };

  /**
   * Destroys a modal
   * @public
   */
  Remodal.prototype.destroy = function() {
    var lookup = $[PLUGIN_NAME].lookup;
    var instanceCount;

    halt(this);
    this.$wrapper.remove();

    delete lookup[this.index];
    instanceCount = $.grep(lookup, function(instance) {
      return !!instance;
    }).length;

    if (instanceCount === 0) {
      this.$overlay.remove();
      this.$bg.removeClass(
        namespacify('is', STATES.CLOSING) + ' ' +
        namespacify('is', STATES.OPENING) + ' ' +
        namespacify('is', STATES.CLOSED) + ' ' +
        namespacify('is', STATES.OPENED));
    }
  };

  /**
   * Special plugin object for instances
   * @public
   * @type {Object}
   */
  $[PLUGIN_NAME] = {
    lookup: []
  };

  /**
   * Plugin constructor
   * @constructor
   * @param {Object} options
   * @returns {JQuery}
   */
  $.fn[PLUGIN_NAME] = function(opts) {
    var instance;
    var $elem;

    this.each(function(index, elem) {
      $elem = $(elem);

      if ($elem.data(PLUGIN_NAME) == null) {
        instance = new Remodal($elem, opts);
        $elem.data(PLUGIN_NAME, instance.index);

        if (
          instance.settings.hashTracking &&
          $elem.attr('data-' + PLUGIN_NAME + '-id') === location.hash.substr(1)
        ) {
          instance.open();
        }
      } else {
        instance = $[PLUGIN_NAME].lookup[$elem.data(PLUGIN_NAME)];
      }
    });

    return instance;
  };

  $(document).ready(function() {

    // data-remodal-target opens a modal window with the special Id
    $(document).on('click', '[data-' + PLUGIN_NAME + '-target]', function(e) {
      e.preventDefault();

      var elem = e.currentTarget;
      var id = elem.getAttribute('data-' + PLUGIN_NAME + '-target');
      var $target = $('[data-' + PLUGIN_NAME + '-id="' + id + '"]');

      $[PLUGIN_NAME].lookup[$target.data(PLUGIN_NAME)].open();
    });

    // Auto initialization of modal windows
    // They should have the 'remodal' class attribute
    // Also you can write the `data-remodal-options` attribute to pass params into the modal
    $(document).find('.' + NAMESPACE).each(function(i, container) {
      var $container = $(container);
      var options = $container.data(PLUGIN_NAME + '-options');

      if (!options) {
        options = {};
      } else if (typeof options === 'string' || options instanceof String) {
        options = parseOptions(options);
      }

      $container[PLUGIN_NAME](options);
    });

    // Handles the keydown event
    $(document).on('keydown.' + NAMESPACE, function(e) {
      if (current && current.settings.closeOnEscape && current.state === STATES.OPENED && e.keyCode === 27) {
        current.close();
      }
    });

    // Handles the hashchange event
    $(window).on('hashchange.' + NAMESPACE, handleHashChangeEvent);
  });
});
/* complete : /javascript/common/responsive/remodal.js*/


/* combine : /javascript/desktop/viewbag/viewbag.js*/
var jdw = jdw || {};
document.onkeypress = keyPress;
function keyPress() {
	if (window.event.keyCode == 13)
	{
   	 event.returnValue=false;
     event.cancel = true;
	}
}

function onEnterUpdate(event, pT, sQ, bO, qty, csrfToken)
{
    if (event.keyCode==13 && dosubmit('#quantity1', 'Quantity'))
    {
        UpdateQuantity(pT, sQ, bO, qty, csrfToken);
    }
}

function UpdateQuantity(personalisation, lineitem, bo_uid, quantity, csrfRandomFormToken) {
   strUrl = '/shop/viewbag/UpdateItemQuantity.action';

   performAjaxRequest(strUrl,
			null,
			null,
			'json',
			'csrfRandomFormToken='+csrfRandomFormToken+'&personalisation='+encodeURIComponent(personalisation)+'&lineitem='+lineitem+'&bo_uid='+bo_uid+'&quantity='+quantity+'&validate=true',
			onSuccessUpdateQuantity, 
			onErrorUpdateQuantity, 
			'POST',
			null);
}

function onSuccessUpdateQuantity()
{
	window.location.href = '/shop/viewbag/ViewBag.action';
}

function onErrorUpdateQuantity(data)
{
	// This calls the generic error page.  
	// It may be an idea to have a specific error for this in the future.
	window.location.href = '/shop/util/errorAction.action';
}

function processClaimCode(claimcode, token) {
	claimcode = claimcode.replace(/\s*/g,"");
	if(isValid(claimcode)){
		if(document.claim_code_entry_form.loggedin.value=='true'){
			displayIncentivesModal(claimcode, token);
		}else{
			displaySignInModal(claimcode, document.claim_code_entry_form.modaltitle.value, document.claim_code_entry_form.modaltext.value);
		}
	}else{
	var html ='  <div id="basketHeading"> '+
    			'	<div class="commonBoxCurveContainer infoCurveBox"> '+
      			'	<div class="curveLT InfoCurveLT"></div> '+
      			'	<div class="curveRT InfoCurveRT"></div> '+
      			'	<div class="curveLB InfoCurveLB"></div> '+
      			'	<div class="curveRB InfoCurveRB"></div> '+
      			'	<p>Invalid promotional code. Please ensure your code contains 5 characters.</p> '+
    			'	</div> '+
  				' </div>';
    document.getElementById('claimmessageContainer').innerHTML = html;	
    window.scrollTo(0,0);
	}
}

// TODO : STD-207. 
// Requirements from WT-135 have meant the creation of warrantyModal.js. This file is included in the 
// head for all desktop & tablet pages and provides functionality to deliver a consistent warranty
// modal on all pages. It offers less functionality than provided here but is intended to be extended 
// to replace all disconnected, warranty modal related js files.

function displayModal(url, useRetainedRRRecs){
	var loc = '/shop/viewbag/ViewBag.action';
	if(useRetainedRRRecs) {
		loc += '?useRetainedRRRecs=true';
	}
	var options = {onClose: function() { window.location=loc; }, hideClose: false, disableClose: false};
	jdwModal.displayModalFromUrl(url, options);
}

function showWarrantiesModal(url, useRetainedRRRecs){
	var modalsContainer = jdw.modalsContainer;
	modalsContainer.hideWebToolkit();
	var options = {
		content: url,
		width: 850,
		height: 400,
		ajax: true,
		id: 'warrantiesModal',
		backButtonDisabled: true,
		fullHeight: 470,
		loadCompletedCallback: jdw.productDetailsWarranty.handleWarrantiesLoadCompletedCallback
	}
	if(typeof onCloseModal != 'undefined') {
		options.onClose = onCloseModal;
	}
	modalsContainer.showModal(options);

	// Adds class 'warrantiesContent' to the modal so specific styles for warranties can be applied without affecting any other modal layouts
	$( '#jdwModalBorder' ).addClass( 'warrantiesContent' );

	// Appends a div which has styles associated with it specifically for use with warranties
	$( '#jdwModalBorder' ).append( '<div class="option-shading"><div class="edge top"></div><div class="edge bottom"></div></div>' );

}


function displaySignInModal(claimcode, modalTitle, modalText){	   
	var html = '<div id="modalParam" title="'+modalTitle+'" width="350" height="100" overlayClose="true" style="display:none;"></div> '+
			'<div id="controls" style="display:none;"> '+
			'	<div class="modalButtonClose btn-new btn-grey" id="modalButtonLeft"> '+
			'		<div class="modalButton"> '+
			'			<a href="#" alt="Decline" title="Cancel">Cancel</a> '+
			'		</div> '+
			'	</div> '+
			'	<div class="modalButtonContinue btn-new btn-green"> '+
			'		<div class="modalButton"> '+
			'			<a href="/shop/viewbag/ViewBagLogin.action?claimcode='+claimcode+'" alt="Sign In" title="Sign In or Register">Sign In or Register</a> '+
			'		</div> '+
			'	</div> '+
			'</div>' + modalText;
			
	// display DIV in modal window	
	openModalJQ(html);
}

function displayAreYouSureDelete(viewbag, lineitem, modalTitle, modalText, warranty){	   
	var html = '<div id="modalParam" title="'+modalTitle+'" width="350" height="100" overlayClose="true" style="display:none;"></div> '+
			'<div id="controls" style="display:none;"> '+
			'	<div class="modalButtonClose" id="modalButtonLeft"> '+
			'		<div class="modalButton"> '+
			'			<div class="buttonCapLt"></div> '+
			'			<a href="#" alt="Decline" title="No">No</a> '+
			'			<div class="buttonCapRt"></div> '+
			'		</div> '+
			'	</div> '+
			'	<div class="modalButtonContinue"> '+
			'		<div class="modalButton"> '+
			'			<div class="buttonCapLt"></div> '+
			'			<a href="/shop/viewbag/RemoveItemViewBag.action?viewbag='+viewbag+'&lineitem='+lineitem+'&warranty='+warranty+'" alt="Yes" title="Yes">Yes</a> '+
			'			<div class="buttonCapRt"></div> '+
			'		</div> '+
			'	</div> '+
			'</div>' + modalText;
			
	// display DIV in modal window	
	openModalJQ(html);
}

function processWishListMove(loginStatus, params, modalTitle, modalText){
	if(loginStatus=='F' || loginStatus=='L'){
		strUrl = '/shop/viewbag/MoveToWishList.action?'+params;
   		window.location.href = strUrl;
	}else{
		displaySignInWishList(params, modalTitle, modalText);
	}
}

function displaySignInWishList(params, modalTitle, modalText){	   
	var html = '<div id="modalParam" title="'+modalTitle+'" width="350" height="100" overlayClose="true" style="display:none;"></div> '+
	' <div id="controls" style="display:none;"> '+
	'			<div class="modalButtonClose" id="modalButtonLeft"> '+
	'				<div class="modalButton"> '+
	'					<div class="buttonCapLt"></div> '+
	'					<a href="#" alt="Decline" title="No">No</a> '+
	'					<div class="buttonCapRt"></div> '+
	'				</div> '+
	'			</div> '+
	'			<div class="modalButtonContinue"> '+
	'				<div class="modalButton"> '+
	'					<div class="buttonCapLt"></div> '+
	'					<a href="/shop/viewbag/MoveToWishListLogin.action?'+params+'" alt="Yes" title="Yes">Yes</a> '+
	'					<div class="buttonCapRt"></div> '+
	'				</div> '+
	'			</div> '+
	'		</div>' + modalText;
			
	// display DIV in modal window	
	openModalJQ(html);
}

function linkClicked(text, titleId){
	MANUAL_LINK_CLICK(titleId + '-  SHOPPING BAG - '+text, titleId+' - YOUR SHOPPING BAG');
}

//Takes the Celebrus Session Id from the cookie and returns it.
function readSessionIdFromCookie() {
    var nameEQ = 'JDWuvt' + "=";
    var ca = document.cookie.split( ';');
    var results = ['',''];
    for( var i=0;i < ca.length;i++) {
    	var c = ca[i];
    	while ( c.charAt( 0)==' ') c = c.substring( 1,c.length);
    	if ( c.indexOf( nameEQ) == 0) {
    		var celebrusKeys = c.substring( nameEQ.length,c.length).split('_');
    		var sessionId = celebrusKeys[2];
    		var visitorId = celebrusKeys[0];
    		
            if (undefined != sessionId) {
          	   results[0] = sessionId;
            }
            
            if (undefined != visitorId) {
           	   results[1] = visitorId;
            }
    	}
    }
    
    return results;
}
/* complete : /javascript/desktop/viewbag/viewbag.js*/


/* combine : /javascript/desktop/wishlist/wishlist.js*/
function deleteWishList(url, modalTitle, modalText){	   
	var html = '<div id="modalParam" title="'+modalTitle+'" width="350" height="100" overlayClose="true" style="display:none;"></div> '+
			'<div id="controls" style="display:none;"> '+
			'	<div class="modalButtonClose" id="modalButtonLeft"> '+
			'		<div class="modalButton"> '+
			'			<div class="buttonCapLt"></div> '+
			'			<a href="#" alt="Decline" title="No">No</a> '+
			'			<div class="buttonCapRt"></div> '+
			'		</div> '+
			'	</div> '+
			'	<div class="modalButtonContinue"> '+
			'		<div class="modalButton"> '+
			'			<div class="buttonCapLt"></div> '+
			'			<a data-jdw-test-id="confirmRemoveFromWishList" href="'+url+'" alt="Yes" title="Yes">Yes</a> '+
			'			<div class="buttonCapRt"></div> '+
			'		</div> '+
			'	</div> '+
			'</div>' + modalText;
			
	// display DIV in modal window	
	openModalJQ(html);
}
/* complete : /javascript/desktop/wishlist/wishlist.js*/


/* combine : /javascript/common/incentives/incentives_modal.js*/
function displayIncentivesModal(claimcode, token){
	if(isValid(claimcode)){
		if(typeof(inRegistration) != 'undefined' &&  inRegistration) {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/registration/incentives/fragment/GetIncentives.action?viewBag=true&modal=true&claimcode='+claimcode + '&csrfRandomFormToken='+token, options);
		} else if(typeof(inCheckout) != 'undefined' &&  inCheckout) {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/checkout/incentives/fragment/GetIncentives.action?viewBag=true&modal=true&claimcode='+claimcode + '&csrfRandomFormToken='+token, options);
		} else {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/incentives/fragment/GetIncentives.action?viewBag=true&modal=true&claimcode='+claimcode + '&csrfRandomFormToken='+token, options);
		}
	} else {
		if(typeof(inRegistration) != 'undefined' && inRegistration) {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/registration/incentives/fragment/ClaimCodesView.action?modal=true&msg=true&csrfRandomFormToken='+token, options);
		} else if(typeof(inCheckout) != 'undefined' &&  inCheckout) {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/checkout/incentives/fragment/GetIncentives.action?viewBag=true&modal=true&claimcode='+claimcode + '&csrfRandomFormToken='+token, options);
		} else {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/incentives/fragment/ClaimCodesView.action?modal=true&msg=true&csrfRandomFormToken='+token, options);
		}
	}
}

function changePromotion(token){
	var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
	jdwModal.displayModalFromUrl('/shop/incentives/fragment/ClaimCodesView.action?viewBag=true&csrfRandomFormToken='+token+'&modal=true', options);
}

function submitIncentivesModal(claimcode, incentive_id, submissionType, seqN, token){
	if(typeof(inRegistration) != 'undefined' && inRegistration) {
		var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
		jdwModal.displayModalFromUrl('/shop/registration/incentives/fragment/SubmitClaimCodes.action?viewBag=true&modal=true&mtul=true&claimcode='+claimcode+'&incentiveId='+incentive_id+'&submissionType='+submissionType+'&seqN='+seqN+'&csrfRandomFormToken='+token, options);
	} else if(typeof(inCheckout) != 'undefined' && inCheckout) {
		var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
		jdwModal.displayModalFromUrl('/shop/checkout/incentives/fragment/SubmitClaimCodes.action?viewBag=true&modal=true&mtul=true&claimcode='+claimcode+'&incentiveId='+incentive_id+'&submissionType='+submissionType+'&seqN='+seqN+'&csrfRandomFormToken='+token, options);
	} else {
		var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
		jdwModal.displayModalFromUrl('/shop/incentives/fragment/SubmitClaimCodes.action?viewBag=true&modal=true&mtul=true&claimcode='+claimcode+'&incentiveId='+incentive_id+'&submissionType='+submissionType+'&seqN='+seqN+'&csrfRandomFormToken='+token, options);
	}
}

function submitIncentives(url){
	url = url.replace("/incentives/", "/incentives/fragment/");
	var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
	jdwModal.displayModalFromUrl(url+"&modal=true", options);
}

function getIncentivesModal(claimcode, token){
	if (validateClaimCode(claimcode)){
		if(typeof(inRegistration) != 'undefined' && inRegistration) {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/registration/incentives/fragment/GetIncentives.action?modal=true&claimcode='+claimcode+'&csrfRandomFormToken='+token, options);
		} else if(typeof(inCheckout) != 'undefined' && inCheckout) {
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/checkout/incentives/fragment/GetIncentives.action?viewBag=true&modal=true&claimcode='+claimcode+'&csrfRandomFormToken='+token, options);
		} else{
			var options = {onClose: function() { window.location='/shop/viewbag/ViewBag.action'; }, hideClose: true, disableClose: true};
			jdwModal.displayModalFromUrl('/shop/incentives/fragment/GetIncentives.action?viewBag=true&modal=true&claimcode='+claimcode+'&csrfRandomFormToken='+token, options);
		}	
	}
}

function add(_incentive_id, claim_code, token) {
    submitIncentivesModal(claim_code, _incentive_id, "add", "", token);
}

function remove(_incentive_id, claim_code, sequenceNumber, token) {
    submitIncentivesModal(claim_code, _incentive_id, "remove", sequenceNumber,token);
}

function removeSharingIncentiveId(_incentive_id, claim_code, sequenceNumber, token) {
    submitIncentivesModal(claim_code, _incentive_id, "removemult", sequenceNumber, token);
}

function clearMessage(){
   	document.getElementById('claimmessage').innerHTML = "";
}

function doManualLinkClick(link) {
	MANUAL_LINK_CLICK(link.href, link.name);
}/* complete : /javascript/common/incentives/incentives_modal.js*/


/* combine : /javascript/common/incentives/incentives_validate.js*/
function validateClaimCode(claimcode) {    
    if (!isValid(claimcode)) {
    	$('#promoAlertField').show();
        $('#claimmessage').html("Invalid promotional code.");
        return false;
    } else {
    	$('#promoAlertField').hide();
    	return true;
    }
}

function isValid(claimcode){
    claimcode = claimcode.replace(/\s*/g,"");   
    if ( isEmpty(claimcode) ) {
        return false;
    } else if (!isCorrectClaimCodeFormat(claimcode)) {
        return false;
    } else {
        return true;
    }
}

function isEmpty(s) {
    return ((s == null) || (s.length == 0))
}

function isCorrectClaimCodeFormat(claimcode) {
	var regexp = new RegExp("^[a-z0-9]{5}$", "i");
    return regexp.test(claimcode);
}/* complete : /javascript/common/incentives/incentives_validate.js*/


/* combine : /javascript/common/jdw_expdelivcountdown.js*/
/**
* Functions associated with delivery countdown timer used on view bag 
* & checkout pages.
*
* CVS Id: $Id: jdw_expdelivcountdown.js,v 1.1 2011/11/02 14:55:52 itmxc Exp $
* CVS Label: $Name:  $
*/

/**
* Functions handling display of countdown timer on pages using it
*/
function countdown(obj)
{
	this.obj			= obj;
	this.Div			= "countdown";
	this.TargetDate;
	this.Seconds;
	this.DisplayFormat	= "%%h%%hrs %%m%%m %%s%%s";
	this.CountActive	= true;	
	this.DisplayStr;
	this.Calculate		= cd_Calculate;
	this.CountBack		= cd_CountBack;
	this.StartDate		= cd_StartDate;
	this.StartSeconds	= cd_StartSeconds;

	if (typeof countdownExpired == 'function') {
		this.ExpiredFunct = countdownExpired;
	}
	else {
		this.ExpiredFunct = null;
	}
}

function cd_Calculate(secs, num1, num2, leadingzero)
{
  s = ((Math.floor(secs/num1))%num2).toString();
  if (s.length < 2 & leadingzero) s = "0" + s;
  return (s);
}

function cd_CountBack(secs)
{
  if(secs < 0){
	secs = 0;
	this.CountActive = false;
	if (this.ExpiredFunct != null) {
		setTimeout(this.obj + ".ExpiredFunct()", 100);
	}
	return false;
   }

  this.DisplayStr = this.DisplayFormat.replace(/%%h%%/g,	this.Calculate(secs,3600,24,false));
  this.DisplayStr = this.DisplayStr.replace(/%%m%%/g,		this.Calculate(secs,60,60,true));
  this.DisplayStr = this.DisplayStr.replace(/%%s%%/g,		this.Calculate(secs,1,60,true));

  document.getElementById(this.Div).innerHTML = this.DisplayStr;
  if (this.CountActive) setTimeout(this.obj +".CountBack(" + (secs-1) + ")", 990);

}
function cd_StartDate()
{
	var dt	= new Date(this.TargetDate);
  	var dn	= new Date();
	dd		= new Date(dt-dn);
	secs		= Math.floor(dd.valueOf()/1000);
	this.CountBack(secs);
}

function cd_StartSeconds()
{
	this.CountBack(this.Seconds);
}
/* complete : /javascript/common/jdw_expdelivcountdown.js*/


/* combine : /javascript/common/libraries/jquery/jquery.ba-dotimeout.min.js*/
/*
 * jQuery doTimeout: Like setTimeout, but better! - v0.4 - 7/15/2009
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var e=d.call(arguments),f=b.apply(this,[c+e[0]].concat(e));return typeof e[0]==="number"||typeof e[1]==="number"?this:f};function b(l){var m=this,h,k={},n=arguments,i=4,g=n[1],j=n[2],o=n[3];if(typeof g!=="string"){i--;g=l=0;j=n[1];o=n[2]}if(l){h=m.eq(0);h.data(l,k=h.data(l)||{})}else{if(g){k=a[g]||(a[g]={})}}k.id&&clearTimeout(k.id);delete k.id;function f(){if(l){h.removeData(l)}else{if(g){delete a[g]}}}function e(){k.id=setTimeout(function(){k.fn()},j)}if(o){k.fn=function(p){o.apply(m,d.call(n,i))&&!p?e():f()};e()}else{if(k.fn){j===undefined?f():k.fn(j===false);return true}else{f()}}}})(jQuery);/* complete : /javascript/common/libraries/jquery/jquery.ba-dotimeout.min.js*/


/* combine : /javascript/productDetailsRedesign/quickView/productDetailsOrderBuilding.js*/
/***********************************************************************************************
 * Order Building Javascript file. Defines the static data and functions as well as the event 
 * binding code required for the Order Building overlay functioaddToBagnality.  
 *
 ***********************************************************************************************/
 
/***********************************************************************************************
 * Static data and functions are all contained within the "oB" object, to avoid namespace 
 * conflicts. 
 ***********************************************************************************************/
var oB = {
	//debugMode: false, // If true, a hidden debug DIV is outputted within the overlay
	slots: [], // Associative array of slot objects indexed by the lpUid e.g. "CH660"
	viewMoreItem: null,
	addToBagMessages: {}, // Map of addStatusId:"message" key:value pairs e.g. 103:"Out Of Stock"
	// Add to bag status Ids. Nb These should correspond to the status Ids returned in the model by the add to bag AJAX action
	addStatus: {ADDED:101, OUT_OF_STOCK:103, TO_FOLLOW:104, INVALID_QUANTITY:105, INVALID_ADD:106}, 
	slotAdded: false,
	transitionDelay: 200,
	ovelayHeight: 0,
	overlayWidth: 0,
	noOfProducts: 0,
	modalFullWidth: 820,
	modalMediumWidth: 800,
	modalSmallWidth: 620,
	modalHeight:600,
	displayOverlay: function(titleIn, autoAddToBagWasDisplayed) {
		if(autoAddToBagWasDisplayed && autoAddToBagWasDisplayed === true ){
			redisplayAutoAddToBagPrompt = true;
		}
		if(titleIn){
			if(redisplayAutoAddToBagPrompt){
				var overlayUrl = '/shop/orderBuilding/ajax/showOverlay.action'+'?title='+titleIn+'&redisplayAutoAddToBagPrompt=true';
			} else {
				var overlayUrl = '/shop/orderBuilding/ajax/showOverlay.action'+'?title='+titleIn;
			}
		}else{
			if(redisplayAutoAddToBagPrompt){
				var overlayUrl = '/shop/orderBuilding/ajax/showOverlay.action?redisplayAutoAddToBagPrompt=true';
			} else {
				var overlayUrl = '/shop/orderBuilding/ajax/showOverlay.action';
			}
		}

		onCloseRefresh = function() {
			if(redisplayAutoAddToBagPrompt){
				location.href = "/shop/viewbag/ViewBag.action?redisplayAutoAddToBagPrompt=true&useRetainedRRRecs=true";
			} else {
				location.href = "/shop/viewbag/ViewBag.action?useRetainedRRRecs=true";
			}
		}
		
		var modalWidth = this.modalFullWidth;
		onFirsCallSuccess = function(data) {
			this.oB.noOfProducts = data.orderBuildingProductsSize;
			if(5 === data.scenarioId) {
				this.oB.noOfProducts = 1;
			}
			if( this.oB.noOfProducts == 1 ) {
				modalWidth = this.oB.modalSmallWidth;
			}
			if( this.oB.noOfProducts == 2 ) {
				modalWidth = this.oB.modalMediumWidth;
			}
			jdw.modalsContainer.showModal({
		        content: overlayUrl,
		        width:modalWidth,
		        headingText:'<div id="orderHeader"><div class="capHeadLt"></div><div class="headContent"><div class="fantasticOffers"></div></div><div class="capHeadRt"></div></div>',
		        ajax: true,
		        id: 'orderbuildingnewmodal',
		        fullHeight:600,
		        onClose: 'onCloseRefresh',
		        closeMoveCallback: oB.changeHeadingBackground
		    });
		}
		
		// Need to make this call to get the number of products back - before giving the width to the modal.
		// Needs to made into one call if possible for performance.
		var sizeUrl = '/shop/orderBuilding/ajax/findSize.action';
		performAjaxRequest(sizeUrl,null,null,'json',null,onFirsCallSuccess,null,'POST',null);
	},
	
	changeHeadingBackground: function(movedOutside)	{
		if(movedOutside) {
			$('.fantasticOffers').css('background-repeat', 'no-repeat');
			$('.fantasticOffers').css('border-radius', '0.5em 0.5em 0 0');

			if( oB.noOfProducts == 1 ) {
				if ($('#sectionContainer').hasClass('sectionContainerLargeWidth')) {
			        //Expanded - product details page displayed
					$('.fantasticOffers').css('width', '820px');
				} else {
					$('.fantasticOffers').css('width', '620px');
				}
			} else {
				$('.fantasticOffers').css('width', '820px');
			}
		} else {
			$('.fantasticOffers').css('background','');
			$('.fantasticOffers').css('background-image', 'url(/content/common/images/orderBuilding/ob-fantastic-deals-header.png)');
			$('.fantasticOffers').css('border-radius', '0.5em 0 0 0');

			if( oB.noOfProducts == 1 ) {
				if ($('#sectionContainer').hasClass('sectionContainerLargeWidth')) {
			        //Expanded - product details page displayed
					$('.fantasticOffers').css('width', '645px');

					$('.fantasticOffers').css('background-position','0px 0px');
				} else {
					$('.fantasticOffers').css('width', '455px');
					$('.fantasticOffers').css('background-position','0px -40px');
				}
			} else {
				$('.fantasticOffers').css('width', '645px');
			}
		}
	},

	clickAnyWhereCallBack: function(data) {
		if (getIEVersionNumber() <= 6) {
			setSelects("visible");
		}	
		// If any items were added then refresh checkout
		if(oB.slotAdded){
			if(redisplayAutoAddToBagPrompt){
				location.href="/shop/viewbag/ViewBag.action?redisplayAutoAddToBagPrompt=true";
			} else {
				location.href="/shop/viewbag/ViewBag.action";
			}
		}
		if ( window.JDWclick ) {
			window.JDWclick( {id:"fantasticDealsCloseFromOutsideModal",tagName:"DIV"} );
		}
	},
    recenterOverlay: function(){
		var newWidth = $('.orderContainer').width();
		var marginCorrection = (newWidth - oB.overlayWidth) / 2;
		oB.overlayWidth = newWidth;

       	$('#modal_outer').animate({'marginLeft':'-='+marginCorrection+'px'},0);
    },
	addToBag: function(itemId,fromDetailsView){
		var addStatus = oB.slots[itemId].addStatus;
		
		if (validateQuantity(true)) {
			if ( !canAddToBag() ) {
				highlightDropDowns();
				messageAnimationFunctions.msgText("<div class='addToBagMessage'>"+$("#invalidAddToBagMessage").val()+"</div>");
			} else {
				oB.addToBagAjaxCall(itemId);
			}
		} else {
		}
	},
	addToBagAjaxCall: function(itemId){
		var ajaxData = oB.slots[itemId].addToBagParams;	
		var addToBagUrl = '/shop/orderBuilding/ajax/addToBag.action?forceNoPersonalisation=true';
		if($('#selectedOptionId').val()) {
			oB.slots[itemId].addToBagParams.selectedOptionId = $('#selectedOptionId').val();
		}
		if($('#quantity').val()) {
			oB.slots[itemId].addToBagParams.quantity = $('#quantity').val();
		}
		
		var success = function (data) {
			oB.handleAddToBagAjaxCall(data,itemId);
		};
		
		performAjaxRequest(addToBagUrl,null,null,'html',ajaxData,success,null,'POST',null);
	},
	handleAddToBagAjaxCall: function(dataString,itemId) {
		var item = $('#'+itemId);
		var addStatus;
		
		try{
			var data = eval('('+dataString+')').model;
			addStatus = data.addStatus
			// Celebrus Data - execute reportAddToBag() function.
			eval( data.celebrusData );
		}catch(err){
			console.error("addToBag return JSON invalid");
			addStatus = oB.addStatus.INVALID_ADD;
		}

		switch(addStatus){
			case oB.addStatus.ADDED:
				oB.slotAdded = true;
				oB.slots[itemId].addStatus = oB.addStatus.ADDED;
				oB.updateAddButton(item,oB.addStatus.ADDED);
				oB.showAddToBagMessage(oB.addStatus.ADDED, oB.slots[itemId].addToBagParams.pdLpUid);
				break;
			case oB.addStatus.OUT_OF_STOCK:
				oB.slots[itemId].addStatus = oB.addStatus.OUT_OF_STOCK;
				oB.updateAddButton(item,oB.addStatus.OUT_OF_STOCK);
				oB.showAddToBagMessage(oB.addStatus.OUT_OF_STOCK, oB.slots[itemId].addToBagParams.pdLpUid);
				break;
			case oB.addStatus.TO_FOLLOW:
				oB.slotAdded = true;
				oB.slots[itemId].addStatus = oB.addStatus.ADDED;
				oB.updateAddButton(item,oB.addStatus.ADDED);
				oB.showAddToBagMessage(oB.addStatus.ADDED, oB.slots[itemId].addToBagParams.pdLpUid);
				break;
			case oB.addStatus.INVALID_ADD:
				oB.showAddToBagMessage(oB.addStatus.INVALID_ADD, oB.slots[itemId].addToBagParams.pdLpUid);
				break;
			case oB.addStatus.INVALID_QUANTITY:
				oB.showAddToBagMessage(oB.addStatus.INVALID_QUANTITY, oB.slots[itemId].addToBagParams.pdLpUid);
				break;
			default: 
				oB.showAddToBagMessage(oB.addStatus.INVALID_ADD, oB.slots[itemId].addToBagParams.pdLpUid);
		}
	},
	showAddToBagMessage: function(status, lpUid){
		messageAnimationFunctions.msgText('<div class="addToBagMessage">'+oB.addToBagMessages[status]+"</div>");		
	},
	updateAddButton: function(item,status){
	},
	expandOverlay: function() {
		$('#modal_container').switchClass('modalContainerDefault','modalContainerWide',0);
		$('#orderHeader .headContent').switchClass('headContent','headContentWide',0);
		$('#orderFooter .capContent').switchClass('capContent','capContentWide',0);

		oB.recenterOverlay();
		if ( jdw.modalsContainer.isGlobalCloseButtonShown() ) {
			oB.changeHeadingBackground(true);
		} else {
			oB.changeHeadingBackground(false);
		}
	
		oB.viewMoreItem.find('#viewDetailsContainer').css('display','block').switchClass
			('viewDetailsDefault','viewDetailsTransition',0);
	},
	shrinkOverlay: function() {
		$('#modal_container').switchClass('modalContainerWide','modalContainerDefault',0);
		$('#orderHeader .headContentWide').switchClass('headContentWide','headContent',0);
		$('#orderFooter .capContentWide').switchClass('capContentWide','capContent',0);
				
		if ( jdw.modalsContainer.isGlobalCloseButtonShown() ) {
			oB.changeHeadingBackground(true);
		} else {
			oB.changeHeadingBackground(false);
		}

		oB.viewMoreItem.find('#viewDetailsContainer').switchClass
			('viewDetailsTransition','viewDetailsDefault',0,function(){
				$(this).css('display','none');
				// Need to force timeout or recenterOverlay() function won't pick up change of width
				$.doTimeout('overlayTimer', 10, function(){ 
		 			oB.recenterOverlay();	
		 			return false;
				});
			}
		);
	},
	showDetailsView: function(selectedItem){
		var selectedItemId = selectedItem.attr('id');
		
		// Daily offer 2 content "leaks" into the details view, so needs to be hidden
		oB.togglePromo2Content(true);
		
		$('.section').each( function(){
			$(this).css('display','none');
		});
		
		$('#'+selectedItemId).css('display','block');
		 
		$('.backToOffers').show();	

		oB.expandOverlay();
		
	
		$('.orderContainer').fadeIn(300);
		
		var params;
		
		params = "pdLpUid=" + oB.slots[selectedItemId].addToBagParams.pdLpUid;
		params += "&pdBoUid=" + oB.slots[selectedItemId].addToBagParams.pdBoUid;
		
		handleLoadOptions(selectedItemId, params);
	},
	showOffersView: function(){
		// Display each item
		$('.section').each( function(){
			$(this).css('display','block');
		});
		
  		// Daily offer 2 content will have been hidden, so re-display
  		oB.togglePromo2Content(false);
		
		oB.shrinkOverlay();
		
		oB.viewMoreItem = null;
		
		$('.backToOffers').hide();		
		
		$('.orderContainer').fadeIn(300);
		
		$('#orderBuilder').find('#productContainerOfferGraphic').show();	
		
		$('#orderBuilder').find('.obProductInfoContainer').show();	
		
	},
	togglePromo2Content: function (hide){
		if($('.dailySpecialOffers').length!=2)
			return;
			
		$('.dailySpecialOffer2').toggleClass('dailySpecialOffer2Hidden');
		
		if(hide){
  			$('.dailySpecialOffer2').find('.sImage').hide().end().find('.sTitle').hide().end().find('.sActions').hide();
  		}else{
  			$('.dailySpecialOffer2').find('.sImage').show().end().find('.sTitle').show().end().find('.sActions').show();
  		}
	},
};
	
/***********************************************************************************************
 *	Overlay event binding code.     
 ***********************************************************************************************/
$(document).ready( function() {	
	/* Banner click */
	$('#orderBuildingContainer').live('click', function (e) {
		e.preventDefault();
		oB.displayOverlay();
	});
	
	/* Back to offers */
	$('.backToOffers').live('click', function(e) {
		e.preventDefault();
		deRegisterClickEvents();
		$("div[id^='optionsHolder']").empty();

		$('.orderContainer').fadeOut(100,function(){
			oB.showOffersView();
		});
		if( oB.noOfProducts==1 ) {
			jdw.modalsContainer.reAnimate(oB.modalSmallWidth,oB.modalHeight);
			$("#sectionContainer").addClass('sectionContainerSmallWidth');
			$('#sectionContainer').removeClass('sectionContainerLargeWidth');
			$('.fantasticOffers').css('width','460px');
			$('#jdwModalContent').css('width', oB.modalSmallWidth + 'px');
			$('.fantasticOffers').css('background-position','0 -40px');
		}
		if( oB.noOfProducts==2 ) {
			jdw.modalsContainer.reAnimate(oB.modalMediumWidth,oB.modalHeight);
			$("#sectionContainer").addClass('sectionContainerSmallWidth');
			$('#sectionContainer').removeClass('sectionContainerLargeWidth');
			$('.fantasticOffers').css('width','645px');
			$('#jdwModalContent').css('width', oB.modalMediumWidth + 'px');
			$('.fantasticOffers').css('background-position','0 0px');
		}
  	});
	
	/* View details */
	$('.sapView').live('click', function (e) {	
		e.preventDefault();
		oB.viewMoreItem = $(this).closest('.section');
		$('.orderContainer').fadeOut(100,function(){
			oB.showDetailsView(oB.viewMoreItem);
		});
	
	});
	/* View details */
	$('.viewOfferButton a').live('click', function (e) {	
		e.preventDefault();
		deRegisterClickEvents();
		showProductDetails($(this));
	});
	
	/*MIRRORING THE CLICK FEATURE OF viewOffer WITH IMAGE CLICK*/
	$('a#obProductImage').live('click', function (e) {	
		e.preventDefault();
		deRegisterClickEvents();
		showProductDetails($(this));
	});
	
	/* Adding item to bag from main overlay */
	$('.saButton a').live('click', function (e) {
		e.preventDefault();
		var itemId = $(this).closest('.section').attr('id');
		oB.addToBag(itemId,false);
   	});
   	
   	/* Adding item to bag within details view */
	$('.vdActions a').live('click', function (e) {
		var itemId = $(this).closest('.section').attr('id');
		oB.addToBag(itemId,true);
   	});
   	
}); 

var addedToBagAddStatus = 101;
var addedToBagTFStatus = 104;
var currentStockMessage;
var redisplayAutoAddToBagPrompt = false;

function showProductDetails(divElement){
	oB.viewMoreItem = $(divElement).closest('.section');
	$('.orderContainer').fadeOut(100,function(){
		oB.showDetailsView(oB.viewMoreItem);
	});
	if( oB.noOfProducts==1 || oB.noOfProducts==2 ) {
		jdw.modalsContainer.reAnimate(oB.modalFullWidth, oB.modalHeight);
		$("#sectionContainer").addClass('sectionContainerLargeWidth');
		$('#sectionContainer').removeClass('sectionContainerSmallWidth');
		$('.fantasticOffers').css('width','645px');
		$('#jdwModalContent').css('width', oB.modalFullWidth + 'px');
		$('.fantasticOffers').css('background-position','0 0');
	}
}

function deRegisterClickEvents() {
	$('#optionColour_select .containerSelect .mainFirstValue').die('click');
	$('#optionSize_select .containerSelect .mainFirstValue').die('click');
	$('#fitting_select .containerSelect .mainFirstValue').die('click');
}

function handleLoadOptions(selectedItemId, params) {
	jdw.quickView.showOrderBuildingDetails(oB.slots[selectedItemId].addToBagParams.pdLpUid, "/shop/orderBuilding/ajax/showQuickView.action?"+params);
}/* complete : /javascript/productDetailsRedesign/quickView/productDetailsOrderBuilding.js*/


/* combine : /javascript/common/strings.js*/
var STRINGS = {};
/* This function should not be used. It is registration
   specific and is retained for compatability only.
   */
function setupStrings(bundle, bundleRoot, secure){
	bundleRoot = bundleRoot || 'uk/co/jdwilliams/shop/';
 // Blocking call, need to wait for the data before continuing to process JS code on the page
	$.ajax({
			'async' : false,
			'url'   : '/shop/registration/' + 
					( secure ? 'jsonStringSecure.action' : 'jsonString.action' ),
			'dataType' : 'json',
			'data' : {'bundle' : bundleRoot + bundle},
			'success' : function(data){
					$.extend(STRINGS, data.strings);
				}
		});
}

/* Populates the global STRINGS object with a set of keys and values representing text that will
   be displayed to the user via JavaScript code. The text is retrieved by an AJAX call to the 
   JsonStringAction class, which returns the contents of the appropriate Struts2 .properties file
   as a JSON object.
   The secure parameter enables us to use this call from both secure and insecure
   pages.  If secure is true, the url used to communicate with the jsonString action is one that
   is included in pageSecurity.properties. 
   Multiple calls to this method within a single page are permitted, and the results accumulate in
   the STRINGS object with later results overwriting earlier ones in the event that identical keys
   are returned.
   */
function getMessageResources(bundle, bundleRoot, urlPrefix, secure) {
	bundleRoot = bundleRoot || 'uk/co/jdwilliams/shop/';
	var urlPrefix = urlPrefix || '/shop/';
	
 	// Blocking call, need to wait for the data before continuing to process JS code on the page
	$.ajax({
			'async' : false,
			'url'   : urlPrefix + 
					( secure ? 'jsonStringSecure.action' : 'jsonString.action' ),
			'dataType' : 'json',
			'data' : {'bundle' : bundleRoot + bundle},
			'success' : function(data){
					$.extend(STRINGS, data.strings);
				}
		});
}
/* complete : /javascript/common/strings.js*/


/* combine : /javascript/common/jdw_formhelper.js*/
// CVS ID $Id: jdw_formhelper.js,v 1.2.4.1 2004/05/10 15:42:02 mikelittle Exp $
// CVS ID $Name:  $

function illegalChars(inValue, strLegalChars) {
    // allow Carriage returns
    var i = 0;
    var j = 0;
    var legal = true;
    var legalChars = 0;

    while ((i < inValue.length) && (legal == true)) {
        j = 0;
        legalChars = 0;
        while ((j < strLegalChars.length) && (legal == true)) {
            if (inValue.charAt(i) == strLegalChars.charAt(j)) {
                legalChars++;
            }
            j++;
        }
        if (legalChars < 1) {
            legal = false;
        }
        i++;
    }
    return !legal;
}

function indexOfIllegalChars(inValue, strLegalChars) {
    // allow Carriage returns
    var i = 0;
    var j = 0;
    var legal = -1;
    var legalChars = 0;

    while ((i < inValue.length) && (legal == -1)) {
        j = 0;
        legalChars = 0;
        while ((j < strLegalChars.length) && (legal == -1)) {
            if (inValue.charAt(i) == strLegalChars.charAt(j)) {
                legalChars++;
            }
            j++;
        }
        if (legalChars < 1) {
            legal = i;
        }
        i++;
    }
    return legal;
}

// handy function remove trailing and leading whitespaces
function trimWhiteSpace(strText) {
    // this will get rid of leading spaces
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

    return strText;
}

function checkPhone(phoneValue)
{
    if (isEmpty(phoneValue))
        return true;
    var i = 0;
    for (j=0; j<phoneValue.length; j++)
    {
        x = phoneValue.charAt(j);
        if (!charInString(x, validWorldPhoneChars))
        {
            return false;
        }
        else if(charInString(x, digits))
        {
            i++;
        }
    }

    return true;
}

var daysInMonth = [12];
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

function isYear (s)
{
    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    if (!isNonnegativeInteger(s)) return false;
    return ((s.length == 2) || (s.length == 4));
}

function isMonth (s)
{
    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    return isIntegerInRange (s, 1, 12);
}

function isDay (s)
{
    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    return isIntegerInRange (s, 1, 31);
}

function daysInFebruary (year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    if (! isYear(year, false))
        return false;

    if (! isMonth(month, false))
        return false;

    if (! isDay(day, false))
        return false;

    var intYear = parseInt(year,10);
    var intMonth = parseInt(month,10);
    var intDay = parseInt(day,10);

    if (intDay > daysInMonth[intMonth]) return false;

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var whitespace = " \t\n\r";
var decimalPointDelimiter = ".";

var validPasswordChars = digits + lowercaseLetters + uppercaseLetters;
var validAcctRefChars = digits + lowercaseLetters + uppercaseLetters;

var phoneNumberDelimiters = "()- ";
var validUSPhoneChars = digits + phoneNumberDelimiters;
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";

var defaultEmptyOK = false;

function isEmpty(s)
{
    return ((s == null) || (s.length == 0))
}

function isAnyValue(s)
{
    if (isEmpty(s))
        return defaultEmptyOK;
    return !isEmpty(s)
}

function isWhitespace (s)
{
    var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i=0; i<s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}

function stripCharsInBag (s, bag)
{
    var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i=0; i<s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

function stripCharsNotInBag (s, bag)
{
    var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i=0; i<s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function stripWhitespace (s)
{
    return stripCharsInBag (s, whitespace)
}

function charInString (c, s)
{
    for (i=0; i<s.length; i++)
        {   if (s.charAt(i) == c) return true;
        }
    return false
}

function stripInitialWhitespace (s)
{
    var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
        i++;

    return s.substring (i, s.length);
}

function isLetter (c)
{
    return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}

function isDigit (c)
{
    return ((c >= "0") && (c <= "9"))
}

function isLetterOrDigit (c)
{
    return (isLetter(c) || isDigit(c))
}

function isInteger (s)
{
    var i;

    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    for (i=0; i<s.length; i++)
    {
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }
    return true;
}

function isIntegerInRange (s, a, b)
{
    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    if (!isInteger(s, false)) return false;

    var num = parseInt(s,10);
    return ((num >= a) && (num <= b));
}

function MFValidate(formField, aBool, prompt)
{
    if (aBool == false)
    {
        formField.focus();
        formField.select();
        alert(prompt);
        formField.focus();
    }
    return aBool;
}

function MFPrompt(prompt)
{
    window.status=prompt;
}

function toLowerCase(s)
{
    return s.toLowerCase;
}

function toUpperCase(s)
{
    return s.toUpperCase;
}

function isSignedInteger (s)
{
    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    else
    {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
            startPos = 1;
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}

function isPositiveInteger (s)
{
    var secondArg = defaultEmptyOK;

    return (isSignedInteger(s, secondArg)
        && ( (isEmpty(s) && secondArg)  || (parseInt(s,10) > 0) ) );
}

function isNonnegativeInteger (s)
{
    var secondArg = defaultEmptyOK;

    return (isSignedInteger(s, secondArg)
        && ( (isEmpty(s) && secondArg)  || (parseInt(s,10) >= 0) ) );
}

function isNegativeInteger (s)
{
    var secondArg = defaultEmptyOK;

    return (isSignedInteger(s, secondArg)
        && ( (isEmpty(s) && secondArg)  || (parseInt(s,10) < 0) ) );
}

function isNonpositiveInteger (s)
{
    var secondArg = defaultEmptyOK;

    return (isSignedInteger(s, secondArg)
        && ( (isEmpty(s) && secondArg)  || (parseInt(s,10) <= 0) ) );
}

function isFloat (s)
{
    var i;
    var seenDecimalPoint = false;

    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }

    if (s == decimalPointDelimiter) return false;

    for (i=0; i<s.length; i++)
    {
        var c = s.charAt(i);

        if ((c == decimalPointDelimiter) && !seenDecimalPoint) seenDecimalPoint = true;
        else if (!isDigit(c)) return false;
    }

    return true;
}

function isSignedFloat (s)
{
    if (isEmpty(s))
    {
        return defaultEmptyOK;
    }
    else
    {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
            startPos = 1;
        return (isFloat(s.substring(startPos, s.length), secondArg))
    }
}

function isAlphabetic (s)
{
    var i;

    if (isEmpty(s))
        return defaultEmptyOK;

    for (i=0; i<s.length; i++)
    {
        var c = s.charAt(i);

        if (!isLetter(c))
            return false;
    }

    return true;
}

function isAlphanumeric (s)
{
    var i;

    if (isEmpty(s))
        return defaultEmptyOK;

    for (i=0; i<s.length; i++)
    {
        // Check that current character is number or letter.
        var c = s.charAt(i);

        if (! (isLetter(c) || isDigit(c) ) )
            return false;
    }

    return true;
}

function validCharsForDeliveryname (s){

	var validChars = "-' " ;
	var validDeliveryNameChars = digits + lowercaseLetters + uppercaseLetters + validChars ;
	
	if(illegalChars(s,validDeliveryNameChars)) {
		return false;
	}
	 
	return true;

}
/* complete : /javascript/common/jdw_formhelper.js*/


/* combine : /javascript/common/libraries/jquery/jquery.livequery.js*/
/*! Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.1.0-pre
 * Requires jQuery 1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {

$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;

		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;

		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});

		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);

		// Make sure it is running
		q.stopped = false;

		// Run it immediately for the first time
		q.run();

		// Contnue the chain
		return this;
	},

	expire: function(type, fn, fn2) {
		var self = this;

		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;

		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});

		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;

	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;

	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;

	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;

		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});

		// Clear out matched elements
		this.elements = [];

		// Stop the Live Query from running until restarted
		this.stopped = true;
	},

	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;

		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);

		// Set elements to the latest set of matched elements
		this.elements = els;

		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);

			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});

			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,

	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},

	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},

	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},

	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;

			// Save a reference to the original method
			var old = $.fn[n];

			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);

				// Request a run of the Live Queries
				$.livequery.run();

				// Return the original methods result
				return r;
			}
		});
	},

	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});

		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},

	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });

})(jQuery);/* complete : /javascript/common/libraries/jquery/jquery.livequery.js*/


/* combine : /javascript/common/jdw_helpHover.js*/
//Create Help hover dialogs
$(document).ready( function() {
	$(".help, .helpNoImage").livequery(function(){ 
	
			$(this).hover(function () {
					if($(this).attr('helpText')) {

						var target = 'body';
						var offLeft = 430; 
						var offTop = 25;

						if ($(this).attr('target')) {
							target = $(this).attr('target');
						}

						if ($(this).attr('offLeft')) {
							offLeft = $(this).attr('offLeft');
						}
									
						$('#helpDiv').remove();
						$(target).append('<div id="helpDiv" style="z-index: 15000;"><div class="helpDivInner">'  + 
						($(this).attr('helpTitle') && $('#helpDiv .title').size() == 0? '<div class="title">' + 
						$(this).attr('helpTitle') + '</div>' : '' ) + $(this).attr('helpText') + ' </div></div>');
					
						var offLeft = ($(this).offset().left-offLeft);
											
						
						
						if($(this).attr('textAbove') && target == 'body') {
							$('#helpDiv')
									.animate({opacity: 0, marginLeft: 0, top: $(this).offset().top - ($('#helpDiv').height()) - (offTop-18), left: $(this).offset().left}, 1)
									.animate({opacity:1});						
						} else if (target == 'body') {
							$('#helpDiv')
									.animate({opacity: 0, marginLeft: ($('#helpDiv').width()/2) + 'px', top: $(this).offset().top + offTop, left: offLeft}, 1)
									.animate({opacity:1});
						} else {
							$('#helpDiv')
									.animate({opacity: 0, marginLeft: ($('#helpDiv').width()/2) + 'px', top: $(this).offset().top - ($('#helpDiv').height()) - (offTop-18), left: offLeft}, 1)
									.animate({opacity:1});	
						}
						


					}			
			}, function () {
					if($(this).attr('helpText')) {
						$('#helpDiv').each(function () {
							$(this).remove();
						 });
					}
			});	
	}, function() { 
			$(this).unbind('mouseover').unbind('mouseout'); 
	});
}); /* complete : /javascript/common/jdw_helpHover.js*/


/* combine : /javascript/common/libraries/jquery/jqueryCssDropdown.js*/
/*
	Developed by Daniel Noormohamed 05 May 2009 for JD Williams
	Using jQuery version:	1.3.2
	Dependant: jquery.cssDropdown.css
	
	----------------
	Changes 18 June 2009 11:05
	----------------
		if there are more than 10 list values in a dropdown the following styles are placed inline to fix the height of the container
				.dropOptions
					height:300px; 
					overflow: auto;
					width: 307px;
				.mainOtherValues 
					width:280px;
					margin-top:1px [delete this style from css file]
		
	
*/


/*
 * This function should be moved to a common javascript file
*/
	function removeHTMLTags(strInputCode){
	 	strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
		 	return (p1 == "lt")? "<" : ">";
		});
		var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
		return strTagStrippedText;
	}

		
	function selectedOptionText(txt, value, currentID, selectedOpt) {
		var strippedTxt = null;
		
		var fspan = $('#' + selectedOpt.current + '_select .dropOptions div:eq(' + selectedOpt.selected + ')');
		if($('.' + fspan.find('span').prop('class'), fspan).css('display') == 'none') {
			$('.' + fspan.find('span').prop('class'), fspan).remove();
			strippedTxt = fspan.text();
		} else {
			strippedTxt = removeHTMLTags(txt);
		}
		
		if(strippedTxt.length > 28)
			strippedTxt = strippedTxt.substr(0,45) + '...';
		$('#' + currentID + ' .getFittingValue').html(strippedTxt).prop('value', value);
	}
 			
	(function($){  
	   $.fn.cssDropdown = function(options) {     
				var selectedIndex =0;
				var currentID = '';
				var parentID = '';

				var defaults = {  
					fromSelect: 'yes',
					version: 1
				};  

				var options = $.extend(defaults, options);  
				   
	   		var cssDropFunctions = {
				filterOptions : function ($t) {
						var n =0;
						var optionList = $t.find('option');
						
						optionList.each(function () {
							
								if($(this).prop('selected') == true) {
									selectedIndex = n;
								}
							if(n == 0) {
								$('#' + parentID).find('.containerSelect').prepend('<div data-jdw-test-id="' + $(this).parent().prop('id') + 'Select" class="mainFirstValue getFittingValue" value="' + $(this).prop('value') + '">' + $(this).text() + '</div>');
							}
							
							$('#' + parentID).find('.containerSelect').find('span').each(function () {
								if($(this).css('display') == 'none') {
									$(this).remove();
								}
							});
															
							n++;
							$('#' + parentID).find('.containerSelect .dropOptions').append('<div ' + (optionList.size() > 10 ? ' style="border-right:0px; " ' : '') + (($(this).prop('value') != "") ? (' id="stProdOption_' + $(this).prop('value') + '"') : '') + ' class="mainOtherValues ' + $(this).prop('class') +'"  value="' + $(this).prop('value') + '">' + $(this).text() + '</div>');

						})
				},
				setMargins : function () {
					if($('#' + parentID).css('margin-bottom') > 2) $('#' + parentID).css('margin-bottom', '0px');
				},
				setSelectNumbers : function (n) {
					$('.mainFirstValue').each(function(){ $(this).prop('number', n++); });
				},
				oddEvenShades : function () {
					$('#' + parentID).find('.containerSelect').find('.mainOtherValues:odd').addClass('odd');
					$('#' + parentID).find('.containerSelect').find('.mainOtherValues:even').addClass('even');					
				},
				ToggleList : function (state) {
						$('#' + currentID + ' .dropOptions').toggleClass('dropOptionsShow');
						$('#' + currentID + ' .mainFirstValue').toggleClass('selectedDrop');		
				},
				showMainElement : function () {
					$('.mainFirstValue').each(function () { $(this).show(); });
				}, 
				triggerChange : function (txt, value) {
					
					selectedOptionText(txt, value, currentID + '_select', {selected : selectedIndex, current: currentID});
										
					$('#' + currentID.split('_')[0] + ' option[value="' +  value + '"]').prop('selected', 'selected')
					$('#' + currentID.split('_')[0]).trigger('change');	
				}, 
				hideSelectbox : function (thisN) {
					$('.mainFirstValue').each(function () { if($(this).prop('number') > thisN) $('.mainFirstValue[number="' + $(this).prop('number') + '"]').hide(); });	
				},
				minimiseMessageBox : function (msgs, emptyThis) {
						if(msgs.height() > 10) msgs.animate({ height: '10px'}, 500).find(emptyThis).empty();									
				}, updateOptions : function () {
					
				}
			}
			
		   return this.each(function() {															
				$t = $(this);
				currentID = $(this).prop('id');
				parentID = $(this).parent().prop('id');
				
				if(options.fromSelect == 'yes') {
						if($('#' + currentID + '_select').size() == 1) {							
							if($t.prop('show') == 'false')
								$('#' + currentID + '_select').hide();
							else {
								$('#' + currentID + '_select').show();
								$('#' + parentID).find('.containerSelect .dropOptions').html('');
								$('#' + parentID).find('.containerSelect .mainFirstValue').remove();
								cssDropFunctions.filterOptions($t);	
														
								$('#' + currentID + '_select .dropOptions div:eq(' + selectedIndex + ')').each(function(){						
									selectedOptionText($(this).text(), $(this).prop('value'), currentID + '_select', {selected : selectedIndex, current: currentID});
							  	});															
							  	
							}
							
						} else {
						
							if($t.css('display') == 'none'){
								$t.hide();
							} else {					
						
								cssDropFunctions.setMargins();
								$('#' + parentID).append('<div id="' + currentID + '_select" class="mainSelect"></div>')
								$('#' + parentID + ' .mainSelect').append('<div class="containerSelect"></div>')
								
								var optionList = $t.find('option');
								$('#' + parentID + ' .mainSelect .containerSelect').append('<div class="dropOptions ' + (optionList.size() > 7 ? ' dropOptionsMore ' : '') + '"></div>')
								
								cssDropFunctions.filterOptions($t);
								
								$(this).hide();
								currentID = $(this).prop('id') + '_select';
							  	
							  	$('#' + currentID + ' .dropOptions div:eq(' + selectedIndex + ')').each(function(){
									selectedOptionText($(this).text(), $(this).prop('value'), currentID, {selected : selectedIndex, current: currentID});
							  	});
							}
						}
						
						if(jdBrowser.msie) {
							$('.dropOptions div').bind('mouseover', function () {
								$(this).addClass('hoverMainOtherValues');
							}).bind('mouseout',  function () {
								$(this).removeClass('hoverMainOtherValues');
							});					
						}
				}
				
				//cssDropFunctions.oddEvenShades();
				cssDropFunctions.setSelectNumbers(1);				
								
				$('#' + currentID).on('click', '.containerSelect .mainFirstValue', function () {		
					
					if($('#' + currentID + ' .dropOptions').css('display') == 'none') {
						cssDropFunctions.minimiseMessageBox($('#stockMsgPanel'), '.messages');
						cssDropFunctions.ToggleList('expand');						
						cssDropFunctions.hideSelectbox($(this).prop('number'));									
					} else {
						cssDropFunctions.ToggleList('shrink');
						cssDropFunctions.showMainElement();						
					}
				})
							
				$('#' + currentID + ' .containerSelect').on("mouseleave", function(){
					if($('#' + currentID + ' .dropOptions').css('display') == 'block') {
						cssDropFunctions.ToggleList();
						cssDropFunctions.showMainElement();
					}
				});
				
				$('#' + currentID).on('click', '.mainOtherValues', function () {
					$t = $(this);
					cssDropFunctions.ToggleList('shrink');
					cssDropFunctions.showMainElement();
					cssDropFunctions.triggerChange($t.html(), $t.prop('value'));
				});																													
		   });  
	   };  
	})(jQuery);  

/*
To use this plugin you will need the following.

1. 
		
		Create a div layer and create a select box using html like the following
		THE DIV LAYER IS NEEDED!
		
			<div id="sizeDiv" name="sizeDiv" class="selectListShowContainer">
			
				<select name="optionSize" id="optionSize" class="optionSize">
					<option value="" class="valid">Choose Size</option>
					<option value="DOUBLE" class="valid">DOUBLE</option>
					<option value="KING" class="valid">KING</option>
					<option value="SINGLE" class="valid">SINGLE</option>
				</select>
				
			</div>

2.
		To convert the select box you execute the following code below. this will 
		convert the whole select box into div layers also moving the value attribute 
		of a option tag to the div
		
		THIS DOES NOT REMOVE THE SELECT BOX, AS IT POPULATES IT WITH THE clicked VALUE
		you can test this using the "//alert($('#optionsForm').serialize());" commented out on line 50 
		
		<script>
			$(document).ready(function () {
				$('#selectboxID').cssDropdown({fromSelect:'yes'});
			});
		</script>

*//* complete : /javascript/common/libraries/jquery/jqueryCssDropdown.js*/


/* combine : /javascript/common/libraries/jquery/flexslider.js*/
/**************************************************
 * JDW Modified version of jQuery FlexSlider
 * Added fix for IE10 not sliding.
 * Line 620 added - annotated with // JDW specific 
 * Line 625 added - annotated with // JDW specific 
**************************************************/
/*
 * jQuery FlexSlider v2.1
 * http://www.woothemes.com/flexslider/
 *
 * Copyright 2012 WooThemes
 * Free to use under the GPLv2 license.
 * http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Contributing author: Tyler Smith (@mbmufffin)
 */

;(function ($) {

  //FlexSlider: Object Instance
  $.flexslider = function(el, options) {
    var slider = $(el),
        vars = $.extend({}, $.flexslider.defaults, options),
        namespace = vars.namespace,
        touch = ("ontouchstart" in window) || window.DocumentTouch && document instanceof DocumentTouch,
        eventType = (touch) ? "touchend" : "click",
        vertical = vars.direction === "vertical",
        reverse = vars.reverse,
        carousel = (vars.itemWidth > 0),
        fade = vars.animation === "fade",
        asNav = vars.asNavFor !== "",
        methods = {};

    // Store a reference to the slider object
    $.data(el, "flexslider", slider);

    // Privat slider methods
    methods = {
      init: function() {
        slider.animating = false;
        slider.currentSlide = vars.startAt;
        slider.animatingTo = slider.currentSlide;
        slider.atEnd = false;
        slider.containerSelector = vars.selector.substr(0,vars.selector.search(' '));
        slider.slides = $(vars.selector, slider);
        slider.container = $(slider.containerSelector, slider);
        slider.count = slider.slides.length;
        // SYNC:
        slider.syncExists = $(vars.sync).length > 0;
        // SLIDE:
        if (vars.animation === "slide") vars.animation = "swing";
        slider.prop = (vertical) ? "top" : "marginLeft";
        slider.args = {};
        // SLIDESHOW:
        slider.manualPause = false;
        // TOUCH/USECSS:
        slider.transitions = !vars.video && !fade && vars.useCSS && (function() {
          var obj = document.createElement('div'),
              props = ['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective'];
          for (var i in props) {
            if ( obj.style[ props[i] ] !== undefined ) {
              slider.pfx = props[i].replace('Perspective','').toLowerCase();
              slider.prop = "-" + slider.pfx + "-transform";
              return true;
            }
          }
          return false;
        }());
        // CONTROLSCONTAINER:
        if (vars.controlsContainer !== "") slider.controlsContainer = $(vars.controlsContainer).length > 0 && $(vars.controlsContainer);
        // MANUAL:
        if (vars.manualControls !== "") slider.manualControls = $(vars.manualControls).length > 0 && $(vars.manualControls);

        // RANDOMIZE:
        if (vars.randomize) {
          slider.slides.sort(function() { return (Math.round(Math.random())-0.5); });
          slider.container.empty().append(slider.slides);
        }

        slider.doMath();

        // ASNAV:
        if (asNav) methods.asNav.setup();

        // INIT
        slider.setup("init");

        // CONTROLNAV:
        if (vars.controlNav) methods.controlNav.setup();

        // DIRECTIONNAV:
        if (vars.directionNav) methods.directionNav.setup();

        // KEYBOARD:
        if (vars.keyboard && ($(slider.containerSelector).length === 1 || vars.multipleKeyboard)) {
          $(document).bind('keyup', function(event) {
            var keycode = event.keyCode;
            if (!slider.animating && (keycode === 39 || keycode === 37)) {
              var target = (keycode === 39) ? slider.getTarget('next') :
                           (keycode === 37) ? slider.getTarget('prev') : false;
              slider.flexAnimate(target, vars.pauseOnAction);
            }
          });
        }
        // MOUSEWHEEL:
        if (vars.mousewheel) {
          slider.bind('mousewheel', function(event, delta, deltaX, deltaY) {
            event.preventDefault();
            var target = (delta < 0) ? slider.getTarget('next') : slider.getTarget('prev');
            slider.flexAnimate(target, vars.pauseOnAction);
          });
        }

        // PAUSEPLAY
        if (vars.pausePlay) methods.pausePlay.setup();

        // SLIDSESHOW
        if (vars.slideshow) {
          if (vars.pauseOnHover) {
            slider.hover(function() {
              if (!slider.manualPlay && !slider.manualPause) slider.pause();
            }, function() {
              if (!slider.manualPause && !slider.manualPlay) slider.play();
            });
          }
          // initialize animation
          (vars.initDelay > 0) ? setTimeout(slider.play, vars.initDelay) : slider.play();
        }

        // TOUCH
        if (touch && vars.touch) methods.touch();

        // FADE&&SMOOTHHEIGHT || SLIDE:
        if (!fade || (fade && vars.smoothHeight)) $(window).bind("resize focus", methods.resize);


        // API: start() Callback
        setTimeout(function(){
          vars.start(slider);
        }, 200);
      },
      asNav: {
        setup: function() {
          slider.asNav = true;
          slider.animatingTo = Math.floor(slider.currentSlide/slider.move);
          slider.currentItem = slider.currentSlide;
          slider.slides.removeClass(namespace + "active-slide").eq(slider.currentItem).addClass(namespace + "active-slide");
          slider.slides.live('click', function(e){
            e.preventDefault();
            var $slide = $(this),
                target = $slide.index();
            //JDW Change Start: check target Tablet zoom image is available or not (productDetailsMain.js-mobile)
                if (typeof(checkForZoom) === "function"){
	                checkForZoom(target);
	            }
            //JDW Change End
            if (!$(vars.asNavFor).data('flexslider').animating && !$slide.hasClass('active')) {
              slider.direction = (slider.currentItem < target) ? "next" : "prev";
              slider.flexAnimate(target, vars.pauseOnAction, false, true, true);
            }
          });
        }
      },
      controlNav: {
        setup: function() {
          if (!slider.manualControls) {
            methods.controlNav.setupPaging();
          } else { // MANUALCONTROLS:
            methods.controlNav.setupManual();
          }
        },
        setupPaging: function() {
          var type = (vars.controlNav === "thumbnails") ? 'control-thumbs' : 'control-paging',
              j = 1,
              item;

          slider.controlNavScaffold = $('<ol class="'+ namespace + 'control-nav ' + namespace + type + '"></ol>');

          if (slider.pagingCount > 1) {
            for (var i = 0; i < slider.pagingCount; i++) {
              item = (vars.controlNav === "thumbnails") ? '<img src="' + slider.slides.eq(i).attr("data-thumb") + '"/>' : '<a>' + j + '</a>';
              slider.controlNavScaffold.append('<li>' + item + '</li>');
              j++;
            }
          }

          // CONTROLSCONTAINER:
          (slider.controlsContainer) ? $(slider.controlsContainer).append(slider.controlNavScaffold) : slider.append(slider.controlNavScaffold);
          methods.controlNav.set();

          methods.controlNav.active();

          slider.controlNavScaffold.delegate('a, img', eventType, function(event) {
            event.preventDefault();
            var $this = $(this),
                target = slider.controlNav.index($this);

            if (!$this.hasClass(namespace + 'active')) {
              slider.direction = (target > slider.currentSlide) ? "next" : "prev";
              slider.flexAnimate(target, vars.pauseOnAction);
            }
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.controlNavScaffold.delegate('a', "click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        setupManual: function() {
          slider.controlNav = slider.manualControls;
          methods.controlNav.active();

          slider.controlNav.live(eventType, function(event) {
            event.preventDefault();
            var $this = $(this),
                target = slider.controlNav.index($this);

            if (!$this.hasClass(namespace + 'active')) {
              (target > slider.currentSlide) ? slider.direction = "next" : slider.direction = "prev";
              slider.flexAnimate(target, vars.pauseOnAction);
            }
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.controlNav.live("click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        set: function() {
          var selector = (vars.controlNav === "thumbnails") ? 'img' : 'a';
          slider.controlNav = $('.' + namespace + 'control-nav li ' + selector, (slider.controlsContainer) ? slider.controlsContainer : slider);
        },
        active: function() {
          slider.controlNav.removeClass(namespace + "active").eq(slider.animatingTo).addClass(namespace + "active");
        },
        update: function(action, pos) {
          if (slider.pagingCount > 1 && action === "add") {
            slider.controlNavScaffold.append($('<li><a>' + slider.count + '</a></li>'));
          } else if (slider.pagingCount === 1) {
            slider.controlNavScaffold.find('li').remove();
          } else {
            slider.controlNav.eq(pos).closest('li').remove();
          }
          methods.controlNav.set();
          (slider.pagingCount > 1 && slider.pagingCount !== slider.controlNav.length) ? slider.update(pos, action) : methods.controlNav.active();
        }
      },
      directionNav: {
        setup: function() {
          var directionNavScaffold = $('<ul class="' + namespace + 'direction-nav"><li class="' + namespace + 'control-prev"><a class="' + namespace + 'prev" href="#" style="display: block;">' + vars.prevText + '</a></li><li class="' + namespace + 'control-next"><a class="' + namespace + 'next" href="#">' + vars.nextText + '</a></li></ul>');

          // CONTROLSCONTAINER:
          if (slider.controlsContainer) {
            $(slider.controlsContainer).append(directionNavScaffold);
            slider.directionNav = $('.' + namespace + 'direction-nav li a', slider.controlsContainer);
          } else {
            slider.append(directionNavScaffold);
            slider.directionNav = $('.' + namespace + 'direction-nav li a', slider);
          }

          methods.directionNav.update();

          slider.directionNav.bind(eventType, function(event) {
            event.preventDefault();
            var target = ($(this).hasClass(namespace + 'next')) ? slider.getTarget('next') : slider.getTarget('prev');
            slider.flexAnimate(target, vars.pauseOnAction);
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.directionNav.bind("click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
       update: function() {
          var disabledClass = namespace + 'disabled';
          if (slider.count <= vars.maxItems) {
            slider.directionNav.addClass(disabledClass);
          } else if (!vars.animationLoop) { 
           if (slider.animatingTo === 0) {
              slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "prev").addClass(disabledClass);
            } else if (slider.animatingTo >= (slider.count-vars.maxItems) || slider.count <= vars.maxItems) {
        slider.directionNav.removeClass(disabledClass).filter('.' + namespace + "next").addClass(disabledClass);
            } else {
              slider.directionNav.removeClass(disabledClass);
            }
         } else {
       slider.directionNav.removeClass(disabledClass);
     }
     }
      },
      pausePlay: {
        setup: function() {
          var pausePlayScaffold = $('<div class="' + namespace + 'pauseplay"><a></a></div>');

          // CONTROLSCONTAINER:
          if (slider.controlsContainer) {
            slider.controlsContainer.append(pausePlayScaffold);
            slider.pausePlay = $('.' + namespace + 'pauseplay a', slider.controlsContainer);
          } else {
            slider.append(pausePlayScaffold);
            slider.pausePlay = $('.' + namespace + 'pauseplay a', slider);
          }

          methods.pausePlay.update((vars.slideshow) ? namespace + 'pause' : namespace + 'play');

          slider.pausePlay.bind(eventType, function(event) {
            event.preventDefault();
            if ($(this).hasClass(namespace + 'pause')) {
              slider.manualPause = true;
              slider.manualPlay = false;
              slider.pause();
            } else {
              slider.manualPause = false;
              slider.manualPlay = true;
              slider.play();
            }
          });
          // Prevent iOS click event bug
          if (touch) {
            slider.pausePlay.bind("click touchstart", function(event) {
              event.preventDefault();
            });
          }
        },
        update: function(state) {
          (state === "play") ? slider.pausePlay.removeClass(namespace + 'pause').addClass(namespace + 'play').text(vars.playText) : slider.pausePlay.removeClass(namespace + 'play').addClass(namespace + 'pause').text(vars.pauseText);
        }
      },
      touch: function() {
        var startX,
          startY,
          offset,
          cwidth,
          dx,
          startT,
          scrolling = false;

        el.addEventListener('touchstart', onTouchStart, false);
        function onTouchStart(e) {
          if (slider.animating) {
            e.preventDefault();
          } else if (e.touches.length === 1) {
            slider.pause();
            // CAROUSEL:
            cwidth = (vertical) ? slider.h : slider. w;
            startT = Number(new Date());
            // CAROUSEL:
            offset = (carousel && reverse && slider.animatingTo === slider.last) ? 0 :
                     (carousel && reverse) ? slider.limit - (((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo) :
                     (carousel && slider.currentSlide === slider.last) ? slider.limit :
                     (carousel) ? ((slider.itemW + vars.itemMargin) * slider.move) * slider.currentSlide :
                     (reverse) ? (slider.last - slider.currentSlide + slider.cloneOffset) * cwidth : (slider.currentSlide + slider.cloneOffset) * cwidth;
            startX = (vertical) ? e.touches[0].pageY : e.touches[0].pageX;
            startY = (vertical) ? e.touches[0].pageX : e.touches[0].pageY;

            el.addEventListener('touchmove', onTouchMove, false);
            el.addEventListener('touchend', onTouchEnd, false);
          }
        }

        function onTouchMove(e) {
          dx = (vertical) ? startX - e.touches[0].pageY : startX - e.touches[0].pageX;
          scrolling = (vertical) ? (Math.abs(dx) < Math.abs(e.touches[0].pageX - startY)) : (Math.abs(dx) < Math.abs(e.touches[0].pageY - startY));

          if (!scrolling || Number(new Date()) - startT > 500) {
            e.preventDefault();
            if (!fade && slider.transitions) {
              if (!vars.animationLoop) {
                dx = dx/((slider.currentSlide === 0 && dx < 0 || slider.currentSlide === slider.last && dx > 0) ? (Math.abs(dx)/cwidth+2) : 1);
              }
              slider.setProps(offset + dx, "setTouch");
            }
          }
        }

        function onTouchEnd(e) {
          // finish the touch by undoing the touch session
          el.removeEventListener('touchmove', onTouchMove, false);

          if (slider.animatingTo === slider.currentSlide && !scrolling && !(dx === null)) {
            var updateDx = (reverse) ? -dx : dx,
                target = (updateDx > 0) ? slider.getTarget('next') : slider.getTarget('prev');

            if (slider.canAdvance(target) && (Number(new Date()) - startT < 550 && Math.abs(updateDx) > 50 || Math.abs(updateDx) > cwidth/2)) {
              slider.flexAnimate(target, vars.pauseOnAction);
            } else {
              if (!fade) slider.flexAnimate(slider.currentSlide, vars.pauseOnAction, true);
            }
          }
          el.removeEventListener('touchend', onTouchEnd, false);
          startX = null;
          startY = null;
          dx = null;
          offset = null;
        }
      },
      resize: function() {
        if (!slider.animating && slider.is(':visible')) {
          if (!carousel) slider.doMath();

          if (fade) {
            // SMOOTH HEIGHT:
            methods.smoothHeight();
          } else if (carousel) { //CAROUSEL:
            slider.slides.width(slider.computedW);
            slider.update(slider.pagingCount);
            slider.setProps();
          }
          else if (vertical) { //VERTICAL:
            slider.viewport.height(slider.h);
            slider.setProps(slider.h, "setTotal");
          } else {
            // SMOOTH HEIGHT:
            if (vars.smoothHeight) methods.smoothHeight();
            slider.newSlides.width(slider.computedW);
            slider.setProps(slider.computedW, "setTotal");
          }
        }
      },
      smoothHeight: function(dur) {
        if (!vertical || fade) {
          var $obj = (fade) ? slider : slider.viewport;
          (dur) ? $obj.animate({"height": slider.slides.eq(slider.animatingTo).height()}, dur) : $obj.height(slider.slides.eq(slider.animatingTo).height());
        }
      },
      sync: function(action) {
        var $obj = $(vars.sync).data("flexslider"),
            target = slider.animatingTo;

        switch (action) {
          case "animate": $obj.flexAnimate(target, vars.pauseOnAction, false, true); break;
          case "play": if (!$obj.playing && !$obj.asNav) { $obj.play(); } break;
          case "pause": $obj.pause(); break;
        }
      }
    }

    // public methods
    slider.flexAnimate = function(target, pause, override, withSync, fromNav) {
      if (asNav && slider.pagingCount === 1) slider.direction = (slider.currentItem < target) ? "next" : "prev";


      if (!slider.animating && (slider.canAdvance(target, fromNav) || override) && slider.is(":visible")) {
        if (asNav && withSync) {
          var master = $(vars.asNavFor).data('flexslider');
          master.flexAnimate(target, true, false, true, fromNav);
          slider.direction = (slider.currentItem < target) ? "next" : "prev";
          master.direction = slider.direction;

          if (Math.ceil((target + 1)/slider.visible) - 1 !== slider.currentSlide) {
            slider.currentItem = target;
            slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
            target = Math.floor(target/slider.visible);
                        return false;
          } else {
            slider.currentItem = target;
            slider.slides.removeClass(namespace + "active-slide").eq(target).addClass(namespace + "active-slide");
            return false;
          }
        }

        slider.animating = true;
        slider.animatingTo = target;
        // API: before() animation Callback
        vars.before(slider);

        // SLIDESHOW:
        if (pause) slider.pause();

        // SYNC:
        if (slider.syncExists && !fromNav) methods.sync("animate");

        // CONTROLNAV
        if (vars.controlNav) methods.controlNav.active();

        // !CAROUSEL:
        // CANDIDATE: slide active class (for add/remove slide)
        if (!carousel) slider.slides.removeClass(namespace + 'active-slide').eq(target).addClass(namespace + 'active-slide');

        // DIRECTIONNAV:
        if (vars.directionNav) methods.directionNav.update();

        if (target === slider.last) {
          // API: end() of cycle Callback
          vars.end(slider);
          // SLIDESHOW && !INFINITE LOOP:
          if (!vars.animationLoop) slider.pause();
        }

        // SLIDE:
        if (!fade) {
          var dimension = (vertical) ? slider.slides.filter(':first').height() : slider.computedW,
              margin, slideString, calcNext;

          // INFINITE LOOP / REVERSE:
          if (carousel) {
                        if(vertical) {
                            margin = (vars.itemHeight > slider.h) ? vars.itemMargin * 2 : vars.itemMargin;
                            calcNext = ((slider.itemH + margin) * slider.move) * slider.animatingTo;
                            slideString = (calcNext > slider.limit && slider.visible !== 1) ? slider.limit : calcNext;
                        } else {
            margin = (vars.itemWidth > slider.w) ? vars.itemMargin * 2 : vars.itemMargin;
            calcNext = ((slider.itemW + margin) * slider.move) * slider.animatingTo;
            slideString = (calcNext > slider.limit && slider.visible !== 1) ? slider.limit : calcNext;
                        }
          } else if (slider.currentSlide === 0 && target === slider.count - 1 && vars.animationLoop && slider.direction !== "next") {
            slideString = (reverse) ? (slider.count + slider.cloneOffset) * dimension : 0;
          } else if (slider.currentSlide === slider.last && target === 0 && vars.animationLoop && slider.direction !== "prev") {
            slideString = (reverse) ? 0 : (slider.count + 1) * dimension;
          } else {
            slideString = (reverse) ? ((slider.count - 1) - target + slider.cloneOffset) * dimension : (target + slider.cloneOffset) * dimension;
          }
          slider.setProps(slideString, "", vars.animationSpeed);
          if (slider.transitions) {
            if (!vars.animationLoop) {
              slider.animating = false;
              slider.currentSlide = slider.animatingTo;
            }
            slider.container.unbind("webkitTransitionEnd transitionend");
            slider.container.bind("webkitTransitionEnd transitionend", function() {
              slider.wrapup(dimension);
            });
          } else {
            slider.container.animate(slider.args, vars.animationSpeed, vars.easing, function(){
              slider.wrapup(dimension);
            });
          }
        } else { // FADE:
            slider.slides.eq(slider.currentSlide).fadeOut(vars.animationSpeed, vars.easing);
            slider.slides.eq(target).fadeIn(vars.animationSpeed, vars.easing, slider.wrapup);
        }
        // SMOOTH HEIGHT:
        if (vars.smoothHeight) methods.smoothHeight(vars.animationSpeed);
      }
    }
    slider.wrapup = function(dimension) {
      // SLIDE:
      if (!fade && !carousel) {
        if (slider.currentSlide === 0 && slider.animatingTo === slider.last && vars.animationLoop) {
          slider.setProps(dimension, "jumpEnd");
        } else if (slider.currentSlide === slider.last && slider.animatingTo === 0 && vars.animationLoop) {
          slider.setProps(dimension, "jumpStart");
        }
      }
      slider.animating = false;
      slider.currentSlide = slider.animatingTo;
      // API: after() animation Callback
      vars.after(slider);
    }

    // SLIDESHOW:
    slider.animateSlides = function() {
      if (!slider.animating) slider.flexAnimate(slider.getTarget("next"));
    }
    // SLIDESHOW:
    slider.pause = function() {
      clearInterval(slider.animatedSlides);
      slider.playing = false;
      // PAUSEPLAY:
      if (vars.pausePlay) methods.pausePlay.update("play");
      // SYNC:
      if (slider.syncExists) methods.sync("pause");
    }
    // SLIDESHOW:
    slider.play = function() {
      slider.animatedSlides = setInterval(slider.animateSlides, vars.slideshowSpeed);
      slider.playing = true;
      // PAUSEPLAY:
      if (vars.pausePlay) methods.pausePlay.update("pause");
      // SYNC:
      if (slider.syncExists) methods.sync("play");
    }
    slider.canAdvance = function(target, fromNav) {
      // ASNAV:
      var last = (asNav) ? slider.pagingCount - 1 : slider.last;
      var last = (asNav) ? slider.pagingCount - 1 : slider.last;
      if (fromNav) { return true; 
                }   else if (asNav && slider.currentItem === slider.count - 1 && target === 0 && slider.direction === "prev") { return true;
                } else if (asNav && slider.currentItem === 0 && target === slider.pagingCount - 1 && slider.direction !== "next") { return false;
                } else if (asNav && slider.count < vars.maxItems) { return false;
                } else if (target === slider.currentSlide && !asNav) { return false;
                } else if (vars.animationLoop) { return true;
                } else if (slider.atEnd && slider.currentSlide === 0 && target === last && slider.direction !== "next") { return false;
                } else if (slider.atEnd && slider.currentSlide === last && target === 0 && slider.direction === "next") { return false;
                } else { return true; 
            }
    }
    slider.getTarget = function(dir) {
      slider.direction = dir;
      if (dir === "next") {
        return (slider.currentSlide === slider.last) ? 0 : slider.currentSlide + 1;
      } else {
        return (slider.currentSlide === 0) ? slider.last : slider.currentSlide - 1;
      }
    }

    // SLIDE:
    slider.setProps = function(pos, special, dur) {
      var target = (function() {
        var posCheck = (pos) ? pos : ((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo,
            posCalc = (function() {
              if (carousel) {
                return (special === "setTouch") ? pos :
                       (reverse && slider.animatingTo === slider.last) ? 0 :
                       (reverse) ? slider.limit - (((slider.itemW + vars.itemMargin) * slider.move) * slider.animatingTo) : posCheck;
              } else {
                switch (special) {
                  case "setTotal": return (reverse) ? ((slider.count - 1) - slider.currentSlide + slider.cloneOffset) * pos : (slider.currentSlide + slider.cloneOffset) * pos;
                  case "setTouch": return (reverse) ? pos : pos;
                  case "jumpEnd": return (reverse) ? pos : slider.count * pos;
                  case "jumpStart": return (reverse) ? slider.count * pos : pos;
                  default: return pos;
                }
              }
            }());
            return (posCalc * -1) + "px";
          }());

      if (slider.transitions) {
        target = (vertical) ? "translate3d(0," + target + ",0)" : "translate3d(" + target + ",0,0)";
        dur = (dur !== undefined) ? (dur/1000) + "s" : "0s";
        slider.container.css("-" + slider.pfx + "-transition-duration", dur);
        slider.container.css("transition-duration", dur); // JDW specific 
      }

      slider.args[slider.prop] = target;
      if (slider.transitions || dur === undefined) slider.container.css(slider.args);
      slider.container.css('transform',target); // JDW specific 
    }

    slider.setup = function(type) {
      // SLIDE:
      if (!fade) {
        var sliderOffset, arr;

        if (type === "init") {
          slider.viewport = $('<div class="' + namespace + 'viewport"></div>').css({"overflow": "hidden", "position": "relative"}).appendTo(slider).append(slider.container);
          // INFINITE LOOP:
          slider.cloneCount = 0;
          slider.cloneOffset = 0;
          // REVERSE:
          if (reverse) {
            arr = $.makeArray(slider.slides).reverse();
            slider.slides = $(arr);
            slider.container.empty().append(slider.slides);
          }
        }
        // INFINITE LOOP && !CAROUSEL:
        if (vars.animationLoop && !carousel) {
          slider.cloneCount = 2;
          slider.cloneOffset = 1;
          // clear out old clones
          if (type !== "init") slider.container.find('.clone').remove();
          slider.container.append(slider.slides.first().clone().addClass('clone')).prepend(slider.slides.last().clone().addClass('clone'));
        }
        slider.newSlides = $(vars.selector, slider);

        sliderOffset = (reverse) ? slider.count - 1 - slider.currentSlide + slider.cloneOffset : slider.currentSlide + slider.cloneOffset;
        // VERTICAL:
        if (vertical && !carousel) {
          slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
          setTimeout(function(){
            slider.newSlides.css({"display": "block"});
            slider.doMath();
            slider.viewport.height(slider.h);
            slider.setProps(sliderOffset * slider.h, "init");
          }, (type === "init") ? 100 : 0);
        } else {
          slider.container.width((slider.count + slider.cloneCount) * 200 + "%");
          slider.setProps(sliderOffset * slider.computedW, "init");
          setTimeout(function(){
            slider.doMath();
            slider.newSlides.css({"width": slider.computedW, "float": "left", "display": "block"});
            // SMOOTH HEIGHT:
            if (vars.smoothHeight) methods.smoothHeight();
          }, (type === "init") ? 100 : 0);
        }
      } else { // FADE:
        slider.slides.css({"width": "100%", "float": "left", "marginRight": "-100%", "position": "relative"});
        if (type === "init") slider.slides.eq(slider.currentSlide).fadeIn(vars.animationSpeed, vars.easing);
        // SMOOTH HEIGHT:
        if (vars.smoothHeight) methods.smoothHeight();
      }
      // !CAROUSEL:
      // CANDIDATE: active slide
      if (!carousel) slider.slides.removeClass(namespace + "active-slide").eq(slider.currentSlide).addClass(namespace + "active-slide");
    }

    slider.doMath = function() {
      var slide = slider.slides.first(),
          slideMargin = vars.itemMargin,
          minItems = vars.minItems,
          maxItems = vars.maxItems;

      slider.w = slider.width();
            if (vertical) slider.w = slider.height();
      slider.boxPadding = slide.outerWidth() - slide.width();

      // CAROUSEL:
      if (carousel) {
        slider.itemT = vars.itemWidth + slideMargin;
        slider.minW = (minItems) ? minItems * slider.itemT : slider.w;
        slider.maxW = (maxItems) ? maxItems * slider.itemT : slider.w;
        /*slider.itemW = (slider.minW > slider.w) ? (slider.w - (slideMargin * minItems))/minItems :
                       (slider.maxW < slider.w) ? (slider.w - (slideMargin * maxItems))/maxItems :
                       (vars.itemWidth > slider.w) ? slider.w : vars.itemWidth;*/
        slider.itemW = (slider.w - (slideMargin * maxItems))/maxItems;
        slider.visible = Math.floor(slider.w/(slider.itemW + slideMargin));
        slider.move = (vars.move > 0 && vars.move < slider.visible ) ? vars.move : slider.visible;
        slider.pagingCount = Math.ceil(((slider.count - slider.visible)/slider.move) + 1);
        slider.last =  slider.pagingCount - 1;
        slider.limit = (slider.pagingCount === 1) ? 0 :
                       (vars.itemWidth > slider.w) ? ((slider.itemW + (slideMargin * 2)) * slider.count) - slider.w - slideMargin : ((slider.itemW + slideMargin) * slider.count) - slider.w - slideMargin;
      } else {
        slider.itemW = (vertical) ? slider.height() : slider.w;
        slider.pagingCount = slider.count;
        slider.last = slider.count - 1;
      }
      slider.computedW = slider.itemW - slider.boxPadding;
    }

    slider.update = function(pos, action) {
      slider.doMath();
      
      // PJ196: Forces slides to resize to the newly computed appropriate size after a resize.
      slider.slides.css({"width": slider.computedW, "float": "left", "display": "block"});

      // update currentSlide and slider.animatingTo if necessary
      if (!carousel) {
        if (pos < slider.currentSlide) {
          slider.currentSlide += 1;
        } else if (pos <= slider.currentSlide && pos !== 0) {
          slider.currentSlide -= 1;
        }
        slider.animatingTo = slider.currentSlide;
      }

      // update controlNav
      if (vars.controlNav && !slider.manualControls) {
        if ((action === "add" && !carousel) || slider.pagingCount > slider.controlNav.length) {
          methods.controlNav.update("add");
        } else if ((action === "remove" && !carousel) || slider.pagingCount < slider.controlNav.length) {
          if (carousel && slider.currentSlide > slider.last) {
            slider.currentSlide -= 1;
            slider.animatingTo -= 1;
          }
          methods.controlNav.update("remove", slider.last);
        }
      }
      // update directionNav
      if (vars.directionNav) methods.directionNav.update();

    }

    slider.addSlide = function(obj, pos) {
      var $obj = $(obj);

      slider.count += 1;
      slider.last = slider.count - 1;

      // append new slide
      if (vertical && reverse) {
        (pos !== undefined) ? slider.slides.eq(slider.count - pos).after($obj) : slider.container.prepend($obj);
      } else {
        (pos !== undefined) ? slider.slides.eq(pos).before($obj) : slider.container.append($obj);
      }

      // update currentSlide, animatingTo, controlNav, and directionNav
      slider.update(pos, "add");

      // update slider.slides
      slider.slides = $(vars.selector + ':not(.clone)', slider);
      // re-setup the slider to accomdate new slide
      slider.setup();

      //FlexSlider: added() Callback
      vars.added(slider);
    }
    slider.removeSlide = function(obj) {
      var pos = (isNaN(obj)) ? slider.slides.index($(obj)) : obj;

      // update count
      slider.count -= 1;
      slider.last = slider.count - 1;

      // remove slide
      if (isNaN(obj)) {
        $(obj, slider.slides).remove();
      } else {
        (vertical && reverse) ? slider.slides.eq(slider.last).remove() : slider.slides.eq(obj).remove();
      }

      // update currentSlide, animatingTo, controlNav, and directionNav
      slider.doMath();
      slider.update(pos, "remove");

      // update slider.slides
      slider.slides = $(vars.selector + ':not(.clone)', slider);
      // re-setup the slider to accomdate new slide
      slider.setup();

      // FlexSlider: removed() Callback
      vars.removed(slider);
    }

    slider.updateScroll = function(flexArray) {
        vars.direction = flexArray.direction;
        vars.maxItems = flexArray.items;
        vertical = vars.direction === "vertical";
       slider.update();
    slider.flexAnimate(0);
    }
    
    slider.updateScrollHorizontal = function(flexArray, scrollTo) {
        vars.direction = "horizontal";
        vars.maxItems = flexArray.items;
        vertical = false;
        slider.update();
        if(typeof scrollTo === 'undefined') {
            scrollTo = 0;
        }
        slider.flexAnimate(0);
        slider.flexAnimate(scrollTo);
    }
    
    //FlexSlider: Initialize
    methods.init();
  }

  //FlexSlider: Default Settings
  $.flexslider.defaults = {
    namespace: "flex-",             //{NEW} String: Prefix string attached to the class of every element generated by the plugin
    selector: ".slides > li",       //{NEW} Selector: Must match a simple pattern. '{container} > {slide}' -- Ignore pattern at your own peril
    animation: "fade",              //String: Select your animation type, "fade" or "slide"
    easing: "swing",               //{NEW} String: Determines the easing method used in jQuery transitions. jQuery easing plugin is supported!
    direction: "horizontal",        //String: Select the sliding direction, "horizontal" or "vertical"
    reverse: false,                 //{NEW} Boolean: Reverse the animation direction
    animationLoop: true,             //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
    smoothHeight: false,            //{NEW} Boolean: Allow height of the slider to animate smoothly in horizontal mode
    startAt: 0,                     //Integer: The slide that the slider should start on. Array notation (0 = first slide)
    slideshow: true,                //Boolean: Animate slider automatically
    slideshowSpeed: 7000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
    animationSpeed: 600,            //Integer: Set the speed of animations, in milliseconds
    initDelay: 0,                   //{NEW} Integer: Set an initialization delay, in milliseconds
    randomize: false,               //Boolean: Randomize slide order

    // Usability features
    pauseOnAction: true,            //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
    pauseOnHover: false,            //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
    useCSS: true,                   //{NEW} Boolean: Slider will use CSS3 transitions if available
    touch: true,                    //{NEW} Boolean: Allow touch swipe navigation of the slider on touch-enabled devices
    video: false,                   //{NEW} Boolean: If using video in the slider, will prevent CSS3 3D Transforms to avoid graphical glitches

    // Primary Controls
    controlNav: true,               //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
    directionNav: true,             //Boolean: Create navigation for previous/next navigation? (true/false)
    prevText: "",           //String: Set the text for the "previous" directionNav item
    nextText: "",               //String: Set the text for the "next" directionNav item

    // Secondary Navigation
    keyboard: true,                 //Boolean: Allow slider navigating via keyboard left/right keys
    multipleKeyboard: false,        //{NEW} Boolean: Allow keyboard navigation to affect multiple sliders. Default behavior cuts out keyboard navigation with more than one slider present.
    mousewheel: false,              //{UPDATED} Boolean: Requires jquery.mousewheel.js (https://github.com/brandonaaron/jquery-mousewheel) - Allows slider navigating via mousewheel
    pausePlay: false,               //Boolean: Create pause/play dynamic element
    pauseText: "Pause",             //String: Set the text for the "pause" pausePlay item
    playText: "Play",               //String: Set the text for the "play" pausePlay item

    // Special properties
    controlsContainer: "",          //{UPDATED} jQuery Object/Selector: Declare which container the navigation elements should be appended too. Default container is the FlexSlider element. Example use would be $(".flexslider-container"). Property is ignored if given element is not found.
    manualControls: "",             //{UPDATED} jQuery Object/Selector: Declare custom control navigation. Examples would be $(".flex-control-nav li") or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
    sync: "",                       //{NEW} Selector: Mirror the actions performed on this slider with another slider. Use with care.
    asNavFor: "",                   //{NEW} Selector: Internal property exposed for turning the slider into a thumbnail navigation for another slider

    // Carousel Options
    itemWidth: 0,                   //{NEW} Integer: Box-model width of individual carousel items, including horizontal borders and padding.
    itemMargin: 0,                  //{NEW} Integer: Margin between carousel items.
    minItems: 0,                    //{NEW} Integer: Minimum number of carousel items that should be visible. Items will resize fluidly when below this.
    maxItems: 0,                    //{NEW} Integer: Maxmimum number of carousel items that should be visible. Items will resize fluidly when above this limit.
    move: 1,                        //{NEW} Integer: Number of carousel items that should move on animation. If 0, slider will move all visible items.

    // Callback API
    start: function(){},            //Callback: function(slider) - Fires when the slider loads the first slide
    before: function(){},           //Callback: function(slider) - Fires asynchronously with each slider animation
    after: function(){},            //Callback: function(slider) - Fires after each slider animation completes
    end: function(){},              //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
    added: function(){},            //{NEW} Callback: function(slider) - Fires after a slide is added
    removed: function(){}           //{NEW} Callback: function(slider) - Fires after a slide is removed
  }


  //FlexSlider: Plugin Function
  $.fn.flexslider = function(options) {
    if (options === undefined) options = {};

    if (typeof options === "object") {
      return this.each(function() {
        var $this = $(this),
            selector = (options.selector) ? options.selector : ".slides > li",
            $slides = $this.find(selector);
        //Added to prevent problems with ajax-refreshed pages being reloaded in full.
        $this.removeData('flexslider');
        if ($this.data('flexslider') === undefined) {
          new $.flexslider(this, options);
        }
      });
    } else {
      // Helper strings to quickly perform functions on the slider
      var $slider = $(this).data('flexslider');
      switch (options) {
        case "play": $slider.play(); break;
        case "pause": $slider.pause(); break;
        case "next": $slider.flexAnimate($slider.getTarget("next"), true); break;
        case "prev":
        case "previous": $slider.flexAnimate($slider.getTarget("prev"), true); break;
        default: if (typeof options === "number") $slider.flexAnimate(options, true);
      }
    }
  }

})(jQuery);/* complete : /javascript/common/libraries/jquery/flexslider.js*/


/* combine : /javascript/common/libraries/jquery/jquery.jcarousel-0.3.3.min.js*/
/*! jCarousel - v0.3.3 - 2015-04-07
* http://sorgalla.com/jcarousel/
* Copyright (c) 2006-2015 Jan Sorgalla; Licensed MIT */
!function(a){"use strict";var b=a.jCarousel={};b.version="0.3.3";var c=/^([+\-]=)?(.+)$/;b.parseTarget=function(a){var b=!1,d="object"!=typeof a?c.exec(a):null;return d?(a=parseInt(d[2],10)||0,d[1]&&(b=!0,"-="===d[1]&&(a*=-1))):"object"!=typeof a&&(a=parseInt(a,10)||0),{target:a,relative:b}},b.detectCarousel=function(a){for(var b;a.length>0;){if(b=a.filter("[data-jcarousel]"),b.length>0)return b;if(b=a.find("[data-jcarousel]"),b.length>0)return b;a=a.parent()}return null},b.base=function(c){return{version:b.version,_options:{},_element:null,_carousel:null,_init:a.noop,_create:a.noop,_destroy:a.noop,_reload:a.noop,create:function(){return this._element.attr("data-"+c.toLowerCase(),!0).data(c,this),!1===this._trigger("create")?this:(this._create(),this._trigger("createend"),this)},destroy:function(){return!1===this._trigger("destroy")?this:(this._destroy(),this._trigger("destroyend"),this._element.removeData(c).removeAttr("data-"+c.toLowerCase()),this)},reload:function(a){return!1===this._trigger("reload")?this:(a&&this.options(a),this._reload(),this._trigger("reloadend"),this)},element:function(){return this._element},options:function(b,c){if(0===arguments.length)return a.extend({},this._options);if("string"==typeof b){if("undefined"==typeof c)return"undefined"==typeof this._options[b]?null:this._options[b];this._options[b]=c}else this._options=a.extend({},this._options,b);return this},carousel:function(){return this._carousel||(this._carousel=b.detectCarousel(this.options("carousel")||this._element),this._carousel||a.error('Could not detect carousel for plugin "'+c+'"')),this._carousel},_trigger:function(b,d,e){var f,g=!1;return e=[this].concat(e||[]),(d||this._element).each(function(){f=a.Event((c+":"+b).toLowerCase()),a(this).trigger(f,e),f.isDefaultPrevented()&&(g=!0)}),!g}}},b.plugin=function(c,d){var e=a[c]=function(b,c){this._element=a(b),this.options(c),this._init(),this.create()};return e.fn=e.prototype=a.extend({},b.base(c),d),a.fn[c]=function(b){var d=Array.prototype.slice.call(arguments,1),f=this;return this.each("string"==typeof b?function(){var e=a(this).data(c);if(!e)return a.error("Cannot call methods on "+c+' prior to initialization; attempted to call method "'+b+'"');if(!a.isFunction(e[b])||"_"===b.charAt(0))return a.error('No such method "'+b+'" for '+c+" instance");var g=e[b].apply(e,d);return g!==e&&"undefined"!=typeof g?(f=g,!1):void 0}:function(){var d=a(this).data(c);d instanceof e?d.reload(b):new e(this,b)}),f},e}}(jQuery),function(a,b){"use strict";var c=function(a){return parseFloat(a)||0};a.jCarousel.plugin("jcarousel",{animating:!1,tail:0,inTail:!1,resizeTimer:null,lt:null,vertical:!1,rtl:!1,circular:!1,underflow:!1,relative:!1,_options:{list:function(){return this.element().children().eq(0)},items:function(){return this.list().children()},animation:400,transitions:!1,wrap:null,vertical:null,rtl:null,center:!1},_list:null,_items:null,_target:a(),_first:a(),_last:a(),_visible:a(),_fullyvisible:a(),_init:function(){var a=this;return this.onWindowResize=function(){a.resizeTimer&&clearTimeout(a.resizeTimer),a.resizeTimer=setTimeout(function(){a.reload()},100)},this},_create:function(){this._reload(),a(b).on("resize.jcarousel",this.onWindowResize)},_destroy:function(){a(b).off("resize.jcarousel",this.onWindowResize)},_reload:function(){this.vertical=this.options("vertical"),null==this.vertical&&(this.vertical=this.list().height()>this.list().width()),this.rtl=this.options("rtl"),null==this.rtl&&(this.rtl=function(b){if("rtl"===(""+b.attr("dir")).toLowerCase())return!0;var c=!1;return b.parents("[dir]").each(function(){return/rtl/i.test(a(this).attr("dir"))?(c=!0,!1):void 0}),c}(this._element)),this.lt=this.vertical?"top":"left",this.relative="relative"===this.list().css("position"),this._list=null,this._items=null;var b=this.index(this._target)>=0?this._target:this.closest();this.circular="circular"===this.options("wrap"),this.underflow=!1;var c={left:0,top:0};return b.length>0&&(this._prepare(b),this.list().find("[data-jcarousel-clone]").remove(),this._items=null,this.underflow=this._fullyvisible.length>=this.items().length,this.circular=this.circular&&!this.underflow,c[this.lt]=this._position(b)+"px"),this.move(c),this},list:function(){if(null===this._list){var b=this.options("list");this._list=a.isFunction(b)?b.call(this):this._element.find(b)}return this._list},items:function(){if(null===this._items){var b=this.options("items");this._items=(a.isFunction(b)?b.call(this):this.list().find(b)).not("[data-jcarousel-clone]")}return this._items},index:function(a){return this.items().index(a)},closest:function(){var b,d=this,e=this.list().position()[this.lt],f=a(),g=!1,h=this.vertical?"bottom":this.rtl&&!this.relative?"left":"right";return this.rtl&&this.relative&&!this.vertical&&(e+=this.list().width()-this.clipping()),this.items().each(function(){if(f=a(this),g)return!1;var i=d.dimension(f);if(e+=i,e>=0){if(b=i-c(f.css("margin-"+h)),!(Math.abs(e)-i+b/2<=0))return!1;g=!0}}),f},target:function(){return this._target},first:function(){return this._first},last:function(){return this._last},visible:function(){return this._visible},fullyvisible:function(){return this._fullyvisible},hasNext:function(){if(!1===this._trigger("hasnext"))return!0;var a=this.options("wrap"),b=this.items().length-1,c=this.options("center")?this._target:this._last;return b>=0&&!this.underflow&&(a&&"first"!==a||this.index(c)<b||this.tail&&!this.inTail)?!0:!1},hasPrev:function(){if(!1===this._trigger("hasprev"))return!0;var a=this.options("wrap");return this.items().length>0&&!this.underflow&&(a&&"last"!==a||this.index(this._first)>0||this.tail&&this.inTail)?!0:!1},clipping:function(){return this._element["inner"+(this.vertical?"Height":"Width")]()},dimension:function(a){return a["outer"+(this.vertical?"Height":"Width")](!0)},scroll:function(b,c,d){if(this.animating)return this;if(!1===this._trigger("scroll",null,[b,c]))return this;a.isFunction(c)&&(d=c,c=!0);var e=a.jCarousel.parseTarget(b);if(e.relative){var f,g,h,i,j,k,l,m,n=this.items().length-1,o=Math.abs(e.target),p=this.options("wrap");if(e.target>0){var q=this.index(this._last);if(q>=n&&this.tail)this.inTail?"both"===p||"last"===p?this._scroll(0,c,d):a.isFunction(d)&&d.call(this,!1):this._scrollTail(c,d);else if(f=this.index(this._target),this.underflow&&f===n&&("circular"===p||"both"===p||"last"===p)||!this.underflow&&q===n&&("both"===p||"last"===p))this._scroll(0,c,d);else if(h=f+o,this.circular&&h>n){for(m=n,j=this.items().get(-1);m++<h;)j=this.items().eq(0),k=this._visible.index(j)>=0,k&&j.after(j.clone(!0).attr("data-jcarousel-clone",!0)),this.list().append(j),k||(l={},l[this.lt]=this.dimension(j),this.moveBy(l)),this._items=null;this._scroll(j,c,d)}else this._scroll(Math.min(h,n),c,d)}else if(this.inTail)this._scroll(Math.max(this.index(this._first)-o+1,0),c,d);else if(g=this.index(this._first),f=this.index(this._target),i=this.underflow?f:g,h=i-o,0>=i&&(this.underflow&&"circular"===p||"both"===p||"first"===p))this._scroll(n,c,d);else if(this.circular&&0>h){for(m=h,j=this.items().get(0);m++<0;){j=this.items().eq(-1),k=this._visible.index(j)>=0,k&&j.after(j.clone(!0).attr("data-jcarousel-clone",!0)),this.list().prepend(j),this._items=null;var r=this.dimension(j);l={},l[this.lt]=-r,this.moveBy(l)}this._scroll(j,c,d)}else this._scroll(Math.max(h,0),c,d)}else this._scroll(e.target,c,d);return this._trigger("scrollend"),this},moveBy:function(a,b){var d=this.list().position(),e=1,f=0;return this.rtl&&!this.vertical&&(e=-1,this.relative&&(f=this.list().width()-this.clipping())),a.left&&(a.left=d.left+f+c(a.left)*e+"px"),a.top&&(a.top=d.top+f+c(a.top)*e+"px"),this.move(a,b)},move:function(b,c){c=c||{};var d=this.options("transitions"),e=!!d,f=!!d.transforms,g=!!d.transforms3d,h=c.duration||0,i=this.list();if(!e&&h>0)return void i.animate(b,c);var j=c.complete||a.noop,k={};if(e){var l={transitionDuration:i.css("transitionDuration"),transitionTimingFunction:i.css("transitionTimingFunction"),transitionProperty:i.css("transitionProperty")},m=j;j=function(){a(this).css(l),m.call(this)},k={transitionDuration:(h>0?h/1e3:0)+"s",transitionTimingFunction:d.easing||c.easing,transitionProperty:h>0?function(){return f||g?"all":b.left?"left":"top"}():"none",transform:"none"}}g?k.transform="translate3d("+(b.left||0)+","+(b.top||0)+",0)":f?k.transform="translate("+(b.left||0)+","+(b.top||0)+")":a.extend(k,b),e&&h>0&&i.one("transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd",j),i.css(k),0>=h&&i.each(function(){j.call(this)})},_scroll:function(b,c,d){if(this.animating)return a.isFunction(d)&&d.call(this,!1),this;if("object"!=typeof b?b=this.items().eq(b):"undefined"==typeof b.jquery&&(b=a(b)),0===b.length)return a.isFunction(d)&&d.call(this,!1),this;this.inTail=!1,this._prepare(b);var e=this._position(b),f=this.list().position()[this.lt];if(e===f)return a.isFunction(d)&&d.call(this,!1),this;var g={};return g[this.lt]=e+"px",this._animate(g,c,d),this},_scrollTail:function(b,c){if(this.animating||!this.tail)return a.isFunction(c)&&c.call(this,!1),this;var d=this.list().position()[this.lt];this.rtl&&this.relative&&!this.vertical&&(d+=this.list().width()-this.clipping()),this.rtl&&!this.vertical?d+=this.tail:d-=this.tail,this.inTail=!0;var e={};return e[this.lt]=d+"px",this._update({target:this._target.next(),fullyvisible:this._fullyvisible.slice(1).add(this._visible.last())}),this._animate(e,b,c),this},_animate:function(b,c,d){if(d=d||a.noop,!1===this._trigger("animate"))return d.call(this,!1),this;this.animating=!0;var e=this.options("animation"),f=a.proxy(function(){this.animating=!1;var a=this.list().find("[data-jcarousel-clone]");a.length>0&&(a.remove(),this._reload()),this._trigger("animateend"),d.call(this,!0)},this),g="object"==typeof e?a.extend({},e):{duration:e},h=g.complete||a.noop;return c===!1?g.duration=0:"undefined"!=typeof a.fx.speeds[g.duration]&&(g.duration=a.fx.speeds[g.duration]),g.complete=function(){f(),h.call(this)},this.move(b,g),this},_prepare:function(b){var d,e,f,g,h=this.index(b),i=h,j=this.dimension(b),k=this.clipping(),l=this.vertical?"bottom":this.rtl?"left":"right",m=this.options("center"),n={target:b,first:b,last:b,visible:b,fullyvisible:k>=j?b:a()};if(m&&(j/=2,k/=2),k>j)for(;;){if(d=this.items().eq(++i),0===d.length){if(!this.circular)break;if(d=this.items().eq(0),b.get(0)===d.get(0))break;if(e=this._visible.index(d)>=0,e&&d.after(d.clone(!0).attr("data-jcarousel-clone",!0)),this.list().append(d),!e){var o={};o[this.lt]=this.dimension(d),this.moveBy(o)}this._items=null}if(g=this.dimension(d),0===g)break;if(j+=g,n.last=d,n.visible=n.visible.add(d),f=c(d.css("margin-"+l)),k>=j-f&&(n.fullyvisible=n.fullyvisible.add(d)),j>=k)break}if(!this.circular&&!m&&k>j)for(i=h;;){if(--i<0)break;if(d=this.items().eq(i),0===d.length)break;if(g=this.dimension(d),0===g)break;if(j+=g,n.first=d,n.visible=n.visible.add(d),f=c(d.css("margin-"+l)),k>=j-f&&(n.fullyvisible=n.fullyvisible.add(d)),j>=k)break}return this._update(n),this.tail=0,m||"circular"===this.options("wrap")||"custom"===this.options("wrap")||this.index(n.last)!==this.items().length-1||(j-=c(n.last.css("margin-"+l)),j>k&&(this.tail=j-k)),this},_position:function(a){var b=this._first,c=b.position()[this.lt],d=this.options("center"),e=d?this.clipping()/2-this.dimension(b)/2:0;return this.rtl&&!this.vertical?(c-=this.relative?this.list().width()-this.dimension(b):this.clipping()-this.dimension(b),c+=e):c-=e,!d&&(this.index(a)>this.index(b)||this.inTail)&&this.tail?(c=this.rtl&&!this.vertical?c-this.tail:c+this.tail,this.inTail=!0):this.inTail=!1,-c},_update:function(b){var c,d=this,e={target:this._target,first:this._first,last:this._last,visible:this._visible,fullyvisible:this._fullyvisible},f=this.index(b.first||e.first)<this.index(e.first),g=function(c){var g=[],h=[];b[c].each(function(){e[c].index(this)<0&&g.push(this)}),e[c].each(function(){b[c].index(this)<0&&h.push(this)}),f?g=g.reverse():h=h.reverse(),d._trigger(c+"in",a(g)),d._trigger(c+"out",a(h)),d["_"+c]=b[c]};for(c in b)g(c);return this}})}(jQuery,window),function(a){"use strict";a.jcarousel.fn.scrollIntoView=function(b,c,d){var e,f=a.jCarousel.parseTarget(b),g=this.index(this._fullyvisible.first()),h=this.index(this._fullyvisible.last());if(e=f.relative?f.target<0?Math.max(0,g+f.target):h+f.target:"object"!=typeof f.target?f.target:this.index(f.target),g>e)return this.scroll(e,c,d);if(e>=g&&h>=e)return a.isFunction(d)&&d.call(this,!1),this;for(var i,j=this.items(),k=this.clipping(),l=this.vertical?"bottom":this.rtl?"left":"right",m=0;;){if(i=j.eq(e),0===i.length)break;if(m+=this.dimension(i),m>=k){var n=parseFloat(i.css("margin-"+l))||0;m-n!==k&&e++;break}if(0>=e)break;e--}return this.scroll(e,c,d)}}(jQuery),function(a){"use strict";a.jCarousel.plugin("jcarouselControl",{_options:{target:"+=1",event:"click",method:"scroll"},_active:null,_init:function(){this.onDestroy=a.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",a.proxy(this._create,this))},this),this.onReload=a.proxy(this._reload,this),this.onEvent=a.proxy(function(b){b.preventDefault();var c=this.options("method");a.isFunction(c)?c.call(this):this.carousel().jcarousel(this.options("method"),this.options("target"))},this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy).on("jcarousel:reloadend jcarousel:scrollend",this.onReload),this._element.on(this.options("event")+".jcarouselcontrol",this.onEvent),this._reload()},_destroy:function(){this._element.off(".jcarouselcontrol",this.onEvent),this.carousel().off("jcarousel:destroy",this.onDestroy).off("jcarousel:reloadend jcarousel:scrollend",this.onReload)},_reload:function(){var b,c=a.jCarousel.parseTarget(this.options("target")),d=this.carousel();if(c.relative)b=d.jcarousel(c.target>0?"hasNext":"hasPrev");else{var e="object"!=typeof c.target?d.jcarousel("items").eq(c.target):c.target;b=d.jcarousel("target").index(e)>=0}return this._active!==b&&(this._trigger(b?"active":"inactive"),this._active=b),this}})}(jQuery),function(a){"use strict";a.jCarousel.plugin("jcarouselPagination",{_options:{perPage:null,item:function(a){return'<a href="#'+a+'">'+a+"</a>"},event:"click",method:"scroll"},_carouselItems:null,_pages:{},_items:{},_currentPage:null,_init:function(){this.onDestroy=a.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",a.proxy(this._create,this))},this),this.onReload=a.proxy(this._reload,this),this.onScroll=a.proxy(this._update,this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy).on("jcarousel:reloadend",this.onReload).on("jcarousel:scrollend",this.onScroll),this._reload()},_destroy:function(){this._clear(),this.carousel().off("jcarousel:destroy",this.onDestroy).off("jcarousel:reloadend",this.onReload).off("jcarousel:scrollend",this.onScroll),this._carouselItems=null},_reload:function(){var b=this.options("perPage");if(this._pages={},this._items={},a.isFunction(b)&&(b=b.call(this)),null==b)this._pages=this._calculatePages();else for(var c,d=parseInt(b,10)||0,e=this._getCarouselItems(),f=1,g=0;;){if(c=e.eq(g++),0===c.length)break;this._pages[f]=this._pages[f]?this._pages[f].add(c):c,g%d===0&&f++}this._clear();var h=this,i=this.carousel().data("jcarousel"),j=this._element,k=this.options("item"),l=this._getCarouselItems().length;a.each(this._pages,function(b,c){var d=h._items[b]=a(k.call(h,b,c));d.on(h.options("event")+".jcarouselpagination",a.proxy(function(){var a=c.eq(0);if(i.circular){var d=i.index(i.target()),e=i.index(a);parseFloat(b)>parseFloat(h._currentPage)?d>e&&(a="+="+(l-d+e)):e>d&&(a="-="+(d+(l-e)))}i[this.options("method")](a)},h)),j.append(d)}),this._update()},_update:function(){var b,c=this.carousel().jcarousel("target");a.each(this._pages,function(a,d){return d.each(function(){return c.is(this)?(b=a,!1):void 0}),b?!1:void 0}),this._currentPage!==b&&(this._trigger("inactive",this._items[this._currentPage]),this._trigger("active",this._items[b])),this._currentPage=b},items:function(){return this._items},reloadCarouselItems:function(){return this._carouselItems=null,this},_clear:function(){this._element.empty(),this._currentPage=null},_calculatePages:function(){for(var a,b,c=this.carousel().data("jcarousel"),d=this._getCarouselItems(),e=c.clipping(),f=0,g=0,h=1,i={};;){if(a=d.eq(g++),0===a.length)break;b=c.dimension(a),f+b>e&&(h++,f=0),f+=b,i[h]=i[h]?i[h].add(a):a}return i},_getCarouselItems:function(){return this._carouselItems||(this._carouselItems=this.carousel().jcarousel("items")),this._carouselItems}})}(jQuery),function(a,b){"use strict";var c,d,e={hidden:"visibilitychange",mozHidden:"mozvisibilitychange",msHidden:"msvisibilitychange",webkitHidden:"webkitvisibilitychange"};a.each(e,function(a,e){return"undefined"!=typeof b[a]?(c=a,d=e,!1):void 0}),a.jCarousel.plugin("jcarouselAutoscroll",{_options:{target:"+=1",interval:3e3,autostart:!0},_timer:null,_started:!1,_init:function(){this.onDestroy=a.proxy(function(){this._destroy(),this.carousel().one("jcarousel:createend",a.proxy(this._create,this))},this),this.onAnimateEnd=a.proxy(this._start,this),this.onVisibilityChange=a.proxy(function(){b[c]?this._stop():this._start()},this)},_create:function(){this.carousel().one("jcarousel:destroy",this.onDestroy),a(b).on(d,this.onVisibilityChange),this.options("autostart")&&this.start()},_destroy:function(){this._stop(),this.carousel().off("jcarousel:destroy",this.onDestroy),a(b).off(d,this.onVisibilityChange)},_start:function(){return this._stop(),this._started?(this.carousel().one("jcarousel:animateend",this.onAnimateEnd),this._timer=setTimeout(a.proxy(function(){this.carousel().jcarousel("scroll",this.options("target"))},this),this.options("interval")),this):void 0},_stop:function(){return this._timer&&(this._timer=clearTimeout(this._timer)),this.carousel().off("jcarousel:animateend",this.onAnimateEnd),this},start:function(){return this._started=!0,this._start(),this},stop:function(){return this._started=!1,this._stop(),this}})}(jQuery,document);/* complete : /javascript/common/libraries/jquery/jquery.jcarousel-0.3.3.min.js*/


/* combine : /javascript/common/celebrus/celebrusHelper.js*/
/*
 * The following functions aid in the creation of Celebrus data tags.
 *
 */
//Function to set up object and pass it to the CSA
function reportAddToBasket(addedProductID, addedValue, addedCurrency,
                        displayName, skuNum, addedQuantity, valueIsPerItem)
{
    var eventObj = new Object();
    eventObj.action = "add";
    eventObj.productID = addedProductID;
    eventObj.value = addedValue;
    eventObj.currency = addedCurrency;
    eventObj.productDisplayName = displayName;
    eventObj.skuNumber = skuNum;
    eventObj.quantity = addedQuantity;
    eventObj.valuePerItem = valueIsPerItem;
    if(window.JDWevent)
        window.JDWevent(eventObj);
}

//Failed to add to basket.
function reportFailedToAddToBasket(addedProductID)
{
    var eventObj = new Object();
    eventObj.action = "failedAdd";
    eventObj.productID = addedProductID;
    if(window.JDWevent)
        window.JDWevent(eventObj);
}

//Amend basket entry.
function reportAmendBasket(amendedProductID, updatedQuantity)
{
    var eventObj = new Object();
    eventObj.action = "amend";
    eventObj.productID = amendedProductID;
    eventObj.newQuantity = updatedQuantity;
    if(window.JDWevent)
        window.JDWevent(eventObj);
}

//Remove basket entry.
function reportRemoveBasketItem(removedProductID)
{
    var eventObj = new Object();
    eventObj.action = "remove";
    eventObj.productID = removedProductID;
    if(window.JDWevent)
        window.JDWevent(eventObj);
}

//Basket total.
function reportBasketTotal(basketTotalVal, basketCurrency)
{
    var eventObj = new Object();
    eventObj.action = "basketTotal";
    eventObj.totalValue = basketTotalVal;
    eventObj.currency = basketCurrency;
    if(window.JDWevent)
        window.JDWevent(eventObj);
}

//Basket Purchased.
function reportPurchase(orderNum, basketTotalVal, basketCurrency)
{
    var eventObj = new Object();
    eventObj.action = "purchase";
    eventObj.orderNumber = orderNum;
    eventObj.totalValue = basketTotalVal;
    eventObj.currency = basketCurrency;
    if(window.JDWevent)
        window.JDWevent(eventObj);
}

//Report 'To Follow' message displayed.
function reportToFollowMessage(productID, toFollowPeriod, value, currency)
{
    var targetObj = new Object();
    targetObj.name = "toFollowMessage";
    targetObj.id = productID + '_' + toFollowPeriod;
    targetObj.value = value + '|' + currency;
    targetObj.tagName = 'DIV';
    if(window.JDWclick)
        window.JDWclick(targetObj);
}

//Report substitute product suggested.
function reportSubstituteProductSuggested(originalProductID, value, currency, substituteProductID)
{
    var targetObj = new Object();
    targetObj.name = "substituteProductSuggested";
    targetObj.id = originalProductID + '_' + substituteProductID;
    targetObj.value = value + '|' + currency;
    targetObj.tagName = 'DIV';
    if(window.JDWclick)
        window.JDWclick(targetObj);
}

//Report that one of the alternative images on the product details page has been clicked.
function reportAltImageClick(productID, alternateImageID)
{
    var targetObj = new Object();
    targetObj.name = "alternativeProductDetailsImageClicked";
    targetObj.id = productID;
    targetObj.value = alternateImageID;
    targetObj.tagName = 'DIV';
    if(window.JDWclick)
        window.JDWclick(targetObj);
}

//Report that the main images have been swapped between.
function reportAltImageDisplayed(productID, alternateImageID)
{
    var targetObj = new Object();
    targetObj.name = "alternativeProductDetailsImageChanged";
    targetObj.id = productID;
    targetObj.value = alternateImageID;
    targetObj.tagName = 'DIV';
    if(window.JDWclick)
        window.JDWclick(targetObj);
}

//Report that a product has been added to the wish-list.
function reportAddToWishlistClick(productID)
{
    var targetObj = new Object();
    targetObj.name = "addedToWishlist";
    targetObj.id = productID;
    if(window.JDWclick)
        window.JDWclick(targetObj);
}

//Report personal account protection page click.
function reportPAPPageClick(pageName)
{
    var targetObj = new Object();
    targetObj.id = "stid_paptrans_" + pageName;
    targetObj.name = "stid_paptrans";
    targetObj.value = pageName;
    targetObj.tagName = 'DIV';
    if(window.JDWclick)
        window.JDWclick(targetObj);
}

//Report a click on Amplience Functionality. Captured using the Amplience invokeTenCMSEvent JS
//function in Amplience.html.
function reportAmplienceClick(amplienceEventObject) {
    var targetObj = new Object();
    url = $.trim(amplienceEventObject.url);
    
    targetObj.name = url;
    targetObj.href = url;
    targetObj.value = url;
    targetObj.id = "amplienceClick";
    
    //using ^ as a separator in Celebrus, don't change without also changing Celebrus.
    targetObj.id += "^" + ($.trim(amplienceEventObject.SSID) == "" ? "undefined" : $.trim(amplienceEventObject.SSID));
    targetObj.id += "^" + ($.trim(amplienceEventObject.element) == "" ? "undefined" : $.trim(amplienceEventObject.element));
    targetObj.id += "^" + ($.trim(amplienceEventObject.eventName) == "" ? "undefined" : $.trim(amplienceEventObject.eventName));
    targetObj.id += "^" + ($.trim(amplienceEventObject.moduleID) == "" ? "undefined" : $.trim(amplienceEventObject.moduleID));
    targetObj.id += "^" + ($.trim(amplienceEventObject.parent) == "" ? "undefined" : $.trim(amplienceEventObject.parent));
    targetObj.id += "^" + ($.trim(amplienceEventObject.value) == "" ? "undefined" : $.trim(amplienceEventObject.value));

    if (window.JDWclick)
        window.JDWclick(targetObj);
}

//Reports slider product displayed.
function reportSliderProduct(url, productId, productIndex, prefix) {
    var targetObj = new Object();
    
    targetObj.name = url;
    targetObj.href = url;
    targetObj.value = url;
    targetObj.id = prefix + "SliderProduct_" + productId + "_" + productIndex;
    
    if (window.JDWclick)
        window.JDWclick(targetObj);
}

//Create a Celebrus target object
function createTargetObj(type, category, selection, remainder, state, href) {
    var targetObj = {};
    targetObj.tagName = "DIV";
    var args = Array.prototype.slice.call(arguments);
    var length = args.length;
    targetObj.id = "celid";
    for (var i=0; i<length-1; i++){
            var val = args[i];
            if (val != null) targetObj.id = targetObj.id + "_" + $.trim(val.toLowerCase());
    }
    targetObj.name    = $.trim(href);
    targetObj.href    = $.trim(href);
    targetObj.value    = $.trim(href);
    return targetObj;
}

//Report that a single select refinement group category has been clicked
function reportSingleSelectRefinementGroupCategoryClicked(link) {
    if(window.JDWclick) {    
        var $link = $(link);
        var selection = $.trim($link.clone().children().remove(".count").end().text()).replace(/[\n\r]+\-/g, "");
        var href = document.getElementById($link.attr('id')).href;    // non jQuery so that the absolute path is retrieved consistently
        if (selection != "clear") {
            var remainder = $link.clone().children(".count").text().replace(new RegExp("[()]","gi"), "");
            var category = $link.closest(".availableFiltersContainer").prev(".refinementHeader").children("span:first").text();
            if($link.closest("ul").hasClass("checkList"))
                var state = $link.hasClass("checked") ? "off" : "on";
            else
                var state = "on";
            window.JDWclick(createTargetObj('cmslhnr', category, selection, remainder, state, href));
        }
        else {
            if($link.parent().hasClass("refinementHeader"))
                reportRefinementGroupClearClicked(link);
            else
                reportSelectedFilterClearClicked(link);
        }
    }
}

//Report that a value has been selected from the product window Sort By list
function reportSortBySelected(selected) {
    if(window.JDWclick)
        var href = window.location.protocol + '//' + window.location.host + $(selected).attr('value');    // need to construct the url because the relative path is from a value attribute rather than href
        window.JDWclick(createTargetObj("cmssb", null, $(selected).find("option:selected").text(), null, "on", href));
}

//Report that a value has been selected from the product window custom drop down Sort By list
function reportCustomDropDownSortBySelected(selected) {
    if(window.JDWclick)
        var href = window.location.protocol + '//' + window.location.host + $(selected).attr('data-jdw-link');	// need to construct the url because the relative path is from a data attribute rather than href
        window.JDWclick(createTargetObj("cmssb", null, $(selected).text(), null, "on", href));
}

//Report that a value has been selected from the product window Products Per Page list
function reportProductsPerPageSelected(selected) {
    if(window.JDWclick) {
        var href = window.location.protocol + '//' + window.location.host + $(selected).attr('value');
        var option = $(selected).find("option:selected").text().replace(" products", "");        
        window.JDWclick(createTargetObj("cmsppp", null, option, null, "on", href));
    }
}

//Report that a filtering group concertina has been clicked
function reportFilteringGroupConcertinaClicked(filterGroup) {
    if(window.JDWclick) {
        var $fg = $(filterGroup);
        window.JDWclick(createTargetObj("cmslhcon", $fg.text(), null, null, (!$fg.hasClass("active") ? "on" : "off"), null));
    }
}

//Report that a filtering group browse categories concertina has been clicked
function reportFilteringGroupBrowseCategoriesConcertinaClicked(filterGroup) {
    if(window.JDWclick) {
        var $fg = $(filterGroup);
        window.JDWclick(createTargetObj("cmsbccon", $fg.text(), null, null, (!$fg.hasClass("active") ? "on" : "off"), null));
    }
}

//Report that a navigation page link has been clicked
function reportNavPageLinkClicked(link) {
    if(window.JDWclick) {
        var $link = $(link);
        var method = link.id.substring(link.id.indexOf("-") + 1);
        var pageno;
        var href = document.getElementById($link.attr('id')).href;
        if (!href) href=document.getElementById($link.parent().attr('id')).href; // mobile
        if(method === "Next" || method === "nextResults") {
            method = "next";
            pageno = $link.parent().siblings('span.current').next().children('a:first').text();
            (pageno=="" ? pageno="na" : false);    // mobile does not identify page numbers
        } else if(method === "Prev" || method === "previousResults") {
            method = "prev";
            pageno = $link.parent().siblings('span.current').prev().children('a:first').text();
            (pageno=="" ? pageno="na" : false);
        } else {
            pageno = method;
            method = "direct";
        }
        window.JDWclick(createTargetObj("cmspn", method, pageno, null, "on", href));
    }
}

//Report that products are displayed in the shop window
function reportProductsDisplayed(productListTotal) {
    if(window.JDWclick) {
        window.JDWclick(createTargetObj("cmspl", productListTotal.toString(), null, null, "on", null));
    }
}

//Report that a price slide change has been made
function reportPriceSliderChanged(values) {
    if(window.JDWclick)
        window.JDWclick(createTargetObj("cmslhnps", "priceslider", (values[0] + "-" + values[1]), "na", "on", null));
}

//Report that the clear all link has been clicked
function reportClearAllClicked(link) {
    if(window.JDWclick){
        var $link = $(link);
        var href = document.getElementById($link.attr('id')).href;
        window.JDWclick(createTargetObj("cmslhnca", "all", "clear", "na", "off", href));
    }
}

//Report that the clear link for a refinement group has been clicked
function reportRefinementGroupClearClicked(link) {
    if(window.JDWclick){
        var $link = $(link);
        var href = document.getElementById($link.attr('id')).href;
        window.JDWclick(createTargetObj("cmslhncg", $link.prev().text(), "clear", "na", "off", href));
    }
}

//Report that the clear link for a selected filter has been clicked
function reportSelectedFilterClearClicked(link) {
    if(window.JDWclick){
        var $link = $(link);
        var href = document.getElementById($link.attr('id')).href;
        window.JDWclick(createTargetObj("cmslhncp", 
                $(link).closest("li").text().replace(new RegExp("(clear)", "gi"), ""),
                "clear", "na", "off", href));
    }
}

//Report that the clear link for a selected filter has been clicked
function reportOffCanvasSelectedFilterClearClicked(link) {
    if(window.JDWclick){
        var href = document.getElementById($(link).attr('id')).href;
        window.JDWclick(createTargetObj("cmslhncp", 
                $.trim($(link).text().replace(new RegExp(" \\(.*\\)", "gi"), "")),
                "clear", "na", "off", href));
    }
}

//Report that refine search has been clicked
function reportRefineSearchClicked(selected) {
    if(window.JDWclick) {
        var href = window.location.protocol + '//' + window.location.host + $(selected).attr('value');
        window.JDWclick(createTargetObj("cmslhnsr", $(selected).find("option:first").text(), 
                $(selected).find("option:selected").text(), "na", "on", href));
    }
}

//Report that refine search has been clicked
function reportOffCanvasRefineSearchClicked(selected) {
	if(window.JDWclick) {
		var href = window.location.protocol + '//' + window.location.host + $(selected).attr('href');
		window.JDWclick(createTargetObj("cmslhnsr", $(selected).closest("ul").attr('id').replace(new RegExp("-refinement", "gi"), ""), 
				$(selected).text().replace(new RegExp(" \\(.*\\)", "gi"), ""), "na", "on", href));
	}
}

//Report that an autocomplete text box option has been selected
function reportTextChanged(text, id, name)
{
    var targetObj = new Object();
    targetObj.name = name;
    targetObj.id = id;
    targetObj.value = text;
    targetObj.tagName = 'input';
    targetObj.type = 'text';
    if(window.JDWtextchange)
        window.JDWtextchange(targetObj);
}/* complete : /javascript/common/celebrus/celebrusHelper.js*/


/* combine : /javascript/common/celebrus/celebrusEventWriter.js*/
/*
 * The following functions aid in the creation of Celebrus events.
 *
 */
//Function to set up object and pass it to the CSA
function celReportAddToBasket(addedProductID, addedValue, addedCurrency,
                        displayName, skuNum, addedQuantity, valueIsPerItem)
{
    try {
        reportAddToBasket(addedProductID, addedValue, addedCurrency,
                        displayName, skuNum, addedQuantity, valueIsPerItem);
    } catch (err) {
    }
}

//Failed to add to basket.
function celReportFailedToAddToBasket(addedProductID)
{
    try {
        reportFailedToAddToBasket(addedProductID);
    } catch (err) {
    }
}

//Amend basket entry.
function celReportAmendBasket(amendedProductID, updatedQuantity)
{
    try {
        reportAmendBasket(amendedProductID, updatedQuantity);
    } catch (err) {
    }
}

//Remove basket entry.
function celReportRemoveBasketItem(removedProductID)
{
    try {
        reportRemoveBasketItem(removedProductID);
    } catch (err) {
    }
}

//Basket total.
function celReportBasketTotal(basketTotalVal, basketCurrency)
{
    try {
        reportBasketTotal(basketTotalVal, basketCurrency);
    } catch (err) {
    }
}

//Basket purchased.
function celReportPurchase(orderNum, basketTotalVal, basketCurrency)
{
    try {
        reportPurchase(orderNum, basketTotalVal, basketCurrency);
    } catch (err) {
    }
}

//Report 'To Follow' message displayed.
function celReportToFollowMessage(productID, toFollowPeriod, value, currency)
{
    try {
        reportToFollowMessage(productID, toFollowPeriod, value, currency);
    } catch (err) {
    }
}

//Report substitute product suggested.
function celReportSubstituteProductSuggested(originalProductID, value, currency, substituteProductID)
{
    try {
        reportSubstituteProductSuggested(originalProductID, value, currency, substituteProductID);
    } catch (err) {
    }
}

//Report that one of the alternative images on the product details page has been clicked.
function celReportAltImageClick(productID, alternateImageID)
{
    try {
        reportAltImageClick(productID, alternateImageID);
    } catch (err) {
    }
}

//Report that the main image on the product details page has been changed.
function celReportAltImageDisplayed(productID, alternateImageID)
{
    try {
        reportAltImageDisplayed(productID, alternateImageID);
    } catch (err) {
    }
}

//Report product added to wishlist.
function celReportAddToWishlist(productCode)
{
    try {
        reportAddToWishlistClick(productCode);
    } catch (err) {
    }
}

//Report personal account protection page click.
function celReportPAPPageClick(pageName)
{
    try {
        reportPAPPageClick(pageName);
    } catch (err) {
    }
}

//Report that a single select refinement group category has been clicked
function celReportSingleSelectRefinementGroupCategoryClicked(link) {
    try {
        reportSingleSelectRefinementGroupCategoryClicked(link);
    } catch (err) {
    }
}

//Report that a value has been selected from the product window Sort By list
function celReportSortBySelected(selected) {
    try {
        reportSortBySelected(selected);
    } catch (err) {
    }
}

//Report that a value has been selected from the product window custom drop down Sort By list
function celReportCustomDropDownSortBySelected(selected) {
    try {
        reportCustomDropDownSortBySelected(selected);
    } catch (err) {
    }
}

//Report that a value has been selected from the product window Products Per Page list
function celReportProductsPerPageSelected(selected) {
    try {
        reportProductsPerPageSelected(selected);
    } catch (err) {
    }
}

//Report that a filtering group concertina has been clicked
function celReportFilteringGroupConcertinaClicked(filterGroup) {
    try {
        reportFilteringGroupConcertinaClicked(filterGroup);
    } catch (err) {
    }
}

//Report that a filtering group browse categories concertina has been clicked
function celReportFilteringGroupBrowseCategoriesConcertinaClicked(filterGroup) {
    try {
        reportFilteringGroupBrowseCategoriesConcertinaClicked(filterGroup);
    } catch (err) {
    }
}

//Report that a navigation page link has been clicked
function celReportNavPageLinkClicked(link) {
    try {
        reportNavPageLinkClicked(link);
    } catch (err) {
    }
}

//Report that products are displayed in the shop window
function celReportProductsDisplayed(productListTotal) {
    try {
    	reportProductsDisplayed(productListTotal);
    } catch (err) {
    }
}

//Report that a price slide change has been made
function celReportPriceSliderChanged(values) {
    try {
        reportPriceSliderChanged(values);
    } catch (err) {
    }
}

//Report that a price slide change has been made
function celReportClearAllClicked(link) {
    try {
        reportClearAllClicked(link);
    } catch (err) {
    }
}

//Report that the clear link for a particular refinement has been clicked
function celReportRefinementGroupClearClicked(link) {
    try {
        reportRefinementGroupClearClicked(link);
    } catch (err) {
    }
}

//Report that the clear link for a refinement group has been clicked
function celReportSelectedFilterClearClicked(link) {
    try {
        reportSelectedFilterClearClicked(link);
    } catch (err) {
    }
}

//Report that the clear link for a refinement group has been clicked
function celReportOffCanvasSelectedFilterClearClicked(link) {
    try {
        reportOffCanvasSelectedFilterClearClicked(link);
    } catch (err) {
    }
}

//Report that refine search has been clicked
function celReportRefineSearchClicked(selected) {
    try {
        reportRefineSearchClicked(selected);
    } catch (err) {
    }
}

//Report that refine search has been clicked
function celReportOffCanvasRefineSearchClicked(selected) {
    try {
        reportOffCanvasRefineSearchClicked(selected);
    } catch (err) {
    }
}

//Report that an autocomplete text box option has been selected
function celReportTextChanged(text, id, name) {
    try {
        reportTextChanged(text, id, name);
    } catch (err) {
    }
}
    
//Takes the object generated by Amplience analytic events and converts it into Celebrus clicks events.
function celReportAmplienceClick(amplienceEventObject) {
    try {
        reportAmplienceClick(amplienceEventObject);
    } catch (err) {    
    }
}

//Reports outfit builder slider product displayed
function celReportOutfitSliderProduct(url, productId, productIndex) {
    try {
        reportSliderProduct(url, productId, productIndex, "outfit");
    } catch (err) {
    }
}

//Reports slider product displayed
function celReportAffinitySliderProduct(url, productId, productIndex) {
    try {
        reportSliderProduct(url, productId, productIndex, "affinity");
    } catch (err) {
    }
}
/* complete : /javascript/common/celebrus/celebrusEventWriter.js*/


/* combine : /javascript/common/celebrus/celebrusEventBuffer.js*/
/**
 * Buffer functions to handle Celebrus API calls while the CelebrusInsert.js is still loading.
 * 
 * If calls to the Celebrus API occur before the CelebrusInsert.js file has loaded the Celebrus API 
 * functions then these functions (by the same name) will 'catch' the calls, and forward them on to 
 * the API once it has loaded, subject to a timeout.
 * 
 * This process takes advantage of Javascripts optional parameters - allowing these buffer 
 * functions to be called without their timer parameter initially, and allowing the genuine 
 * Celebrus functions by the same name to accept & ignore the timer parameter if they are called 
 * from these buffer functions.
 */ 

/* Time (milliseconds) to wait between polling for the Celebrus API */
var celAPIPoll_pollDelay = 100;

/* Time (seconds) to continue polling for Celebrus API before giving up */
var celAPIPoll_timeout = 5;

/* Calculated number of polls required before timeout is reached */
var celAPIPoll_limit = celAPIPoll_timeout * 1000 / celAPIPoll_pollDelay;


/**
 * Buffer function to handle Celebrus JDWclick API call while the CelebrusInsert.js is still 
 * loading.
 * @param obj The object which the Celebrus API function will process into an event.
 * @param timer A counter to allow the call stack to exit if the JDWclick Celebrus function
 * does not become available after the number of seconds denoted in celAPIPoll_timeout.
 */
function JDWclick(obj, timer) {
	if (timer == undefined) timer = 0;
	if (timer < celAPIPoll_limit) {
		setTimeout(function(){window.JDWclick(obj, timer+1);}, celAPIPoll_pollDelay);
	}
}

/**
 * Buffer function to handle Celebrus JDWtextchange API call while the CelebrusInsert.js is still 
 * loading.
 * @param obj The object which the Celebrus API function will process into an event.
 * @param timer A counter to allow the call stack to exit if the JDWclick Celebrus function
 * does not become available after the number of seconds denoted in celAPIPoll_timeout.
 */
function JDWtextchange(obj, timer) {
	if (timer == undefined) timer = 0;
	if (timer < celAPIPoll_limit) {
		setTimeout(function(){window.JDWtextchange(obj, timer+1);}, celAPIPoll_pollDelay);
	}
}

/**
 * Buffer function to handle Celebrus JDWformsubmit API call while the CelebrusInsert.js is still 
 * loading.
 * @param obj The object which the Celebrus API function will process into an event.
 * @param timer A counter to allow the call stack to exit if the JDWclick Celebrus function
 * does not become available after the number of seconds denoted in celAPIPoll_timeout.
 */
function JDWformsubmit(obj, timer) {
	if (timer == undefined) timer = 0;
	if (timer < celAPIPoll_limit) {
		setTimeout(function(){window.JDWformsubmit(obj, timer+1);}, celAPIPoll_pollDelay);
	}
}

/**
 * Buffer function to handle Celebrus JDWevent API call while the CelebrusInsert.js is still 
 * loading.
 * @param obj The object which the Celebrus API function will process into an event.
 * @param timer A counter to allow the call stack to exit if the JDWclick Celebrus function
 * does not become available after the number of seconds denoted in celAPIPoll_timeout.
 */
function JDWevent(obj, timer) {
	if (timer == undefined) timer = 0;
	if (timer < celAPIPoll_limit) {
		setTimeout(function(){window.JDWevent(obj, timer+1);}, celAPIPoll_pollDelay);
	}
}
/* complete : /javascript/common/celebrus/celebrusEventBuffer.js*/


/* combine : /javascript/common/p13n-1.2.js*/
/*! p13n.js Copyright 2007-2017 RichRelevance, Inc. All Rights Reserved. Build V1.2.3.20170406 */
/* Document.write had to be removed from p13n.js to work in C3 after ajax refresh
 * This line writes the appropriate div to the page without document.write
 * If p13n.js is ever replaced then this line must be included and document.write removed
 */
function r3_generic(){this.createScript=function(a){return a}}function rr_addLoadEvent(a){RR.ol(a)}function r3_item(){this.setId=function(a){RR.set.call(this,a,"id")},this.setName=function(a){RR.set.call(this,a,"name")},this.setRecommendable=function(a){RR.set.call(this,a,"recommendable")},this.setPrice=function(a){RR.set.call(this,a,"price")},this.setSalePrice=function(a){RR.set.call(this,a,"salePrice")},this.setBrand=function(a){RR.set.call(this,a,"brand")},this.addAttribute=function(a,b){var c=a+":"+b;RR.add.call(this,c,"attributes")},this.setEndDate=function(a){RR.set.call(this,a,"endDate")},this.setImageId=function(a){RR.set.call(this,a,"imageId")},this.setLinkId=function(a){RR.set.call(this,a,"linkId")},this.setRating=function(a){RR.set.call(this,a,"rating")},this.setReleaseDate=function(a){RR.set.call(this,a,"releaseDate")},this.addCategory=function(a,b){var c=a+":"+b;RR.add.call(this,c,"categories")},this.addCategoryId=function(a){RR.add.call(this,a,"categoryIds")},this.createScript=function(a){return this.categories&&(a+="&cs="+encodeURIComponent(this.categories)),this.categoryIds&&(a+="&cis="+encodeURIComponent(this.categoryIds)),this.id&&(a+="&p="+encodeURIComponent(this.id)),this.name&&(a+="&n="+encodeURIComponent(this.name)),this.imageId&&(a+="&ii="+encodeURIComponent(this.imageId)),this.linkId&&(a+="&li="+encodeURIComponent(this.linkId)),this.releaseDate&&(a+="&rd="+encodeURIComponent(this.releaseDate)),this.price&&(a+="&np="+encodeURIComponent(this.price)),this.salePrice&&(a+="&sp="+encodeURIComponent(this.salePrice)),this.endDate&&(a+="&ed="+encodeURIComponent(this.endDate)),this.rating&&(a+="&r="+encodeURIComponent(this.rating)),typeof this.recommendable!=RR.U&&(a+="&re="+encodeURIComponent(this.recommendable)),this.brand&&(a+="&b="+encodeURIComponent(this.brand)),this.attributes&&(a+="&at="+encodeURIComponent(this.attributes)),a}}function r3_category(){this.setId=function(a){RR.set.call(this,a,"id")},this.setName=function(a){RR.set.call(this,a,"name")},this.setParentId=function(a){RR.set.call(this,a,"parentId")},this.setTopName=function(a){RR.set.call(this,a,"topName")},this.addItemId=RR.addItemId,this.createScript=function(a){return this.name&&(a+="&cn="+encodeURIComponent(this.name)),this.id&&(a+="&c="+encodeURIComponent(this.id)),this.parentId&&(a+="&pc="+encodeURIComponent(this.parentId)),this.topName&&(a+="&tcn="+encodeURIComponent(this.topName)),a}}function r3_cart(){this.addItemId=RR.addItemId,this.addItemIdCentsQuantity=RR.addItemIdCentsQuantity,this.addItemIdDollarsAndCentsQuantity=RR.addItemIdDollarsAndCentsQuantity,this.addItemIdPriceQuantity=RR.addItemIdPriceQuantity,this.createScript=function(a){return this.purchasesCents&&(a+="&ppc="+encodeURIComponent(this.purchasesCents)),this.purchasesDollarsAndCents&&(a+="&pp="+encodeURIComponent(this.purchasesDollarsAndCents)),this.quantities&&(a+="&q="+encodeURIComponent(this.quantities)),this.purchasesPrice&&(a+="&pp="+encodeURIComponent(this.purchasesPrice)),a}}function r3_addtocart(){this.addItemIdToCart=RR.addItemIdToCart,this.createScript=function(a){return this.addedToCartItemIds&&(a+="&atcid="+encodeURIComponent(this.addedToCartItemIds)),a}}function r3_purchased(){this.addItemId=RR.addItemIdCentsQuantity,this.addItemIdCentsQuantity=RR.addItemIdCentsQuantity,this.addItemIdDollarsAndCentsQuantity=RR.addItemIdDollarsAndCentsQuantity,this.addItemIdPriceQuantity=RR.addItemIdPriceQuantity,this.setOrderNumber=function(a){this.orderNumber=a},this.createScript=function(a){return this.orderNumber&&(a+="&o="+encodeURIComponent(this.orderNumber)),this.purchasesCents&&(a+="&ppc="+encodeURIComponent(this.purchasesCents)),this.purchasesDollarsAndCents&&(a+="&pp="+encodeURIComponent(this.purchasesDollarsAndCents)),this.quantities&&(a+="&q="+encodeURIComponent(this.quantities)),this.purchasesPrice&&(a+="&pp="+encodeURIComponent(this.purchasesPrice)),a}}function r3_search(){this.addItemId=RR.addItemId,this.setTerms=RR.addSearchTerm,this.createScript=function(a){return a}}function r3_wishlist(){this.addItemId=RR.addItemId,this.createScript=function(a){return a}}function r3_addtoregistry(){this.addItemIdCentsQuantity=RR.addItemIdCentsQuantity,this.createScript=function(a){return a}}function r3_common(){function a(a,b){rr_placement_place_holders.push({elementId:a,placementType:b})}var b={startRow:-1,count:-1,priceRanges:[],filterAttributes:{}};this.baseUrl="http://recs.richrelevance.com/rrserver/",this.jsFileName="p13n_generated.js",this.addCategoryHintId=function(a){RR.add.call(this,a,"categoryHintIds")},this.addClickthruParams=function(a,b){var c=encodeURIComponent(a)+":"+encodeURIComponent(b);RR.add.call(this,c,"clickthruParams")},this.addContext=function(a,b){RR.addObject.call(this,a,"context",b)},this.addFilter=function(a){RR.add.call(this,a,"filters")},this.addFilterBrand=function(a){RR.add.call(this,a,"filterBrands")},this.addFilterCategory=function(a){RR.add.call(this,a,"filterCategories")},this.addItemId=RR.addItemId,this.addItemIdToCart=RR.addItemIdToCart,this.addPlacementType=function(b,c){RR.add.call(this,b,"placementTypes"),c&&a(c,b)},this.addRefinement=function(a,b){var c=a+":"+b;RR.add.call(this,c,"refinements")},this.setRefinementFallback=function(a){var b=Boolean(a)?"t":"f";RR.set.call(this,b,"doRefinementsFallback")},this.addSearchTerm=RR.addSearchTerm,this.addSegment=function(a,b){var c;c=void 0===b?a:a+":"+b,RR.add.call(this,c,"segments")},this.blockItemId=function(a){RR.add.call(this,a,"blockeditemIds")},this.forceDisplayMode=function(){RR.set.call(this,!0,"displayModeForced")},this.forceDevMode=function(){RR.set.call(this,!0,"devModeForced")},this.setApiKey=function(a){RR.set.call(this,a,"apiKey")},this.setBaseUrl=function(a){RR.set.call(this,a,"baseUrl")},this.setCartValue=function(a){RR.set.call(this,a,"cartValue")},this.setChannel=function(a){RR.set.call(this,a,"channel")},this.setClickthruServer=function(a){RR.set.call(this,a,"clickthruServer")},this.setFilterBrandsIncludeMatchingElements=function(a){RR.set.call(this,a,"filterBrandsInclude")},this.setForcedTreatment=function(a){RR.set.call(this,a,"forcedTreatment")},this.setMVTForcedTreatment=function(a){RR.set.call(this,a,"mvtforcedTreatment")},this.setPageBrand=function(a){RR.set.call(this,a,"brand")},this.setImageServer=function(a){RR.set.call(this,a,"imageServer")},this.setRegionId=function(a){RR.set.call(this,a,"regionId")},this.setLanguage=function(a){RR.set.call(this,a,"language")},this.setCurrency=function(a){RR.set.call(this,a,"currency")},this.setRegistryId=function(a){RR.set.call(this,a,"registryId")},this.setRegistryType=function(a){RR.set.call(this,a,"registryType")},this.setSessionId=function(a){RR.set.call(this,a,"sessionId")},this.setUserId=function(a){RR.set.call(this,a,"userId")},this.useDummyData=function(){RR.set.call(this,!0,"dummyDataUsed"),RR.set.call(this,!0,"displayModeForced")},this.RICHSORT={paginate:function(a,c){b.startRow=a,b.count=c},filterPrice:function(a){b.priceRanges=a||[]},filterAttribute:function(a,c){b.filterAttributes[a]=c}},this.initFromParams=function(){var a=RR.checkParamCookieValue("RR Environment","r3_env","r3_envCookie","r3_env");if(a&&""!==a){var b=(0===this.baseUrl.toLowerCase().indexOf("https://")?"https://":"http://")+a+".richrelevance.com/rrserver/";RR.set.call(this,b,"baseUrl")}if(RR.lc("r3_forceDisplay=true")&&(RR.set.call(this,!0,"debugMode"),RR.set.call(this,!0,"displayModeForced")),RR.lc("r3_forceDev=true")&&(RR.set.call(this,!0,"debugMode"),RR.set.call(this,!0,"devModeForced")),RR.lc("r3_rad=true")){RR.set.call(this,!0,"debugMode"),RR.set.call(this,!0,"devModeForced"),RR.set.call(this,!0,"rad");var c=RR.pq("r3_radLevel");""!==c&&RR.set.call(this,c,"radLevel")}RR.lc("r3_useDummyData=true")&&(RR.set.call(this,!0,"debugMode"),RR.set.call(this,!0,"dummyDataUsed"),RR.set.call(this,!0,"devModeForced"));var d=RR.pq("r3_forcedTreatment");d&&""!==d&&RR.set.call(this,d,"forcedTreatment");var e=RR.checkParamCookieValue("RR MVT Treatment","r3_mvtTreatmentId","r3_mvtCookie","r3_mvtTreatmentId");e&&""!==e&&RR.set.call(this,e,"mvtforcedTreatment");var f=RR.pq("r3_ftp");f&&""!==f&&RR.set.call(this,f,"forcedFtp");var g=RR.pq("r3_responseDetails");g&&""!==g&&RR.set.call(this,g,"rap"),RR.lc("r3_debugMode=true")?RR.set.call(this,!0,"debugMode"):RR.lc("r3_debugMode=false")&&RR.set.call(this,!1,"debugMode"),RR.lc("rr_vg=")&&RR.set.call(this,RR.pq("rr_vg"),"viewGuid"),RR.lc("rm=")&&RR.set.call(this,RR.pq("rm"),"fromRichMail"),RR.lc("rr_u=")&&RR.set.call(this,RR.pq("rr_u"),"userId")},this.createScript=function(a,c,d){var e,f,g,h,i,j,k,l,m="",n=[],o=[],p=0,q=new Date;if(this.initFromParams(),a=this.baseUrl+this.jsFileName+"?a="+encodeURIComponent(this.apiKey)+"&ts="+q.getTime()+"&v="+rr_v+(0===this.baseUrl.toLowerCase().indexOf("https://")?"&ssl=t":"")+a,this.placementTypes?a+="&pt="+encodeURIComponent(this.placementTypes):d&&(this.addPlacementType(d),a+="&pt="+encodeURIComponent(d),a+="&pte=t"),this.userId&&(a+="&u="+encodeURIComponent(this.userId)),this.sessionId&&(a+="&s="+encodeURIComponent(this.sessionId)),this.viewGuid&&""!==this.viewGuid&&(a+="&vg="+encodeURIComponent(this.viewGuid)),this.segments&&(a+="&sgs="+encodeURIComponent(this.segments)),this.channel&&(a+="&channelId="+encodeURIComponent(this.channel)),this.clickthruServer&&(a+="&cts="+encodeURIComponent(this.clickthruServer)),this.imageServer&&(a+="&imgsrv="+encodeURIComponent(this.imageServer)),this.addedToCartItemIds&&(a+="&atcid="+encodeURIComponent(this.addedToCartItemIds)),this.cartValue&&(a+="&cv="+encodeURIComponent(this.cartValue)),this.forcedTreatment&&""!==this.forcedTreatment&&(a+="&ftr="+encodeURIComponent(this.forcedTreatment)),this.mvtforcedTreatment&&""!==this.mvtforcedTreatment&&(a+="&mvt_ftr="+encodeURIComponent(this.mvtforcedTreatment)),this.forcedFtp&&""!==this.forcedFtp&&(a+="&ftp="+encodeURIComponent(this.forcedFtp)),this.rap&&""!==this.rap&&(a+="&rap="+encodeURIComponent(this.rap)),this.fromRichMail&&""!==this.fromRichMail&&(a+="&rm="+encodeURIComponent(this.fromRichMail)),this.categoryHintIds&&(a+="&chi="+encodeURIComponent(this.categoryHintIds)),this.brand&&(a+="&fpb="+encodeURIComponent(this.brand)),this.filterBrands&&(a+="&filbr="+encodeURIComponent(this.filterBrands)),this.filterBrandsInclude&&(a+="&filbrinc="+encodeURIComponent(this.filterBrandsInclude)),this.filterCategories&&(a+="&filcat="+encodeURIComponent(this.filterCategories)),this.filterCategoriesInclude&&(a+="&filcatinc="+encodeURIComponent(this.filterCategoriesInclude)),this.clickthruParams&&(a+="&ctp="+encodeURIComponent(this.clickthruParams)),this.regionId&&(a+="&rid="+encodeURIComponent(this.regionId)),this.language&&(a+="&language="+encodeURIComponent(this.language)),this.currency&&(a+="&currency="+encodeURIComponent(this.currency)),this.filters&&(a+="&if="+encodeURIComponent(this.filters)),this.refinements&&(a+="&rfm="+encodeURIComponent(this.refinements),this.doRefinementsFallback&&(a+="&rfb="+encodeURIComponent(this.doRefinementsFallback))),typeof this.rad!=RR.U&&(a+="&rad=t"),typeof this.radLevel!=RR.U&&(a+="&radl="+encodeURIComponent(this.radLevel)),typeof this.context!=RR.U)for(e in this.context)if(f=this.context[e],a+="&"+e+"=",RR.isArray(f))a+=encodeURIComponent(f.join("|"));else if(f===Object(f)){g=[],h="";for(i in f)h=i+":",h+=RR.isArray(f[i])?f[i].join(";"):f[i],g.push(h);a+=encodeURIComponent(g.join("|"))}else a+=encodeURIComponent(f);if(this.registryId&&(a+="&rg="+encodeURIComponent(this.registryId)),this.registryType&&(a+="&rgt="+encodeURIComponent(this.registryType)),typeof this.searchTerms!=RR.U&&(a+="&st="+encodeURIComponent(this.searchTerms)),this.jsonCallback&&(a+="&jcb="+encodeURIComponent(this.jsonCallback)),this.blockeditemIds&&(a+="&bi="+encodeURIComponent(this.blockeditemIds)),this.itemIds&&(a+="&p="+encodeURIComponent(this.itemIds)),b.startRow>0&&(a+="&rssr="+encodeURIComponent(b.startRow)),b.count>0&&(a+="&rsrc="+encodeURIComponent(b.count)),"undefined"!=typeof b.priceRanges&&b.priceRanges.length>0){for(j=b.priceRanges.length;p<j;p+=1)o.push(b.priceRanges[p].join(";"));a+="&rspr="+encodeURIComponent(o.join("|"))}for(k in b.filterAttributes)n.push(k+":"+b.filterAttributes[k].join(";"));return n.length>0&&(a+="&rsfoa="+encodeURIComponent(n.join("|"))),this.debugMode&&(this.displayModeForced&&this.displayModeForced===!0&&(a+="&fdm=t"),this.devModeForced&&this.devModeForced===!0&&(a+="&dev=t"),this.dummyDataUsed&&this.dummyDataUsed===!0&&(a+="&udd=t")),""!==RR.d.referrer&&typeof RR.d.referrer!=RR.U?m=RR.d.referrer:""!==RR.d.referer&&typeof RR.d.referer!=RR.U&&(m=RR.d.referer),""!==m&&(a+="&pref="+encodeURIComponent(m)),l=RR.c("rr_rcs"),l.length&&(a+="&rcs="+l),a+="&l=1"}}function r3_placement(a){var b="rr_placement_"+rr_placement_place_holders.length;$('div.rrPlacement').first().attr('id','rr_placement_' + rr_placement_place_holders.length).removeClass('rrPlacement');rr_placement_place_holders.push({elementId:b,placementType:a})}function r3(a,b,c){typeof c!=RR.U&&c||RR.js()}function rr_flush_onload(){RR.onloadCalled||(RR.onloadCalled=!0,rr_onload_called=!0,rr_flush())}function rr_flush(){}function rr_insert_placement(a,b){RR.insert(a,b,rr_placements)}var rr_v="1.2.3.20170406",rr_onload_called=!1,rr_placements=[],rr_placement_place_holders=[],RR,r3_home,r3_error,r3_personal,r3_brand,R3_COMMON;r3_home=r3_generic,r3_error=r3_generic,r3_personal=r3_generic,r3_brand=r3_generic,RR=function(){function a(b,c){var d,e=b.cloneNode(!1);if("SCRIPT"===e.nodeName)e.text=b.innerHTML,c.appendChild(e);else if("#text"===e.nodeName)c.appendChild(e);else for(c.appendChild(e),d=0;d<b.childNodes.length;d++)a(b.childNodes[d],e)}function b(a){var b=document.createElement("script");b.type="text/javascript",b.charset=RR.charset,b.src=a,b.async=!0,document.getElementsByTagName("head")[0].appendChild(b)}function c(a){var b=a.split(".").reverse(),c=b.length;return c>=3&&b[1].match(/^(com|edu|gov|net|mil|org|nom|co|name|info|biz)$/i)?b[2]+"."+b[1]+"."+b[0]:b[1]+"."+b[0]}return{U:"undefined",charset:"UTF-8",rcsCookieDefaultDuration:730,setCharset:function(a){RR.charset=a},isArray:function(a){return"[object Array]"==Object.prototype.toString.call(a)},fixName:function(a){var b=String(a);return b.indexOf("&amp;")>-1&&(b=b.replace(/&amp;/g,"&")),b.indexOf("&#039;")>-1&&(b=b.replace(/&#039;/g,"'")),b},l:location.href,d:document,c:function(a,b,d,e){if(typeof b==RR.U||null===b){if(d!=-1){if(RR.d.cookie.length>0)for(var f=RR.d.cookie.split(";").reverse(),g=0,h=f.length;g<h;g++){var i=f[g];i="function"==typeof i.trim?i.trim():i.replace(/^\s+|\s+$/g,"");var j=i.indexOf(a+"=");if(0===j){j=j+a.length+1;var k=i.length;return unescape(i.substring(j,k))}}return""}RR.d.cookie=a+"=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT"}else if(d){var l=new Date,m=e?c(window.location.hostname):"";l=new Date(l.getTime()+1e3*d*60*60*24),RR.d.cookie=a+"="+escape(b)+";path=/;domain="+m+";expires="+l.toUTCString()}else RR.d.cookie=a+"="+escape(b)},id:function(a){return RR.d.getElementById(a)},lc:function(a){if(a.indexOf("=")===-1&&(a+="="),a.indexOf("?")===-1&&a.indexOf("&")===-1){var b=RR.l.indexOf("?"+a);return b===-1&&(b=RR.l.indexOf("&"+a)),b!==-1}return RR.l.indexOf(a)!==-1},ol:function(a){if("function"!=typeof window.onload)window.onload=a;else{if(typeof window.rr_onloads==RR.U){var b=window.onload;window.rr_onloads=[b],window.onload=function(a){for(;window.rr_onloads.length>0;){var b=window.rr_onloads.shift();b&&"function"==typeof b&&b.call(window,a)}}}window.rr_onloads.push(a)}},pq:function(a){var b=RR.l.indexOf("?"+a+"=");b==-1&&(b=RR.l.indexOf("&"+a+"="));var c;if(b!==-1){b++;var d=RR.l.indexOf("&",b);c=d!=-1?RR.l.substring(b+a.length+1,d):RR.l.substring(b+a.length+1,RR.l.length)}else c="";return c},debugWindow:function(a){var b=RR.d.createElement("DIV");b.innerHTML=a,b.style.position="absolute",b.style.top="0px",b.style.right="0px",b.style.zIndex="10000",b.style.width="200px",b.style.border="2px solid black",b.style.padding="5px",b.style.background="#DDD",RR.d.body.insertBefore(b,RR.d.body.firstChild)},jsonCallback:function(a){},defaultCallback:function(b){var c,d,e,f,g,h,i,j,k=b.placements,l=rr_placement_place_holders;for(h=0;h<l.length;h++)if(g=!1,c=RR.id(l[h].elementId),c&&typeof c!=RR.U)for(i=0;i<k.length;i++)if(!k[i].used&&k[i].placementType==l[h].placementType){if(k[i].placeholderIndex=h,k[i].used=!0,k[i].html.indexOf("<script")==-1?(c.innerHTML=k[i].html,g=!0):RR.d.implementation.hasFeature("Range","2.0")&&RR.d.createRange&&(e=RR.d.createRange(),e.selectNodeContents&&e.createContextualFragment&&e.detach&&(e.selectNodeContents(c),f=e.createContextualFragment(k[i].html),c.appendChild(f),e.detach(),g=!0)),!g)for(d=RR.d.createElement("div"),d.innerHTML=k[i].html,j=0;j<d.childNodes.length;j++)a(d.childNodes[j],c);break}for(rr_placements=[],i=0;i<k.length;i++)rr_placements[i]=[k[i].used?1:0,k[i].placementType,k[i].html];if(typeof rr_remote_data!==RR.U&&rr_remote_data.length){var m=RR.rcsCookieDuration||RR.rcsCookieDefaultDuration;RR.c("rr_rcs",rr_remote_data.toString(),m,!0)}},onloadCalled:!1,js:function(a){var c="",d=!1,e="";if(typeof R3_COMMON!=RR.U&&typeof R3_COMMON.baseUrl!=RR.U&&typeof R3_COMMON.apiKey!=RR.U)return typeof R3_COMMON.placementTypes!==RR.U&&""!==R3_COMMON.placementTypes||(d=!0),typeof R3_PURCHASED!==RR.U?(e="purchase_complete_page",c=R3_PURCHASED.createScript(c)):typeof R3_CART!==RR.U?(e="cart_page",c=R3_CART.createScript(c)):typeof R3_ADDTOCART!==RR.U?(e="add_to_cart_page",c=R3_ADDTOCART.createScript(c)):typeof R3_ADDTOREGISTRY!==RR.U?(e="add_to_registry_page",c=R3_ADDTOREGISTRY.createScript(c)):typeof R3_ITEM!==RR.U?(e="item_page",c=R3_ITEM.createScript(c)):typeof R3_BRAND!==RR.U?(e="brand_page",c=R3_BRAND.createScript(c)):typeof R3_CATEGORY!==RR.U?(e="category_page",c=R3_CATEGORY.createScript(c)):typeof R3_SEARCH!==RR.U?(e="search_page",c=R3_SEARCH.createScript(c)):typeof R3_WISHLIST!==RR.U?(e="cart_page",c=R3_WISHLIST.createScript(c)):typeof R3_HOME!==RR.U?(e="home_page",c=R3_HOME.createScript(c)):typeof R3_PERSONAL!==RR.U?(e="personal_page",c=R3_PERSONAL.createScript(c)):typeof R3_GENERIC!==RR.U?(e="generic_page",c=R3_GENERIC.createScript(c)):typeof R3_ERROR!==RR.U&&(e="error_page",c=R3_ERROR.createScript(c)),c=R3_COMMON.createScript(c,d,e),a||(setTimeout(function(){b(c)},10),RR.ol(rr_flush_onload)),c},insert:function(b,c,d){var e,f,g,h,j,k;for(j=0;j<d.length;j++)if(e=!1,0===d[j][0]&&d[j][1]==c){if(d[j][0]=1,d[j][2].indexOf("<script")==-1?(b.innerHTML=d[j][2],e=!0):RR.d.implementation.hasFeature("Range","2.0")&&RR.d.createRange&&(g=RR.d.createRange(),g.selectNodeContents&&g.createContextualFragment&&g.detach&&(g.selectNodeContents(b),h=g.createContextualFragment(d[j][2]),b.appendChild(h),g.detach(),e=!0)),!e)for(f=RR.d.createElement("div"),f.innerHTML=d[i][2],k=0;k<f.childNodes.length;k++)a(f.childNodes[k],b);return}},get:function(a){return this[a]},set:function(a,b){return this[b]=RR.fixName(a),this[b]},add:function(a,b){return typeof this[b]==RR.U&&(this[b]=""),this[b]+="|"+RR.fixName(a),this[b]},addObject:function(a,b,c){var d,e,f;(typeof this[b]==RR.U||c)&&(this[b]={});for(d in a)if(e=a[d],void 0===this[b][d])this[b][d]=e;else if(this[b][d]===Object(this[b][d])&&e===Object(e))for(f in e)this[b][d][f]=e[f];else{var g=this[b][d],h=e;RR.isArray(g)||(g=[g]),RR.isArray(e)||(h=[e]),this[b][d]=g.concat(h)}},addItemId:function(a,b){var c=a;typeof b!=RR.U&&(c=c+"~"+b),RR.add.call(window.R3_COMMON,c,"itemIds")},addItemIdToCart:function(a,b){var c=a;typeof b!=RR.U&&(c=c+"~"+b),RR.add.call(this,c,"addedToCartItemIds")},addSearchTerm:function(a){RR.add.call(window.R3_COMMON,a,"searchTerms")},genericAddItemPriceQuantity:function(a,b,c,d,e){typeof c==RR.U&&(c=0),typeof e==RR.U&&(e=-1),e=String(e),e.indexOf(".")!=-1&&(e=e.substring(0,e.indexOf("."))),RR.addItemId.call(this,a,b),RR.add.call(this,c,d),RR.add.call(this,e,"quantities")},addItemIdCentsQuantity:function(a,b,c,d){RR.genericAddItemPriceQuantity.call(this,a,d,b,"purchasesCents",c)},addItemIdDollarsAndCentsQuantity:function(a,b,c,d){RR.genericAddItemPriceQuantity.call(this,a,d,b,"purchasesDollarsAndCents",c)},addItemIdPriceQuantity:function(a,b,c,d){RR.genericAddItemPriceQuantity.call(this,a,d,b,"purchasesPrice",c)},checkParamCookieValue:function(a,b,c,d){var e=RR.pq(b),f=RR.pq(c),g=new RegExp("^\\w+$");if(g.test(e))return"session"===f?RR.c(d,e):isNaN(parseInt(f))?RR.c(d,null,-1):RR.c(d,e,f),RR.debugWindow(a+' set to "'+e+'".'),e;if(e=RR.c(d),e&&g.test(e)){if("remove"!==mvtCookie)return RR.debugWindow(a+' set to "'+e+'". To remove from cookie, add '+c+"=remove to your query parameters."),e;RR.c(d,null,-1)}return null}}}();/* complete : /javascript/common/p13n-1.2.js*/


/* combine : /javascript/common/jdwAffinities.js*/
var titleFunctions = [];
var placements = new Array();
var placementsArray = new Array();
var mobilePlacementIndex=0;
var mobileLastPlacementIndex=0;
var celvar_automatedAffinitiesSource = "rr";;
var insideClickthrough = false;
var localClickthrough;
var RR_pageId;
var R3_COMMON;
var R3_HOME;
var R3_ITEM;
var R3_SEARCH;
var R3_CATEGORY;
var R3_CART;
var R3_PURCHASED;
if(typeof isPdpAffinities == "undefined"){
	isPdpAffinities = false;
}
var currency = "&pound;";
if(typeof dataLayer != "undefined"){
	if( dataLayer[0].Currency === 'EUR'){
		currency="&euro;";
	}
}
var calledBefore = 0;
var offset = 0;

var automatedAffinitiesCallbackReceived = false;
var automatedAffinitiesSupplied = false;
var automatedAffinitiesDocumentReadyFired = false;

var noOfPlacements = 0;
if(typeof manualAffinityProducts != "undefined") {
	noOfPlacements = 1;
}

function jdwAffinitiesDisplayedOnPage() {
	celvar_automatedAffinitiesSource = "jdw";
}

function PlacementProduct(productCode, clickUrl) {
	this.productCode = productCode;
	this.clickUrl = clickUrl;
}

function Placement(index, strategy) {
	this.addProduct = function (product) {
		this.products[product.productCode] = product;
		this.productArray.push(product);
	};
	this.index = index;
	this.strategy = strategy;
	this.products = {};
	this.productArray = new Array();
	this.fragments = "";
	this.placementId = "#rr_placement_" + index;
}

// boolean tracks the first time that we create the click handler for RR carousel clicks as pages
// which refresh their content via ajax (category pages) will call processAffinities each time
// leading to several click handlers stacking up which breaks things.
var clicksDelegated = false;
function processAffinities(affinityData) {
	if(typeof useRetainedRRRecs != 'undefined' && !useRetainedRRRecs) {
		// Store the new RR recommendations via ajax
		RR_storeRRRecommendations(affinityData);
	}
	automatedAffinitiesCallbackReceived = true;
	
	// Add position information to manual affinities carousel for celebrus tracking
	noOfPlacements = noOfPlacements + affinityData.length;
	if(typeof manualAffinityProducts != "undefined") {
		$('#jdw-rr-slider-holder-manual1').attr('name', '1of'+noOfPlacements);
	}
	
	automatedAffinitiesSupplied = affinityData.length > 0;
	if (automatedAffinitiesSupplied) {
		//If page reloads rapidly due to ajax we can end up with more placements returned from RR than
		//we have slots to put them in.
		// This ensures that we only use the most recent results returned.
		if (calledBefore>0){
			offset= (affinityData.length/(++calledBefore));
			affinityData = affinityData.slice(offset);
		}
		placementsArray = affinityData;
		placements.length=0;
		//placements is still used in a few places, have to phase it out in next release.
		for (var placementIndex = 0; placementIndex < affinityData.length; placementIndex++) {
			var currentPlacement = new Placement(placementIndex, affinityData[placementIndex].message);
			placements.push(currentPlacement);
			var placementItemCount = affinityData[placementIndex].items.length;
			// On mobile, show the accordion if there are items to show in in
			if(placementItemCount > 0) {
				$("#affinityWrapper"+(placementIndex+1)).removeClass("beforeResponse");
			}
			for (var itemIndex = 0; itemIndex < placementItemCount; itemIndex++) {
				var productCode = affinityData[placementIndex].items[itemIndex].itemId;
				var clickUrl = affinityData[placementIndex].items[itemIndex].url;
				var placementProduct = new PlacementProduct(productCode, clickUrl);
				currentPlacement.addProduct(placementProduct);
			}
			if(!isPdpAffinities){
				requestFragments(placementIndex);	
			}
		}
		if(isPdpAffinities){
			$.each(affinityData, function (index, affinity){
				//process the items in the array and display in the relevant slots.
				if(affinity.placement_name == 'item_page.rr1'){
					addResponsiveAffinities(1,affinity.items, affinity.message);
				}else if (affinity.placement_name == 'item_page.rr2'){
					addResponsiveAffinities(2,affinity.items, affinity.message);
				}else if (affinity.placement_name == 'item_page.rr3'){
					addResponsiveAffinities(3,affinity.items, affinity.message);
				}else if (affinity.placement_name == 'item_page.mobile_rr2'){
					addMobileAffinities(1,affinity.items, affinity.message,0);
				}else if (affinity.placement_name == 'item_page.mobile_rr3'){
					addMobileAffinities(2,affinity.items, affinity.message,0);
				}else if(affinity.placement_name === "add_to_cart_page.rr1"){
					buildPostAddtoBagSlider(affinity.items, affinity.message);
				}else if(affinity.placement_name==='item_page.search_referrer_rr1' && searchReferrerEnabled){
					buildSearchReferrerSlider(affinity.items, affinity.message, false);
				}else if(affinity.placement_name==='item_page.mobile_search_referrer_rr1'&& searchReferrerEnabled){
					buildSearchReferrerSlider(affinity.items, affinity.message, true);
				}
			});	
		}
	} else {
		if (automatedAffinitiesDocumentReadyFired) {
			// We have not received any items from RR so they must be in listening
			// mode - therefore we need to show our own recently viewed items
			showJdwRecentlyViewedItems();
		}
	}
	
	// New handler for RR clickthroughs etc.
	if( (!clicksDelegated) && !( typeof responsive != 'undefined' && responsive )){
		var placementClass = '.rr_placement';
		$(placementClass).delegate(".productPreview a", "click", function() {
			var placement_div = $(this).parents(placementClass);
			var placement_id = placement_div.prop("id");
			var placement_index = placement_id.substring(placement_id.length-1);
			var placement = placements[placement_index];
			var id = $(this).prop("id");
			var productCode = id.substr(id.indexOf("-") + 1);
			if(!insideClickthrough) {
				insideClickthrough = true;
				$.ajax({
					url: placement.products[productCode].clickUrl
				});
				localClickthrough = $(this);
				setTimeout(function() {
					var e = jQuery.Event("click");
					if(!e.isDefaultPrevented()) {
						//Wait 200 ticks to give the RR ajax call a chance to complete before we
						//navigate away from this page.
						//nb. Suspect this runs in a separate thread and so doesn't actually delay
						//anything or do anything :-\
					}
					insideClickthrough = false;
				}, 200);
				return true;
			} else {
				return false;
			}
		});
		clicksDelegated = true;
	}
}

function addMobileAffinities(divid, itemArray, message, startAt){
	var count=0;
	var colourImages='';
	if(itemArray.length > 0){
		$.each(itemArray, function(index,item){
			if(index >= startAt){
				var url = (item.url).split("ct=");
				if(item.colour_images.trim().length >1){
					colourImages = item.colour_images.split(",");	
				}
				var divtag = '<div id="celid_cms3r3_affinities_pos-'+index+'_item-'+item.itemId+'" class="two-col-grid">';
				divtag += '<div class="productFragment productPreview" itemscope="" itemtype="http://schema.org/Product" itemid="'+item.itemId+'">';
				divtag += '<meta content="'+item.name+'" itemprop="name"><meta itemprop="sku" content="'+item.itemId+'">';
				divtag += '<a id="image-'+item.itemId+'" data-jdw-test-id="productCode_'+item.itemId+'" href="'+unescape(url[1])+'">';
				if(colourImages.length > 1 || item.colour_images.length==0){
					divtag += '<div id="prodItem"><img src="'+item.image+'" alt="'+item.name+'" itemprop="image"></div>';	
				}else{
					var colourImage = colourImages[0].split("|");
					divtag += '<div id="prodItem"><img src="'+colourImage[1]+'" alt="'+item.name+'" itemprop="image"></div>';
				}
				divtag += '<div class="productInfo">';
				divtag += '<h3 itemprop="name">'+item.name+'</h3>';
				divtag += '<p class="savePrice"></p>';
				divtag += '<p class="productPrice">'+ currency + item.saleprice+'</p>';
				divtag += '</div>';
				divtag += '</a>';
				divtag += '</div></div></div>';
				$("div#affinities"+divid).find("div.rr_placement").append(divtag);
				++count;
				return count < view_more_increment;
			}
		});
		if($("div#tab_affinity"+divid+"Details").hasClass("disabled")){
			$("div#tab_affinity"+divid+"Details").removeClass("disabled");	
		}
		$("div#affinities"+divid).css("display", "block");
		$("div#rr_placement_"+divid*1-1).css("display", "block");
		$("div#affinities"+divid).find("div.rr_placement").css("display", "block");
		if($("div#affinityWrapper0").length) {
		   divid = (divid*1)-1;
		}
		$("div#affinityWrapper"+divid).find("h2").html(message);
		$("div#affinityWrapper"+divid).css("display", "block");
	}
}

function mobileViewMorePlacements(divid, placementIndex, startAt) {
	var idstring = divid.split("-");
	addMobileAffinities(idstring[idstring.length-1], placementsArray[placementIndex].items, placementsArray[placementIndex].message, startAt);
	return (startAt+view_more_increment >= placementsArray[placementIndex].items.length
			|| startAt+view_more_increment >= 16);
}

function addResponsiveAffinities(divid, itemArray, message){
	var ulTag = '<ul id="ul-rr_placement_'+divid+'" class="jdw-rr-scroll-content"></ul>';
	var liTag = '';
	var colourImages = '';
	if(itemArray.length > 0){
		$("div#jdw-rr-slider-holder-rr"+divid).find("div.jdw-rr-productHolder").append(ulTag);
		$.each(itemArray, function(index,item){
			var url = (item.url).split("ct=");
			if(item.colour_images.trim().length >1){
				colourImages = item.colour_images.split(",");	
			}
			index=(index*1)+1;
			liTag = '<li id="celid_cms3r3_affinities_pos-'+index+'_item-'+item.itemId+'" class="productPreview" jdw-thumbnail-index="'+index+'">';
			liTag += '<div class="productPreviewTop">';
			liTag += '<a id="image-'+item.itemId+'" href="'+unescape(url[1])+'" title="'+item.name+'" class="affinityimagelink">';
			if(colourImages.length > 1 || item.colour_images.length==0){
				liTag += '<img class="jdw-rr-prodImage" src="'+item.image+'" alt="'+item.name+'"/>';
			}else{
				var colourImage = colourImages[0].split("|");
				liTag += '<img class="jdw-rr-prodImage" src="'+colourImage[1]+'" alt="'+item.name+'"/>';
			}			
			liTag += '</a>';
			if((item.rating).length>1){
				var ratingNum = getRating(item.rating);
				var ratingText = getRatingText(ratingNum);
				liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';
				liTag += '<strong class="score '+ratingText+'" title="'+ratingNum+' out of 5 stars">Average customer rating is '+ratingNum+' out of 5 stars.</strong>';
				liTag += '</div>';	
			}else{
				liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"></div>';
			}
			liTag += '<div class="jdw-rr-productInfo"><h2 itemprop="name">'+item.name+'</h2></div>';
			liTag += '</div>';
			liTag += '<div class="productPreviewBottom">';
			liTag += '<div class="jdw-rr-priceInfo"><p class="jdw-rr-priceText">';
			if(item.saleprice != item.price){
				var saveprice = (item.price*1) - (item.saleprice*1) ; 
				liTag += '<p class="salePrice">Save upto '+ currency + saveprice.toFixed(2)+'</p>';
				liTag += '<p class="wasPriceFormat">was up to '+currency + item.price+'</p>';	
			}
			liTag += '<p class="productPrice">'+currency + item.saleprice+'</p>';
			liTag += '</p></div>';
			liTag += '<a id="button-'+item.itemId+'" class="jdw-rr-button" href="/shop/'+item.name+"/"+item.itemId+'/product/details/show.action?pdBoUid='+item.itemId+'" title="'+item.name+'">Shop Now</a>';
			liTag += '</div>';
			$("ul#ul-rr_placement_"+divid).append(liTag);
		});
	}
	$("div#jdw-rr-slider-holder-rr"+divid).closest(".pdp-affinities").children("h3").html(message);
	$("div#jdw-rr-slider-holder-rr"+divid).find("div.jdw-rr-productHolder").css("display", "block");
	$("div#jdw-rr-slider-holder-rr"+divid).closest(".pdp-affinities").removeClass("pdp-affinities-hidden");
	$('.jdw-rr-productHolder').each(function(index) {
		new jdw.simpleScroller().create(this, $(this).children('ul').children('li').length,  index);
	});
}

function buildSearchReferrerSlider(itemArray, message, isMobile){
    var ulTag = $("div#rr-search-referrer-container ul");
    if(isMobile){
           ulTag = $("div.rr-search-referrer-flexslider ul.slides");
    }
    var liTag = '';
    var colourImages = '';
    if(itemArray.length > 0){
           $.each(itemArray, function(index,item){
                  if(index <4){
                	    var url = (item.url).split("ct=");
                        if(item.colour_images.trim().length >1){
                               colourImages = item.colour_images.split(",");   
                        }
                        index=(index*1)+1;
                        liTag = '<li id="celid_cms3r3_affinities_pos-'+index+'_item-'+item.itemId+'" class="rr-search-referrer-column" jdw-thumbnail-index="'+index+'">';
                        liTag += '<a href="'+unescape(url[1])+'">';
                        liTag += '<div class="rr-search-referrer-content">';
                        if(colourImages.length > 1 || item.colour_images.length==0){
                               liTag += '<img src="'+item.image+'" alt="'+item.name+'"/>';
                        }else{
                               var colourImage = colourImages[0].split("|");
                               liTag += '<img src="'+colourImage[1]+'" alt="'+item.name+'"/>';
                        }
                        liTag += '<div class="rr-search-referrer-info">';
                        liTag += '<div class="rsProductName">';
                        liTag += '<span class="rr-search-referrer-product-name">'+item.name+'</span>';
                        liTag += '</div>';
                        if((item.rating).length>1){
                               var ratingNum = getRating(item.rating);
                               var ratingText = getRatingText(ratingNum);
                               liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating">';
                               liTag += '<strong id="rsProductReviewStyle" class="score '+ratingText+'" title="'+ratingNum+' out of 5 stars">Average customer rating is '+ratingNum+' out of 5 stars.</strong>';
                               liTag += '</div>';   
                        }else{
                               liTag += '<div class="jdw-rr-stars rating" itemprop="aggregateRating" itemscope itemtype="http://schema.org/AggregateRating"></div>';
                        }
                        liTag += '<div class="jdw-rr-priceInfo">';
                        if(item.saleprice != item.price){
                               var saveprice = (item.price*1) - (item.saleprice*1) ; 
                               liTag += '<p id="pSalePrice" class="salePrice">Save upto '+ currency + saveprice.toFixed(2)+'</p>';
                               liTag += '<p id="pWasPrice" class="wasPriceFormat">was up to '+currency + item.price+'</p>';   
                        }
                        liTag += '<p id="pProductPrice" class="productPrice">'+currency + item.saleprice+'</p>';
                        liTag += '</div>';
                        liTag += '</div>';
                        liTag += '</div>';
                        liTag += '</a>';
                        liTag += '</li>';
                        ulTag.append(liTag);
                  }
           });
    }
    $("h3.rr-search-referrer-title").html(message);
    $("div#rr-search-referrer-container").css("display", "block");
    if(isMobile){
    	callTheSlider();
    }
}


function callTheSlider(){
  $('.flexslider').flexslider({
    animation: "slide"
  });
}

function getRatingText(rating){
	var text = "";
	if(rating.indexOf("0.") != -1){
		text = "half";
	}else if(rating.indexOf("1.") != -1){
		text = "one";
		if( (rating*1)>1.5 ){
			text = "oneAndHalf";
		}
	}else if(rating.indexOf("2.") != -1){
		text="two";
		if( (rating*1)>2.5 ){
			text = "twoAndHalf";
		}
	}else if(rating.indexOf("3.") != -1){
		text = "three";
		if( (rating*1)>3.5 ){
			text = "threeAndHalf";
		}
	}else if(rating.indexOf("4.") != -1){
		text = "four";
		if( (rating*1)>4.5 ){
			text = "fourAndHalf";
		}
	}else if(rating.indexOf("5.") != -1){
		text = "five";
	}
	return text;
}

function getRating(ratingUrl){
	var rating = ratingUrl.split("/");
	return rating[rating.length-3];
}
//added this to fix Post addto bag slider
function buildPostAddtoBagSlider(itemArray, message){
	if(rrAffinityData === undefined){
		var productParameters = "";
		$.each(itemArray, function(index,item){
			productParameters += "&productIds=" + item.itemId;
		});
		var ajaxUrlJsonResponse = "/shop/product/ajax/OutfitAffinityProducts.action?displayPriceRanges=true&maxProducts=";
		$.ajax({
			url: ajaxUrlJsonResponse+maxProductsInCarousel + productParameters,
			dataType: "json",
			async:false,
			success: function(data){
				rrAffinityData = data.outfitMap;
				rrAffinityMessage = message;
			},
			error: function (data, status, xhr){
				if (typeof console != "undefined") {
					console.log("Error in fragment request");
				}
			},
			complete: function(){
				jdw.productDetailsOutfitBuilder.openOutfitBuilder(currentAddToBagReturnData);				
			}
		});	
	}
}


function requestFragments(placementIndex, startAt) {
	// Most calls won't provide a startAt value so default to zero
	if(typeof(startAt)==='undefined') startAt = 0;
	
	var placement = placements[placementIndex];
	var productParameters = "";
	
	if(placement.productArray.length == 0) {
		// If RR sent us nothing back don't bother going through the second ajax call to render
		// products.
		return;
	}
	
	for (var i = startAt; i < placement.productArray.length; i++) {
		productParameters += "&productIds=" + placement.productArray[i].productCode;
	}
	
	var ajaxUrl = "/shop/product/fragment/AffinityProductFragmentList.action?displayPriceRanges=true&maxProducts=";
	if(typeof responsive != 'undefined' && responsive) {
		ajaxUrl = "/shop/product/ajax/AffinityProductFragmentListResponsive.action?displayPriceRanges=true&maxProducts=";
	}
	
	var ajaxUrlJsonResponse = "/shop/product/ajax/OutfitAffinityProducts.action?displayPriceRanges=true&maxProducts=";
	
	if(placementIndex == 0) {
		$.ajax({
			url: ajaxUrlJsonResponse+maxProductsInCarousel + productParameters,
			dataType: "json",
			success: function(data){
				rrAffinityData = data.outfitMap;
				rrAffinityMessage = placements[0].strategy;
			},
			error: function (data, status, xhr){
				if (typeof console != "undefined") {
					console.log("Error in fragment request");
				}
			}

		});
	}
	
	
	$.ajax({
		url: ajaxUrl+maxProductsInCarousel + productParameters,
		success: (function (_placements, _placementIndex){
			return function (data, status, xhr){
				_placements[_placementIndex].fragments = data;
				var placementId = _placements[_placementIndex].placementId;
				if ($(placementId).length) {
					populateAutomatedAffinities(_placements, _placementIndex, startAt);
				} else {
					setTimeout(function(){
						if ($(placementId).length) {
							populateAutomatedAffinities(_placements, _placementIndex, startAt);
						} else {
							$(document).ready(function () {populateAutomatedAffinities(_placements, _placementIndex, startAt);});
						}
					}, 500);
				}
			};
		})(placements, placementIndex),
		error: function (data, status, xhr){
			if (typeof console != "undefined") {
				console.log("Error in fragment request");
			}
		}

	});
}

function setupJCarousel(carouselBase, len) {
	var minLengthForCarousel = (typeof MIN_LIST_ITEMS_FOR_JCAROUSEL !== "undefined") ? MIN_LIST_ITEMS_FOR_JCAROUSEL : 4;
	if (((typeof len !== "undefined") ? len : carouselBase.children("li").length) > minLengthForCarousel) {
		if (typeof(carouselBase.jcarousel) == "function") {
			carouselBase.jcarousel();
		}
	}
}

function processPageAffinities(placements, placementIndex) {
	var placement = placements[placementIndex];
	var affinities = $(placement.placementId).parentsUntil(".affinityWrapper", ".carouselContainer").parent();
	affinities.find("h2.carouselHeader").html(placement.strategy);
	var affinityList = affinities.find('ul');
	var affinityCount = affinityList.children("li.carouselElement").length;
	if (affinityCount) {
		if (typeof(initCarousel) == "function") {
			initCarousel(placementIndex);
		}

		affinities.show();
	}
}

function processResponsivePageAffinities(placements, placementIndex) {
	var placement = placements[placementIndex];
	var affinities = $(placement.placementId).parentsUntil(".pdp-affinities").parent();
	affinities.find('h3').html(placement.strategy);
	var posOnPage = placementIndex + 1;
	if(typeof manualAffinityProducts != "undefined") {
		posOnPage = posOnPage + 1;
	}
	$(placement.placementId).parent().attr("name", posOnPage+"of"+noOfPlacements);
	affinities.removeClass('pdp-affinities-hidden');
}

function populateAutomatedAffinities(placements, placementIndex, startAt) {
	var placement = placements[placementIndex];

	var ulTag = '<ul>';
	if(typeof responsive != 'undefined' && responsive === true) {
		ulTag = '<ul class="jdw-rr-scroll-content">';
	}
	
	if(startAt === 0) {
		$(placement.placementId).html(ulTag+placement.fragments+'</ul>').show();
	} else {
		$(placement.placementId + " ul").append(placement.fragments);
	}

	if(typeof responsive != 'undefined' && responsive) {
		processResponsivePageAffinities(placements, placementIndex);
	} else {
		processPageAffinities(placements, placementIndex);
	}
	
	// Call back to the page that the affinities have loaded.
	if(typeof(affinitiesLoaded) !== 'undefined' && affinitiesLoaded.length > placementIndex) {
		affinitiesLoaded[placementIndex](placement.productArray.length);
	}
}

function RR_init(pageId) {
	
	if (!resetForAjax()){
		return false;
	}
	RR_pageId = pageId;
	R3_COMMON = new r3_common();
	R3_COMMON.setApiKey(RR_apiKey);
	R3_COMMON.setBaseUrl(window.location.protocol+'//'+RR_server);
	R3_COMMON.setClickthruServer(window.location.protocol+'//'+window.location.host);
	R3_COMMON.setSessionId(RR_sessionId);
	R3_COMMON.setUserId(RR_userId);
	var isTablet = $('meta[name=jdw-isTablet]').attr("value") == "true";
	var isMobile = $('meta[name=jdw-isMobileDevice]').attr("value") == "true";
	var channel = RR_apiKey;
	if(isTablet) {
		channel += "-tablet";
	} else if(isMobile) {
		channel += "-mobile";
	} else {
		channel += "-desktop";
	}
	R3_COMMON.setChannel(channel);
	return true;
}

function RR_initHome() {
	if (!RR_init("home_page")){
		return false;
	};
	R3_HOME=new r3_home();
	RR_setupHome();
	r3();
}

function RR_initItem() {
	if (!RR_init("item_page")){
		return false;
	}
	R3_ITEM=new r3_item();
	R3_ITEM.setId(RR_item);
	RR_setupItem();
	r3();
}

function RR_initSearch() {
	if (!RR_init("search_page")){
		return false;
	}
	
	R3_SEARCH=new r3_search();
	R3_SEARCH.setTerms(RR_searchTerm);
	RR_setupSearch();
	r3();
}

function RR_initCategory() {
	if (!RR_init("category_page")){
		return false;
	}
	R3_CATEGORY=new r3_category();
	R3_CATEGORY.setId(RR_categoryId);
	R3_CATEGORY.setName(RR_categoryName);
	RR_setupCategory();
	r3();
}

function RR_initCart() {
	// If we have kept hold of existing recommendations, we want to load those existing rather than
	// request new ones
	if(typeof useRetainedRRRecs != 'undefined' && useRetainedRRRecs) {
		RR_loadRetainedRecommendations();
		return false;
	}
	if (!RR_init("cart_page")){
		return false;
	}
	R3_CART=new r3_cart();
	RR_setupCart();
	r3();
}

function RR_initPurchased(title) {
	if (!RR_init("purchased_page")){
		return false;
	}
	R3_PURCHASED=new r3_purchased();
	R3_PURCHASED.setOrderNumber(RR_orderNumber);
	titleFunctions['RR_setupPurchased'+title]();
	r3();
}
// Posts the Rich Relevance recommendations to the PersistRRRecommendationsAction via ajax. The
// action stores the recs as a JSON string in the session so they can be retrieved and re-displayed
// in on-screen carousels.
function RR_storeRRRecommendations(affinityData) {
	$.ajax({
		url: "/shop/viewbag/ajax/StoreRRRecommendations.action",
		data: {recommendationsJson: JSON.stringify(affinityData)},
		error: function() {
			if (typeof console != "undefined") {
				console.log("Failed to store RR recommendations.");
			}
		},
		type: "POST"
	});
}
// Makes an ajax call to the PersistRRRecommendationsAction to retrieve any Rich Relevance
// recommendations stored in the session and passes the retrieved placements array into
// processAffinities to build carousels displaying them.
function RR_loadRetainedRecommendations() {
	$.ajax({
		url: "/shop/viewbag/ajax/RetrieveRRRecommendations.action",
		success: function(data) {
			var affinityData = JSON.parse(data.recommendationsJson);
			processAffinities(affinityData);
		},
		error: function() {
			if (typeof console != "undefined") {
				console.log("Unable to retrieve stored RR recommendations.");
			}
		}
	});
}

function resetForAjax(){
	// Clear the itemObjArray as it seems to be holding onto previous placement details resulting
	// in duplicated carousels in some specific cases (i.e. when the user has no 'recently viewed'
	// items to populate the second placement)
	if(typeof itemObjArray !== "undefined") {
		itemObjArray = new Array();
	}

	rr_placement_place_holders.length=0;
	RR.onloadCalled = false;
	var makeRRCall = true;

	function getHash(){
		try{
			return History.getHash();
		}catch (error){
			return false;
		}
	}

	if (getHash()){
		//this is not the base version of the page

		if (History.stateChanged){
			//page refreshed due to ajax

		}else{
			//*Not* refreshed by ajax, page is about to be reloaded. RR call should be aborted
			makeRRCall=false;
			rr_onload_called = false;
		}
	}
	return makeRRCall;
}

function initCarousel(placementIndex) {
    setProductSlider("#rr_placement_" + placementIndex, getSliderAttributes());
    var x = 1;
}

function setProductSlider(containerSelector, slideArray) {
	var container = $(containerSelector);
	container.addClass("flexslider");
	$(containerSelector+" ul").addClass("slides");
	
	//NB. To prevent problems with revisiting pages refreshed via ajax, the flexslider library has
	//been amended slightly. Line 851 $this.removeData('flexslider'); has been added.
	//This will potentially need to be added if the flexslider library is updated beyond v2.1 
    container.flexslider({
        animation: "slide",
        direction: slideArray.direction,
        controlNav: false,
        touch: false,
        animationLoop: false,
        slideshow: false,
        itemWidth: $(containerSelector +' ul.slides > li').outerWidth(),
        itemHeight: 130,
        itemMargin: 0,
        maxItems: slideArray.items,
        move: 1
    });
    // parseInt($('.rr_placement.flexslider li.carouselElement:first-child').css('margin-right').replace('px', ''))
    setProductSliderCSS(containerSelector, slideArray);
}

function setProductSliderCSS(containerSelector, slideArray) {
	var container = $(containerSelector);
    if ($(containerSelector + " ul > li").length <= slideArray.items) {
        container.find('.flex-prev').hide();
        container.find('.flex-next').hide();
        if (!container.hasClass('inactive')) container.addClass('inactive');
    } else {
        container.find('.flex-prev').show();
        container.find('.flex-next').show();
        if (container.hasClass('inactive')) container.removeClass('inactive');
    }
}

function getSliderAttributes() {
    /* Horizontal by default */
    var direction = $(window).width() > 769 ? "horizontal" : "vertical";
    
    var items = direction == "horizontal" ? 4 : 3;
    if (typeof HORIZONTAL_OVERRIDE !== "undefined" && direction == "horizontal") {
    	items = HORIZONTAL_OVERRIDE;
    }
    if (typeof VERTICAL_OVERRIDE !== "undefined" && direction == "vertical") {
    	items = VERTICAL_OVERRIDE;
    }
    
    return {'direction' : 'horizontal', 'items' : items}; 
}

function showJdwRecentlyViewedItems() {
	if ($("#recentlyViewedContainer").length) {
		$("#recentlyViewedContainer").show();
	} else if ($("#recentlyViewedItems").length) {
		$("#recentlyViewedItems").show();
	}
}

function mobileViewMore(placementIndex, startAt) {
	requestFragments(placementIndex, startAt);
	// Return value, true means there are no more fragments left and the view more button should
	// be disabled.
	return (startAt+view_more_increment >= placements[placementIndex].productArray.length
			|| startAt+view_more_increment >= 16);
}

$(document).ready(function() {
	if (automatedAffinitiesCallbackReceived
		&& !automatedAffinitiesSupplied) {
		// We have not received any items from RR so they must be in listening
		// mode - therefore we need to show our own recently viewed items
		showJdwRecentlyViewedItems();
	}
	automatedAffinitiesDocumentReadyFired = true;
});


// Mobile manual affinities details to allow view more for manual
//Expect an array manualAffinityProducts containing product ids to be defined on the page.
var fragments;
var manualPlacementId = '#manual_placement_0';
function requestManualFragments(startAt) {
	// Most calls won't provide a startAt value so default to zero
	if(typeof(startAt)==='undefined') startAt = 0;
	
	var productParameters = "";
	for (var i = startAt; i < manualAffinityProducts.length; i++) {
		productParameters += "&productIds=" + manualAffinityProducts[i];
	}
	$.ajax({
		url: "/shop/product/fragment/AffinityProductFragmentList.action?displayPriceRanges=true&maxProducts="+maxProductsInCarousel + productParameters,
		success: (function (data, status, xhr){
			fragments = data;
			if ($(manualPlacementId).length) {
				populateManualAffinities(startAt);
			} else {
				setTimeout(function(){
					if ($(manualPlacementId).length) {
						populateManualAffinities(startAt);
					} else {
						$(document).ready(function () {populateManualAffinities(startAt);});
					}
				}, 500);
			}
		}),
		error: function (data, status, xhr){
			if (typeof console != "undefined") {
				console.log("Error in fragment request");
			}
		}
	});
}

function populateManualAffinities(startAt) {
	if(startAt === 0) {
		$(manualPlacementId).html('<ul>'+fragments+'</ul>').show();
	} else {
		$(manualPlacementId + " ul").append(fragments);
	}
}

function manualViewMore(startAt) {
	requestManualFragments(startAt);
	// Return value, true means there are no more fragments left and the view more button should
	// be disabled.
	return (startAt+view_more_increment >= manualAffinityProducts.length
			|| startAt+view_more_increment >= 16);
}/* complete : /javascript/common/jdwAffinities.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsFormSubmit.js*/
function submitAjaxForm( actionName, callbackFunction, params, prefix ) {
	var urlStr = "/shop/product/details/ajax/" + actionName + ".action";
	if ( params ) {
		urlStr = urlStr + "?" + params + "&detaildError=true";
	}
	performAjaxRequest(	urlStr,
						null,
						null,
						'json',
						$('#' + prefix + '_optionsForm').serialize(),
						callbackFunction, 
						function() { enableAjaxElements(prefix); }, 
						'POST',
						getUniqueClass('#atbInner')
	);
}
/* complete : /javascript/productDetailsRedesign/productDetailsFormSubmit.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsOptions.js*/
var currentStockMessage;

$(document).ready(function() {
    if(!isProductDetailsLoaded()) {
        return attachProductDetailsOptionsEvents(productDetailsPrefix);
    }
});

//construct js object for the Product details and QuickView


function setupProductInfoObject(prefix) {
    var formId = prefix + "_optionsForm";
    var getHiddenFieldVal = function(name){
        return $("#"+ formId).children("input[name^='"+ name +"']").val();
    };
    
    var getInitialAltImagesData = function() {
        var altText ="initialMainAltImageData_altText_";
        var mainProductLocation = "initialAltImagesData_mainProductLocation_";
        var largeLocation = "initialAltImagesData_largeLocation_";
        var thumbLocation = "initialAltImagesData_thumbLocation_";
        var zoomifyLocation = "initialAltImagesData_zoomifyLocation_";
        var desktopZoomLocation = "initialAltImagesData_desktopZoomLocation_";
        var tabletZoomLocation = "initialAltImagesData_tabletZoomLocation_";
        var quickViewLocation = "initialAltImagesData_quickviewLocation_";
        var noOfAltImages = $("#"+ formId).children("input[name^='"+ mainProductLocation +"']").length;
        
        var initialAltImagesData = [];
        
        for (var i = 0; i < noOfAltImages; i++) {
            initialAltImagesData.push({altText: getHiddenFieldVal(altText + i),
                mainProductLocation: getHiddenFieldVal(mainProductLocation + i),
                largeLocation: getHiddenFieldVal(largeLocation + i),
                thumbLocation: getHiddenFieldVal(thumbLocation + i),
                zoomifyLocation: getHiddenFieldVal(zoomifyLocation + i),
                desktopZoomLocation: getHiddenFieldVal(desktopZoomLocation + i),
                tabletZoomLocation: getHiddenFieldVal(tabletZoomLocation + i)});
        }
        return initialAltImagesData;
        
    };
    
    var productInfoObj = {
            "messages":{
                "invalid":getHiddenFieldVal("invalidAddToBagMessage"),
                "outOfStockAddToWishListMessage":getHiddenFieldVal("outOfStockAddToWishListMessage"),
                "incompleteAddToWishListMessage":getHiddenFieldVal("incompleteAddToWishListMessage")},
            "initialStockMessage":getHiddenFieldVal("initialStockMessage"),
            "pagePrefix":getHiddenFieldVal("actionPrefix"),
            "hasFittings":getHiddenFieldVal("hasFittings"),
            "fitting":getHiddenFieldVal("fittings"),
            "optionColour":getHiddenFieldVal("optionColour"),
            "optionSize":getHiddenFieldVal("optionSize"),
            "initialMainImageData":{
                "altText": getHiddenFieldVal("initialMainImageData_altText"),
                "mainProductLocation": getHiddenFieldVal("initialMainImageData_mainProductLocation"),
                "largeLocation": getHiddenFieldVal("initialMainImageData_largeLocation"),
                "thumbLocation": getHiddenFieldVal("initialMainImageData_thumbLocation"),
                "zoomifyLocation": getHiddenFieldVal("initialMainImageData_zoomifyLocation"),
                "desktopZoomLocation": getHiddenFieldVal("initialMainImageData_desktopZoomLocation"),
                "tabletZoomLocation": getHiddenFieldVal("initialMainImageData_tabletZoomLocation"),
                "quickviewLocation": getHiddenFieldVal("initialMainImageData_quickviewLocation")},
            "initialMainAltImageData": {
                "altText": getHiddenFieldVal("initialMainAltImageData_altText"),
                "mainProductLocation": getHiddenFieldVal("initialMainAltImageData_mainProductLocation"),
                "largeLocation": getHiddenFieldVal("initialMainAltImageData_largeLocation"),
                "thumbLocation": getHiddenFieldVal("initialMainAltImageData_thumbLocation"),
                "zoomifyLocation": getHiddenFieldVal("initialMainAltImageData_zoomifyLocation"),
                "desktopZoomLocation": getHiddenFieldVal("initialMainAltImageData_desktopZoomLocation"),
                "tabletZoomLocation": getHiddenFieldVal("initialMainAltImageData_tabletZoomLocation"),
                "quickviewLocation": getHiddenFieldVal("initialMainAltImageData_quickviewLocation")},
            "initialAltImagesData" : getInitialAltImagesData()
            };
    return productInfoObj;
}

function getUrlParameter(param)
{
    var pageURL = window.location.search.substring(1);
    var urlVariables = pageURL.split('&');
    for (var i = 0; i < urlVariables.length; i++) 
    {
        var parameterName = urlVariables[i].split('=');
        if (parameterName[0] == param) 
        {
            return parameterName[1];
        }
    }
} 

function attachProductDetailsOptionsEvents(prefix) {

    var productInfoObj = setupProductInfoObject(prefix);
    var fittingEle = $("#"+ prefix +"_fitting");
    var optionsColourEle = $("#"+ prefix +"_optionColour");
    var optionsSizeEle = $("#"+ prefix +"_optionSize");
    var quantityEle = $("#"+ prefix +"_quantity");
    fittingEle.unbind('change');
    optionsColourEle.unbind('change');
    optionsSizeEle.unbind('change');
    quantityEle.unbind('change');
    
    fittingEle.change(prefix, onSelectFittings);
    optionsColourEle.change(prefix, onSelectColour);
    optionsSizeEle.change(prefix, onSelectSize);
    quantityEle.change(prefix, onSelectQuantity);

    if ($("#" + prefix + "_optionsForm").length > 0) {
    	$("#" + prefix + "_optionsForm")[0].reset();
    }

    // Set the selected values in the fitting, colour and size dropdowns
    if (productInfoObj.hasFittings
        && (productInfoObj.fitting != '')) {
        $fittingDrop = $("#"+ prefix +"_fitting").find("option[value='" + productInfoObj.fitting + "']");
		$fittingDrop.prop("selected", "true");
    }
    if (productInfoObj.optionColour != '') {
        $colourDrop = $("#"+ prefix +"_optionColour").find("option[value='" + productInfoObj.optionColour + "']");
		$colourDrop.prop("selected", "true");
    }
    if (productInfoObj.optionSize != '') {
        $sizeDrop = $("#"+ prefix +"_optionSize").find("option[value='" + productInfoObj.optionSize + "']");
		$sizeDrop.prop("selected", "true");
    }
    // Setup quantity
    $quantityDrop = $("#"+ prefix +"_quantity").find("option[value='0']");
	$quantityDrop.prop("selected", "true");

    if (prefix != '') {
        $prefix = prefix;
    }
    
    fittingEle.cssDropdown();
    optionsColourEle.cssDropdown();
    optionsSizeEle.cssDropdown();
    quantityEle.cssDropdown();
    
    currentStockMessage = productInfoObj.initialStockMessage;
    $('.fadeMsgBox .' + prefix + '_msg').html(currentStockMessage);

    refreshPrices(prefix, $("#"+ prefix +"_unformattedPrice").val(),
                  $("#"+ prefix +"_unformattedDeliveryCharge").val(),
                  $("#"+ prefix +"_currencyUnicodeSymbol").val());
    
    //check which productDetails type and call populateImageAndImageAnchors
    if (typeof String.prototype.startsWith != 'function') {
          // see below for better implementation!
          String.prototype.startsWith = function (str){
            return this.indexOf(str) == 0;
          };
        }
    
    var localInitialMainImageData = productInfoObj.initialMainImageData;
    var localInitialMainAltImageData = productInfoObj.initialMainAltImageData;
    var localInitialAltImagesData = productInfoObj.initialAltImagesData;
    
    
    if(prefix.startsWith("standard")) {
        jdw.productDetailsMedia.populateImageAndImageAnchors(prefix, localInitialMainImageData, localInitialMainAltImageData, localInitialAltImagesData);
    } else {
        jdw.productDetailsQuickViewMedia.populateImageAndImageAnchors(prefix, localInitialMainImageData, localInitialMainAltImageData, localInitialAltImagesData);
    }
    
    enableAjaxElements(prefix);
    syncAnchorAttributes(prefix);
    displaySelectedOptionIdIfRequired(getUrlParameter("optionId"));
    
    if(isProductDetailsLoaded()) {
    
        $('#quickViewSingle .warrantyButtonContainer, .ampl-content .warrantyButtonContainer').delegate('a', 'click', function(event) {
            var pdw = jdw.productDetailsWarranty;
            event.preventDefault();
            pdw.hideBackToProductButton(false);
            var urlString=$(this).attr("href");
            var title=$(this).attr("title");
            pdw.showWarrantyModal(urlString, false, title);
            return false;
        });    
    }
}

function syncAnchorAttributes(prefix) {
	if(prefix.startsWith("standard")) {
		var productInfoObj = setupProductInfoObject(prefix);
	    var urlObject = new URLAnchorObject(window.location.hash.replace("#",""));
	    // external generated URLS (e.g. by dressipi) may be URIencoded
		var urlObjectColour = urlObject.getAttr("colour");
		var urlObjectSize = urlObject.getAttr("size");
	    var anchorColour = urlObjectColour?decodeURI(urlObjectColour):null;
	    var anchorSize = urlObjectSize?decodeURI(urlObjectSize):null;
	    if ((anchorColour && (anchorColour != productInfoObj.optionColour))
	        || (anchorSize && (anchorSize != productInfoObj.optionSize))) {
	        if (anchorColour) {
	            $colourDrop = $("#"+ prefix +"_optionColour").find("option[value='" + anchorColour + "']");
	            $colourDrop.attr("selected", "true");
	        }
	        if (anchorSize) {
	            $sizeDrop = $("#"+ prefix +"_optionSize").find("option[value='" + anchorSize + "']");
	            $sizeDrop.attr("selected", "true");
	        }
	        submitAjaxForm("refreshForSizeOrColour", handleAjaxResultForSyncAnchorAttributes, "elementId=" + prefix, prefix);
	        disableAjaxElements(prefix);
	    } else {
	        updateUrlWithOptions(prefix);
	    }
	}
}

function handleAjaxResultOnChangeFitting(event) {
    var prefix = event.elementId;
    var productInfoObj = setupProductInfoObject(prefix);
    var model = event.model;
    if(!isProductDetailsLoaded()) {
        window.location = "/shop/" + productInfoObj.pagePrefix + "product/details/show.action" + model.fittingUrl;
    } else {
    	if (prefix.startsWith("plpsingleview")) {
    		$.get("/shop/quickview/product/details/showPLPSingleQuickBuy.action" + model.fittingUrl, function(data) {
                $("#"+ prefix +"_fitting").remove();
                $("#"+ prefix +"_optionColour").remove();
                $("#"+ prefix +"_optionSize").remove();
                $("#"+ prefix +"_mainImage").remove();
                $('#modal_container').empty();
                $('#modal_container').html(data);
                attachProductDetailsOptionsEvents(prefix);
                $('#quickBuyModalClose').click(function() {
                    closeModalJQ();
                });
            });
    	} else if (prefix.startsWith("plpmultibuy")) {
    		$.get("/shop/quickview/product/details/showPLPMultiBuyQuickView.action" + model.fittingUrl, function(data) {
                $("#"+ prefix +"_fitting").remove();
                $("#"+ prefix +"_optionColour").remove();
                $("#"+ prefix +"_optionSize").remove();
                $("#"+ prefix +"_mainImage").remove();
        
                caro.frames.each(function(n) {
                    $(this).empty();
                });
        
                caro.frames.eq(caro.currentIndex).html(data);
                attachProductDetailsOptionsEvents(prefix);
            });
    	} else if (isMultiBuy == true) {
            $.get("/shop/quickview/product/details/showMultiBuyQuickView.action" + model.fittingUrl, function(data) {
                $("#"+ prefix +"_fitting").remove();
                $("#"+ prefix +"_optionColour").remove();
                $("#"+ prefix +"_optionSize").remove();
                $("#"+ prefix +"_mainImage").remove();
        
                caro.frames.each(function(n) {
                    $(this).empty();
                });
        
                caro.frames.eq(caro.currentIndex).html(data);
                attachProductDetailsOptionsEvents(prefix);
            });
        } else {
            $.get("/shop/quickview/product/details/showSingleQuickBuy.action" + model.fittingUrl, function(data) {
                $("#"+ prefix +"_fitting").remove();
                $("#"+ prefix +"_optionColour").remove();
                $("#"+ prefix +"_optionSize").remove();
                $("#"+ prefix +"_mainImage").remove();
                $('#modal_container').empty();
                $('#modal_container').html(data);
                attachProductDetailsOptionsEvents(prefix);
                $('#quickBuyModalClose').click(function() {
                    closeModalJQ();
                });
            });
        }
    }
}
function handleAjaxResultForSizeOrColourChange(returnObj) {
    var prefix = returnObj.elementId;
    populateOptions(prefix, returnObj);
    populateStockMessages(returnObj);

    $("#"+ prefix +"_selectedOptionId").val(returnObj.model.selectedOptionId);
    displaySelectedOptionIdIfRequired(returnObj.model.selectedOptionId);
    $("#"+ prefix +"_canAddToBag").val(returnObj.canAddToBag);
    $("#"+ prefix +"_invalidSelection").val( returnObj.model.invalidSelection);
    $("#"+ prefix +"_outOfStock").val(returnObj.model.outOfStock);

    refreshPrices( prefix, returnObj.model.unformattedPrice,
                   returnObj.model.unformattedDeliveryCharge,
                   returnObj.model.currencyUnicodeSymbol);
    enableAjaxElements(prefix);
    
    // In quickView, two animations trigger with a delay between each so we want to resize
    // immediately to accomadate the label that appears immediately and then resize again for the
    // label that takes a while to fade in. We could skip the first resize but then there's a second
    // or two where content is obviously dropping out of view.
    jdw.quickView.forceSliderResize(prefix);
    jdw.quickView.forceSliderResize(prefix, 1000);
}

function displaySelectedOptionIdIfRequired(prefix, optionId) {
    var prodCatNumberOptIdElem = $("#prodCatNumberOptId"); 
    if (prodCatNumberOptIdElem.length) {
        if (typeof optionId != 'undefined' && optionId != '') {
            prodCatNumberOptIdElem.html(optionId);
        } else {
            prodCatNumberOptIdElem.html('');
        }
    }
}

function populateStockMessages(data) {
    if (data != null) {
        if (data.model != null) {
            var msg = data.model.stockInformationMessage;
            if (msg != null) {
                messageAnimationFunctions.msgText(msg, data.elementId);
            }
            // Store this globally so that we can re-display it without an AJAX call
            currentStockMessage = msg;
            //Celebrus Data - inform speed trap when 'To Follow' or 'Substitute' message is displayed.
            eval( data.model.celebrusData ); 
        }
    }
}

function populateAllOptions( prefix, data ) {
    if ( data.model.fittingSelectItemList ) {
        var numFittings = data.model.fittingSelectItemList.length;
        if ( numFittings > 1 ) {
            writeOptionData( data.model.fittingSelectItemList, prefix + "_fitting", data.model.fitting );
        }
    }
    populateOptions( prefix, data );
}

function populateOptions(prefix, data) {
    if (data.model.colourDropdownVisible) {
        $("#colourDiv").show();
        writeOptionData(data.model.colourSelectItemList, prefix + "_optionColour", data.model.optionColour);
        /* The following if statement is only necessary while using the cssDropdown js code
            when rendering our selects.  The whole of the css dropdown code needs re-visiting
            so that it becomes transparent to the calling code; eg, looks like a normal dropdown
            select, and fires and responds to the various select events in a consistent manner
        */
        if ($("#"+ prefix +"_optionColour_select").size() == 1) {
            $("#" + prefix + "_optionColour").attr('show', 'true');
            $("#" + prefix + "_optionColour").cssDropdown();
        } else {
            $("#optionColourLabel").show();
            $("#" + prefix + "_optionColour").show();
        }
    } else {
        /* The following if statement is only necessary while using the cssDropdown js code
            when rendering our selects.  The whole of the css dropdown code needs re-visiting
            so that it becomes transparent to the calling code; eg, looks like a normal dropdown
            select, and fires and responds to the various select events in a consistent manner
        */
        if ($("#"+ prefix +"_optionColour_select").size() == 1)
            $("#" + prefix + "_optionColour").attr('show', 'false');
        else {
            $("#optionColourLabel").hide();
            $("#"+ prefix +"_optionColour").hide();
        }
    }
    if (data.model.sizeDropdownVisible) {
        $("#" + prefix + "_sizeDiv").show();
        writeOptionData(data.model.sizeSelectItemList, prefix + "_optionSize", data.model.optionSize);

        /* The following if statement is only necessary while using the cssDropdown js code
            when rendering our selects.  The whole of the css dropdown code needs re-visiting
            so that it becomes transparent to the calling code; eg, looks like a normal dropdown
            select, and fires and responds to the various select events in a consistent manner
        */
        if ($("#"+ prefix +"_optionSize_select").size() == 1) {
            $("#"+ prefix +"_optionSize").attr('show', 'true');
            $("#"+ prefix +"_optionSize").cssDropdown();
        } else {
            $("#optionSizeLabel").show();
            $("#"+ prefix +"_optionSize").show();
        }
    } else {
        /* The following if statement is only necessary while using the cssDropdown js code
            when rendering our selects.  The whole of the css dropdown code needs re-visiting
            so that it becomes transparent to the calling code; eg, looks like a normal dropdown
            select, and fires and responds to the various select events in a consistent manner
        */
        if ($("#"+ prefix +"_optionSize_select").size() == 1)
            $("#"+ prefix +"_optionSize").attr('show', 'false');
        else {
            $("#optionSizeLabel").hide();
            $("#"+ prefix +"_optionSize").hide();
        }
    }
    
    $("#" + prefix + "_quantityDiv").show();
    if ($("#"+ prefix +"_quantity_select").size() == 1) {
        $("#"+ prefix +"_quantity").attr('show', 'true');
        $("#"+ prefix +"_quantity").cssDropdown();
    } else {
        $("#quantityLabel").show();
        $("#"+ prefix +"_quantity").show();
    }
}

function writeOptionData(optionList, selectObjName, selectedValue) {
    if (optionList) {
        populateSelect(optionList, selectObjName, selectedValue);
    }
}

function populateSelect(optionList, selectObjName, selectedValue) {
    var index = 0;
    var selectObj = $("#"+selectObjName)[0];
    while (index < optionList.length) {
        var option = optionList[index];
        var optionId = option.valueId;
        selectObj.options[index] = new Option(option.displayString, optionId);
        if (selectedValue == optionId) {
            selectObj.selectedIndex = [index];
            selectObj.options[index].selected = true;
        }
        selectObj.options[index].className = option.displayCssClass;
        index++;
    }
    while (selectObj.options[index]) {
        selectObj.options[index] = null;
    }
}

function disableAjaxElements(prefix) {
    var elementNames = [ 'optionColour', 'optionSize' ];
    for (var index = 0; index < elementNames.length; index++ ) {
        disableAjaxElement(elementNames[index], prefix);
    }
}

function disableAjaxElement(elementName, prefix) {
    if($("#" + prefix + elementName).length){
        $("#" + prefix + elementName)[0].disabled = true;    
    }    
}

function enableAjaxElements(prefix) {
    var elementNames = [ prefix + '_optionColour', prefix + '_optionSize' ];
    for (var index = 0; index < elementNames.length; index++ ) {
        enableAjaxElement(elementNames[index]);
    }
}

function enableAjaxElement(elementName) {
    $("#" + elementName).removeAttr("disabled");
}

// updates the url with the currently selected colour and size options,
// to enable bookmarking of the product details page with the options preserved 
function updateUrlWithOptions(prefix){
    //this only update the url on selected option from main PDP
    if(prefix.indexOf("standard_") == 0) {
        var urlAnchorObject = new URLAnchorObject();
        urlAnchorObject.addAttr("colour", $('#' + prefix + '_optionColour :selected').val());
        urlAnchorObject.addAttr("size", $('#'+ prefix +'_optionSize :selected').val());

        // update anchor
        var tmpLocation = window.location;
        if(!isProductDetailsLoaded()) {
            var tmpHref = tmpLocation.pathname + tmpLocation.search + '#' + urlAnchorObject.toString();
            window.location.replace(tmpHref);
        } else {
            // Strip optionId param if it exists
            var tmpSearch = tmpLocation.search;
            var optIdStr = "optionId";
            var optionId = $.url.param("optionId");
            if (typeof optionId != 'undefined' && optionId != '') {
                optIdStr += ("=" + optionId);
                tmpSearch = tmpSearch.replace("?" + optIdStr, "").replace("&" + optIdStr, "");
                if (tmpSearch.charAt(0) == "&") {
                    tmpSearch = "?" + tmpSearch.substr(1);
                }        
            }
            var tmpHref = tmpLocation.pathname + tmpLocation.search + '#' + urlAnchorObject.toString();
            window.location.replace(tmpHref);
        }
    }
}

function URLAnchorObject(args) {
    this.attrs = new Object();
    var KEY_VALUE_PAIR_SEPARATOR = ':';
    var KEY_VALUE_PAIR_LIST_DELIMITER = ',';

    // Methods ----------------------------------------
    
    this.parseAndAddAttrs = function(attrsString) {
        if (attrsString) {
            var parameters = attrsString.split(KEY_VALUE_PAIR_LIST_DELIMITER);
            for (var i = 0; i < parameters.length; i++) {
                var sections = parameters[i].split(KEY_VALUE_PAIR_SEPARATOR);
                this.attrs[sections[0]] = sections[1];
            }
        }
    };
    this.addAttrs = function(attrs) {
        for (attrName in attrs) {
            this.addAttr(attrName, attrs[attrName]);
        }
    };
    this.addAttr = function(name, val) {
        this.attrs[name] = val;
    };
    this.getAttr = function(name) {
        return this.attrs[name];
    };
    this.toString = function() {
        var outStr = "";
        var first = true;
        for (attrName in this.attrs) {
            if (first) { first = false;
            } else { outStr = outStr + KEY_VALUE_PAIR_LIST_DELIMITER;
            }
            outStr = outStr + attrName + KEY_VALUE_PAIR_SEPARATOR +
                    (this.attrs[attrName] ? this.attrs[attrName] : "");
        }
        return outStr;
    };
    
    // Initialise ---------------------------------------------
    
    if (typeof args == 'string') {
        this.parseAndAddAttrs(args);
    } else {
        this.addAttrs(args);
    }
}

function refreshPrices(prefix, unformattedPrice, unformattedDeliveryCharge, currencyUnicodeSymbol) {
    $("#"+ prefix +"_unformattedPrice").val(unformattedPrice);
    $("#"+ prefix +"_unformattedDeliveryCharge").val(unformattedDeliveryCharge);
    $("#"+ prefix +"_currencyUnicodeSymbol").val(currencyUnicodeSymbol);
    reallyRefreshTotalItemPrice(prefix);
}

function reallyRefreshTotalItemPrice(prefix) {
    if (validateQuantity(prefix, false)) {
        var quantity = $("#"+ prefix +"_quantitySelect").val();
        var unformattedPrice = $("#"+ prefix +"_unformattedPrice").val();
        var unformattedDeliveryCharge = $("#"+ prefix +"_unformattedDeliveryCharge").val();
        var currencyUnicodeSymbol = $("#"+ prefix +"_currencyUnicodeSymbol").val();
        refreshTotalItemPriceElement(prefix, prefix + "_totalPriceCont", prefix + "_totalPriceValue",
                                     unformattedPrice, quantity, currencyUnicodeSymbol);
        refreshTotalItemPriceElement(prefix, prefix + "_deliverySupp", prefix + "_deliverySuppCharge",
                                     unformattedDeliveryCharge, quantity, currencyUnicodeSymbol);
    } else {
        $("#"+ prefix +"_totalPriceCont").fadeOut("slow");
        $("#"+ prefix +"_deliverySupp").fadeOut("slow");
    }
}

function validateQuantity(prefix, displayMessage) {
    var quantity = $("#" + prefix + "_quantitySelect").val();
    if (!(quantity == "") && !/\s+/.test(quantity) && !isNaN(quantity) && (quantity > 0)) {
        if (quantity < 76) {
            if ($('#'+ prefix +'_stockMsgPanel').height() > 10) {
                $('#'+ prefix +'_stockMsgPanel').animate({ height: '10px'}, 500).find('.messages').empty();
                messageAnimationFunctions.msgText(currentStockMessage, prefix);
            }
            return true;
        } else {
            if (displayMessage) {
                messageAnimationFunctions.bounceMessage($("#exceededQuantityMessage").val(), prefix);
            }
            return false;
        }
    } else {
        if (displayMessage) {
            messageAnimationFunctions.bounceMessage($("#invalidQuantityMessage").val(), prefix);
        }
        return false;
    }
}

function refreshTotalItemPriceElement(prefix, itemDivId, itemId, unformattedAmount, quantity, currencyUnicodeSymbol) {
    var freeGift = $("#"+ prefix +"_freeGift").val() == 'true';
    if (!freeGift) {
        $("#" + itemDivId).stop(true, true);
        if (unformattedAmount && (unformattedAmount != "") && (unformattedAmount != "0")) {
            $("#" + itemId).html(formatCurrency(Math.round(quantity * unformattedAmount) / 100, currencyUnicodeSymbol));
            if (canAddToBag(prefix)) {
                $("#" + itemDivId).fadeIn("slow");
            } else {
                $("#" + itemDivId).fadeOut("slow");
            }
        } else {
            $("#" + itemDivId).fadeOut("slow");
        }
    } else {
        if (canAddToBag(prefix)) {
            $("#" + itemDivId).fadeIn("slow");
        } else {
            $("#" + itemDivId).fadeOut("slow");
        }
    }
}

//Check we are on a page where document.ready() would apply javascript events before the product details
//page has been created.
function isProductDetailsLoaded() {
    return (typeof onPCMPage != 'undefined' || typeof isQofPage != 'undefined' || typeof isOrderBuildingPage != 'undefined'); // var defined in amplience.html
}

function formatCurrency(amount, currencyUnicodeSymbol) {
    var thousandsDelimiter = ",";
    var amountArray = new String(amount).split(".", 2);
    var fractionPart = amountArray[1];
    if ((fractionPart == undefined) || (fractionPart.length < 1)) { fractionPart = "00"; }
    if (fractionPart.length < 2) { fractionPart += "0"; }
    var integerPart = parseInt(amountArray[0]);
    if (isNaN(integerPart) || (integerPart < 0)) { return ""; }
    var integerPartWithDelimeters = new String(integerPart);
    amountArray = [];
    while (integerPartWithDelimeters.length > 3) {
        var integerPartWithDelimetersPart =
                integerPartWithDelimeters.substr(integerPartWithDelimeters.length - 3);
        amountArray.unshift(integerPartWithDelimetersPart);
        integerPartWithDelimeters =
                integerPartWithDelimeters.substr(0, integerPartWithDelimeters.length - 3);
    }
    if (integerPartWithDelimeters.length > 0) {
        amountArray.unshift(integerPartWithDelimeters);
    }
    integerPartWithDelimeters = amountArray.join(thousandsDelimiter);
    return eval('"' + currencyUnicodeSymbol + '"') + integerPartWithDelimeters + '.' + fractionPart;
}

function highlightDropDowns() {
	//Use the prefix value to ensure we only update boxes related to the product
	//the customer is interacting with.
	$('select[id^=' + $prefix + "]").each(function () {
        if($(this).val() == "" || $(this).val() == '0' || $(this).val() == '-1')
            $('#' + $(this).attr('id') + '_select .mainFirstValue').addClass('noSelectedOption');
    });
}
/* complete : /javascript/productDetailsRedesign/productDetailsOptions.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsFittings.js*/

function onSelectFittings(event) {
	var prefix = event.data;
	var fittingsObj = $("#" + prefix + "_fitting")[0];
	var fittingIds = fittingsObj.options[fittingsObj.selectedIndex].value.split(':');
	var viewContextVal = $("input[id='"+ prefix + "_viewContext']").val();
	var prefixIndex = "";
	var prefixArray = prefix.split("_");
	var prefixArraySize = prefixArray.length;
	if(prefixArraySize == 3) {
		prefixIndex = prefixArray[prefixArraySize-1];
	}
	
	urlString='/shop/quickview/product/details/show.action?pdLpUid='+fittingIds[0]+'&pdBoUid='+fittingIds[1]+'&fitting='+fittingsObj.options[fittingsObj.selectedIndex].value+'&viewContext='+ viewContextVal+'&prefixIndex='+ prefixIndex;
	
	if (prefix.startsWith("qof")){
		jdw.quickView.showQofDetails(urlString, prefix);
	} else if (prefix.startsWith("quickview")) {
		jdw.quickView.showHtmlDetails(urlString);
	} else if (prefix.startsWith("outfit")) {
		jdw.quickView.showOutfitFittings(urlString, prefix);
	} else if (prefix.startsWith("affinity")) {
	    jdw.quickView.showAffinityFittings(urlString, prefix);
	} else {
		$("#" + prefix + "_pdLpUid").val(fittingIds[0]);
		$("#" + prefix + "_pdBoUid").val(fittingIds[1]);
		submitAjaxForm('changeFitting', handleAjaxResultOnChangeFitting, "elementId=" + prefix, prefix);
	}
	clearAddedToBagTick(prefix);
	
}

function onSelectColour(event) {
	var prefix = event.data;
	if(prefix.startsWith("standard")) { 
		submitAjaxForm("refreshForColour", handleAjaxResultForColourChange, "saveOptionsToSessionEnabled=true&elementId="+ prefix, prefix);
	} else {
		submitAjaxForm("refreshForColour", handleAjaxResultForQuickViewColourChange, "elementId="+ prefix, prefix);
	}
	disableAjaxElements(prefix);
	updateUrlWithOptions(prefix);
	clearAddedToBagTick(prefix);
}

function onSelectSize(event) {
	var prefix = event.data;
	if(prefix.startsWith("standard")) { 
		submitAjaxForm("refreshForSize", handleAjaxResultForSizeOrColourChange, "saveOptionsToSessionEnabled=true&elementId="+ prefix, prefix);
	} else {
		submitAjaxForm("refreshForSize", handleAjaxResultForSizeOrColourChange, "elementId="+ prefix, prefix);
	}
	disableAjaxElements(prefix);
	updateUrlWithOptions(prefix);
	clearAddedToBagTick(prefix);
}

function onSelectQuantity(event) {
	var prefix = event.data;
	reallyRefreshTotalItemPrice(prefix);
	clearAddedToBagTick(prefix);
}

function handleAjaxResultForSyncAnchorAttributes(returnObj) {
	var prefix = returnObj.elementId;
	if(prefix.startsWith("standard")) { 
		jdw.productDetailsMedia.populateImageAndImageAnchors(prefix, returnObj.mainImage, returnObj.mainAltImage, returnObj.altImages);
		jdw.productDetailsMedia.populateVideoLinkParameters();
	} else {
		jdw.productDetailsQuickViewMedia.populateImageAndImageAnchors(prefix, returnObj.mainImage, returnObj.mainAltImage, returnObj.altImages);
	}
	
	handleAjaxResultForSizeOrColourChange(returnObj);
}

function handleAjaxResultForColourChange(returnObj) {
	jdw.productDetailsMedia.populateImageAndImageAnchors(returnObj.elementId, returnObj.mainImage, returnObj.mainAltImage, returnObj.altImages);
	jdw.productDetailsMedia.populateVideoLinkParameters();
	handleAjaxResultForSizeOrColourChange(returnObj);
}
function handleAjaxResultForQuickViewColourChange(returnObj) {
	var prefix = returnObj.elementId;
	jdw.productDetailsQuickViewMedia.populateImageAndImageAnchors(prefix, returnObj.mainImage, returnObj.mainAltImage, returnObj.altImages);
	handleAjaxResultForSizeOrColourChange(returnObj);
	}

function clearAddedToBagTick(prefix) { 
	var addToBagBtn = $('a[jdwprefix*='+prefix+'].primaryBtn').removeClass('icon-tick');
	if (addToBagBtn) {
		addToBagBtn.removeClass('icon-tick').text('Add to Bag');
	}
} /* complete : /javascript/productDetailsRedesign/productDetailsFittings.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsDropdown.js*/
/*
    Developed by Daniel Noormohamed 05 May 2009 for JD Williams
    Using jQuery version:    1.3.2
    Dependant: jquery.cssDropdown.css
    
    ----------------
    Changes 18 June 2009 11:05
    ----------------
        if there are more than 10 list values in a dropdown the following styles are placed inline to fix the height of the container
                .dropOptions
                    height:300px; 
                    overflow: auto;
                    width: 307px;
                .mainOtherValues 
                    width:280px;
                    margin-top:1px [delete this style from css file]
        
    
*/


/*
 * This function should be moved to a common javascript file
*/
    function removeHTMLTags(strInputCode){
         strInputCode = strInputCode.replace(/&(lt|gt);/g, function (strMatch, p1){
             return (p1 == "lt")? "<" : ">";
        });
        var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
        return strTagStrippedText;
    }

        
    function selectedOptionText(txt, value, currentID, selectedOpt) {
        var strippedTxt = null;
        
        var fspan = $('#' + selectedOpt.current + '_select .dropOptions div:eq(' + selectedOpt.selected + ')');
        if($('.' + fspan.find('span').attr('class'), fspan).css('display') == 'none') {
            $('.' + fspan.find('span').attr('class'), fspan).remove();
            strippedTxt = fspan.text();
        } else {
            strippedTxt = removeHTMLTags(txt);
        }
        
        if(strippedTxt.length > 25)    {
            truncateColourTextIfRequired(currentID, strippedTxt, txt);
            $('#' + currentID + ' .getFittingValue').attr('value', value);
        } else {
            $('#' + currentID + ' .getFittingValue').html(strippedTxt).attr('value', value);
        }        
    }
    
    function truncateColourTextIfRequired(currentID, strippedTxt, txt) {
        var selOpt = $('#' + currentID + ' .getFittingValue');
        //Only perform truncation if element is visible. This is because we cannot do width based calculations otherwise.
        if (typeof selOpt != "undefined" && strippedTxt.length > 0 && selOpt.is(':visible')) {
        	// Clear down element and add empty span
        	selOpt.html('');
        	var span = $('<span style="display:inline-block; white-space:nowrap"></span>');
        	selOpt.append(span);
        	// Calculate wrap index by adding 1 char at a time,
        	// until span width exceeds element width.
        	var wrapIndex = -1;
        	for ( var i = 0; i < strippedTxt.length; i++ ) {
        		span.append(strippedTxt.charAt(i));
        		if ( span.width() >= selOpt.width() ) {
        			wrapIndex = i-1;
        			break;
        		}
        	}
        	// Set final value
        	if ( wrapIndex > -1 ) {
        		var suffix = "...";
        		selOpt.html(strippedTxt.substring(0, wrapIndex-suffix.length) + suffix);
        	} else {
        		selOpt.html(txt);
        	}
        }
    }
             
    (function($){  
           $.fn.cssDropdown = function(options) {
                    var selectedIndex =0;
                    var currentID = '';
                    var parentID = '';

                    var defaults = {
                        fromSelect: 'yes',
                        version: 1
                    };  

                    var options = $.extend(defaults, options);  
                       
                   var cssDropFunctions = {
                    filterOptions : function ($t) {
                            var n =0;
                            var optionList = $t.find('option');
                            
                            optionList.each(function () {
                                
                                var id = $(this).parent().attr('id') + 'Select';
                                var idSplit = id.split("_");
                                var celebrusName;
                                if(idSplit[0] === "outfit") {
                                    celebrusName = idSplit[0] + "_" + idSplit[3];
                                } else {
                                    celebrusName = idSplit[0] + "_" + idSplit[2];
                                }
                                
                                    if($(this).prop('selected') == true) {
                                        selectedIndex = n;
                                    }
                                if(n == 0) {
                                    $('#' + parentID).find('.containerSelect').prepend(
                                            '<div data-jdw-test-id="' + id + '" id="' + id + '" class="mainFirstValue '
                                            + 'getFittingValue" value="' + $(this).attr('value') + '" name="' + celebrusName 
                                            + '">' + $(this).text() + '</div>');
                                }
                                
                                $('#' + parentID).find('.containerSelect').find('span').each(function () {
                                    if($(this).css('display') == 'none') {
                                        $(this).remove();
                                    }
                                });
                                
                                n++;
                                $('#' + parentID).find('.containerSelect .dropOptions').append('<div ' + (optionList.size() > 10 ? ' style="border-right:0px; " ' : '') + (($(this).attr('value') != "") ? (' id="stProdOption_' + $(this).attr('value') + '"') : '') + ' class="mainOtherValues ' + $(this).attr('class') +'"  value="' + $(this).attr('value') + '">' + $(this).text() + '</div>');

                            })
                    },
                    setMargins : function () {
                        if($('#' + parentID).css('margin-bottom') > 2) $('#' + parentID).css('margin-bottom', '0px');
                    },
                    setSelectNumbers : function (n) {
                        $('.mainFirstValue').each(function(){ $(this).attr('number', n++); });
                    },
                    oddEvenShades : function () {
                        $('#' + parentID).find('.containerSelect').find('.mainOtherValues:odd').addClass('odd');
                        $('#' + parentID).find('.containerSelect').find('.mainOtherValues:even').addClass('even');
                    },
                    ToggleList : function (state) {
                            $('#' + currentID + ' .dropOptions').parents('.control-group').toggleClass('control-group-open');
                            $('#' + currentID + ' .dropOptions').toggleClass('dropOptionsShow');
                            $('#' + currentID + ' .mainFirstValue').toggleClass('selectedDrop');
                    },
                    showMainElement : function () {
                        $('.mainFirstValue').each(function () { $(this).show(); });
                    }, 
                    triggerChange : function (txt, value) {
                        
                        selectedOptionText(txt, value, currentID, {selected : selectedIndex, current: currentID});
                        var selectId = currentID.replace("_select","");
                        $('#' + selectId + ' option[value="' +  value + '"]').prop('selected', 'selected');
                        $('#' + selectId).trigger('change');    
                    }, 
                    hideSelectbox : function (thisN) {
                        $('.mainFirstValue').each(function () {
                            if(parseInt($(this).attr('number')) > parseInt(thisN)) {
                                $('.mainFirstValue[number="' + $(this).attr('number') + '"]').hide();
                            }
                        });
                    },
                    minimiseMessageBox : function (msgs, emptyThis) {
                            if(msgs.height() > 10) msgs.animate({ height: '10px'}, 500).find(emptyThis).empty();
                    }, updateOptions : function () {
                        
                    }
                };
                
               return this.each(function() {
                    $t = $(this);
                    currentID = $(this).attr('id');
                    parentID = $(this).parent().attr('id');
                    
                    if(options.fromSelect == 'yes') {
                            if($('#' + currentID + '_select').size() == 1) {
                                if($t.prop('show') == 'false')
                                    $('#' + currentID + '_select').hide();
                                else {
                                    $('#' + currentID + '_select').show();
                                    $('#' + parentID).find('.containerSelect .dropOptions').html('');
                                    $('#' + parentID).find('.containerSelect .mainFirstValue').remove();
                                    cssDropFunctions.filterOptions($t);    
                                                            
                                    $('#' + currentID + '_select .dropOptions div:eq(' + selectedIndex + ')').each(function(){
                                        selectedOptionText($(this).text(), $(this).attr('value'), currentID + '_select', {selected : selectedIndex, current: currentID});
                                      });
                                    currentID = $(this).attr('id') + '_select';
                                }
                                
                            } else {
                                    cssDropFunctions.setMargins();
                                    $('#' + parentID).append('<div id="' + currentID + '_select" class="mainSelect"></div>')
                                    $('#' + parentID + ' .mainSelect').append('<div class="containerSelect"></div>')
                                    
                                    var optionList = $t.find('option');
                                    $('#' + parentID + ' .mainSelect .containerSelect').append('<div class="dropOptions ' + (optionList.size() > 7 ? ' dropOptionsMore ' : '') + '"></div>')
                                    
                                    cssDropFunctions.filterOptions($t);
                                    
                                    $(this).hide();
                                    currentID = $(this).attr('id') + '_select';
                                      
                                      $('#' + currentID + ' .dropOptions div:eq(' + selectedIndex + ')').each(function(){
                                        selectedOptionText($(this).text(), $(this).attr('value'), currentID, {selected : selectedIndex, current: currentID});
                                      });
                            }
                            
                            if(jdBrowser.msie) {
                                $('.dropOptions div').bind('mouseover', function () {
                                    $(this).addClass('hoverMainOtherValues');
                                }).bind('mouseout',  function () {
                                    $(this).removeClass('hoverMainOtherValues');
                                });                    
                            }
                    }
                    
                    //cssDropFunctions.oddEvenShades();
                    cssDropFunctions.setSelectNumbers(1);
                        
                $('#' + currentID + ' .containerSelect .mainFirstValue').on('click', function () {
                        if($('#' + currentID + ' .dropOptions').css('display') == 'none') {
                            //extract prefix from currentID
                            var currentIDArray = currentID.split("_");
                            prefix = currentIDArray[0] + "_" + currentIDArray[1];
                            cssDropFunctions.minimiseMessageBox($('#'+ prefix +'_stockMsgPanel'), '.messages');
                            cssDropFunctions.ToggleList('expand');
                        } else {
                            cssDropFunctions.ToggleList('shrink');
                            cssDropFunctions.showMainElement();
                        }
                    })
                    
                $('#' + currentID + ' .containerSelect').on("mouseleave", function(){
                    if($('#' + currentID + ' .dropOptions').css('display') == 'block') {
                            cssDropFunctions.ToggleList();
                            cssDropFunctions.showMainElement();
                        }
                    });
                    
                    $('#' + currentID).find('.mainOtherValues').on('click', function () {
                        $t = $(this);
                        cssDropFunctions.ToggleList('shrink');
                        cssDropFunctions.showMainElement();
                        cssDropFunctions.triggerChange($t.html(), $t.attr('value'));
                    });
               });  
           };  
        })(jQuery);  

/*
To use this plugin you will need the following.

1. 
        
        Create a div layer and create a select box using html like the following
        THE DIV LAYER IS NEEDED!
        
            <div id="sizeDiv" name="sizeDiv" class="selectListShowContainer">
            
                <select name="optionSize" id="optionSize" class="optionSize">
                    <option value="" class="valid">Choose Size</option>
                    <option value="DOUBLE" class="valid">DOUBLE</option>
                    <option value="KING" class="valid">KING</option>
                    <option value="SINGLE" class="valid">SINGLE</option>
                </select>
                
            </div>

2.
        To convert the select box you execute the following code below. this will 
        convert the whole select box into div layers also moving the value attribute 
        of a option tag to the div
        
        THIS DOES NOT REMOVE THE SELECT BOX, AS IT POPULATES IT WITH THE clicked VALUE
        you can test this using the "//alert($('[id$="_optionsForm"]').serialise());" commented out on line 50 
        
        <script>
            $(document).ready(function () {
                $('#selectboxID').cssDropdown({fromSelect:'yes'});
            });
        </script>

*/
/* complete : /javascript/productDetailsRedesign/productDetailsDropdown.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsAddtoBag.js*/
var currentAddToBagReturnData = null;
var addedToBagAddStatus = 101;
var addedToBagTFStatus = 104;
var isTablet = $('meta[name=jdw-isTablet]').attr("value") == "true";

function onClickAddToBag() {
    $('.loading-spinner').fadeIn('fast', function () {});
    var prefix = $prefix;
    if (validateQuantity(prefix, true)) {
        if ( !canAddToBag(prefix) ) {
            highlightDropDowns();
            messageAnimationFunctions.msgText( $("#" + prefix + "_invalidAddToBagMessage").val(), prefix);
            $('.loading-spinner').fadeOut('fast', function () {});
            jdw.quickView.forceSliderResize(prefix, 1000);
            return false;
        }
        return true;
    } else {
        $('.loading-spinner').fadeOut('fast', function () {});
        jdw.quickView.forceSliderResize(prefix, 1000)
        return false;
    }
}

function canAddToBag(prefix) {
    var canAddToBag = $("#"+ prefix +"_canAddToBag").val();
    return (canAddToBag != null) && ("true" == canAddToBag.toLowerCase());
}

function displayAddToBagModalMessage(retMsg, prefix){
    var html = '<div id="addToBagMessageModal" width="650" height="85" title="' + retMsg.title + '" overlayClose="true" >';
    if (retMsg.text) {
        html = html + '<p>' + retMsg.text + '</p>';
    }
    html = html +
    '<div id="controls">'+
        '<div class=btn primaryBtn icon-tick" id="modalButtonRight" onclick="' + writeHrefUrlForMessageData(retMsg.href1Url, prefix) + '">' +
            '<div class="modalButton">'+
                '<div class="btn primaryBtn icon-tick"/>' +
                '<a class="btn primaryBtn icon-tick continue-with-order-btn">' + retMsg.href1Text + '</a>' +
                '<div/>'+
            '</div>' +
        '</div>' + 
        '<div class="prev btn tertiaryBtn" id="modalButtonLeft" onclick="' + writeHrefUrlForMessageData(retMsg.href2Url, prefix) + '">' +
            '<a class="prev btn tertiaryBtn icon-leftarrow enter-personalisation-btn">' + retMsg.href2Text + '</a>' +
        '</div>' +
    '</div></div>' ;

    var modalsContainer = jdw.modalsContainer;
    if(typeof modalsContainer == 'undefined'){
        modalsContainer =  parent.jdw.modalsContainer;
    }
    modalsContainer.showModal({
        content: function() { return html; },
        width: 685,
        height: 90,
        ajax: false,
        id: 'addToBagModalMessage',
        backButtonDisabled: true,
        closeButtonDisabled: true,
        headerClass: 'addToBagMessageModalHeader',
        contentClass: 'addToBagMessageModalContent',
        footerClass: 'addToBagMessageModalFooter',
        headingText: retMsg.title,
        fullHeight: 173
    });
}

function writeHrefUrlForMessageData(value, prefix) {
    if ( value == ":close" ) {
        url = "javascript:jdw.productDetailsAddToBag.closeAddToBagMessageModal();";
    } else if ( value == ":addBackOrder" ) {
        url = "javascript:jdw.productDetailsAddToBag.doIgnoreDelayAdd('" + prefix + "');";
    } else if ( value == ":forceMtul" ) {
        url = "javascript:jdw.productDetailsAddToBag.doForceMtul('" + prefix + "');";
    } else if ( value == ":forceNoPersonalisation" ) {
        url = "javascript:jdw.productDetailsAddToBag.doForceNoPersonalisation('" + prefix + "');";
    } else {
        url = value;
    }
    return url;
}

function handleAjaxResultForAddToBag( dataStr ) {
    var dataLayerEvent = jQuery.parseJSON(dataStr.gapDataLayer);
    if((dataLayerEvent) && (Object.keys(dataLayerEvent).length != 0)) {
        window.dataLayer.push(dataLayerEvent);
    }
    var returnObj = eval( dataStr );
    var prefix = $prefix;
    currentAddToBagReturnData = returnObj;
    populateReturnVars( returnObj );
    updateBagItems( returnObj.model.numberOfBasketItems );
    if ( returnObj.model.hasWarranty == true ) {
        displayAddToBagMessage( returnObj );
        var pdw = jdw.productDetailsWarranty;
        if(typeof pdw == 'undefined'){
            pdw = parent.jdw.productDetailsWarranty;
            pdw.handleWarranties( returnObj );
        }else{
            pdw.handleWarranties( returnObj );
        }
    } else {
        displayAddToBagMessage( returnObj );
    }
    if (returnObj.model.addStatus == addedToBagAddStatus || returnObj.model.addStatus == addedToBagTFStatus ) {
        //when product is valid to addtobag will go here
    	if (prefix.startsWith('standard') && automatedAffinitiesEnabled){
    		$("div#rr-search-referrer-container").css("display", "none");
    		$("div.rr-search-referrer ul").remove();
        	callPostAddToBagSlider(returnObj);	
        }
    	
        if( (!prefix.startsWith('qof')) && (!prefix.startsWith('singleview') && (!prefix.startsWith('multibuy'))) ){
            $("#"+ prefix +"_continueToCheckout").fadeIn( "slow" );
        }
        if (prefix.startsWith('multibuy')) {
        	$('#multibuy_continueToCheckout').fadeIn("slow");
        	$('.ampl-thumb-active').addClass('ampl-add-to-bag');
        }
        var addToBagBtn = $('a[jdwprefix*='+returnObj.elementId+'].primaryBtn').addClass('icon-tick'); 
        addToBagBtn.addClass('icon-tick').text('Added to Bag');
    }

    if (returnObj != null) {

        if (returnObj.model.stockStatusChanged == true) {
            populateAllOptions( prefix, returnObj );
            // Store this globally so that we can re-display it without an AJAX call
            currentStockMessage = returnObj.stockInformationMessage;
            $("#" + prefix + "_canAddToBag").val( returnObj.canAddToBag );
        }
        //Celebrus Data - execute reportAddToBag() function.
        eval( returnObj.model.celebrusData );
    }
    $('.loading-spinner').fadeOut('fast', function () {});
    jdw.quickView.forceSliderResize(prefix, 1000);
}

function populateReturnVars( data ) {
    $("#lineItem").val( data.model.lineItem );
}

function displayAddToBagMessage( data ) {
    var messageData = data.model.addToBagMessageData;
    var quickView = jdw.quickView;
    if(typeof quickView == 'undefined'){
        quickView =  parent.jdw.quickView;
    }

    if(typeof quickView != 'undefined'){
        quickView.setMessageData(messageData);
    }
    // display in a bouncy div or a modal greybox
    if (messageData.message) {
        messageAnimationFunctions.msgText(messageData.message, data.elementId);
    } else  {
    	//TODO: better way to identify the page type to use correct modal.
    	if(isTablet && !(typeof pdpPage == "undefined")) {
    		jdw.productDetailsMain.showTabletPersonalisationModal(messageData);
    	} else {
    		displayAddToBagModalMessage(messageData, data.elementId);
    	}
        
    }
}

function callPostAddToBagSlider(data){
	if(typeof window.R3_ITEM !=='undefined') window.R3_ITEM = undefined;
	if(typeof window.R3_SEARCH !=='undefined') window.R3_SEARCH = undefined;
	if(typeof window.R3_ADDTOCART !=='undefined') window.R3_ADDTOCART = undefined;
	if(typeof window.R3_CART !=='undefined') window.R3_CART = undefined;
	if(typeof window.R3_PURCHASED !=='undefined') window.R3_PURCHASED = undefined;
	
	window.R3_COMMON.placementTypes='';
	//if used on the item page previously
	window.R3_COMMON.categoryHintIds='';
	window.R3_COMMON.addedToCartItemIds = '';
	window.R3_COMMON.itemIds= '';
	window.R3_COMMON.searchTerms= undefined;



	window.R3_COMMON.addPlacementType('add_to_cart_page.rr1');
	window.R3_ADDTOCART = new r3_addtocart();
	
	R3_ADDTOCART.addItemIdToCart(data.model.pdLpUid);
	
	rr_flush_onload();
	
	r3(); 
}

var jdw = jdw || {};

(function() {
    "use strict";

    jdw.ProductDetailsAddToBag = function() {

        this.doIgnoreDelayAdd = function(prefix) {
            this.closeAddToBagMessageModal();
            // set the ignoreDelay 'flag', but otherwise perform a normal add to bag ...
            submitAjaxForm("addToBag", handleAjaxResultForAddToBag, "ignoreDelay=true&elementId=" + prefix, prefix);
        }

        this.doForceMtul = function(prefix) {
            this.closeAddToBagMessageModal();
            // set the ignoreDelay 'flag', but otherwise perform a normal add to bag ...
            submitAjaxForm("addToBag", handleAjaxResultForAddToBag, "forceMtul=true&elementId="+ prefix, prefix);
        }

        this.doForceNoPersonalisation = function(prefix) {
            this.closeAddToBagMessageModal();
            var urlStr = "/shop/product/details/ajax/addToBag.action?forceNoPersonalisation=true&elementId=" + prefix;
            var form = $( '#' + prefix + '_optionsForm' );
            performAjaxRequest(urlStr,
            	null,
                null,
                'json',
                form.serialize(),
                handleAjaxResultForAddToBag,
                function() { enableAjaxElements(); },
                'POST',
                getUniqueClass('#atbInner')
            );
            
            return false;
        }

        this.closeAddToBagMessageModal = function() {
            var modalsContainer = jdw.modalsContainer;
            if(typeof modalsContainer == 'undefined'){
                modalsContainer =  parent.jdw.modalsContainer;
            }
            if(modalsContainer.modalLength()==0){
                modalsContainer.closeModal();
            }else{
                var quickView = window != window.parent ? parent.jdw.quickView : jdw.quickView;
                var iframeContent = '';
                if(quickView.getIframeSrc().length>1){
                    iframeContent = "<iframe id='quickViewFrame' class='quickViewModalIframe' src='"+quickView.getIframeSrc()+"' width='100%' height='580' frameborder='0' scrolling='no'></iframe>";
                }
                modalsContainer.showPreviousModal(1,iframeContent);
            }
            return false;
        }
    };

    if (!jdw.productDetailsAddToBag) {
        jdw.productDetailsAddToBag = new jdw.ProductDetailsAddToBag();
    }
})();


/* complete : /javascript/productDetailsRedesign/productDetailsAddtoBag.js*/


/* combine : /javascript/productDetailsRedesign/product.messages.js*/
var stockMsgHeightShrink = (jdBrowser.msie ? (jdBrowser.version == 6.0 ? '0px' :'9px') : '6px');

var messageAnimationFunctions = {
	msgPanelOptions : {
		height : 54,			//height to animate (in px)
		delay : 1500, 			//animation delay
		defaultFontColor : '#006600' //default font colour
	},
	// animate the return message
	bounceMessage : function(msg, prefix) {
		messageAnimationFunctions.slide({
			height: messageAnimationFunctions.msgPanelOptions.height + 'px',
			duration: messageAnimationFunctions.msgPanelOptions.delay,
			data: msg,
			elementId: prefix
			});
				
		return false;
	},
	// create a slide and bounce effect 
	slide : function (slideOptions) {
		/*
		{slideOptions as JSON}
			height					animate to height
			duration 				delay on animation
			data
		*/
		var $tmessage = $('#'+ slideOptions.elementId +'_stockMsgPanel');
		
		$tmessage.animate({opacity:1}, 0, function () {
			
			var msgBox = $tmessage.find('.messages');
			$tmessage.animate({ height: stockMsgHeightShrink, 'fontSize': '0px'}, 500, function () {
				$('body').attr('style','');	
				msgBox.show();	
				msgBox.html(slideOptions.data);	
				msgBox.fadeTo(slideOptions.duration, 1);
				//changes the colour of the message box font to default
				msgBox.css({'color':messageAnimationFunctions.msgPanelOptions.defaultFontColor, 'fontSize':'12px'});
				
				messageAnimationFunctions.msgFadeOut(900);
				$(this).animate({ height: slideOptions.height}, slideOptions.duration,'easeOutBounce');
				
				if(jdBrowser.msie == true && jdBrowser.version == 6.0) {
					msgBox.css('backgroundColor','#e6e4e4');
				}
			});																	
		});	
	},		
		
	msgText : function (text, prefix) {
		if ( text != null ){
			var fadeMsgBox = $('.fadeMsgBox .' + prefix + '_msg');
			var msgs = $('#' + prefix + '_stockMsgPanel');
			
			if(msgs.height() > 10) {			
				msgs.animate({ height: '10px'}, 500, function () {				
					$(this).find('.messages').html('');						
					if(fadeMsgBox.css('display') == 'block'){
						messageAnimationFunctions.msgFadeOut(700, function () {
								fadeMsgBox.html(text);
								messageAnimationFunctions.msgFadeIn(700, prefix);
						}, prefix);						
					} else {
						fadeMsgBox.html(text);
						messageAnimationFunctions.msgFadeIn(700, prefix);						
					}
				});
			} else {
				if(fadeMsgBox.css('display') == 'block'){
					messageAnimationFunctions.msgFadeOut(700, function () {
							fadeMsgBox.html(text);
							messageAnimationFunctions.msgFadeIn(700, prefix);
					}, prefix);						
				} else {
					fadeMsgBox.html(text);
					messageAnimationFunctions.msgFadeIn(700, prefix);						
				}				
			}
		}
	},
	
	msgFadeIn : function (speed, prefix) {
		
		var fadeMsgBox = $('.fadeMsgBox .' + prefix + '_msg');		
			fadeMsgBox.fadeIn(speed ? speed : 100);
			
	},
	
	msgFadeOut : function (speed, callback, prefix) {
		
		callback = (callback ? callback : function () { return true; });
		
		var fadeMsgBox = $('.fadeMsgBox .' + prefix + '_msg');
		
		if(fadeMsgBox.css('display') == 'block')
			fadeMsgBox.fadeOut(speed ? speed : 100, callback);
	}
};

	
/* complete : /javascript/productDetailsRedesign/product.messages.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsWarranties.js*/
// TODO : STD-207.
// Requirements from WT-135 have meant the creation of warrantyModal.js. This file is included in the 
// head for all desktop & tablet pages and provides functionality to deliver a consistent warranty
// modal on all pages. It offers less functionality than provided here but is intended to be extended 
// to replace all disconnected, warranty modal related js files.

var jdw = jdw || {};

jdw.ProductDetailsWarranty = function(){
	var pdw = this;
	var isTablet = $('meta[name=jdw-isTablet]').attr("value") == "true";
	this.setup = function(){
		if(!isTablet) {
			$("div.warrantyButtonContainer a").unbind('click').bind('click', pdw.showWarranty);
		}
	}
	
	this.hideBackToProductButton = function(fromQuickView){
		if($("div#jdwModalBacktoProductButton").length){
			$("div#jdwModalFooter").find("div#jdwModalBacktoProductButton").remove();	
		}
	}
	
	
	this.showQuickviewWarranty = function(event, urlString, title){
		pdw.hideBackToProductButton(true);
		pdw.showWarrantyModal(urlString, true, title);
		$("div#jdwModalFooter").append("<div id='jdwModalBacktoProductButton'><span><a class='prev btn tertiaryBtn icon-leftarrow' onclick='window.parent.closeWarrantyModal()' href='#'>Back to product</a></span></div>");
		return false;
	}
	
	this.showWarranty = function(event){
		event.preventDefault();
		pdw.hideBackToProductButton(false);
		var urlString=$(this).attr("href");
		var title=$(this).attr("title");
		pdw.showWarrantyModal(urlString, false, title);
		return false;
	}
	
	this.showWarrantyModal = function(urlString, closeButtonDisabled, title){
		var modalsContainer = jdw.modalsContainer;
		if(typeof modalsContainer == 'undefined'){
			modalsContainer =  parent.jdw.modalsContainer;
		}
		var options = {headingText: typeof title !== 'undefined' ? title : '',
	            content: urlString,
	            width: 850,
	            height: 360,
	            ajax: true,
	            id: 'moreInfoModal',
	            backButtonDisabled:true,
	            closeButtonDisabled: closeButtonDisabled ? true : false,
	            fullHeight: 460};
		if(typeof onCloseModal != 'undefined') {
			options.onClose = onCloseModal;
		}
		modalsContainer.showModal(options);
		$('#jdwModalContent').addClass('webToolkit');
		$('#jdwModalBorder').addClass('warrantiesContent');
	}
	
	this.handleWarranties = function(returnObj){
		var url;
		if (isTablet){
			url = "/shop/warranties/tabletOffer.action?" 
		} else {
			url = "/shop/warranties/offer.action?";
		}
		url = url 
			+ "lpUid=" + returnObj.model.pdLpUid
            + "&boUid=" + returnObj.model.pdBoUid
            + "&selectedOptionId=" + returnObj.model.selectedOptionId
            + "&quantity=" + returnObj.model.quantity;
		
		if (isTablet){
		    jdw.mobileAjax.performAjaxRequest(url, null, null, 'html', null, onSuccessWar,
		    		null, 'GET', null, null); 
		} else {
			var modalsContainer = jdw.modalsContainer;
			if(typeof modalsContainer == 'undefined'){
			modalsContainer =  parent.jdw.modalsContainer;
			}
			jdw.productDetailsWarranty.hideBackToProductButton();
			modalsContainer.hideWebToolkit();
			var options = {
				content: url,
				width: 850,
				height: 400,
				ajax: true,
				id: 'warrantiesModal',
				backButtonDisabled: true,
				fullHeight: 470,
				loadCompletedCallback: jdw.productDetailsWarranty.handleWarrantiesLoadCompletedCallback
			}
			if(typeof onCloseModal != 'undefined') {
				options.onClose = onCloseModal;
			}
			modalsContainer.showModal(options);
	
			// Adds class 'warrantiesContent' to the modal so specific styles for warranties can be applied without affecting any other modal layouts
			$( '#jdwModalBorder' ).addClass( 'warrantiesContent' );
	
			// Appends a div which has styles associated with it specifically for use with warranties
			//$( '#jdwModalBorder' ).append( '<div class="option-shading"><div class="edge top"></div><div class="edge bottom"></div></div>' );
		}
	}

	this.handleWarrantiesLoadCompletedCallback = function(){
        var modalTitle = $('h1#jdwModalTitle');
        var modalParam = $('div#modalParam');
        if (typeof modalTitle !== 'undefined' && typeof modalParam !== 'undefined') modalTitle.html(modalParam.attr('title'));
		//$( '#jdwModalBorder' ).append( '<div class="option-shading"><div class="edge top"></div><div class="edge bottom"></div></div>' );
	}
	
	this.handleWarrantyClickToDecline = handleWarrantyClickToDecline;
	
	this.handleWarrantyMoreInfo = function(link, title){
		handleWarrantyMoreInfo(link, title);
	}
	
	this.addWarrantyForProduct = function(link, title, backButtonText){
		addWarrantyForProduct(link, title, backButtonText);
	}
}

function addWarrantyForProduct(link, title, backButtonText){
	var modalsContainer = jdw.modalsContainer;
	if(typeof modalsContainer == 'undefined'){
		modalsContainer =  parent.jdw.modalsContainer;
	}
	jdw.productDetailsWarranty.hideBackToProductButton();
	var content='';
	$.ajax({
		url: link,
		async:false,
		type: "POST",
		success: function(data){content=data;},
		dataType: "html"
		});
	var html = function(){return content;};
	var jQueryHtml = $($.parseHTML(content, document, true));
	var dataLayerEvent = jQuery.parseJSON(jQueryHtml.find("#gapData").val());
	if((dataLayerEvent) && (Object.keys(dataLayerEvent).length != 0)) {
        window.dataLayer.push(dataLayerEvent);
    }
	var options = {
		headingText: typeof title !== 'undefined' ? title : '',
		content: html,
		width: 850,
        height: 400,
        ajax: false,
        id: 'AddWarrantiesModal',
        backButtonDisabled: true,
        closeButtonDisabled: true,
        fullHeight: 470,
        headerClass: 'addWarrantyForProductHeader',
        contentClass: 'addWarrantyForProductContent',
        footerClass: 'addWarrantyForProductFooter'
        };
	if(typeof onCloseModal != 'undefined') {
		options.onClose = onCloseModal;
	}
	modalsContainer.showModal(options);
	$('#jdwModalBorder').find('.option-shading').remove();
	$("div#jdwModalFooter").append("<div id='jdwModalBacktoProductButton'>" +
			"<a class='prev btn tertiaryBtn icon-leftarrow' onclick='return handleCloseWarrantyWindow();' href='#'" +
			" alt='Go to product' title='Go to product'>"+backButtonText+"</a>" +
			"</div>");
	return false;
}


function handleCloseWarranty() {
    displayAddToBagMessage(currentAddToBagReturnData);
}

function handleWarrantyMoreInfo(link, title){
	jdw.productDetailsWarranty.hideBackToProductButton();
	var modalsContainer = jdw.modalsContainer;
	if(typeof modalsContainer == 'undefined'){
		modalsContainer =  parent.jdw.modalsContainer;
	}
	var options = {headingText: title,
        content: link,
        width: 850,
        height: 360,
        ajax: true,
        id: 'moreInfoModal',
        fullHeight: 470};
	if(typeof onCloseModal != 'undefined') {
		options.onClose = onCloseModal;
	}
	modalsContainer.showModal(options);
	$("#jdwModalContent").addClass("webToolkit");
	$('#jdwModalBorder').find('.option-shading').remove();
	return false;
}

function handleWarrantyClickToDecline(){
	var modalsContainer = jdw.modalsContainer;
	if(typeof modalsContainer == 'undefined'){
		modalsContainer =  parent.jdw.modalsContainer;
	}
	if(modalsContainer.modalLength()==0){
		modalsContainer.closeModal();
	}else{
		reopenProductDetailsModal(modalsContainer, 1);
	}
	$('#jdwModalBorder').removeClass('warrantiesContent');
}
    
function handleCloseWarrantyWindow(){
	var modalsContainer = jdw.modalsContainer;
	if(typeof modalsContainer == 'undefined'){
		modalsContainer =  parent.jdw.modalsContainer;
	}
	jdw.productDetailsWarranty.hideBackToProductButton();
	modalsContainer.hideWebToolkit();
	if(modalsContainer.modalLength()==1){
		modalsContainer.closeModal();
	}else{		
		reopenProductDetailsModal(modalsContainer, 0);
	}
	$('#jdwModalBorder').removeClass('warrantiesContent');
}


function closeWarrantyModal(){
	var modalsContainer = jdw.modalsContainer;
	if(typeof modalsContainer == 'undefined'){
		modalsContainer =  parent.jdw.modalsContainer;
	}
	if(modalsContainer.modalLength()==0){
		modalsContainer.closeModal();
	}else{
		jdw.productDetailsWarranty.hideBackToProductButton();
		modalsContainer.hideWebToolkit();
		var quickView = window != window.parent ? parent.jdw.quickView : jdw.quickView;
		var iframeContent = '';
		if(quickView.getIframeSrc().length>1){
			iframeContent = "<iframe id='quickViewFrame' src='"+quickView.getIframeSrc()+"' width='100%' height='520' frameborder='0' scrolling='no'></iframe>";
		}
		modalsContainer.showPreviousModal(1,iframeContent);
		if(quickView.isCheckoutButtonVisible()){
			$("iframe#quickViewFrame").load(showCheckoutButton);	
		}
	}
	$('#jdwModalBorder').removeClass('warrantiesContent');
}

function reopenProductDetailsModal(modalsContainer, index) {
	jdw.productDetailsWarranty.hideBackToProductButton();
	modalsContainer.hideWebToolkit();
	modalsContainer.showPreviousModal(index, $currentModalContent[0]);
	showCheckoutButton();
	
}

if ( !jdw.productDetailsWarranty ) {
	jdw.productDetailsWarranty = new jdw.ProductDetailsWarranty();
}
$(document).ready( function() {
	jdw.productDetailsWarranty.setup();
});

//*******************TABLET ONLY FUNCTIONS********************
function onSuccessWar(data) {

	if (jdw.tabletModalsContainer) { // We have the tablet modal code.  Let's use it.
		onSuccessWarrantiesTablet( data );
		return;
	}
	
	data = "<script>var quantity='" + returnObj.model.quantity + "'; var productOptionId ='" + 
	selectedOptionId + "';</script>" + data;

	window.location.href='#warrantyAnchor';
	$('#warrantyCover').html(data);
	// add a click handler to throw a PAGEVIEWTAG when the warranty details are viewed.
	// We have to do it like this because the terms are only a fragment when displayed by mobile...
	$('div.wOption a').click( throwPageViewTagForWarranty );
	$('#warrantyCover').fadeIn(500);
}


function extractQueryParameters(theUrl) {
	var decodedUrl = decodeURI(theUrl);
	var matchResult = /(^[^\?]+\?)(.*$)/.exec(decodedUrl);
	var queryString = matchResult[2] || "";
	var params = {};
	queryString.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function(matchedString, name, value) {
		if (name) params[name] = value;
	});
	return params;
}

function onSuccessWarrantiesTablet( data ) {
	
    function dismiss() {
    	modals.dismissAllModals();
    }
    
	var node = $( data );
	var modals = jdw.tabletModalsContainer;
	modals.setSmallModalContent({ content: node });
	modals.bindRelLinks(node);

	$('#warrantyAddedText').hide();
	$('#side-small').addClass('warrenty-message');
	
	// Appends a div which has styles associated with it specifically for use with warranties
	$('.warrenty-message').append('<div class="option-shading"><div class="edge top"></div><div class="edge bottom"></div></div>');

	$('div.decline-button a', node).click( dismiss );
	$('div.add-bag a', node).click( function() {
		var theUrl = $(this).attr('href');
		
		jdw.mobileAjax.performAjaxRequest(
				theUrl,                  // urlString
				null,                    // beforeSendFunction
				null,                    // onCompleteFunction
				'json',                  // dataType
				null,                    // formData
				function (data) {            // onSuccessFunction
					var dataLayerEvent = jQuery.parseJSON(data.gapDataLayer);
				    if((dataLayerEvent) && (Object.keys(dataLayerEvent).length != 0)) {
				        window.dataLayer.push(dataLayerEvent);
				    }
					updateBagCount(data.numberOfItemsInBasket);
					$('#warrantyAddedText, #warrenty-container, #optionBox, #slide-options').toggle();

		    		var parameters = extractQueryParameters(theUrl); 
				},
				null,                    // onErrorFunction
				'GET',                   // sendMethod
				null,                    // triggerData
				null);                   // sessionTimeoutFunction
		
		return false; // Prevent the default action from firing.
	});
	
 	modals.showSmallModal();
}

function updateBagCount(numberOfItemsInBasket){
	if($("#numItemsInBag").length>0){
		$("#numItemsInBag").text(numberOfItemsInBasket);
	}else{
		$("#numItemsInBag", window.parent.document).text(numberOfItemsInBasket);
	}
}

//********END TABLET ONLY FUNCTIONS********************************

/* complete : /javascript/productDetailsRedesign/productDetailsWarranties.js*/


/* combine : /javascript/productdetails/desktop/productDetailsMediaModalVideo.js*/
var jdw = jdw || {};
if(!jdw.modalsContainer) jdw.modalsContainer = new jdw.ModalsContainer();
(function() { 
	"use strict";
	
	// ------------------------------------------------------------------- //
	// jdw.MediaModalVideo - functionality to play videos in a modal ----- //
	// ------------------------------------------------------------------- //
	jdw.MediaModalVideo = function() {
		
		// Public -------------------------------------------------------- //
		this.playModalMedia = function(mediaVars) {
			if (!mediaVars.width) mediaVars.width = modalDefaults.width;
			if (!mediaVars.height) mediaVars.height = modalDefaults.height;
			createContainer(mediaVars);
		}
		
		// Private variables --------------------------------------------- //
		var mediaDefaults = {
			playerVideo: "0810AW_CWPlayer10.swf",
			player360: "0810AW_360Player.swf",
			mediaServer: "http://hosting.drct2u.com/Staging/"
		};
		
		var modalDefaults = {
			width: 500,
			height: 300,
			modalHeightPadding: 97,
			modalWidthPadding: 80
		};
		
		var flashvars = {
			videoPath:  "",
			videoW: modalDefaults.width,
			videoH: modalDefaults.height
		};
		
		var params = {
			menu: "false",
			wmode: "transparent",
			swliveconnect: "false",
			allowscriptaccess: "always",
			allownetworking: "all",
			scale: "noscale"
		};
		
		var attributes = { id: "videoNote" };	
		
		var videoModalContainer = 
			'<div id="videoModalContainer"><div id="noFlashContainer">' 
			+ '<a href="http://www.adobe.com/go/getflashplayer">'
			+ '<img src="http://www.adobe.com/images/shared/download_buttons/'
			+ 'get_flash_player.gif" alt="Get Adobe Flash player"/></a></div></div>';
		
		// Private functions --------------------------------------------- //
		var createContainer = function(mediaVars) {
			var modalVars = {	
				id: 'videoPlayerModal',
				width: (mediaVars.width + modalDefaults.modalWidthPadding),
				height: mediaVars.height,
				fullHeight: (mediaVars.height + modalDefaults.modalHeightPadding),			
				headingText: '',
				ajax: false,
				backButtonDisabled: true,
				content: function() { return videoModalContainer; }
			};
			jdw.modalsContainer.showModal(modalVars);
			playMedia(mediaVars);
		}
		
		var playMedia = function(mediaVars) {
			switch(mediaVars.type) {
				case 'ModalVideo':
					if (!mediaVars.player) mediaVars.player = mediaDefaults.playerVideo;
					playFlashVideo(mediaVars);
					break;
				case 'Modal360':
					if (!mediaVars.player) mediaVars.player = mediaDefaults.player360;
					playFlashVideo(mediaVars);
					break;
			}
		}
			
		var playFlashVideo = function(mediaVars) {
			setFlashVars(mediaVars);
			swfobject.embedSWF(mediaDefaults.mediaServer + mediaVars.player + cacheHack(), 
				"noFlashContainer", mediaVars.width, mediaVars.height, "9.0.0", false, 
				flashvars, params, attributes);
		}
		
		var setFlashVars = function(mediaVars) {
			flashvars.videoPath = mediaDefaults.mediaServer + mediaVars.media;
			flashvars.videoW = mediaVars.width;
			flashvars.videoH = mediaVars.height;
		}
		
		var cacheHack = function() {
			return "?t=" + new Date().getTime();
		}
	}
	
	// Set up ------------------------------------------------------------ //
	if (!jdw.mediaModalVideo) jdw.mediaModalVideo = new jdw.MediaModalVideo();
	
})();
/* complete : /javascript/productdetails/desktop/productDetailsMediaModalVideo.js*/


/* combine : /javascript/productdetails/desktop/productDetailsSubstitutes.js*/
function openSubDialog(link) {
    var urlString = link.href;
    if (top != self) {
        urlString = urlString + "&useTarget=true";
    }

    if (pagePrefix != null) {
        urlString = urlString + "&pagePrefix=" + pagePrefix;
    }

    $.get(urlString, function(data) {
        if (top != self) {
            top.openModalJQ(data, null, null, false, false, false);
        } else {
            openModalJQ(data, null, null, false, false, false);
        }
    });
}
function mobileOpenSubDialog(link) {
    var urlStr = link.href;
    if (top != self) {
        urlStr = urlStr + "&useTarget=true";
    }

    if (pagePrefix != null) {
        urlStr = urlStr + "&pagePrefix=" + pagePrefix;
    }
    performAjaxRequest( urlStr,
                        null,
                        null,
                        'json',
                        null,
                        handleAjaxResultForOpenSubDialog,
                        null,
                        'GET',
                        null,
                        null);
}

function handleAjaxResultForOpenSubDialog(data) {
    window.location.replace(data.productDetailsUrl);
}/* complete : /javascript/productdetails/desktop/productDetailsSubstitutes.js*/


/* combine : /javascript/productDetailsRedesign/quickView/productDetailsQuickView.js*/
/**
 * code which activates the quickView modal from the productDetails window.
 *
 */
var jdw = jdw || {};

var isTablet = $('meta[name=jdw-isTablet]').attr("value") == "true";

jdw.QuickView = function(){
    var iframeSrc='';
    var showCheckoutButton=false;
    var cmProductType='';
    var qv = this;
    var messageData='';
    var seoProductDetailsURL='';
    var optionSelected=false;
    
    this.setup = function(){
        $("ul#recentlyViewedThumbnails li a").bind('click',function(event){
            event.preventDefault();
            qv.setSeoProductDetailsURL($(this).attr("href"));
            qv.setProductType("RECENTLY VIEWED");
            var url = constructQuickViewURL($(this).attr("href"), $(this).attr("id"), qv.getProductType());
            showHtmlDetails(url);
        });
        // tablet goes straight to PLP page for performance reasons
        if(typeof isTablet == 'undefined' || !isTablet) {
	        $(document).delegate(".affinityWrapper li .productPreview a","click",function(event){
	            event.preventDefault();
	            qv.setSeoProductDetailsURL($(this).attr("href"));
	            qv.setProductType("AFFINITY");
	            var url = constructQuickViewURL($(this).attr("href"), $(this).attr("id"), qv.getProductType());
	            showHtmlDetails(url);
	        });
        }
        if(typeof isTablet == 'undefined' || !isTablet) {
            $("div#promotions").find("div.productPreviewImage, div.productPreviewText").find("a").bind('click', function(event){
                event.preventDefault();
                qv.setSeoProductDetailsURL($(this).attr("href"));
                if ($("div#promotions").find("#merchandiseIncentiveProductsPanel").length > 0) {
                    qv.setProductType("MULTISAVINGS");
                    var url = constructMultiSavingsQuickViewURL($(this).attr("href"), $(this).attr("id"), qv.getProductType());
                    showHtmlDetails(url);
                } else {
                    qv.setProductType("PROMO PROD");
                    var url = constructQuickViewURL($(this).attr("href"), $(this).attr("id"), qv.getProductType());
                    showHtmlDetails(url);
                }
            });
        }
        // For order builder vertical placement
        $("#orderBuildingVertical li .productPreview").delegate("a", "click", function(event) {
            event.preventDefault();
            qv.setSeoProductDetailsURL($(this).attr("href"));
            qv.setProductType("AFFINITY");
            var url = constructOrderBuildingQuickViewURL($(this).attr("href"), $(this).attr("id"), qv.getProductType());
            showHtmlDetails(url, "orderBuildingHeader");
        });
        var isIE8orBelow = ! jQuery.support.opacity;
        if( ! isIE8orBelow ) {
            $(".pdp-affinities").delegate("li.productPreview a", "click", function(event) {
                event.preventDefault();
                qv.setSeoProductDetailsURL($(this).attr("href"));
                qv.setProductType("AFFINITY");
                // Find the slot id, fixed on page
                var sliderHolder = $(this).parentsUntil(".jdw-rr-slider-holder").parent()[0];
                var slotId = sliderHolder['id'];
                var slotIndex = slotId.substring(slotId.length-1);
                // Find the rr-placement id, relative to first RR placement (moves based on manual affinities)
                var productHolder = $(this).parentsUntil(".jdw-rr-productHolder").parent()[0];
                var placementId = productHolder['id'];
                var placementIndex = placementId.substring(placementId.length-1);
                var productList = [];
                //Retrieving list of products from RR using getAutomatedAffinites(placementIndex)
                //resulted in problems if RR returned a product we no longer had with royal slider
                //and the list displayed on the page getting out of sync. Therefore we retrieve
                //the products from the page to prevent this error.
                $.each($(this).closest("ul.jdw-rr-scroll-content").children(), function(index, element) {
                	var prod = $(element).attr("id").split("-");
                	var prodId = prod[prod.length-1];
                	productList.push(prodId);
                });
                
                var selectedProductId = $(this).attr("id").substring($(this).attr("id").length-5);
                var selectedProductIndex = $(this).closest("li").attr("jdw-thumbnail-index") - 1;
                
                var url = "/shop/affinitySlot"+slotIndex+"/product/details/show.action?pdLpUid="
                	+ selectedProductId + "&prefixIndex=" + selectedProductIndex;
                
                // make ajax call to update the content in the slide container
                jdw.quickView.showAffinitySlotDetails(url, slotIndex, selectedProductIndex, productList, selectedProductId);
            });

            $(".pdp-affinities").delegate("li.productPreviewManual a", "click", function(event) {
                event.preventDefault();
                qv.setSeoProductDetailsURL($(this).attr("href"));
                qv.setProductType("AFFINITY");
                // If there are manual affinity products on the page there should be a javascript String
                // of their ids already built in the page.
                var selectedProductId = $(this).attr("id").substring($(this).attr("id").length-5);
                var selectedProductIndex = $(this).parent().attr("jdw-thumbnail-index") - 1;
                
                var url = "/shop/affinitySlot1/product/details/show.action?pdLpUid=" + selectedProductId + "&prefixIndex=" + selectedProductIndex;
                
                // make ajax call to update the content in the slide container
                jdw.quickView.showAffinitySlotDetails(url, 1, selectedProductIndex, manualAffinityProducts, selectedProductId);
            });
        }
    };
    this.setOptionSelected = function(selected){
        optionSelected=selected;
    };
    this.isOptionSelected = function(){
        return optionSelected;
    };
    this.setSeoProductDetailsURL=function(url){
        seoProductDetailsURL=url;
    };
    this.getSeoProductDetailsURL=function(){
        if(qv.isOptionSelected()){
            return seoProductDetailsURL.substr(0, seoProductDetailsURL.indexOf("?") + 1) +
            iframeSrc.substr(iframeSrc.indexOf("?") + 1);
        }
        return seoProductDetailsURL;
    };
    this.setMessageData = function(message){
        messageData = message;
    };
    this.getMessageData = function(){
        return messageData;
    };
    this.setProductType = function(type){
        cmProductType = type;
    };
    this.getProductType = function(){
        return cmProductType;
    };
    this.setIframeSource = function(url){
        iframeSrc = url;
    };
    this.getIframeSrc = function(){
        return iframeSrc;
    };
    this.showHideCheckoutButton=function(val){
        showCheckoutButton = val;
    };
    this.isCheckoutButtonVisible=function(){
        return showCheckoutButton;
    };
    this.getUrlParameter = function(param, urlAnchor){
        var urlParams = urlAnchor.indexOf("&") != -1 ? urlAnchor.split("&") : [urlAnchor];
        for(var i=0;i< urlParams.length;i++){
            var urlParam = urlParams[i].split("=");
            if(urlParam[0]==param){
                return urlParam[1];
            }
        }
    };

    this.updateURLParameter = function(url, param, paramVal){
        var newAdditionalURL = "";
        var tempArray = url.split("?");
        var baseURL = tempArray[0];
        var additionalURL = tempArray[1];
        var temp = "";
        if (additionalURL) {
            tempArray = additionalURL.split("&");
            for (var i=0; i<tempArray.length; i++){
                if(tempArray[i].split('=')[0] != param){
                    newAdditionalURL += temp + tempArray[i];
                    temp = "&";
                }
            }
        }
        var rows_txt = temp + "" + param + "=" + paramVal;
        return baseURL + "?" + newAdditionalURL + rows_txt;
    };

    this.showHtmlDetails = function(url, headerClass) {
        showHtmlDetails(url, headerClass);
    };

    this.showOutfitFittings = function(url, prefix) {
        showOutfitFittings(url, prefix);
    };
    
    this.showAffinityFittings = function(url, prefix) {
        showAffinityFittings(url, prefix);
    };

    this.showQofDetails = function(url, prefix) {
        showQofDetails(url, prefix);
    };

    this.showOrderBuildingDetails = function(selectedId, url) {
        showOrderBuildingDetails(selectedId, url);
    };

    this.showOutfitDetails = function(url, productIds) {
        showOutfitDetails(url, productIds);
    };
    
    this.showAffinitySlotDetails = function(url, placementIndex, position, productIds, selectedProductId) {
        showAffinitySlotDetails(url, placementIndex, position, productIds, selectedProductId);
    };
    
    this.forceSliderResize = function(prefix, delay) {
        forceSliderResize(prefix, delay);
    };

    var constructQuickViewURL = function(url, hrefId, productType){
        var href=url.split("?");
        var pdbouid=qv.getUrlParameter('pdBoUid',href[1]);
        var pdlpuid=hrefId.split("-")[1];
        var url = '/shop/quickview/product/details/show.action?pdLpUid='+pdlpuid.substring(0,5)+'&pdBoUid='+pdbouid+'&viewContext='+productType;
        return url;
    };
    
    var constructMultiSavingsQuickViewURL = function(url, hrefId, productType){
        var href=url.split("?");
        var pdbouid=qv.getUrlParameter('pdBoUid',href[1]);
        var pdlpuid=hrefId.split("-")[1];
        var url = '/shop/quickview/product/details/showMultiSavingsQuickView.action?pdLpUid='+pdlpuid.substring(0,5)+'&pdBoUid='+pdbouid+'&viewContext='+productType;
        return url;
    };

    var constructOrderBuildingQuickViewURL = function(url, hrefId, productType) {
        var href=url.split("?");
        var pdbouid=qv.getUrlParameter('pdBoUid', href[1]);
        var pdlpuid=hrefId.split("-")[1];
        var url = '/shop/orderBuilding/ajax/showQuickView.action?pdLpUid='+pdlpuid.substring(0,5)+'&pdBoUid='+pdbouid+'&viewContext='+productType;
        return url;
    };
    
    var getAutomatedAffinities = function(placementIndex) {
        var productArray = placements[placementIndex].productArray;
        var productIds = [];
        for(var i=0; i<productArray.length; i++) {
            productIds.push(productArray[i].productCode);
        }
        return productIds;
    };

    var showHtmlDetails = function(url, headerClass){
        jdw.productDetailsWarranty.hideBackToProductButton();
        qv.showHideCheckoutButton(false);
        qv.setIframeSource('');
        function onSuccessQuickView(displayContent) {
            var content = function() {return displayContent;};
            $("#jdwModalContent").html("");
            var options = {
                content: content,
                width: 820,
                height: 580,
                headingText:'<div id="orderHeader"><div class="capHeadLt"></div><div class="headContent"></div><div class="capHeadRt"></div></div>',
                ajax: false,
                id: 'quickviewnewmodal',
                fullHeight: 650,
                backButtonDisabled:true,
                loadCompletedCallback: function() {jdw.modalsContainer.moveCloseButton();}
            };

            // Attach an onClose method if the page defines one
            if(typeof onCloseModal !== 'undefined') {
                options.onClose = onCloseModal;
            }
            if(typeof headerClass !== 'undefined') {
                options.headerClass = headerClass;
            }
            jdw.modalsContainer.showModal(options);
            jdw.productDetailsWarranty.setup();
            
        }
        performAjaxRequest(url,null,null,'html',null,onSuccessQuickView,null,'GET',null,null);
    };

    var showOutfitDetails = function(url, productIds) {
        
        function fireRichRelevanceTag () {
            var slider = $('.outfitBuilderSlider').data('royalSlider');
            var slideId = slider.currSlideId;
            var productCode = slider.slides[slideId].content.attr('jdw-productid');
            // Check that product is RR (May be a manual affinity)
            if ( typeof placements != 'undefined' && typeof placements[0].products[productCode] != 'undefined') {
                $.ajax({
                    url: placements[0].products[productCode].clickUrl
                });
            }

        }

        var lastSlideIndex;
        function bindAfterSlideChangeEvent(slider) {
            // At the first or last slide in the slider, we hide the left or right button but the
            // user can still click-drag as if to change the slide past the end of the slider and
            // RoyalSlider still fires an AfterSlideChange event even though the slide displayed
            // won't change. So, we need to check whether the slide index actually changes before
            // acting on the slider change.
            slider.ev.on('rsDragStart', function(event) {
                lastSlideIndex = slider.currSlideId;
            });
            
            slider.ev.on('rsAfterSlideChange', function(event) {
                if(lastSlideIndex != slider.currSlideId) {
                    if (slider.slides[slider.currSlideId].content.context.childElementCount == 0) {
                        var selectedProductId = slider.currSlide.content.context.id.substring(7, 12);
                        var url = "/shop/outfitBuilder/product/details/show.action?pdLpUid=" + selectedProductId + "&prefixIndex=" + slider.currSlideId;
                        performAjaxRequest(url,null,null,'html',null,onSuccessOutfitQuickView,null,'GET',null,null);
                    } else {
                        completeSlide(slider);
                    }
                }
            });
        }

        function completeSlide(slider) {
                var celebrusData = slider.currSlide.content.attr("id").split("_");
                
                celReportOutfitSliderProduct(slider.currSlide.content.prop("baseURI"), celebrusData[1], celebrusData[2]);
    
                //remove rsNavSelected class from all thumbnail divs
                $("div.rsTab").removeClass("rsNavSelected");
                //add rsNavSelected class to target thumbnail div
                $("div[jdw-thumbnail-index='"+ slider.currSlideId +"']").addClass("rsNavSelected");
                fireRichRelevanceTag();

                //remove all thumbnails of the oufitQuickView before royalSlider calculate the height of the slider
                $("[id^='outfit']").find(".altProductPhotos").remove();
        }

        function slideDownOutfitBuilderSlider( isSlideChange ) {
            $('.outfitBuilderSlider').slideDown( "slow", function() {
                setTimeout(function(){
                    $('.outfitBuilderSlider').royalSlider('updateSliderSize', true);
                    
                    var offset = $('.outfitBuilderSlider').offset();
                    $('html, body').animate({
                        scrollTop: offset.top -300
                    }, 1000);
                }, 50);
            });
            // Only fire RR tag if this is not a slide change.
            // (Slide change handler will take care of this otherwise).
            if ( !isSlideChange ) {
            	fireRichRelevanceTag();
            }
        }
        
        function bindCloseSlideEvent() {
            $('.closeLinkWrap').click(function() {
                $('.outfitBuilderSlider').slideUp();
                $('.outfitBuilderThumbs .rsNavSelected').removeClass('rsNavSelected');
            });
        }

        function onSuccessOutfitQuickView(displayContent) {
        	var slider = $(".outfitBuilderSlider").data('royalSlider');
    		var productId = slider.currSlide.content.context.id.substring(7, 12);
            $(".outfitBuilderSlider #slider_" + productId + "_" + slider.currSlideId).html(displayContent);
            completeSlide(slider);
            $("#slider_" + productId + "_" + slider.currSlideId).removeClass('pdp-backgroundLoaderClass');
            calcSliderHeight(".outfitBuilderSlider ");// slider is already open and new item added
        }
        
        function setupProductDataContainers(productIds) {
			var data = "";
			for(var i = 0; i < productIds.length; i++){
				data = data + "<div id='slider_" + productIds[i] + "_" + i + "' class='outfitBuilderProduct pdp-backgroundLoaderClass' jdw-productId='" + productIds[i] + "'></div>";
			}
			
            $("div.outfitBuilderSlider").html("");
            $("div.outfitBuilderSlider").html(data);

            //remove zoomify image div to remove the fallback message
            $('div [id$="_prodImageZoomify"]').remove();

            $('.outfitBuilderSlider').royalSlider({
                controlNavigation:"tabs",
                autoHeight: true,
                autoScaleSlider: true,
                autoScaleSliderHeight: 300,
                fadeinLoadedSlide: false,
                imageScaleMode: 'none',
                navigateByClick: false,
                arrowsNavAutoHide: false,
                fitInViewport: false
            });
            
            //add a close button for slider and bind click to slideUp the container
            $('.outfitBuilderSlider .rsOverflow').prepend('<div id="sliderCloseLink" class="closeLinkWrap"><a class="closeLink" href="javascript:void(0);">X</a></div>');
            bindCloseSlideEvent();
            
            //get the selected slide index from the rsNavSelected
            var selectedProductIndex = $("div.rsNavSelected").attr("jdw-thumbnail-index");
            var slider = $(".outfitBuilderSlider").data('royalSlider');
            //slide to a correct slide after click on thumbnail
            var isSlideChange = !(slider.currSlideId == selectedProductIndex);
            if (isSlideChange) {
            	slider.goTo(selectedProductIndex);
            }

            //to detect the current slide on the page and set the active css class on thumbnail div
            bindAfterSlideChangeEvent(slider);

            //slide down the outfit slider
            slideDownOutfitBuilderSlider( isSlideChange );
            
            //unbind the ajax click event from thumbnails and bind new one to slide to the correct slide
            $("div[jdw-thumbnail-index]").unbind("click").bind("click", function(){
                var selectedThumbnailIndex = $(this).attr("jdw-thumbnail-index");
                var slider = $(".outfitBuilderSlider").data('royalSlider');
                var isSlideChange = !(slider.currSlideId == selectedThumbnailIndex);
                slideDownOutfitBuilderSlider( isSlideChange );
                if ( isSlideChange ) {
                	slider.goTo(selectedThumbnailIndex);
                }
            });
            //remove class at thumbnails
            $('.outfitBuilderThumbs').removeClass('outfitThumbSelected');
            $("div.loading-spinner").hide();
                
        }
        
        var beforeLoading = function() { };
    	beforeLoading.hideUpdatingOverlay = true;

    	// build slider and display loading icons
    	setupProductDataContainers(productIds);

        performAjaxRequest(url,beforeLoading,null,'html',null,onSuccessOutfitQuickView,null,'GET',null,null);
    };

    var showAffinitySlotDetails = function(url, slotIndex, position, productIds, selectedProductId) {
    	function fireRichRelevanceTag ( slider, slotIndex) {
        	var placementIndex = slotIndex-1;
			// Adjust index if page has manual affinities (Not stored in placements object).
			if  (hasManualAffinities) { placementIndex--; }
			// Slot 1 always contains Manual Affinities, which we do not want to fire RR events for.
			if ( placementIndex > -1 ) {
				var placement = placements[placementIndex];
				var slideId = slider.currSlideId;
				var productCode = slider.slides[slideId].content.attr('jdw-productid');
				$.ajax({
					url: placement.products[productCode].clickUrl
				});
			}
        }
    	
    	var lastSlideIndex;
        function bindAfterSlideChangeEvent(slider) {
            // At the first or last slide in the slider, we hide the left or right button but the
            // user can still click-drag as if to change the slide past the end of the slider and
            // RoyalSlider still fires an AfterSlideChange event even though the slide displayed
            // won't change. So, we need to check whether the slide index actually changes before
            // acting on the slider change.
            slider.ev.on('rsDragStart', function(event) {
                lastSlideIndex = slider.currSlideId;
            });
            
            slider.ev.on('rsAfterSlideChange', function(event) {
                if(lastSlideIndex != slider.currSlideId) {
                    if (slider.slides[slider.currSlideId].content.context.childElementCount == 0) {
                        var selectedProductId = slider.currSlide.content.context.id.substring(7, 12);
                        var url = "/shop/affinitySlot"+slotIndex+"/product/details/show.action?pdLpUid=" + selectedProductId;
                        performAjaxRequest(url,null,null,'html',null,onSuccessAffinityLoad,null,'GET',null,null);
                    } else {
                        completeSlide(slider);
                    }
                }
            });
        }

        function completeSlide(slider) {
        	// Fire Celebrus tags
        	var celebrusData = slider.currSlide.content.attr("id").split("_");
        	celReportAffinitySliderProduct(slider.currSlide.content.prop("baseURI"), celebrusData[1], celebrusData[2]);            
            //remove rsNavSelected class from all thumbnail divs
            $("li.productPreview").removeClass("rsNavSelected");
            $("li.productPreviewManual").removeClass("rsNavSelected");
            //add rsNavSelected class to target thumbnail div
            var affinitySlider = $("#jdw-rr-" + (slotIndex));
            var affinitySliderImage = $("#jdw-rr-" + (slotIndex)).find("li[jdw-thumbnail-index='"+ (slider.currSlideId + 1) +"']");
            affinitySliderImage.addClass("rsNavSelected");
        	
        	// Check if affinity slider needs scrolling
        	var sliderBounds = $(affinitySlider).width();
        	var imagePos = $(affinitySliderImage).offset().left;
        	
        	if (imagePos < 0) {
        		$('#jdwScrollButtonLeft-rr' + slotIndex).click();
        	} else if (imagePos > sliderBounds) {
        		$('#jdwScrollButtonRight-rr' + slotIndex).click();
        	}
        	
        	// Fire Rich Relevance click event
        	fireRichRelevanceTag( slider, slotIndex );
        }
        
        function onSuccessAffinityLoad(displayContent) {
        	var sliderSelector = "#affinitySlot"+slotIndex+"Slider";
        	var slider = $(sliderSelector).data('royalSlider');
        	
    		var productId = slider.currSlide.content.context.id.substring(7, 12);
    		var slideSelector = sliderSelector + " #slider_" + productId + "_" + slider.currSlideId;
    		
            $(slideSelector).html(displayContent);
            
            $(slideSelector).removeClass("pdp-backgroundLoaderClass");
            calcSliderHeight("#affinitySlot"+slotIndex+"Slider");// slider is already open and new item added
            
            removeThumbnails();
            completeSlide(slider);
            
        }
        
       

        function removeThumbnails() {
            // remove all thumbnails underneath the main product image
            $('#affinitySlot'+slotIndex+'Slider').find('.rsSlide').each(function() {
                $( this ).find('#horizontalAltNav').remove();
            });
        }
        
        function slideDownAffinitySlotSlider( isSlideChange ) {
            // Close any other open sliders
            for(var i=1; i<=3; i++) {
                if(i != slotIndex) {
                    $('#affinitySlot'+i+'Slider').slideUp();
                }
            }
            // Open this slider
            $('#affinitySlot'+slotIndex+'Slider').slideDown( "slow", function() {
                setTimeout(function(){
                    $('#affinitySlot'+slotIndex+'Slider').royalSlider('updateSliderSize', true);
                    
                    var offset = $('#affinitySlot'+slotIndex+'Slider').offset();
                    $('html, body').animate({
                        scrollTop: offset.top -300
                    }, 500);
                }, 50);
            });
            //remove rsNavSelected class from all thumbnail divs
            $("li.productPreview").removeClass("rsNavSelected");
            $("li.productPreviewManual").removeClass("rsNavSelected");
            // Re-mark the thumbnail relating to the current showing slide as selected
            var slider = $("#affinitySlot"+slotIndex+"Slider").data('royalSlider');
            if(typeof slider != "undefined") {
                $("#jdw-rr-" + (slotIndex)).find("li[jdw-thumbnail-index='"+ (slider.currSlideId + 1) +"']").addClass("rsNavSelected");
            }
            
            // Fire Rich Relevance click event if this is not a slide change 
            // (Otherwise event will be fired by slideChange handler).
            if ( !isSlideChange ) {
				fireRichRelevanceTag( slider, slotIndex );
			}
        }
        
        function bindCloseSlideEvent() {
            $('.closeLinkWrap').click(function() {
                $('#affinitySlot'+slotIndex+'Slider').slideUp();
                // Remove highlight from carousel
                $("li.productPreview").removeClass("rsNavSelected");
            });
        }

        function onSuccessAffinityQuickView(displayContent) {
        	var sliderSelector = "#affinitySlot"+slotIndex+"Slider";
        	var slider = $(sliderSelector).data('royalSlider');
        	
        	var slideSelector = sliderSelector + " #slider_" + selectedProductId + "_" + position;
        	$(slideSelector).html(displayContent);
            
            //Remove default spinner
            $(slideSelector).removeClass("pdp-backgroundLoaderClass");
            
            calcSliderHeight('#affinitySlot'+slotIndex+'Slider');// first time slider is opened and ajax call made for first item
            
            removeThumbnails();
            
            //slide to a correct slide after click on thumbnail
            slider.goTo(position);
        }

        function setupProductDataContainers(productIds) {
			var data = "";
			for(var i = 0; i < productIds.length; i++){
				data = data + "<div id='slider_" + productIds[i] + "_" + i + "' class='affinityProduct pdp-backgroundLoaderClass' jdw-productId='" + productIds[i] + "'></div>";
			}
			
			$("div#affinitySlot"+slotIndex+"Slider").html("");
            $("div#affinitySlot"+slotIndex+"Slider").html(data);
            //remove zoomify image div to remove the fallback message
            $('div [id$="_prodImageZoomify"]').remove();

            if(typeof($('#affinitySlot'+slotIndex+'Slider').data('royalSlider')) != 'undefined') {
                $('#affinitySlot'+slotIndex+'Slider').data('royalSlider').destroy();
            }
            
            $('#affinitySlot'+slotIndex+'Slider').royalSlider({
                controlNavigation:"tabs",
                autoHeight: true,
                autoScaleSlider: true,
                autoScaleSliderHeight: 300,
                fadeinLoadedSlide: false,
                imageScaleMode: 'none',
                arrowsNavAutoHide: false,
                fitInViewport: false,
                navigateByClick: false
            });
            
            //add a close button for slider and bind click to slideUp the container
            $('#affinitySlot'+slotIndex+'Slider .rsOverflow').prepend('<div class="closeLinkWrap"><a class="closeLink" href="javascript:void(0);">X</a></div>');
            bindCloseSlideEvent();
            
            //get the selected slide index from the rsNavSelected
            //var selectedProductIndex = $("div.rsNavSelected").attr("jdw-thumbnail-index");
            var slider = $("#affinitySlot"+slotIndex+"Slider").data('royalSlider');
            //slide to a correct slide after click on thumbnail
            var isSlideChange = ! (slider.currSlideId == position);
            if (isSlideChange) { slider.goTo(position); }
            
            /* For performance reasons, RoyalSlider only maintains a certain number of slides in the DOM
             *  (4 each way from the currently selected slide by default). Because of this, we attach an event 
             * handler to remove unwanted thumbnails beneath the main product image when a slide is selected.
            */
            slider.ev.on('rsBeforeAnimStart', function(event) {
            	// remove all thumbnails underneath the main product image
                $('#affinitySlot'+slotIndex+'Slider').find('.rsSlide').each(function() {
                    $( this ).find('#horizontalAltNav').remove();
                });
            });
            
            //to detect the current slide on the page and set the active css class on thumbnail div
            bindAfterSlideChangeEvent(slider);

            //slide down the outfit slider
            slideDownAffinitySlotSlider(isSlideChange);
            //bind click event handler for the close slider div
            $('.closeLink').bind('click', function() {
                $('#affinitySlot'+slotIndex+'Slider').slideUp( "slow");
            });
            $("div#affinitySlot"+slotIndex+"-loading-spinner").hide();
        }
        
        var slider = $("#affinitySlot"+slotIndex+"Slider").data('royalSlider');
        // Check if the slider for this slot is already built
        if(typeof(slider) != 'undefined') {
            // If the slider does exist, show it
        	var isSlideChange = ! (slider.currSlideId == position);
            slideDownAffinitySlotSlider(isSlideChange);
            if (slider.slides[position].content.context.childElementCount == 0) {
                performAjaxRequest(url,null,null,'html',null,onSuccessAffinityQuickView,null,'GET',null,null);
            } else {
                //slide to a correct slide after click on thumbnail
                if (isSlideChange) { slider.goTo(position); }
            }
        } else {
        	// build slider and display loading icons
        	setupProductDataContainers(productIds);

        	// if the slider isn't yet build, request the preview data
            performAjaxRequest(url,null,null,'html',null,onSuccessAffinityQuickView,null,'GET',null,null);
        }
    };
    
    var showOutfitFittings = function(url, prefix) {

        function onSuccessOutfitFittings(displayContent) {
            var outfitbuilderSlide = $("#" + prefix + "_optionsForm").parents(".outfitBuilderProduct");
            $(outfitbuilderSlide).html("");
            $(outfitbuilderSlide).html(displayContent);

            //update jdw-productid
            var newProductId = $(outfitbuilderSlide).find(".productHeading [id$='_prodCatNumber']").html();
            var newProductIdWithoutSuffix = newProductId.substring(0, newProductId.length - 2);
            $(outfitbuilderSlide).attr("jdw-productid", newProductIdWithoutSuffix);

            //update outfit banner Thumbnail images
            var oldProductId = prefix.substring(7, prefix.length-2);
            var selectedThumbnailImg = $("[jdw-product-id='" + oldProductId + "']");
            var newThumbnailUrl = $("#outfit_" + newProductId + "_mainImageThumbImage").attr("src");
            $(selectedThumbnailImg).attr("src", newThumbnailUrl);

            //remove thumbnails at Outfit fitting
            $(outfitbuilderSlide).find(".altProductPhotos").remove();

            //update slide height
            $('.outfitBuilderSlider').royalSlider('updateSliderSize', true);
        }
        url = url + "&productDetailsType=OUTFIT";
        performAjaxRequest(url,null,null,'html',null,onSuccessOutfitFittings,null,'GET',null,null);
    };

    var showAffinityFittings = function(url, prefix) {

        function onSuccessAffinityFittings(displayContent) {
            var affinitySlide = $("#" + prefix + "_optionsForm").parents(".affinityProduct");
            $(affinitySlide).html("");
            $(affinitySlide).html(displayContent);
            
            //update jdw-productid
            var newProductId = $(affinitySlide).find(".productHeading [id$='_prodCatNumber']").html();
            var newProductIdWithoutSuffix = newProductId.substring(0, newProductId.length - 2);
            $(affinitySlide).attr("jdw-productid", newProductIdWithoutSuffix);
            
            //remove thumbnails at Outfit fitting
            $(affinitySlide).find(".altProductPhotos").remove();
            
            //update slide height
            forceSliderResize(prefix);
        }
        var type = prefix.substring(0, prefix.indexOf("_"));
        url = url + "&productDetailsType="+type.toUpperCase();
        performAjaxRequest(url,null,null,'html',null,onSuccessAffinityFittings,null,'GET',null,null);
    };

    var showQofDetails = function(url, prefix) {
        var prefixIndex = prefix.substring(12);
        //12 is the position of the index in the prefix

        var productCodePattern = new RegExp('[A-Za-z]{2}[0-9]{3}[A-Za-z0-9]{2}');

        function onSuccessQof(displayContent) {
            $('div.quickView_' + prefixIndex + ' div.mainContent').html("");
            $('div.quickView_' + prefixIndex + ' div.mainContent').html(displayContent);
            var productId = (productCodePattern.exec($('div.quickView_' + prefixIndex + ' div.mainContent form').attr('id')))[0];
            $('div.quickView_' + prefixIndex).attr('id', 'qof_' + productId + '_' + prefixIndex);
            var prodDetailsFrame = $('div.quickView_' + prefixIndex).parent('div.prodDetailsFrame');
            $(prodDetailsFrame).find('span.frameHeaderProduct').attr('id','frameHeaderProductId-' + productId).text(productId);
            $(prodDetailsFrame).find('div.prodDetailsFrameHeader').attr('id', 'prodDetailsFrameHeader-' + productId).find('a').attr('id', 'anchor-' + productId).attr('name', productId);
            $(prodDetailsFrame).attr('id', 'prodDetailsFrame-'+ productId);

        }
        url = url + "&prefixIndex=" + prefixIndex + "&productDetailsType=QOF";
        performAjaxRequest(url,null,null,'html',null,onSuccessQof,null,'GET',null,null);
    };

    var showOrderBuildingDetails = function(selectedProductId, url) {
        function onSuccessOrderBuilding(displayContent) {
            $("div[id^='optionsHolder']").empty();
            $("div[id^='optionsHolder']").html("");
            $('#optionsHolder' + selectedProductId).html(displayContent);
            $("#obPanelInfo-"+selectedProductId).insertAfter("#optionsHolder" + selectedProductId + " .productHeading");
            $('.obProductInfoContainer').hide();
        }
        performAjaxRequest(url,null,null,'html',null,onSuccessOrderBuilding,null,'GET',null,null);
    };
    
    var forceSliderResize = function(prefix, delay) {
        delay = (typeof delay === 'undefined') ? 0 : delay;
    
        setTimeout(function() {
            if(prefix.startsWith('outfit')) {
                $('.outfitBuilderSlider').royalSlider('updateSliderSize', true);
            
            } else if(prefix.startsWith('affinity')) {
                $('#'+prefix+'_optionsForm').parents('.affinitySlotSlider').royalSlider('updateSliderSize', true);
            }
        }, delay);
    };
};

function calcSliderHeight(slider){
	var calculatedHeight = $(slider).find('.productDetailsPage').height();
	$(slider).children('.rsOverflow').height(calculatedHeight);
}

function showCheckoutButton(){
    var quickView = window != window.parent ? parent.jdw.quickView : jdw.quickView;
    quickView.showHideCheckoutButton(true);
    var messageData = quickView.getMessageData();
    $("#modalContent").contents().find('.fadeMsgBox .' + $prefix + '_msg').html(messageData.message).fadeIn(700);
    $("#"+ $prefix +"_continueToCheckout").fadeIn("slow");
}

function addWarrantyToBasket(url){
    var modalsContainer = window != window.parent ? parent.jdw.modalsContainer : jdw.modalsContainer;
    jdw.modalsContainer.showModal({
        headingText: "Add warranty to bag",
        content: url,
        width: 850,
        height: 370,
        ajax: true,
        id: 'moreInfoModal',
        fullHeight: 450
    });
    return false;
}

//SETUP ---------------------------------------------------------------
if(!jdw.modalsContainer && !isTablet){
    jdw.modalsContainer = new jdw.ModalsContainer();
}
if ( !jdw.productDetailsWarranty ) {
    jdw.productDetailsWarranty = new jdw.ProductDetailsWarranty();
}
if ( !jdw.quickView ) {
    jdw.quickView = new jdw.QuickView();
}
$(document).ready( function() {
    jdw.quickView.setup();
});
/* complete : /javascript/productDetailsRedesign/quickView/productDetailsQuickView.js*/


/* combine : /javascript/productdetails/desktop/productDetailsMoreInfo.js*/
var jdw = jdw || {};

(function() {
	"use strict";
	jdw.ProductDetailsMoreInfo = function() {

	    /* Public functions */
    	this.setup = function() {
    		$("#moreInfoAnchor").bind("click", onclickMoreInfoAnchor);
    	}

    	/* Private constants and variables */
    	var MOREINFO_WIDTH = 850;
    	var MOREINFO_HEIGHT = 370;
    	var MOREINFO_FULL_HEIGHT = 445;

    	/* Private functions */
    	var onclickMoreInfoAnchor = function(event) {
    		var href = $("#moreInfoAnchor").attr('href');
    		var html = "";
    		if (href.indexOf('.gif') > -1
    			|| href.indexOf('.png') > -1
    			|| href.indexOf('.jpg') > -1
    			|| href.indexOf('.jpeg') > -1) {
    			html = "<img class='moreInfoImage' src='" + href + "'/>";
    		} else {
    			html = "<iframe class='moreInfoIFrame' src='" + href + "' height='346' width='829'></iframe>";
    		}
    		var modalsContainer = window != window.parent ? parent.jdw.modalsContainer : jdw.modalsContainer;
    		modalsContainer.showModal({headingText: "More Information",
    			                       content: function() {return html;},
    			                       width: MOREINFO_WIDTH,
    			                       height: MOREINFO_HEIGHT,
    			                       ajax: false,
    			                       id: 'moreInfoModal',
    			                       fullHeight: MOREINFO_FULL_HEIGHT});
    		return false;
    	}
	};

	/* Initialise */
	if (!jdw.productDetailsMoreInfo) jdw.productDetailsMoreInfo = new jdw.ProductDetailsMoreInfo();
})();

$(document).ready(function(e) {
	jdw.productDetailsMoreInfo.setup();
});
/* complete : /javascript/productdetails/desktop/productDetailsMoreInfo.js*/


/* combine : /javascript/productdetails/desktop/productDetailsGuides.js*/
var jdw = jdw || {};

jdw.ProductGuides = function() {
	this.bindSizeGuideTabs = function() {
		var tabs = $('#navTabs li');
		var firstTab = tabs[0];
		var firstTabLink = $('a',firstTab)[0];
		loadContent( firstTabLink.href, firstTab, tabs );
		
		// Celebrus fake click for first product guide
		if ( window.JDWclick ) {
			window.JDWclick( firstTabLink );
		}
		
		tabs.each( function(index, element) {
			$('a',element).unbind('click').bind('click', function(event){
				event.preventDefault();
				loadContent( this.href, element, tabs );
			});
		});
	}
	var currentRequest = null;
	var currentUrl = null;
	loadContent = function( href, tabElement, allTabs ) {
		new jdw.Overlay({
			container: $('#sizeGuide_content')
		});
		
		$.ajax({
			url : href,
			beforeSend : function( requestObj ) {
				if ( currentRequest ) {
					currentRequest.abort();
				}
				currentRequest = requestObj;
				currentUrl = href;
			},
			error : function() {},
			success : function( data, status, requestObj ) {
				if ( currentUrl == href ) {
					$('#sizeGuide_content').html( data );

					// Check for session timeout ...
					var redirectUrl = requestObj.getResponseHeader('REDIRECT_URL');
					if (redirectUrl != null && redirectUrl.length > 0) {
						location.href = redirectUrl.split(',')[0];
					} else {
						// Unselect the currently selected tab, and select the one that was clicked ...
						allTabs.each( function(index,e){ $(e).removeClass('selected') } );
						$(tabElement).addClass('selected');
					}
				}
			},
			cache : false,
			contentType : "text/html"
		});		
	}
	this.onCloseSizeGuides = function() {
//		alert("Closing!!!");
		// Speedtrap (Celebrus) : Let them know that the modal window has been closed ...
		if ( window.JDWclick ) {
			window.JDWclick( {id:"ProdGuide_Close",tagName:"DIV"} );
		}
	}
}
/* The following Overlay object is intended to be a generic "loading..." indicator, but time 
 *  constraints have meant that this cannot be implemented in a fully generic fashion.
 * Ideally, this should be in its own JS file, or at least in a common JS file, and re-used 
 *  wherever it is required.
*/
jdw.Overlay= function( options ) {
	this.container = options.container;

	this.container.html(
		'<div class="jdwOverlay" style="position:relative;height:100%;text-align:center;"></div>'
	);
	setTimeout( 'showSwirly()', 1000 );
	
	// === PRIVATE ------------------------
	
	showSwirly = function() {
		$('.jdwOverlay').html('<img style="position:relative;top:40%" src="' + imageServerUrl 
				+ '/content/images/product_details/loading.gif"/>');
	}
}
/* complete : /javascript/productdetails/desktop/productDetailsGuides.js*/


/* combine : /javascript/productDetailsRedesign/productDetailsCommon.js*/
// Common DESKTOP/TABLET/MOBILE JavaScript for Product Details

// Accordian
$(function() {
    var defaultOpen = 1;
    $('#accordion .content').hide();

    $('#accordion h2:first').addClass('active').next().slideDown('medium');

    $('#accordion h2').click(function() {
    
    function deliveryOptionsOnSuccess(data) {
        $('#productReturnsContent').html("").html(data);
        $('#productReturnsContent').addClass("ajaxRequested");
    }
    function showLoadingSpinnerOnStart() {
        $('.delivery-loading-spinner').show();
    }
    function hideLoadingSpinnerOnComplete() {
	    $('#productReturnsContent').show();
        $('.delivery-loading-spinner').hide();
    }
      if(!($('#productReturnsContent').hasClass("ajaxRequested"))) {
          var url = "/shop/product/details/ajax/deliveryOptions.action?productId=" 
              + offeredProductId + "&optionId=" + defaultOptionId;
          performAjaxRequest(url, showLoadingSpinnerOnStart, hideLoadingSpinnerOnComplete, "html",
              null, deliveryOptionsOnSuccess, null, "GET", null, null);
      } 
      if($(this).hasClass('active')) {

        $(this).removeClass('active');
        $(this).next().slideUp('medium');

      } else {
        $(this).addClass('active');
        $(this).next().slideDown('medium');

      }
  });
 });


// REVIEWS TABS
$(function () {
    $('body').delegate('.pdp-reviews-tab', 'click touch', function() {
        if (!$( this ).hasClass('active')) {
            $( this ).toggleClass('active');
            $( this ).siblings('li').toggleClass('active');
            $(this).parent().siblings('#bvTabContent').children('#ratings').toggleClass('active');
            $(this).parent().siblings('#bvTabContent').children('#qa').toggleClass('active');
        }
        
    });
  });
 

// Remove non ISO-8859-1 characters from personalisation text
function removeInvalidPersonalisationChars(object) {
    var _this = object;
    
    setTimeout( function() {       
        var text = $(_this).val();
        $(_this).val(text.replace(/[^\x20-\x7E\xA0-\xFF]/g, ''));
    }, 100);
}

// Handle input focus on personalisation
function handlePersonalisationInputFocus() {
    $('#personalisationConfirmNone').slideUp(500);
}


/* ---------------------------- AFFINITIES -----------------------*/

var jdw = jdw || {};
jdw.simpleScroller = function() {
	var imgWidth = 236; // hard coded value
	
	this.create = function(scroller, num, index){
		
		// change for image width - Chrome struggles with jQuery width()
		$(scroller).children('.jdw-rr-scroll-content').width(imgWidth * num); // set width of image holder so it forces scroll bars
		
		$(scroller).children('.jdw-rr-scroll-content').attr('data-width', $(scroller).children('.jdw-rr-scroll-content').width());
		$(scroller).children('.jdw-rr-scroll-content').attr('data-items', $(scroller).children('.jdw-rr-scroll-content').children('li').length);
		$(scroller).children('.jdw-rr-scroll-content').attr('data-diff', ($(scroller).children('.jdw-rr-scroll-content').width() - $(scroller).width()));
		
		if($(scroller).children('.jdw-rr-scroll-content').attr('data-diff') <= 0){
			$(scroller).parent().parent().parent().find('.jdw-rr-arrow-left').hide();
			$(scroller).parent().parent().parent().find('.jdw-rr-arrow-right').hide();
		}
		
		// add unique id to each button
		$(scroller).parent().parent().parent().find('.jdw-rr-arrow-right').attr("id","jdwScrollButtonRight-"+$(scroller).parent('.jdw-rr-slider-holder').attr('id').replace("jdw-rr-slider-holder-", ""));
		$(scroller).parent().parent().parent().find('.jdw-rr-arrow-left').attr("id","jdwScrollButtonLeft-"+$(scroller).parent('.jdw-rr-slider-holder').attr('id').replace("jdw-rr-slider-holder-", ""));
		$(scroller).parent().parent().parent().find('.jdw-rr-arrow-left').addClass("jdw-rr-arrow-disable");
		
	};
	
	$('.jdw-rr-arrow-right').unbind().click(function() {
		// use unique id to target scrollContent
		$('#jdw-rr-slider-holder-'+$(this).attr('id').replace('jdwScrollButtonRight-', "")).children('.jdw-rr-productHolder').animate( { scrollLeft: '+='+imgWidth }, 500);
		
	});
	
	$('.jdw-rr-arrow-left').unbind().click(function() {	
		$('#jdw-rr-slider-holder-'+$(this).attr('id').replace('jdwScrollButtonLeft-', "")).children('.jdw-rr-productHolder').animate( { scrollLeft: '-='+imgWidth }, 500);
	});
	
	$('.jdw-rr-productHolder').each(function() { // loop through the li's
		
		 $(this).scroll( function() {
		    	
		    	if ($(this).scrollLeft() == 0) {
		    		$(this).parent().parent().parent().find(".jdw-rr-arrow-left").addClass("jdw-rr-arrow-disable");
		    	} else {
		    		$(this).parent().parent().parent().find(".jdw-rr-arrow-left").removeClass("jdw-rr-arrow-disable");
		    	}
		    	
		    	if ($(this).scrollLeft() < ($(this).children('.jdw-rr-scroll-content').data('width') - $(this).width() - ($(this).children('.jdw-rr-scroll-content').data('items') * 2))) {
		    		$(this).parent().parent().parent().find(".jdw-rr-arrow-right").removeClass("jdw-rr-arrow-disable");
		    	} else {
		    		$(this).parent().parent().parent().find(".jdw-rr-arrow-right").addClass("jdw-rr-arrow-disable");
		    	}
		    });
	});
	
	$('.pdp-affinities').each(function(index) { // loop through the li's
		
		$(this).attr('id', "jdw-rr-"+(index+1)); 
	});
};

$(window).load(function() {
	buildWasNowPrice();	
});


///////////////////////////////////////////////////////////////////

function buildWasNowPrice(){
	if ($('#copyWasPriceContainer').outerHeight() > 160){
		$('#copyWasPriceContainer').addClass('copyWasPriceContainerScrollable');
	}
	$( "#copyWasPriceContainer" ).fadeTo( "slow" , 1, function() {   
	});
}





/* complete : /javascript/productDetailsRedesign/productDetailsCommon.js*/


/* combine : /javascript/productDetailsRedesign/quickView/productDetailsQuickViewMedia.js*/
var jdw = jdw || {};
(function() { 
	"use strict";
	/*
	<!-- ------------------------------------------------------------------- -->
	<!-- jdw.ProductDetailsMedia - display prod details images and videos -- -->
	<!-- ------------------------------------------------------------------- -->
	*/
	//to have different namespace from jdw.ProductDetailsMedia because we are going to
	//include both productDetailsQuickViewMedia.js and productDetailsMedia at the same time
	jdw.ProductDetailsQuickViewMedia = function() {
	
		/* Public */
		this.setup = function(prefix) {
			createImageObjects();
			imageServerUrl = $("#imageServerUrl").val();
		}
		this.populateImageAndImageAnchors = function(prefix, mainImageData, mainAltImageData, altImagesData) {
			if (mainImageData) {
				mainImage.setValues(mainImageData);
			}
			refreshMainImage(prefix, mainImage);
			populateAltImageThumbnails(prefix, mainImageData, mainAltImageData, altImagesData);
		}
		
		
		this.populateVideoLinkParameters = function() {}
	
		/* Private constants and variables */
		var ZOOMIFY_IMAGE_WIDTH = 500,
			ZOOMIFY_IMAGE_HEIGHT = 500,
			MAIN_PRODUCT_IMAGE_WIDTH = 500,
			MAIN_PRODUCT_IMAGE_HEIGHT = 500,
			MIN_CAROUSEL_SIZE = 5;
		
		var mainImage,
			mainAltImage,
			mainProductImage,
			zoomImage,
			imageServerUrl,
			altImageMap = {};
		
		/* Private functions */
		var createImageObjects = function() {
			mainImage = new ImageAnchorObject();
			mainAltImage = new ImageAnchorObject();
			mainProductImage = new ImageAnchorObject();
			zoomImage = new ImageAnchorObject();
		}
		
		/* change from event obj to image Obj, and pass prefix */
		var onclickAnchor = function(prefix, imgObj) {
			refreshMainImage(prefix, imgObj);
			return false;
		}
		
		
		var onclickAltImageThumb = function(event) {
			var prefix = event.data.prefix;
			celReportAltImageClick($("#pdLpUid").val(), $(this).attr('id'));
			setSelectedAltImg(prefix, $(this).closest("li"));
			onclickAnchor(prefix, event.data.img);
			event.preventDefault();
			return true;
		}
		var refreshMainImage = function(prefix, imageObj) {
			if (imageObj) {
				$("#"+ prefix +"_prodImagePanelEmbeddedVideo").hide();
				var imgType = imageObj.getImageType();
				if (imgType === 'QUICKVIEW' || imgType === 'MAIN_PRODUCT' || imgType === 'LARGE') {
					var imgDomObj = $("#"+ prefix +"_mainImage");
					if (imgDomObj) {
						var desc = $("h1").first().text();
						imgDomObj.attr({ 
							title: desc, 
							alt: desc, 
							src: imageObj.getImageUrl() 
						});
						$("#"+ prefix +"_prodImagePanelMainFlash").hide();
						$("#"+ prefix +"_prodImagePanelMainImage").show();	
					}
				} else {					
					$("#" + prefix + "_prodImagePanelMainImage").hide();
					$("#" + prefix + "_prodImagePanelMainFlash").show();
				}
				refreshLargerImageLink(imageObj);
			}
		}
		
		var refreshLargerImageLink = function(imageObj) {
			if (imageObj) {
				var imgType = imageObj.getZoomImageType();
				if (imgType) {
					if (imgType === 'QUICKVIEW' ||imgType === 'MAIN_PRODUCT' || imgType === 'LARGE') {
						mainProductImage.copyValues(imageObj);
						(imgType === 'MAIN_PRODUCT') ? showHideMainProductImageAnchor(true) :  showHideMainProductImageAnchor(false);
						showHideZoomImageAnchor(false);
					} else {
						zoomImage.copyValues(imageObj);
						showHideMainProductImageAnchor(false);						
					}
				} else {
					showHideMainProductImageAnchor(false);
					showHideZoomImageAnchor(false);
				}
			}
		}
		
		var showHideZoomImageAnchor = function(show) {
			(show) ? $("#zoomImageAnchor").show() : $("#zoomImageAnchor").hide();
			showHideProdImageLinkSeparator();
		}
		
		var showHideMainProductImageAnchor = function(show) {
			(show) ? $("#mainProductImageAnchor").show() : $("#mainProductImageAnchor").hide();
			showHideProdImageLinkSeparator();
		}
		
		var showHideLargeImageAnchors = function(show) {
			showHideMainProductImageAnchor(show);
			showHideZoomImageAnchor(show)
		}
		
		var showHidePlayVideoText = function(prefix, show){
			var embeddedProductVideoUrl = $("#"+ prefix +"_embeddedProductVideoUrl").val();
			if (embeddedProductVideoUrl && ("" !== embeddedProductVideoUrl)) {
				(show) ? $("#" + prefix + "_embeddedVideoImageAnchor").show() : $("#"+ prefix +"_embeddedVideoImageAnchor").hide();
			}
			showHideProdImageLinkSeparator();
		}
		
		var showHideProdImageLinkSeparator = function() {
			($("#prodImageAnchorContainer a").is(":visible") 
				&& $("#prodVideoImageAnchorContainer a").is(":visible")) 
			? $("#prodImageLinkSeparator").show() : $("#prodImageLinkSeparator").hide();
		}
		var populateAltImageThumbnails = function(prefix, mainImageData, mainAltImageData, altImagesData) {
			var div = $("#"+ prefix +"_AltImageThumbnailsCarouselContainer"),
				ul = $('<ul/>', { id: prefix + "_AltImageThumbnails" }).addClass("jcarousel-skin-standard");
			if (mainImageData) {
				var thumbCount = 0;
				thumbCount = populateAltImageThumbnail(prefix, ul, "mainImage", mainImageData, thumbCount);
				thumbCount = populateAltImageThumbnail(prefix, ul, "mainAlt", mainAltImageData, thumbCount);
				thumbCount = processAltImagesArray(prefix, ul, altImagesData, thumbCount);
				var lis = $(ul).find("li");
				if (lis.size()) lis.first().addClass("prodImageThumbSelected");				
				div.empty().append(ul);				
				if (typeof onQuickOrderForm != 'undefined' && onQuickOrderForm) {// this is true only for quick form					
					if (lis.length >= 1) $(ul).jcarousel({ vertical: true, visible: 4 });
				}else{
					if (lis.length >= MIN_CAROUSEL_SIZE) $(ul).jcarousel({ horizontal: true, visible: 4 });
				}
			} else {
				div.empty().append(ul);
				ul.hide();
			} 
		}
		var processAltImagesArray = function(prefix, altImgThumbs, altImagesData, thumbCount) {
			if (altImagesData) {
				for (var i=0; i<altImagesData.length; i++) {
					thumbCount = populateAltImageThumbnail(prefix, altImgThumbs, ("view" + i), altImagesData[i], thumbCount);
				}
			}
			return thumbCount;
		}
		var populateAltImageThumbnail = function(prefix, altImgThumbs, idPrefix, imageData, thumbCount) {
			if (imageData && imageData.thumbLocation) {
				thumbCount++;
				idPrefix = prefix + "_" + idPrefix;
				var li = createAltImageListItem(idPrefix, imageData.altText, imageData.thumbLocation, thumbCount),
					altImg = altImageMap[idPrefix];
				altImg = new ImageAnchorObject();
				altImg.setValues(imageData);
				var imgWrapper = {"img":altImg,"prefix":prefix};
				$(li).bind("click", imgWrapper, onclickAltImageThumb);
				altImgThumbs.append(li);
			}
			return thumbCount;
		}
		
		
		var createAltImageListItem = function(idPrefix, altText, imageLocation, thumbCount) {
			var id = idPrefix + "ThumbImageAnchor",
				imgTag = $('<img/>', { id: (idPrefix + "ThumbImage"), src: imageLocation, alt: altText }), 
				anchorTag = $('<a/>', { id: id, name: id, href: id, html: imgTag }),
				divTag = $('<div/>', { id: (idPrefix + "ThumbImageAnchorContainer"), html: anchorTag }),
				listItem = $('<li/>', { html: divTag });
			divTag.addClass("prodImageThumb");	
			listItem.addClass("prodImageThumb");
			listItem.attr('id', "celid_cms3r3_altImages_pos-" + thumbCount);
			return listItem;  
		}
		
		var scrollCarouselLast = function(prefix) {
			var altImgThumbs = $("#"+ prefix +"_AltImageThumbnails"),
				altImgItms = altImgThumbs.find("li"),
				len = altImgItms.length;
			setSelectedAltImg(prefix, altImgItms.last());
			if (len >= MIN_CAROUSEL_SIZE) {
				altImgThumbs.jcarousel('scroll', (len - 1));
			}	
		}
		
		var setSelectedAltImg = function(prefix, elem) {
			$("#"+ prefix +"_AltImageThumbnails li").removeClass("prodImageThumbSelected");
			elem.addClass("prodImageThumbSelected");
		}

		var showEmbeddedVideo = function() {}
		
		var getParamsForShowEmbeddedVideo = function() {}
		
		/*
		 * Image object type definition
		 */		
		var ImageAnchorObject = function() {
		
			/* Public functions */
			this.copyValues = function(imageObj) {
				if (imageObj) {
					imageType = imageObj.getImageType();
					imagePath = imageObj.getImageUrl();
					thumbImagePath = imageObj.getThumbImageUrl();
					zoomImageType = imageObj.getZoomImageType();
					zoomImagePath = imageObj.getZoomImageUrl();
					altText = imageObj.getAltText();
				}
			}
			this.setValues = function(imageData) {
				if (imageData) {
					setImageTypeAndPath(imageData);
					setZoomImagePath(imageData);
					thumbImagePath = imageData.thumbLocation;
					altText = imageData.altText;
				}
			}
			this.getImageType = function() { return imageType; }
			this.getImageUrl = function() {	return imagePath; }
			this.getThumbImageUrl = function() { return thumbImagePath;	}
			this.getZoomImageType = function() { return zoomImageType; }
			this.getZoomImageUrl = function() {	return zoomImagePath; }			
			this.getAltText = function() { return altText; }			
			
			/* Private variables */
			var imageType,
				imagePath,
				thumbImagePath,
				zoomImageType,
				zoomImagePath,
				altText;
			
			/* Private functions */
			var setImageTypeAndPath = function(imageData) {
				if (imageData.quickviewLocation){
					imageType = 'QUICKVIEW';
					imagePath = imageData.quickviewLocation;
				} else if (imageData.mainProductLocation) {
					imageType = 'MAIN_PRODUCT';
					imagePath = imageData.mainProductLocation;
				} else if (imageData.largeLocation) {
					imageType = 'LARGE';
					imagePath = imageData.largeLocation;
				} else if (imageData.zoomifyLocation) {
					imageType = 'ZOOM';
					imagePath = encodeURIComponent(imageData.zoomifyLocation);
				}
			}
			var setZoomImagePath = function(imageData) {
				if (imageData.zoomifyLocation) {
					zoomImageType = 'ZOOM';
					zoomImagePath = encodeURIComponent(imageData.zoomifyLocation);
				} else if (imageData.mainProductLocation) {
					zoomImageType = 'MAIN_PRODUCT';
					zoomImagePath = imageData.mainProductLocation;
				} else if (imageData.largeLocation) {
					zoomImageType = 'LARGE';
					zoomImagePath = imageData.largeLocation;
				}				
			}
		}
	};
	
	/* Initialise */
	if (!jdw.productDetailsQuickViewMedia) jdw.productDetailsQuickViewMedia = new jdw.ProductDetailsQuickViewMedia();
})();
/* complete : /javascript/productDetailsRedesign/quickView/productDetailsQuickViewMedia.js*/


/* combine : /javascript/productreviews/productReviewsLoader.js*/
//Used to asynchronously load bvapi.js - bvapiUrl must be declared in the page which uses it 
window.loadBazaarvoiceApi = function(callback) {
    if (window.$BV) {
        callback();
    } else {
        $.ajax({
            url: bvapiUrl,
            cache: true,
            dataType: "script",
            success: function() {
                $($BV.docReady);
                callback();
            }
        });
    }
};/* complete : /javascript/productreviews/productReviewsLoader.js*/


/* combine : /javascript/productDetailsRedesign/quickView/productDetailsQuickViewModal.js*/
/**
 * Code runs from within the quickViewModal to add some behaviour to the modal.
 * 
 */
var jdw = jdw || {};

jdw.QuickViewModal = function(){
	
	this.setup = function(prefix){
		$("div#" + prefix + "_continueToCheckout a").unbind('click').bind('click', continueToCheckout);
		
		if(!isTablet) {
			$("div#" + prefix + "_warrantyButtonContainer a").unbind('click').bind('click', function(event){
				event.preventDefault();
				var pdw = jdw.productDetailsWarranty;
				if(typeof pdw == 'undefined'){
					pdw = parent.jdw.productDetailsWarranty;
				} 
				pdw.showQuickviewWarranty(event, $(this).attr("href"),$(this).attr("title"));
			});
		} else {
			jdw.tabletModalsContainer.bindRelLinks($("div#" + prefix + "_warrantyButtonContainer"));
		}
	};
	
	var continueToCheckout = function(event){
		var urlString=$(this).attr("href");
		parent.location.href=urlString;
	}
	
};

if ( !jdw.quickViewModal ) {
	jdw.quickViewModal = new jdw.QuickViewModal();
}/* complete : /javascript/productDetailsRedesign/quickView/productDetailsQuickViewModal.js*/


/* combine : /javascript/mobile/common/actionTags.js*/
// actionTags.js

function writeDynamicTag( tagCode ) {
	if ( tagCode ) {
			$('#dynamicTagScript').append( '<script type="text/javascript">try { ' + tagCode + ' } catch(e){}</script>');
	}
}
//overture parameters 
var pm_tagname = "universalTag.txt";
var pm_accountid;
var pm_customargs;

//rocket fule vars
var cachebust = (Math.random() + "").substr(2);
//shopzilla parameters
var mid;
var cust_type;
var order_value;
var order_id;
var units_ordered;

//google parameters
var google_conversion_id;
var google_conversion_language = "en_GB";
var google_conversion_format = "1";
var google_conversion_color = "FFFFFF";
var google_conversion_value;
var google_conversion_label;


//doubleclick parameters
var axel = Math.random()+"";
var a = axel * 10000000000000;

//shopping.com
var merchant_id;
var order_id;
var order_amt;	
var category_id = "";
var category_name = "";
var product_id = "";
var product_name = "";

//nexTag
var id;
var rev;
var order;
var cats = "";
var prods = "";
var units = "";

// mediaplex CACHEBUSTER value
var mpt = new Date();
var mpts = mpt.getTimezoneOffset() + mpt.getTime();

//channel advisor checkout complete
function channel_adv_cc(clientId) {
	//channel advisor checkout complete
	document.writeln('<IMG SRC="https://tracking.searchmarketing.com/thankyou.asp?' +
		'SMCID='+ clientId +'&oVal='+ escape(jTotalValue) + 
		'&OrderID=' + escape(jOrderid) + 
		'&ProductID=' +	escape(jProductUids) + '" ' +
		'WIDTH="1" HEIGHT="1" BORDER="0">');		
}

// affiliate window dwin tag 
function affiliateWindow_dwin(merchantId) {
	$(document).ready(function() {
		var tag = '<script src="https://www.dwin1.com/'+merchantId+'.js" type="text/javascript" defer="defer"></script>';
		$('#dynamicTagScript').append(tag);
	  });  
}

//affiliate window checkout completed
function affiliateWindow_cc(merchantId) {
	(jNewWebCustomer == 'Y') ? customerType="new" : customerType="existing";
	affiliateWindow_cc_product(merchantId, customerType);

	document.writeln('<script type="text/javascript">');
	document.writeln('var AWIN={};');
	document.writeln('AWIN.Tracking={};');
	document.writeln('AWIN.Tracking.Sale={};');
	document.writeln('AWIN.Tracking.Sale.amount="' + escape(jTotalValue) + '";');
	document.writeln('AWIN.Tracking.Sale.currency="' + escape(jCurrency) + '";');
	document.writeln('AWIN.Tracking.Sale.orderRef="' + escape(jOrderid) + '";');
	document.writeln('AWIN.Tracking.Sale.parts="' + customerType + ':' + escape(jTotalValue) + '";');
	document.writeln('AWIN.Tracking.Sale.voucher="";');
	document.writeln('AWIN.Tracking.Sale.test="0";');
	document.writeln('</script>');
	document.writeln('<script src="https://www.dwin1.com/'+merchantId+'.js" type="text/javascript" defer="defer"></script>');
}

function affiliateWindow_cc_product(merchantId, customerType) {
	document.writeln('<form style="display:none;" name="aw_basket_form">');
	document.writeln('<textarea wrap="physical" id="aw_basket">');
	
	var productIds = jProductUidsMT.split("|");
	var productNames = jProductNamesMT.split("|");
	var productPrices = jProductPricesMT.split("|");	
	var productQuantities = jProductQuantitiesMT.split("|");		
	var d = '|';
		
	for (var i=0; i<productIds.length; i++ ) {
		var s = 'AW:P' + d 
			+ merchantId + d 
			+ jOrderid + d 
			+ productIds[i] + d 
			+ productNames[i] + d 
			+ productPrices[i] + d 
			+ productQuantities[i] + d 
			+ '' + d 
			+ customerType + d
			+ '';
		document.writeln(s);
	}
	document.writeln('</textarea>');
	document.writeln('</form>');
}

function google(conversion_id, label, conversion_format, conversion_value) {
    google_conversion_id =  conversion_id;
    google_conversion_value = conversion_value ? conversion_value : 1.0;
	google_conversion_label =  label;
	google_conversion_format = conversion_format;
}

function googleUrchin(code) {
    //_uacct = "UA-245925-1"; VLD
    //_uacct = "UA-245925-2"; PMA
    //_uacct = "UA-245925-3"; NAT    
    _uacct = code;
	urchinTracker();
}

function getProtocol() {
	return isSecureProtocol() ? "https://" : "http://";
}

function isSecureProtocol() {
	return location.href.indexOf("https") === 0;
}

function facebook_tracking(id, h) {
	try {  FB.Insights.impression({
	     'id': id,
	     'h' : h  });
	} catch (e) {}
}

//responsys checkout complete - UK titles
function responsys_cc_uk() {
	responsys_cc('X0Gzc2X%3DWQpglLjHJlTQGrizfmGfr2rsYHeAdeGcX6AO', 'Em6kwSd_Zf9OrW5gM0fktuw');	
}

//responsys checkout complete - IRISH titles
function responsys_cc_irish() {
	responsys_cc('X0Gzc2X%3DWQpglLjHJlTQGmwzai1azdqTT3w6zbzbsqRuzbzfG', 'EsiGhFlmEtiGNUyZwIdzjqM');	
}

//responsys checkout complete - common code.
function responsys_cc(firstParameter, secondParameter) {
	document.writeln('<img src="' + getProtocol() 
		+ 'link.e-comms.net/pub/cct?_ri_=' + firstParameter 
		+ '&_ei_=' + secondParameter 
		+ '&action=once'
		+ '&OrderID=' + escape(jOrderid)
		+ '&OrderTotal=' + escape(jTotalValue)
		+ '&numItems=' + escape(jQuantity)
		+ '&customerID=' + escape(jAccountid) 
		+ '&Type=purchase'
		+ '" height="1" width="1">');
}


// Responsys conversion pixel.
function responsys_conversionpixel_cc(id,seg){
	document.writeln('<script src="' + getProtocol() + 'secure.adnxs.com/px?id='+id+'&seg='+seg+'&order_id='+escape(jOrderid)+'&value='+escape(jTotalValue)+'&t=1" type="text/javascript"></script>');
}

//responsys signin complete cookie
function responsys_signin_complete() {
	document.writeln('<!-- BEGIN: Responsys Signin complete pixel -->');
	document.writeln('<script type="text/javascript" src="' + getProtocol() + 'tag.yieldoptimizer.com/ps/ps?t=s&p=1332&u=$lookup(CUSTOMER_ID_)$" async="true" defer></script>');
	document.writeln('<!-- END: Responsys Signin complete pixel -->');
}

//Responsys create customer (encrypted) email address image pixel.
function responsys_create_customer_email_address_pixel(){
	if (typeof(jEncryptedCustomerEmailAddressPixel) === "undefined"){
		// No encrypted customer email address pixel.
		return;
	}
	document.writeln(jEncryptedCustomerEmailAddressPixel);
}

//Get dressipi widget loader from Dressipi
//Is called by atlasActiontags.properties and takes widget functions as an array to be called
//after the widget_loader is finished and prevent sync problems.
function dressipiGetJS(dressipiFunctionsArray) {
	if(dressipiEnabled){
		$.getScript('https://' + dressipiHost + '/assets/widget_loader.js').done(function() {
			for (var i=0; i<dressipiFunctionsArray.length;i++) {
				dressipiFunctionsArray[i]();
			}
		});
	}
}

//Generate dressipi pdp size widget if the appropiate div exists (will only exist if properties
//enabled).
function dressipiPDPSizeWidget() {
	if (dressipiSizingWidgetEnabled) {
		Dressipi.initSizingWidget($("#dressipiPDPSizeWidget").get(0), {
			callback: function(element, message) {
				if (element && message && message === 'loaded') {
					element.classList.add("dressipiPDPSizeWidgetShow");
					element.classList.remove("dressipiPDPSizeWidgetHide");
				}
			},
			productCode: offeredProductId.substring(0, 5)
		});
	}
}
	
//Generate dressipi pdp outfit widget if the appropiate div exists (will only exist if properties
//enabled).
function dressipiPDPOutfitWidget() {
	if (dressipiPDPWidgetEnabled) {
		Dressipi.initOutfitsWidget($("#dressipiPDPOutfitWidget").get(0), {
			callback: function(element, message) {
				if (element && message && message === 'loaded') {
					element.classList.add("dressipiPDPOutfitWidgetShow");
					element.classList.remove("dressipiPDPOutfitWidgetHide");
				}
			}, 
			productCode: offeredProductId.substring(0, 5)
		});
		
	}
}

function dressipiPLPWidget(){
	$(document).ready(function(){
		if(plpWidgetEnabled && dressipiHierarchyPath) {
			if ($("#dressipiPLPWidget").is(':empty')) {
				Dressipi.initPlpWidget($("#dressipiPLPWidget").get(0), {
					callback: function(element, message) {
						if (element && message && message === 'loaded') {
							element.classList.add("dressipiPLPWidgetShow");
							element.classList.remove("dressipiPLPWidgetHide");
						}
					}, 
					plpType: dressipiHierarchyPath
				});	
			}
		}	
	});
}

function dressipiPLPTracking(){
	if(dressipiEnabled && typeof Dressipi != "undefined") {
        Dressipi.initPlpTracking({"listing": {"items":productArray, 
                           "filters": [] }, "page": {"breadcrumb": dressipiHierarchyPath}});
	}
}

//Generate dressipi view bag widget if the appropiate div exists (will only exist if properties
//enabled).
function dressipiViewBagWidget() {
	if (dressipiViewBagWidgetEnabled) {
		var itemsArray = [];
		if (dataLayer[0] && dataLayer[0].BagItems && dataLayer[0].BagItems.shoppingBagItems) {
			var bagEntries = dataLayer[0].BagItems.shoppingBagItems;
			for(var i=0; i<bagEntries.length; i++) {
				var itemRow = {};
				// dressipi SKU is a combination of productId and selected OptionId
				itemRow.id = bagEntries[i].productId.value+bagEntries[i].optionId.value;
				itemsArray.push(itemRow);
			}
			if (itemsArray.length > 0) {
				Dressipi.initShoppingBasketWidget($("#dressipiViewBagWidget").get(0),{
					callback: function(element, message) {
						if (element && message && message === 'loaded') {
							element.classList.add("dressipiViewBagWidgetShow");
							element.classList.remove("dressipiViewBagWidgetHide");
						}
					},
					items: itemsArray
				});	
			}
		} 
	}
}/* complete : /javascript/mobile/common/actionTags.js*/


