/* 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/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/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/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/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/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/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/productDetailsRedesign/quickView/productDetailsQuickviewMultibuy.js*/
var jdw = jdw || {};
var caro;
var isMultiBuy = false;

jdw.addMultiBuyEventsQuickViewEvents = function() {
	isMultiBuy = true;
	quickView = window != window.parent ? parent.jdw.quickView : jdw.quickView;
	
    caro = {
        viewport:$('#amplCaroViewport'),
        slide:$('#amplCaroSlide'),
        frames:$('#amplCaroSlide .ampl-caro-frame'),
        ctrlLft:$('#amplCaroCtrlLft'),
        ctrlRgt:$('#amplCaroCtrlRgt'),
        currentIndex:0,
        ajaxProductUrl:[],
        ajaxFullProductUrl:[],
        ajaxProductCode:[],
        totalProducts:$('.ampl-thumbs li').length - 1
    };
        
        
    caro.ctrlLft.click(function() {
        if(caro.currentIndex > 0) {
            caro.currentIndex -= 1;
        }

        animateCarousel();
    });
    
    caro.ctrlRgt.click(function() {
        if(caro.currentIndex < caro.totalProducts) {
            caro.currentIndex += 1;
        }
        
        animateCarousel();
    });
    
    $('.ampl-thumbs li').each(function(i) {
        var thumb = $(this),
        thumbIndex = i;
        
        caro.ajaxProductUrl[i] = thumb.attr('data-url');
        caro.ajaxFullProductUrl[i] = thumb.attr('data-fullDetailsUrl');
        caro.ajaxProductCode[i] = thumb.attr('data-productCode');
        
        thumb.click(function() {
            caro.currentIndex = thumbIndex;
            animateCarousel();
        });
        
        if(thumbIndex === 0) {
            thumb.trigger('click'); 
        }
    });
    
    function animateCarousel() {
    	var prefix = "multibuy_" + caro.ajaxProductCode[caro.currentIndex] ;
        $('.ampl-thumb-active').removeClass('ampl-thumb-active');
        $('.ampl-thumbs li').eq(caro.currentIndex).addClass('ampl-thumb-active');
        
    	$('#' + prefix + '_fitting').remove();
    	$('#' + prefix + '_optionColour').remove();
    	$('#' + prefix + '_optionSize').remove();
    	$('#' + prefix + '_mainImage').remove();
    	location.hash="";
    	
    	quickView.setSeoProductDetailsURL(caro.ajaxFullProductUrl[caro.currentIndex] + "&pageName=" + pageName);
    	
    	var prodUrl = caro.ajaxProductUrl[caro.currentIndex];
    	
    	caro.frames.each(function(n) {
			$(this).removeClass('visible');
    	});
    	
    	$.get(caro.ajaxProductUrl[caro.currentIndex], function(data) {
            caro.frames.each(function(n) {
				$(this).empty();
	    	});

	        caro.frames.eq(caro.currentIndex).html(data);
	        $(caro.frames[caro.currentIndex]).addClass('visible');
	        attachProductDetailsOptionsEvents(prefix);
	       
        });
              
        caro.ctrlLft.show();  
        caro.ctrlRgt.show();
        
        if(caro.currentIndex === caro.totalProducts) {
            caro.ctrlRgt.hide();
        }
        
        if(caro.currentIndex === 0) {
            caro.ctrlLft.hide();   
        }
        
        prodCode = prodUrl.split("pdLpUid=");
        prodCode = prodCode[1].substring(0, 5);
        
      }
    
    $('#quickBuyModalClose, #modal_overlay').click(function() {
    	isMultiBuy = false;
    	$('body').removeClass('freezeScroll');
        closeModalJQ(function() {
        	$('#modal_outer').removeClass('multiBuyModal');
        });
    	if(typeof onCloseModal !== 'undefined') {
			options.onClose = onCloseModal();
		}
    });
};

jdw.initiateMultiBuy = function() {
    $('.ampl-test-link').each(function() {
        var multiBuyUrl = $(this).attr('href');
        $(this).attr('href','javascript:void(0)');
        $(this).click(function() {
        	jdw.openMultiBuyModal(multiBuyUrl);
        });
    });
};

jdw.openMultiBuyModal = function(multiBuyUrl) {
	$.ajax({
		url: multiBuyUrl,
		type: 'GET',
		success: function(data) {
			$('body').addClass('freezeScroll');
			jdw.multibuyModal = openModalJQ(data, multiBuyUrl,null, false, false, { hideHeader:true, hideFooter:true, width:820 });
	        jdw.addMultiBuyEventsQuickViewEvents();
	        $('#modal_outer').addClass('multiBuyModal');
		},
		error: function(data) {
			jdw.multibuyModal = openModalJQ(data.responseText, multiBuyUrl,null, false, false, { hideHeader:true, hideFooter:true, width:930 });
			$('#modal_container').prepend('<div id="quickBuyModalClose" class="ampl-modal-close">X</div>');
			$('#quickBuyModalClose, #modal_overlay').click(function() {
		        closeModalJQ();
		    });
		}
    });
};

jdw.openPLPMultiBuyModal = function(multiBuyUrl) {
	$.ajax({
		url: multiBuyUrl,
		type: 'GET',
		beforeSend: function(data) {
            $('body').prepend('<div id="spinner_container"><div class="progress"><div></div></div></div>').addClass('freezeScroll');
        },
		success: function(data) {
			$('body').addClass('freezeScroll');
			jdw.multibuyModal = openModalJQ(data, multiBuyUrl,null, false, false, { hideHeader:true, hideFooter:true, width:820 });
	        jdw.addMultiBuyEventsQuickViewEvents();
	        $('#modal_outer').addClass('multiBuyModal');
	        $('#spinner_container').remove();
		},
		error: function(data) {
			jdw.multibuyModal = openModalJQ(data.responseText, multiBuyUrl,null, false, false, { hideHeader:true, hideFooter:true, width:930 });
			$('#modal_container').prepend('<div id="quickBuyModalClose" class="ampl-modal-close">X</div>');
			$('#quickBuyModalClose, #modal_overlay').click(function() {
		        closeModalJQ();
		    });
			$('#spinner_container').remove();
		}
    });
};

function handleAjaxResultForMultiBuyAddToBagAndConversionTag(dataStr) {
	if (dataStr.model.addStatus == addedToBagAddStatus || dataStr.model.addStatus == addedToBagTFStatus ) {
		$('#multiBuyCheckout').show();
	}
	handleAjaxResultForAddToBag(dataStr);
}

$(document).ready(jdw.initiateMultiBuy);

/* complete : /javascript/productDetailsRedesign/quickView/productDetailsQuickviewMultibuy.js*/


/* combine : /javascript/productdetails/desktop/quickView/productDetailsQuickviewSingle.js*/
var jdw = jdw || {};

jdw.addQuickViewEvents = function() {
    $('#quickBuyModalClose, #modal_overlay').click(function() {
        $('body').removeClass('freezeScroll');
        closeModalJQ(function() {
            $('#modal_outer').removeClass('singleBuyModal');      
        });
        if(typeof onCloseModal !== 'undefined') {
            onCloseModal();
        }
    });
};

jdw.initiateQuickView = function() {
    $('.ampl-singletest-link').each(function() {
        var singleBuyUrl = $(this).attr('href');
        $(this).attr('href','javascript:void(0)');
        $(this).click(function() {
            jdw.openSingleBuyModal(singleBuyUrl);
        });
    });
};

jdw.openSingleBuyModal = function(singleBuyUrl) {
    $.ajax({
        url: singleBuyUrl,
        type: 'GET',
        beforeSend: function(data) {
            $('body').prepend('<div id="spinner_container"><div class="progress"><div></div></div></div>').addClass('freezeScroll');
        },
        success: function(data) {
            jdw.singleBuyModal = openModalJQ(data, singleBuyUrl,null, false, false, { hideHeader:true, hideFooter:true, width:500 });            
            /* Really bad way to handle error page. If the call has not returned a product then run the error */
            if (!$('[id$="_optionsForm"]').length) {
                handleError(data);
                return;
            }            
            jdw.addQuickViewEvents();
            //18 is the index where the prefix ends in the form id
            var prefix = $('[id$="_optionsForm"]').attr("id").substring(0,18);
            attachProductDetailsOptionsEvents(prefix);
            $('#modal_outer').addClass('singleBuyModal');
            $('#spinner_container').remove();
        },
        error: handleError = function(data) {
            jdw.singleBuyModal = openModalJQ(data.responseText, singleBuyUrl,null, false, false, { hideHeader:true, hideFooter:true, width:500 });
            $('#modal_container').addClass('quickview-no-product').prepend('<div id="quickBuyModalClose" class="ampl-modal-close">Close</div>');
            jdw.addQuickViewEvents();
            $('#spinner_container').remove();
        },
        complete: function() {
            $('#spinner_container').remove();
        }
    });
    
};

jdw.openPLPSingleBuyModal = function(singleBuyUrl) {
    $.ajax({
        url: singleBuyUrl,
        type: 'GET',
        beforeSend: function(data) {
            $('body').prepend('<div id="spinner_container"><div class="progress"><div></div></div></div>').addClass('freezeScroll');
        },
        success: function(data) {
            jdw.singleBuyModal = openModalJQ(data, singleBuyUrl,null, false, false, { hideHeader:true, hideFooter:true });            
            /* Really bad way to handle error page. If the call has not returned a product then run the error */
            if (!$('[id$="_optionsForm"]').length) {
                handleError(data);
                return;
            }            
            jdw.addQuickViewEvents();
            //18 is the index where the prefix ends in the form id
            var prefix = $('[id$="_optionsForm"]').attr("id").substring(0,18);
            attachProductDetailsOptionsEvents(prefix);
            $('#modal_outer').addClass('singleBuyModal');
            $('#spinner_container').remove();
        },
        error: handleError = function(data) {
            jdw.singleBuyModal = openModalJQ(data.responseText, singleBuyUrl,null, false, false, { hideHeader:true, hideFooter:true });
            jdw.addQuickViewEvents();
            $('#spinner_container').remove();
        },
        complete: function() {
            $('#spinner_container').remove();
        }
    });
    
};

function handleAjaxResultForSingleBuyAddToBagAndConversionTag(dataStr) {
       handleAjaxResultForAddToBag(dataStr);
}

$(document).ready(jdw.initiateQuickView);
/* complete : /javascript/productdetails/desktop/quickView/productDetailsQuickviewSingle.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/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/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/jdw_ajax.js*/
$.fn.Sleep = function(duration, callback) {
	if(!callback)callback=function(){return false;};
	$(this).animate({dummy:1}, duration, callback);
	return this;
};
	
var modalLinkStack=[];       

var modalDefaults = {
	delay: 300,
	width : 500,
	height: 300,
	controlsHeight: 50,
	headerHeight: 50,			
	scrollTop: 60,			
	controls : '',
	closeDefault : '<div class="modalButtonClose modalButtonCloseFooter"><div class="modalButton"><div class="buttonCapLt"></div><a href="#" alt="Click to close this window" title="Click to close this window">Close this window</a><div class="buttonCapRt"></div></div></div>',
	backDefault : '<div class="modalButtonBack" id="modalButtonLeft" style="display:none;"><div class="modalButton"><div class="buttonCapLt"></div><a id="modalBackAnchor" href="#" alt="Click to Go Back" title="Click to go back">Back</a><div class="buttonCapRt"></div></div></div>',
	overlayClose : 'true', 
	backButton : 'true',
	nonModal: 'false'
};
			
var modalFunctions = {
	create : {
		container : function (data, showScrollbars, options) {			
			var new_overlay = 0;
			if($('#modal_overlay').size() == 0) {
				$('body').append('<div id="modal_overlay" style="display: none"></div>');
				$('body').append('<div id="modal_coremetrics_node" style="display: none"></div>');
				$('body').append('<div id="modal_outer" style="display: none"></div>');
				$('#modal_outer').append('<div id="modal_container" class="displayOverlay modal_container">' + data + '</div>');
				var new_overlay = 1;
			} else {
				$('#modal_outer').find('#modal_container').html(data);
			}

			$('#modal_overlay').css({'width':'100%'});
			if(jdBrowser.msie == true) {
				$('#modal_overlay').fadeTo(1, 0.8);
			}
			
			var modalParam = $('#modal_outer').find('#modalParam');
			
			if($('#modal_outer').find('#modalParam').attr('title'))
				modalDefaults.title = modalParam.attr('title');
			if($('#modal_outer').find('#modalParam').attr('overlayClose'))
				modalDefaults.overlayClose = modalParam.attr('overlayClose');
			if($('#modal_outer').find('#modalParam').attr('backButton'))
				modalDefaults.backButton = modalParam.attr('backButton');
			if($('#modal_outer').find('#modalParam').attr('nonModal'))
				modalDefaults.nonModal = modalParam.attr('nonModal');
			if($('#modal_outer').find('#modalParam').attr('width'))	
				modalDefaults.width = modalParam.attr('width');
			if($('#modal_outer').find('#modalParam').attr('height'))
				modalDefaults.height = modalParam.attr('height');
			if($('#modal_outer').find('#modalParam').attr('controlsHeight'))
				modalDefaults.controlsHeight = modalParam.attr('controlsHeight');
			if($('#modal_outer').find('#modalParam').attr('scrollTopValue')) {
				modalDefaults.scrollTop = parseInt(modalParam.attr('scrollTopValue'));
		    }
		    
		    if(options && options.height) {
		    	modalDefaults.height = options.height;
		    }if(options && options.width) {
		    	modalDefaults.width = options.width;
		    }
			
			var marginLeft;	
            if($('#modal_outer').find('#modalParam').attr('marginLeft')){
				marginLeft =  parseInt(modalParam.attr('marginLeft'));
			} else {
			 	 marginLeft = -(modalDefaults.width/2);
			}				
			
			var outerHeight = parseInt(modalDefaults.height) + parseInt(modalDefaults.controlsHeight) + parseInt(modalDefaults.headerHeight);
			$('#modal_outer').css({'height': outerHeight + 'px','margin-left' : marginLeft + 'px', 'margin-top' : '-' + (outerHeight/2) + 'px'});
			$('#modal_outer').css({'position':'absolute', 'top': ($(window).scrollTop() + modalDefaults.scrollTop)+'px', 'marginTop': '0px'})
			
			var overflow = 'hidden';
			if(showScrollbars) {
			    overflow = 'auto';
			}
			var backgroundColor = $('#modal_outer').find('#modal_container').css("backgroundColor");
			if($('#modal_outer').find('#modalParam').attr('backgroundColor')) {
				backgroundColor = modalParam.attr('backgroundColor');
		    }
			var border = $('#modal_outer').find('#modal_container').css("border")
			if($('#modal_outer').find('#modalParam').attr('border')) {
				border = modalParam.attr('border');
		    }
			var height = $(document).height();
			$('#modal_overlay').css({'position':'absolute', 'height': height});
			
			if(jdBrowser.msie){
				var modalContainerCSS = $('#modal_outer').find('#modal_container');
				var paddingtop = modalContainerCSS.css('padding-top').split("px")[0];
				var paddingbottom = modalContainerCSS.css('padding-bottom').split("px")[0];
	 		
				modalDefaults.height = parseInt(modalDefaults.height) + parseInt(paddingtop);
			}
			
			var modalContainer = $('#modal_outer').find('#modal_container');
			if ( typeof border != 'undefined' ){
				modalContainer.css({'height': (modalDefaults.height-20) + 'px', 'width': (modalDefaults.width-20) + 'px', 'overflow': overflow, 'backgroundColor': backgroundColor, 'border': border + 'px'});
			} else {
				modalContainer.css({'height': (modalDefaults.height-20) + 'px', 'width': (modalDefaults.width-20) + 'px', 'overflow': overflow, 'backgroundColor': backgroundColor});
			}
			
		}, header :	function (options) {
			
			var hideHeader = options ? options.hideHeader : false;
			if(!hideHeader) {
				if($('#modal_outer').find('#modal_header').size() == 0) {
					if ( typeof modalDefaults.title != 'undefined' ){
						$('#modal_outer').prepend('<div id="modal_header"><p class="title"></p></div>');
					} else {
						$('#modal_outer').prepend('<div id="modal_header"></div>');
					}
					
					if(options && options.closeButtonHeader) {
						$('#modal_header').append('<div class="modalButtonClose"><div class="buttonCapLt"></div><a style="cursor:pointer;">Close this window</a><div class="buttonCapRt"></div></div>');
					}
					
					if ( typeof modalDefaults.title != 'undefined' ){
						$('#modal_outer').find('#modal_header').find('.title').html(modalDefaults.title);
					}
					$('#modal_outer').find('#modal_header').css({'width': (modalDefaults.width-12) + 'px'});
				}	
			}
		}, footer : function(options) {
			
			var hideFooter = options ? options.hideFooter : false;
			if(!hideFooter) {
				modalDefaults.controls = modalFunctions.getModalControls(options);
				
				if($('#modal_outer').find('#controls').html()) {
					modalDefaults.controls = $('#modal_outer').find('#controls').html();
					$('#modal_outer').find('#controls').remove();
				}
				
				if($('#modal_outer').find('#modal_control').size() == 1)
					$('#modal_outer').find('#modal_control').remove();
				
				$('#modal_outer').append('<div id="modal_control">' + modalDefaults.controls + '</div>');
				$('#modal_outer').find('#modal_control').css({'width': (modalDefaults.width-20) + 'px'});
			}
		}, closeBtn : function (options) {
			var disableClose = options ? options.disableClose : false;
			if (modalDefaults.overlayClose == 'false' || disableClose) {
				$('.modalButtonClose').hide();
			}
			if(options && !options.closeButtonFooter) {
				$('.modalButtonCloseFooter').hide();
			}
		}, backBtn : function (disableClose, showScrollbars) {
		   	if (modalLinkStack.length > 1 && modalDefaults.backButton=='true'){		   		
		   		var options = {
		   				fromBack: true,
		   				scrollbars: showScrollbars,
		   				closeButtonFooter: !disableClose
		   		};
		   		$('#modalBackAnchor').attr("modalBack", true);
		   		$('#modalBackAnchor').click(function() {
		   			jdwModal.displayModalFromUrl(modalLinkStack[modalLinkStack.length - 2], options);
		   		});
		   		//fade in 
		   		$('.modalButtonBack').show();	  	
  	       } 
		}	
	}, executeModal : function (data, disableClose, showScrollbars, options) {
	    if (getIEVersionNumber() <= 6) {
			setSelects("hidden");
		}
				
		if($('#modal_outer').find('#modal_container').size() == 1) {
			$('#modal_overlay').animate({opacity: 0.7}, 200, function () {
				$('#modal_overlay').animate({opacity: 0.8}, 200);
			});					
			
			this.create.container(data, showScrollbars, options);
						
			modalDefaults.controls = modalFunctions.getModalControls(options);
			
			if($('#modal_outer').find('#modal_container').find('#controls').html()) {
				modalDefaults.controls = $('#modal_outer').find('#modal_container').find('#controls').html();
				$('#modal_outer #modal_container #controls').fadeIn();
			}
			
			if(!options || !options.hideFooter) {
				$('#modal_outer').find('#modal_control').html(modalDefaults.controls);
			}
			
			this.create.header(options);
			$('#modal_outer').find('#modal_control').remove();
			this.create.footer(options);
   			this.create.closeBtn(options);
			this.create.backBtn(disableClose, showScrollbars);
		} else {
			this.create.container(data, showScrollbars,options);
			this.create.header(options);
			this.create.footer(options);
			this.create.closeBtn(options);
			
			if (typeof onPCMPage != 'undefined') {
				setTimeout(function() {
					$('#modal_overlay, #modal_outer').animate({opacity: 'show'}, 10, function () {
						$('#modal_overlay').animate({opacity: 0.8}, 350, 'linear', function(){
							$('.modalLoadFocus').first().focus();
							// Amplience workaround, adding a callback function is the long term solution
							$("#fitting").cssDropdown();
							$("#optionColourSelect").cssDropdown();
							$("#optionSizeSelect").cssDropdown();
						});
					}); 
				}, 500);				
			} else {
				setTimeout(function() {
					$('#modal_overlay, #modal_outer').animate({opacity: 'show'}, 10, function () {
						$('#modal_overlay').animate({opacity: 0.8}, 350, 'linear', function(){$('.modalLoadFocus').first().focus();});
					}); 
				}, 500);				
			}	
		}

		
		$('#modal_outer #modal_container').scrollTop(0);
		
		if(options && options.onSuccess) {
			options.onSuccess();
		}

	}, getModalControls : function(options) {

			var continueUrl; 
			var continueText; 
			var nextButton;
			var backButton = modalDefaults.backDefault;;
			var continueButton;
			var closeButton = modalDefaults.closeDefault;
			
			if(options) {
				continueUrl = (options.continueUrl ? options.continueUrl : null);
				continueText = (options.continueText ? options.continueText : 'Continue');		
			
				if(options.backText) {
					backButton = '<div class="modalButtonBack" id="modalButtonLeft" style="display:none;">' +
								 '<div class="modalButton"><div class="buttonCapLt"></div><a id="modalBackAnchor" ' +
								 'href="#" alt="Click to Go Back" title="Click to go back">' + options.backText + '</a>' +
								 '<div class="buttonCapRt"></div></div></div>';
				} 
				
				if(continueUrl) {
					continueButton = '<div class="btn primaryBtn icon-tick" id="modalButtonRight"><div class="modalButton">' +
								 	 '<div class="buttonCapLt"></div><a id="modalContinueAnchor" ' + 
								 	 'onclick="'+ continueUrl + '"' + 
								 	 ' alt="Click to move forward" title="Click to move forward">' + continueText + 
								 	 '</a><div class="buttonCapRt"></div></div></div>';
				}
			
				if(options.closeText) {
					closeButton = '<div class="modalButtonClose" id="modalButtonLeft">' +
								  '<div class="modalButton"><div class="buttonCapLt"></div><a id="modalBackAnchor" ' +
								  'href="#" alt="Click to close" title="Click to close">' + options.closeText + '</a>' +
								  '<div class="buttonCapRt"></div></div></div>';
				} 
			}	
			
			var controls;
			if(backButton)
				controls = backButton;
				
			if(continueButton)
				controls+=continueButton;
			
			if(closeButton)
				controls+=closeButton;
				
			return controls;
	}
}

function getIEVersionNumber() {
	if (/MSIE\s(\d+\.\d+);/.test(navigator.userAgent)) {
   		return new Number(RegExp.$1);
	} else {
   		return 999;
	}
}

function setSelects(visibility) {
    selects = document.getElementsByTagName('select');
    for(i = 0; i < selects.length; i++) {
        selects[i].style.visibility = visibility;
    }
}

function openModalJQ(data, url, fromBack, disableClose,  showScrollbars, options) {
	reset();	
	if(url)
		updateLinkStack(url, fromBack);   
   	    
    modalFunctions.executeModal(data, disableClose, showScrollbars, options);
    
    return false;
}

var closeModalDuration = 350;
function closeModalJQ() {
	$('#modal_overlay, #modal_outer').animate({opacity:'hide'}, closeModalDuration, function () { $(this).remove(); });
	if (getIEVersionNumber() <= 6) {
		setSelects("visible");
	}	
	if(jdBrowser.msie == true) {
		$('body, html').css({'overflow':''});
		$('body, html').attr('style', '');
	}
	
	setTimeout(function () {
			if(typeof yourvar != 'undefined' && jdwModalOptions.onClose) {
				jdwModalOptions.onClose();
			}
		
			// clear stored links
			modalLinkStack = [];	
			jdwModalOptions = {};
		}, closeModalDuration + 500);
}

function enableCloseModalJQByClickingOutsideBorder(callBack) {
	/* Close overlay by clicking anywhere outside it's borders do this here so 
	when you close the overlay you go back to the home page. */		
	$('body').on('click', callBack, window.clickAnyWhereClickHandler);
}

function clickAnyWhereClickHandler(e){ 	// Add new event handler
	if($('#modal_overlay').size()!=0 && $(e.target).closest('.orderContainer').length==0){
		$('body').die('click', window.clickAnyWhereClickHandler); // Unbind default event handler defined in jdw_ajax.js
		closeModalJQ();
		//The call back function name is passed in as a string,
		//so the .on() function does not execute with 2 params, but uses 3 params.
		var clickAnyWhereCallBack = e.data;
		if (clickAnyWhereCallBack) {
			eval(clickAnyWhereCallBack + "()");
		}
	}
}

function disableCloseModalJQByClickingOutsideBorder(){
	$('body').die('click', window.clickAnyWhereClickHandler);	
}

function updateLinkStack(url,fromBack){
	// if not modal back button
    if (url && !fromBack) {
    	pushLink(url);
    } else if(fromBack) {
    	popLink();
    }
}

function pushLink(url) {		
	//push link onto stack
	if(modalLinkStack.length==0){
	  	modalLinkStack[0] = url;
	}else{
	 	modalLinkStack[modalLinkStack.length] = url;
	}
}

function popLink(){
	//pop link from stack
	modalLinkStack.splice(modalLinkStack.length - 1,1);
}

function reset(){
   	modalDefaults.backButton='true';
   	modalDefaults.overlayClose='true';
   	modalDefaults.nonModal='false';
}

$(document).on('click', '.modalButtonClose', function(event){
	event.preventDefault(); 
	closeModalJQ(); 
	
	var onCloseFunctionName = $(this).attr('onClose');
	if ( onCloseFunctionName ) {
		eval( onCloseFunctionName + '()' );
	}
});

$(window).resize(function(){
		$('#modal_outer, #prodImageZoomify').css({'position':'absolute', 'top': ($(window).scrollTop() + 60)+'px', 'marginTop': '0px'})
		
		var height = $(document).height();
		var width =  $(document).width();
		$('#modal_overlay').css({'position':'absolute', 'height': height, 'width' : width });
});

function checkForRedirect(xmlHttpRequest) {
	var redirectUrl = xmlHttpRequest.getResponseHeader('REDIRECT_URL');
	if (redirectUrl == null || redirectUrl.length == 0) {
		return true;
	} else {
		location.href = redirectUrl;
	}
}

function getUniqueClass(selected) {
   	var uniqueID = new Date().getTime() + "Class";
   	$(selected).addClass(uniqueID);
   	
   	return uniqueID;
}

function ajaxGet(selected, successCallback, url) {
   	
   	if (!url) {
		var url = $(selected).attr('href');
	}
	
	if (!successCallback.hideUpdatingOverlay) {
	    overlay.create({'msg':'Updating', 'showDelay' : 1000, 'trigger': getUniqueClass(selected)});
	}

	var xhtmlRequest = $.get(url, function (data) {
		closedelay = overlay.closeOverlay();
	    if (checkForRedirect(xhtmlRequest)) {
	       successCallback(data);	
	    }
	});	
}

var closedelay;

function performAjaxRequest( urlString, beforeSendFunction, onCompleteFunction, dataType, data,
						onSuccessFunction, onErrorFunction, sendMethod, triggerData, 
						sessionTimeoutFunction ) {
	var xhtmlRequest;
	var createUpdatingOverlay = true;
	
	// Default blank value of sendMethod to explicitly say 'GET' as a blank value seems to upset the
	// android browser.
	if(!sendMethod) {
		sendMethod = 'GET';
	}
	
	if (beforeSendFunction && beforeSendFunction.hideUpdatingOverlay) {
		createUpdatingOverlay = false;
	}
	
	var options = {
		url: urlString,
		beforeSend: function(data) {
			if (createUpdatingOverlay) {
			    overlay.create({ trigger:triggerData,
			    				 cssStyle:{height:'100%',marginLeft:'0px', marginTop:'0px',width:'100%'}, msg : 'Please Wait'});
			}
			if ( dataType ) {
				data.setRequestHeader( 'ajaxDataType', dataType );
			}
			if (beforeSendFunction) {
				var result = beforeSendFunction(data);
				if(result == false) {
					closedelay = overlay.closeOverlay();
				}
					
				return result;
			}
		},
		complete: function(data) {
			closedelay = overlay.closeOverlay();
			if (onCompleteFunction) {
				onCompleteFunction(data);
			}
		},
		dataType: dataType,
		data: data,
		contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		success: function(data) {
			var dataType = xhtmlRequest.getResponseHeader('ajaxDataType');
			if ( 'json' === dataType ) {
				// For requests that expect a json response, session timeouts can be a problem
				//  since the redirect check below this code will return html.
				if ( data.isSessionTimeout ) {
					if ( sessionTimeoutFunction ) {
						sessionTimeoutFunction( data );
					} else {
						window.location = "/shop/session/timeout/sessionTimeout.action";
					}
					return;
				}
			}
			if (checkForRedirect(xhtmlRequest)) {
				if(onSuccessFunction) {
					onSuccessFunction(data, urlString);
				}
			}
		},
		error: function(data) {
			if(onErrorFunction) {
				onErrorFunction(data);
			} else {
				window.location = "/shop/session/timeout/sessionTimeout.action";
			}
		},
		type: sendMethod
	};
	
	xhtmlRequest = $.ajax(options);
}

		/* complete : /javascript/common/libraries/jdw_ajax.js*/


/* combine : /javascript/desktop/common/jdw_Modal.js*/
/* Facade to provide a simplified interface to display modal windows. */

var jdwModalOptions = {};

var jdwModal = function() {
	return {
	
		/*  Displays a modal window using the provided data.
		 *  ---------------------------------------------------------------
		 *	
		 *	data : 		A String of data to be displayed.
		 *			
		 *	options:	Object containing named options as appropriate.
		 *			
		 *	Available options are:
		 *	----------------------
		 *	continueUrl:	when continue button is clicked the modal will close and navigate to this URL. If not specified button will be hidden.
		 *	continueText:	the text displayed on the continue button default is 'Continue'.
		 *	closeText:		the text displayed on the close button. Default is 'Close'.
		 *  fromBack:		
		 *  hideClose:		hides the close button if true
		 *  closeButtonHeader: determines if we have a close button in the header
		 *  closeButtonFooter:		show a close button in the footer
		 * 	onSuccess: callback function
		 *  onClose:				function to call when the modal closes.
		 */	 		 
		displayModalFromData : function(data,options) {		
			var fromBack = false;
		 	var hideClose = false;
		 	if(options.fromBack) {
		 		fromBack = true;
		 		hideClose = true;
		 	}
			if(options && options.onClose) {
				jdwModalOptions.onClose = options.onClose;
			}
			openModalJQ(data,null,fromBack,hideClose,false,options); 		
		},
		
		/**  Displays a modal window retrieving the data from the given URL.
		 *  ---------------------------------------------------------------
		 *	
		 *	url : 		The url providing the data to display within the modal.  This can
		 *				also be a simple string to display in the modal.
		 *			
		 *	options:	Object containing named options as appropriate.
		 *			
		 *	Available options are:
		 *	----------------------
		 *	continueUrl:			when continue button is clicked the modal will close and navigate to this URL. If not specified button will be hidden.
		 *	continueText:			the text displayed on the continue button default is 'Continue'.
		 *	closeText:				the text displayed on the close button. Default is 'Close'.
		 *	backText:				the text displayed on the back button. Default is 'Back'.	
		 *	buttons:				an HTML snippet specifying the buttons that will appear (overrides all other options to do with buttons).		
		 *	hideBack:				force hiding of the back button.
		 *	hideClose:				force hiding of the close button.
		 * 	hideHeader:				hide the top panel where the title goes.
		 *  hideFooter:				hide the bottom panel where the buttons are.
		 *  onClose:				function to call when the modal closes.
		 *  width:					the width of the modal
		 *  height:					the height of the modal
		 *  closeButtonHeader:		show a header with a close button
		 *  closeButtonFooter:		show a close button in the footer
		 *  scrollbars:				show scrollbars on the modal
		 *  triggerData :			class name of a div for the updating overlay to cover
		 */	 
		displayModalFromUrl : function(url,options) {		
						
			var fromBack = (options ? options.fromBack : false);
			var hideClose = (options ? options.hideClose : false);
			var scrollbars = (options ? options.scrollbars : false);
					
			if(options && options.onClose) {
				jdwModalOptions.onClose = options.onClose;
			}
			
			var successCallback = function(data) {
				openModalJQ(data,url,fromBack,hideClose,scrollbars,options); 
			};
			
			var errorCallback = function(data) {
				if (data.status == 0) {
					openModalJQ('An unexpected error has occurred.  Please close this box and try again.',url,fromBack,hideClose,false,options); 
				}
			}
						
			performAjaxRequest(url,options.beforeSendFunction,null,null,null,successCallback,errorCallback,'GET',options.triggerData);	
		}
	}
}();/* complete : /javascript/desktop/common/jdw_Modal.js*/


