﻿
$(document).ready(function () {
    // File location constants
    var IconsDirectory = '/assets/en/site/icons/';
    var HeroImageMissingFile = $('#missing_image_large_path').val();
    var FabricImageFormat = IconsDirectory + '{0}-Swatch.gif';
    var FabricMissingSwatch = IconsDirectory + 'missing-Swatch.gif'
    var MissingColourSwatch = IconsDirectory + 'missing-colour.gif';
    var MissingSelColourSwatch = IconsDirectory + 'missing-colour-S.gif';
    var clickToZoomCaption = $('#hdnClickToZoomCaption').val();
    var noZoomImageCaption = $('#hdnNoZoomImageCaption').val();
    var flashWidth = $('#flash_width').val();
    var flashHeight = $('#flash_height').val();

    var alternativesExist;
    var VariantClicked;


    // Variables for flash zoom
    //Write flash file to DOM
    //flashvars need to be set according to image required
    var flashvars = {
        lowResImage: HeroImageMissingFile,
        highResImage: HeroImageMissingFile,
        width: flashWidth,
        height: flashHeight
    };
    var params = {
        wmode: "transparent",
        menu: "false",
        align: "left",
        swfLiveConnect: "true",
        allowScriptAccess: "always",
        allowFullScreen: "true",
        quality: "high"
    };
    var attributes = {
};

function showFlashObject() {
    swfobject.embedSWF("/assets/script/ImageMain.swf", "image-zoom", flashWidth, flashHeight, "10.0.0", "", flashvars, params, attributes);
};

// show the flash image - initially missing image
showFlashObject();
// can't zoom initially
$('#image-zoom').hide();

// set the flash image hover text
$('.img-wrap').attr('title', noZoomImageCaption);
$('.img-wrap').attr('alt', noZoomImageCaption);
$('.img-wrap').attr('tooltip', noZoomImageCaption);

function HtmlDecode(text) {
    return $('<div/>').html(text).text();
};

function SpanDecode(text) {
    return $('<span/>').html(text).text();
};

// reset the mouse cursor from progress/waiting
function resetMouse() {
    $("*").css("cursor", "auto");
    $('a').css('cursor', 'pointer');
    $('button').css('cursor', 'pointer')
    $('img').css('cursor', 'pointer');
    $('#FabricSwatchImg').css("cursor", "auto");
    $('#AddedImg').css("cursor", "auto");
    //$('.jqzoom img').css('cursor', 'crosshair');
if ($('.product-details-img a.jqzoom img').attr('src') != null && $('.product-details-img a.jqzoom img').attr('src') != 'undefined') {    
if ($('.product-details-img a.jqzoom img').attr('src').search(/no_image/) != -1) {
        $('.jqzoom img').css('cursor', 'auto');
    }
    if ($('.product-details-img a.jqzoom').attr('href') == '') {
        $('.jqzoom img').css('cursor', 'auto');
    }
}
};

// only show background arrow if the volume pricing area visible
if ($('#product-info .buy-save-table').is(':visible')) {
    $('#product-info #select-quantity').addClass('show-background');
}

// disable mouse clicks in Firefox to prevent user being able to save images
// (doesn't work in IE)
$(".product-details-img").live('click', function (e) {
    if ((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1)) {
        //
    }
    else if (e.button == 2) {
        return false;
    }
});
$(".product-details-img").live('dblclick', function (e) {
    return false;
});
$(".product-details-img").dblclick(function () {
    return false;
});
$(".product-details-img").click(function (e) {
    if (e.button == 2) {
        return false;
    }
});

$('.jqzoom').click(function (e) {
    return false;
});

$('.jqzoom img').css('cursor', 'auto');

// ** zoom not used **
//
//var jqzoomOptions = {
//    zoomType: 'standard',
//    zoomWidth: 331,
//    zoomHeight: 340,
//    xOffset: 35,
//    yOffset: -5,
//    position: "right",
//    lens: true,
//    lensReset: false,
//    imageOpacity: 0.6,
//    title: false,
//    alwaysOn: false,
//    showEffect: 'show',
//    hideEffect: 'hide',
//    fadeinSpeed: 'fast',
//    fadeoutSpeed: 'slow'
//};

$('.image-hover').show();
$.ui.dialog.defaults.bgiframe = true;

//$(".jqzoom").jqzoom(jqzoomOptions);
$('.jqzoom img').attr('alt', noZoomImageCaption);
$('.jqzoom img').attr('title', noZoomImageCaption);

//$('#video-dialog').dialog({ modal: true, autoOpen: false })
//$('.product-details-img .jqmovie a').click(function () {
//    var source = $(document.createElement("source")).attr({ src: $(this).attr('href'), type: 'video/ogg' });
//    $('#video-frame, #video-main').attr({ src: $(this).attr('href') });
//    $('#video-main').empty().append(source);
//    $('#video-dialog').dialog('open');
//    return false;
//});

// product description 'more' link click
$('.shortdesclnk').click(function () {
    // hide short dsec section
    $('.divShortDesc').attr('style', 'display:none');
    // show long desc section
    $('.divLongDesc').attr('style', 'display:block');
    return false;
});
// product description 'less' link click
$('.longdesclnk').click(function () {
    // show short dsec section
    $('.divShortDesc').attr('style', 'display:block');
    // hide long desc section
    $('.divLongDesc').attr('style', 'display:none');
    return false;
});


// ensure blank product hero image set to missing image
if ($('.product-details-img a.jqzoom img').attr('src') == '') {
    $('.product-details-img a.jqzoom img').attr('src', HeroImageMissingFile);
    $('.product-details-img a.jqzoom img').attr('height', flashHeight);
    $('.product-details-img a.jqzoom img').attr('width', flashWidth);
}

// ensure alterntive images with missing image have correct img size
$('.product-details-img .jqthumb img').each(function (index, item) {
    if ($(this).attr('src').search(/no_image/) != -1) {
    }
});

if (($(".product-details-img .jqthumb img").length - $(".product-details-img .jqthumb img:hidden").length) == 0) {
    $(".product-thumbs").hide();
}


// product thumbnails
$('.product-details-img .jqthumb a').click(function () {
    var zoom = $(this).parent().parent().siblings('.jqzoom');

    // If 'No image' image is displayed, dont zoom it.
    //'no_image' in the below line is supposed to be a part of image name. if we change the image name, need to updated this line.
    if ($(this).attr('href') != '' && $(this).attr('href').search(/no_image/) == -1) {
        zoom.attr('href', $(this).attr('href').replace(/\/large\//, '/xlarge/'));

        // check if the zoom image exists - if not don't show the hover message...
        try {
            $.ajax({
                url: zoom.attr('href'),
                type: 'HEAD',
                error:
                function () {
                    $('.image-hover').text('');

                    // set the flash zoom image to missing image
                    var lowImg = flashvars.lowResImage;
                    flashvars = {
                        lowResImage: lowImg,
                        highResImage: lowImg,
                        width: flashWidth,
                        height: flashHeight
                    };
                    // re-load the flash image
                    showFlashObject();

                },
                success:
                function () {
                    $('.image-hover').text('');
                    //$('.jqzoom img').css('cursor', 'crosshair');
                }
            });
        }
        catch (e) {

        }

    }
    else {
        zoom.attr('href', '');
        $('.image-hover').text('');
        $('.jqzoom').css('cursor', 'default');
    }

    // ensure blank product hero image set to missing image
    var imgSrc = $(this).attr('href');
    if (imgSrc == '') {
        imgSrc = HeroImageMissingFile;
        zoom.children('img:first').attr('src', imgSrc);
        zoom.children('img:first').attr('height', flashHeight);
        zoom.children('img:first').attr('width', flashWidth);
    }
    else {
        // set the hero image
        zoom.children('img:first').attr('src', imgSrc);
    }

    // set correct size for missing hero image
    if (imgSrc.search(/no_image/) != -1) {
        zoom.children('img:first').attr('height', flashHeight);
        zoom.children('img:first').attr('width', flashWidth);
    }

    //    // Reset the zoom imagery - replace the anchor to remove previous jqzoom association
    //    $(".jqzoom").replaceWith($(".jqzoom").clone());
    //    $(".jqzoom").jqzoom(jqzoomOptions);

    $('.jqzoom img').attr('alt', noZoomImageCaption);
    $('.jqzoom img').attr('title', noZoomImageCaption);

    // set the flash zoom image
    if (imgSrc == HeroImageMissingFile) {
        flashvars = {
            lowResImage: imgSrc,
            highResImage: imgSrc,
            width: flashWidth,
            height: flashHeight
        };
    }
    else {
        if ($('.product-details-img a.jqzoom').attr('href') == '') {
            flashvars = {
                lowResImage: imgSrc,
                highResImage: imgSrc,
                width: flashWidth,
                height: flashHeight
            };
        }
        else {
            flashvars = {
                lowResImage: imgSrc,
                highResImage: $('.product-details-img a.jqzoom').attr('href'),
                width: flashWidth,
                height: flashHeight
            };
        }
    }
    // re-load the flash image
    showFlashObject();
    if (flashvars.highResImage == HeroImageMissingFile) {   // can't zoom
        $('#image-zoom').hide();
        // set the flash image hover text
        $('.img-wrap').attr('title', noZoomImageCaption);
        $('.img-wrap').attr('alt', noZoomImageCaption);
        $('.img-wrap').attr('tooltip', noZoomImageCaption);
        $('.jqzoom img').css('cursor', 'auto');
    }
    else {
        // set the flash image hover text
        $('.img-wrap').attr('title', clickToZoomCaption);
        $('.img-wrap').attr('alt', clickToZoomCaption);
        $('.img-wrap').attr('tooltip', clickToZoomCaption);
    }

    // unhighlight all the thumbs
    $('.product-details-img .jqthumb').each(function (index, item) {
        $(this).attr('style', 'border: none;');
    });

    // highlight the selected thumb
    $(this).parent().attr('style', 'border: thin solid black;');

    // show correct mouse cursor
    if ($('.product-details-img a.jqzoom img').attr('src').search(/no_image/) != -1) {
        $('.jqzoom img').css('cursor', 'auto');
    }
    else {
        //$('.jqzoom img').css('cursor', 'crosshair');
    }

    //    // remove 'loading zoom' when there is no zoom image
    //    $('.jqzoom').mouseover(function () {
    //        if ($('.jqzoom').attr('href') == '') {
    //            $('.preload').remove();
    //        }
    //    });

    return false;
});

$('.close-popup').click(function () {
    $(this).parent().fadeOut('fast');
    return false;
});

//This is the function for the onClick of the whishlist hyperlink
$("#wishlist-link").click(function () {
    var output = '';
    if (typeof $('.product-options .product-key').val() != "undefined") {
        output += $('.product-options .product-key').val();
    }
    else if (typeof $('.product-options .product-key').val() == "undefined") {
        output = '';
    }
    if (typeof $('.product select.property.colour').val() != "undefined") {
        output += $('.product select.property.colour').val();
    }
    else if (typeof $('.product select.property.colour').val() == "undefined") {
        output = '';
    }
    if (typeof $('.product-options select.property.size').val() != "undefined") {
        output += $('.product-options select.property.size').val();
    }
    else if (typeof $('.product-options select.property.size').val() == "undefined") {
        output = '';
    }
    //Populate the querystring only if the fully formed variant id exists.
    this.href = this.href + '&vid=' + output;
});

// not used
//    $.ui.dialog.defaults.bgiframe = true;
//    $('#product-comparison').dialog({ modal: true, autoOpen: false, width: 540 });
//    $('button.add-to-comparison').click(function () {
//        var fn = function (results, status) {
//            commerce.ui.new_comparison_list(results, status);
//            $('#product-comparison').dialog('open');
//        };
//        // HACK: Workaround for IE6/7 non-standards compliance whereby
//        //       the 'value' for the button is not honoured, but in fact
//        //       returns the inner html instead.
//        var t = null;
//        if (typeof ActiveXObject !== 'undefined' && $(this).val() === $(this).html()) {
//            //this.outerHTML = this.outerHTML;
//            var n = this.getAttributeNode('value');
//            if (!n) return true;
//            t = n.value;
//        }
//        commerce.product.consider(t || $(this).val(), { success: fn, error: fn });
//        return false;
//    });

//    $('#product-comparison .remove-all.button').click(function () {
//        commerce.product.disregard(null, { success: commerce.ui.new_comparison_list });
//        return false;
//    });


function RoundToCurrency(value) {
    var roundTo = 2;
    return value.toFixed(roundTo);
}


// initially select the variant to the first variant
$("#product-config").find(".product-options .option-list option:first").attr('selected', 'selected');


// initially set the correct image on page load to the variant selected...
var varSelected = $("#product-config").find(".product-options select.property");
if (varSelected != null && varSelected != 'undefined' && varSelected != '') {
    if (varSelected.val() != null && varSelected.val() != 'undefined' && varSelected.val() != '') {
        SetImages(varSelected.val());

        // also update display of the variant details
        var container = $(".product-options");
        var eventObj = $.extend(eventObj, { data: commerce.ui.swatchify_resolve(container) });
        if (eventObj.data === null)
            return;

        var options = {};
        options = $.extend({ async: true, success: function (data, status) {

            // update the display
            UpdateVariantDisplay(data, false);

            // update the product print link
            var productPrintBaseLink = $('#hdnProductPrintBaseLink').val();
            productPrintBaseLink = productPrintBaseLink + "?pid=" + pid;
            if (vid != null && vid != 'undefined' && vid != '') {
                productPrintBaseLink = productPrintBaseLink + "&vid=" + vid;
            }
            $('#ProductPrintLink').attr('href', productPrintBaseLink);

        },
            error: function (data, status) {
                resetMouse();
                return false;
            }
        },
		 options);

        var pid = '';
        var vid = '';
        var daysCaption = $('#hdnDaysCaption').val();
        var selectedSwatchText = $('#hdnSelectedSwatchText').val();
        var requestSwatchPageId = $('#hdnRequestSwatchPageId').val();

        var quantity = $('.QtyDropDown');
        quantity = quantity.size() == 0 ? '1' : quantity.val();

        if (eventObj.data.id != null && eventObj.data.id != 'undefined') {
            pid = eventObj.data.product;
            vid = eventObj.data.id;
            commerce._callws($.extend({ url: '/SiteWebServices/products.asmx/GetBestPriceForProductDisplay', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify({ "productKey": eventObj.data.product, "variantKey": eventObj.data.id, "quantity": quantity, "daysCaption": daysCaption, "selectedSwatchText": selectedSwatchText, "requestSwatchPageId": requestSwatchPageId, fabricImageFormat: FabricImageFormat }) }, options));
        }
        else if (eventObj.data.product != null && eventObj.data.product != 'undefined') {
            pid = eventObj.data.product;
            commerce._callws($.extend({ url: '/SiteWebServices/products.asmx/GetBestPriceForProductDisplay', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify({ "productKey": eventObj.data.product, "variantKey": eventObj.data.product, "quantity": quantity, "daysCaption": daysCaption, "selectedSwatchText": selectedSwatchText, "requestSwatchPageId": requestSwatchPageId, fabricImageFormat: FabricImageFormat }) }, options));
        }
        else {
            var id = $("input[type='hidden'].product-key").val();
            var pr = commerce.product.find(id);
            if (pr == null) { return true; } // ..submit the form; we can't find the product!..
            pid = id;
            vid = pr.id;
            commerce._callws($.extend({ url: '/SiteWebServices/products.asmx/GetBestPriceForProductDisplay', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify({ "productKey": id, "variantKey": pr.id, "quantity": quantity, "daysCaption": daysCaption, "selectedSwatchText": selectedSwatchText, "requestSwatchPageId": requestSwatchPageId, fabricImageFormat: FabricImageFormat }) }, options));
        }
    }
    else {
        // no variants - check out of stock here on page display
        var prod_id = $('.product-key').val();
        var out_Stock = $('.pnlOutOfStockMsg').attr('style').indexOf('display: block');
        var made_Order = $('.outstockbackmsg').attr('style').indexOf('display: block');
        if (out_Stock != null && out_Stock != 'undefined' && out_Stock > '-1') {
            // out of stock event
            var cat_id = $('#product-cat').val();
            Omniture.SendOutOfStockEvent(prod_id, s_account, prod_id, cat_id);
        }
        else {
            if (made_Order != null && made_Order != 'undefined' && made_Order > '-1') {
                // made to order event
                var cat_id = $('#product-cat').val();
                Omniture.SendMadeToOrderEvent(prod_id, s_account, prod_id, cat_id);
            }
        }

        var img = $('a.jqzoom img'); // ..find the image element..

        // If 'No image' image is displayed, dont zoom it.
        //'no_image' in the below line is supposed to be a part of image name. if we change the image name, need to updated this line.
        if (img.attr('src') != null && img.attr('src') != 'undefined' && img.attr('src') != '' && img.attr('src').search(/no_image/) == -1) {
            $('.product-details-img a.jqzoom').attr('href', $(img).attr('src').replace(/\/large\//, '/xlarge/'));

            // check if the zoom image exists - if not don't show the hover message...
            try {
                $.ajax({
                    url: $('.product-details-img a.jqzoom').attr('href'),
                    type: 'HEAD',
                    error:
                function () {
                    $('.image-hover').text('');

                    // set the flash zoom image to missing image
                    var lowImg = flashvars.lowResImage;
                    flashvars = {
                        lowResImage: lowImg,
                        highResImage: lowImg,
                        width: flashWidth,
                        height: flashHeight
                    };
                    // re-load the flash image
                    showFlashObject();
                },
                    success:
                function () {
                    $('.image-hover').text('');
                }
                });
            }
            catch (e) {

            }
        }
        else {
            img.attr('src', HeroImageMissingFile)
            img.attr('height', flashHeight);
            img.attr('width', flashWidth);
            $('.product-details-img a.jqzoom').attr('href', HeroImageMissingFile);
            $('.image-hover').text('');
            $('.jqzoom').css('cursor', 'default');
        }

        // ensure blank product hero image set to missing image
        var imgSrc = img.attr('src')
        if (imgSrc == '') {
            imgSrc = HeroImageMissingFile;
            img.attr('src', imgSrc);
            img.attr('height', flashHeight);
            img.attr('width', flashWidth);
        }

        //        // Reset the zoom imagery - replace the anchor to remove previous jqzoom association
        //        $(".jqzoom").replaceWith($(".jqzoom").clone());
        //        $(".jqzoom").jqzoom(jqzoomOptions);

        $('.jqzoom img').attr('alt', noZoomImageCaption);
        $('.jqzoom img').attr('title', noZoomImageCaption);

        // highlight the first thumb
        if ($('a#AltMedium-0').attr('href') != '') {
            $('a#AltMedium-0').parent().attr('style', 'border: thin solid black;');
        }

        //        // remove 'loading zoom' when there is no zoom image
        //        $('.jqzoom').mouseover(function () {
        //            if ($('.jqzoom').attr('href') == '') {
        //                $('.preload').remove();
        //            }
        //        });

        // set the flash zoom image
        if (imgSrc == HeroImageMissingFile) {
            flashvars = {
                lowResImage: imgSrc,
                highResImage: imgSrc,
                width: flashWidth,
                height: flashHeight
            };
        }
        else {
            if ($('.product-details-img a.jqzoom').attr('href') == '') {
                flashvars = {
                    lowResImage: imgSrc,
                    highResImage: imgSrc,
                    width: flashWidth,
                    height: flashHeight
                };
            }
            else {
                flashvars = {
                    lowResImage: imgSrc,
                    highResImage: $('.product-details-img a.jqzoom').attr('href'),
                    width: flashWidth,
                    height: flashHeight
                };
            }
        }
        // re-load the flash image
        showFlashObject();

        if (flashvars.highResImage == HeroImageMissingFile) {   // can't zoom
            $('#image-zoom').hide();
            // set the flash image hover text
            $('.img-wrap').attr('title', noZoomImageCaption);
            $('.img-wrap').attr('alt', noZoomImageCaption);
            $('.img-wrap').attr('tooltip', noZoomImageCaption);
            $('.jqzoom img').css('cursor', 'auto');

            // prevent flash zoom using ajax to ensure page displayed first           
            $.ajax({
                url: imgSrc,
                type: 'HEAD',
                error:
                function () {
                    // can't zoom
                    $('#image-zoom').hide();
                    $('.jqzoom img').css('cursor', 'auto');
                },
                success:
                function () {
                    // can't zoom
                    $('#image-zoom').hide();
                    $('.jqzoom img').css('cursor', 'auto');
                }
            });
        }
        else {
            // set the flash image hover text
            $('.img-wrap').attr('title', clickToZoomCaption);
            $('.img-wrap').attr('alt', clickToZoomCaption);
            $('.img-wrap').attr('tooltip', clickToZoomCaption);
        }
    }
}


// update the display for the selected variant
function UpdateVariantDisplay(data, sendStockEvent) {

    if (data != null && data != 'undefined' && data.data != null && data.data != 'undefined') {
        if (data.data.nameString != null && data.data.nameString != '' && data.data.nameString != 'undefined') {
            $('#ProductNameDisplay').html(HtmlDecode(data.data.nameString));
            document.title = HtmlDecode(SpanDecode(data.data.nameString));
        }
        if (data.data.wasnowPrice != null && data.data.wasnowPrice != 'undefined' && data.data.wasnowPrice != '') {
            $('#price-format').html(HtmlDecode(data.data.wasnowPrice));
        }
        else {
            if (data.data.price != null && data.data.price != 'undefined' && data.data.price != '') {
                $('#price-format').html(HtmlDecode(data.data.price));
            }
        }
        if (data.data.dimensions != null && data.data.dimensions != 'undefined') {
            $('#dimensionsText').html(HtmlDecode(data.data.dimensions));
        }
        if (data.data.material != null && data.data.material != 'undefined') {
            $('#materialText').html(HtmlDecode(data.data.material));
        }
        if (data.data.deliveryTime != null && data.data.deliveryTime != 'undefined') {
            $('#deliveryTimeText').html(HtmlDecode(data.data.deliveryTime));
        }
        var isInStock = false;
        var isPreBack = false;
        if (data.data.isInStock != null && data.data.isInStock != '' && data.data.isInStock != 'undefined' && (data.data.isInStock == 'true' || data.data.isInStock == true)) {
            isInStock = true;
        }
        if (data.data.isPreBack != null && data.data.isPreBack != '' && data.data.isPreBack != 'undefined' && (data.data.isPreBack == 'true' || data.data.isPreBack == true)) {
            isPreBack = true;
        }
        $('.divDelInfo').attr('style', 'display:none');
        if (isInStock) {
            $('.divDelInfo').attr('style', 'display:block');
        }
        $('.pnlOutOfStockMsg').attr('style', 'display:none');
        $('.outstockbackmsg').attr('style', 'display:none');

        if (!isInStock && sendStockEvent) {
            loadjscssfile("../assets/script/s_code.min.js", "js");
            loadjscssfile("../assets/script/s_plugins.min.js", "js");
            if (isPreBack) {
                $('.outstockbackmsg').attr('style', 'display:block');

                // made to order event
                var prod_id = '';
                if (data.data.prodid != null && data.data.prodid != '' && data.data.prodid != 'undefined') {
                    errVal = data.data.prodid;
                    prod_id = data.data.prodid;
                }
                if (data.data.varid != null && data.data.varid != '' && data.data.varid != 'undefined') {
                    errVal = errVal + " - " + data.data.varid;
                }
                var cat_id = $('#product-cat').val();
                Omniture.SendMadeToOrderEvent(errVal, s_account, prod_id, cat_id);

            }
            else {
                $('.pnlOutOfStockMsg').attr('style', 'display:block');

                // out of stock event
                var errVal = $('.outstockmsg').html();
                var prod_id = '';
                if (data.data.prodid != null && data.data.prodid != '' && data.data.prodid != 'undefined') {
                    errVal = data.data.prodid;
                    prod_id = data.data.prodid;
                }
                if (data.data.varid != null && data.data.varid != '' && data.data.varid != 'undefined') {
                    errVal = errVal + " - " + data.data.varid;
                }
                var cat_id = $('#product-cat').val();
                Omniture.SendOutOfStockEvent(errVal, s_account, prod_id, cat_id);
            }
        }
        var availableQty = 1;
        if (data.data.availableQty != null && data.data.availableQty != '' && data.data.availableQty != 'undefined') {
            availableQty = data.data.availableQty;
        }
        $('.QtyDropDown > option').remove();
        for (var i = 1; i <= availableQty; i++) {
            $('.QtyDropDown').append($('<option></option>').val(i).html(i));
        }
        $('.QtyDropDown').val('1');

        // if called from variant click, display request swatch overlay if the product requires it
        if (VariantClicked == true) {
            if (data.data.canRequestSwatch != null && data.data.canRequestSwatch != '' && data.data.canRequestSwatch != 'undefined' && (data.data.canRequestSwatch == 'true' || data.data.canRequestSwatch == true)) {
                // set the swatch details
                if (data.data.fabricText != null && data.data.fabricText != 'undefined') {
                    $('#SwatchSelected').html(HtmlDecode(data.data.fabricText));
                }
                if (data.data.selectedSwatchString != null && data.data.selectedSwatchString != 'undefined') {
                    $('#SwatchSelectedText').html(HtmlDecode(data.data.selectedSwatchString));
                }
                if (data.data.requestSwatchLink != null && data.data.requestSwatchLink != 'undefined') {
                    $('#RequestSwatchLink').attr('href', HtmlDecode(data.data.requestSwatchLink));
                }
                if (data.data.fabricSwatchImg != null && data.data.fabricSwatchImg != 'undefined') {
                    $('#FabricSwatchImg').attr('src', HtmlDecode(data.data.fabricSwatchImg));
                }
                // check if the fabric swatch image exists...
                try {
                    $.ajax({
                        url: $('#FabricSwatchImg').attr('src'),
                        type: 'HEAD',
                        error:
                function () {
                    $('#FabricSwatchImg').attr('src', FabricMissingSwatch)
                },
                        success:
                function () {
                    //
                }
                    });
                }
                catch (e) {

                }

                // show swatch overlay
                $('.tool-tip-wrap.swatch-info').css('top', $('.option-list dt').position().top - ($('.swatch-info').height() / 2) + $('.option-list dt').height());  // correct position
                $('.tool-tip-wrap.swatch-info').fadeIn(300);
            }
        }

        // reset mouse cursor
        resetMouse();

        VariantClicked = false; // re-enable variant clicks
    }

};

// initially set the 'select colour' text
var ColourOption = $(".option-list dt :contains('Colour')");
if (ColourOption != null && ColourOption != '' && ColourOption != 'undefined') {
    var colourCaption = $('#hdnSelectaColour').val();
    ColourOption.text(colourCaption);
}
// initially set the 'select colour' text - French
var ColourOption = $(".option-list dt :contains('Coleur')");
if (ColourOption != null && ColourOption != '' && ColourOption != 'undefined') {
    var colourCaption = $('#hdnSelectaColour').val();
    ColourOption.text(colourCaption);
}
// initially set the 'select colour' text - US
var ColourOption = $(".option-list dt :contains('Color')");
if (ColourOption != null && ColourOption != '' && ColourOption != 'undefined') {
    var colourCaption = $('#hdnSelectaColour').val();
    ColourOption.text(colourCaption);
}

// function to handle changing the displayed images for a variant selected
function SetImages(variantKey) {

    alternativesExist = false;

    // clear all selected icons
    $('.swatch img').each(function (index, item) {
        if ($(this).attr('src') != '' && $(this).attr('src') != null && $(this).attr('src') != 'undefined') {
            // check the colour icon exists...
            if ($(this).attr('class') == 'missing-swatch') {
                $(this).attr('src', MissingColourSwatch);
            }
            else {
                $(this).attr('src', IconsDirectory + $(this).attr('id') + '.gif');
            }
        }
    });

    if (variantKey !== undefined) variantKey = variantKey.replace(' ', '');

    // set the selected variant icon
    var thisImg = $('#' + variantKey);
    if (thisImg != null && thisImg != 'undefined' && thisImg.attr('id') != 'undefined' && thisImg.attr('id') != null && thisImg.attr('id') != '') {
        // check the selected colour icon exists
        var selImgsrc = IconsDirectory + thisImg.attr('id') + '-S.gif';
        thisImg.attr('src', selImgsrc);
        try {
            $.ajax({
                url: selImgsrc,
                type: 'HEAD',
                error:
                        function () {
                            thisImg.attr('src', MissingSelColourSwatch);
                        },
                success:
                        function () {
                            //
                        }
            });
        }
        catch (e) {

        }
    }

    // variant clicked
    $('a.swatch').click(function () {
        if (VariantClicked == true) {
            return false; // disable varaint mouse clicks until this variant details have been loaded
        }
        VariantClicked = true;
        $('.tool-tip-wrap').hide();  // hide overlays
    });

    var img = $('a.jqzoom img'); // ..find the image element..
    var ImgAttr = img.attr('src');
    var newHeroImg = $('#HdnVariantHeroImage-' + variantKey).val();
    // ..if the image urls are different, we shall reset the image
    // url to be that of the new product selected..
    if (newHeroImg != null && newHeroImg != 'undefined' && newHeroImg != '') {
        if (img.attr('src') != newHeroImg) {
            img.attr('src', newHeroImg);
        }
    }
    else {
        img.attr('src', '');
    }

    // ensure blank product hero image set to missing image
    if (img.attr('src') == '') {
        img.attr('src', HeroImageMissingFile);
        img.attr('height', flashHeight);
        img.attr('width', flashWidth);
    }

    // set correct size for missing hero image
if (newHeroImg != null && newHeroImg != 'undefined' && newHeroImg != '') {
    if (newHeroImg.search(/no_image/) != -1) {
        img.attr('height', flashHeight);
        img.attr('width', flashWidth);
    }
}
    // If 'No image' image is displayed, dont zoom it.
    //'no_image' in the below line is supposed to be a part of image name. if we change the image name, need to updated this line.
    if (img.attr('src') != null && img.attr('src') != 'undefined' && img.attr('src') != '' && img.attr('src').search(/no_image/) == -1) {
        $('.product-details-img a.jqzoom').attr('href', $(img).attr('src').replace(/\/large\//, '/xlarge/'));

        // check if the zoom image exists - if not don't show the hover message...            
        try {
            $.ajax({
                url: $('.product-details-img a.jqzoom').attr('href'),
                type: 'HEAD',
                error:
                function () {
                    $('.image-hover').text('');

                    // set the flash zoom image to missing image
                    var lowImg = flashvars.lowResImage;
                    flashvars = {
                        lowResImage: lowImg,
                        highResImage: lowImg,
                        width: flashWidth,
                        height: flashHeight
                    };
                    // re-load the flash image
                    showFlashObject();
                },
                success:
                function () {
                    $('.image-hover').text('');
                }
            });
        }
        catch (e) {

        }


        //        // Reset the zoom imagery - replace the anchor to remove previous jqzoom association
        //        $(".jqzoom").replaceWith($(".jqzoom").clone());
        //        $(".jqzoom").jqzoom(jqzoomOptions);

        $('.jqzoom img').attr('alt', noZoomImageCaption);
        $('.jqzoom img').attr('title', noZoomImageCaption);

        // set the flash zoom image
        flashvars = {
            lowResImage: img.attr('src'),
            highResImage: $('.product-details-img a.jqzoom').attr('href'),
            width: flashWidth,
            height: flashHeight
        };
        // re-load the flash image
        showFlashObject();

        // set the flash image hover text
        $('.img-wrap').attr('title', clickToZoomCaption);
        $('.img-wrap').attr('alt', clickToZoomCaption);
        $('.img-wrap').attr('tooltip', clickToZoomCaption);
    }
    else {
        img.attr('src', HeroImageMissingFile)
        img.attr('height', flashHeight);
        img.attr('width', flashWidth);
        $('.product-details-img a.jqzoom').attr('href', HeroImageMissingFile);
        $('.image-hover').text('');
        $('.jqzoom').css('cursor', 'default');

        // ensure blank product hero image set to missing image
        var imgSrc = img.attr('src')
        if (imgSrc == '') {
            imgSrc = HeroImageMissingFile;
            img.attr('src', imgSrc);
            img.attr('height', flashHeight);
            img.attr('width', flashWidth);
        }

        //        $(".jqzoom").replaceWith($(".jqzoom").clone());
        //        $(".jqzoom").jqzoom(jqzoomOptions);

        $('.jqzoom img').attr('alt', noZoomImageCaption);
        $('.jqzoom img').attr('title', noZoomImageCaption);

        // set the flash zoom image
        flashvars = {
            lowResImage: imgSrc,
            highResImage: imgSrc,
            width: flashWidth,
            height: flashHeight
        };
        // re-load the flash image
        showFlashObject();

        if (flashvars.highResImage == HeroImageMissingFile) {   // can't zoom
            $('#image-zoom').hide();
            // set the flash image hover text
            $('.img-wrap').attr('title', noZoomImageCaption);
            $('.img-wrap').attr('alt', noZoomImageCaption);
            $('.img-wrap').attr('tooltip', noZoomImageCaption);
            $('.jqzoom img').css('cursor', 'auto');

            // prevent flash zoom using ajax to ensure page displayed first           
            $.ajax({
                url: imgSrc,
                type: 'HEAD',
                error:
                function () {
                    // can't zoom
                    $('#image-zoom').hide();
                    $('.jqzoom img').css('cursor', 'auto');
                },
                success:
                function () {
                    // can't zoom
                    $('#image-zoom').hide();
                    $('.jqzoom img').css('cursor', 'auto');
                }
            });
        }
        else {
            // set the flash image hover text
            $('.img-wrap').attr('title', clickToZoomCaption);
            $('.img-wrap').attr('alt', clickToZoomCaption);
            $('.img-wrap').attr('tooltip', clickToZoomCaption);
        }


    }

    // now do alternatives...
    // first, hide all alternatives in case this variant has no alternative...
    var opts = $(".option-list option");
    if (opts != null && opts != 'undefined' && opts.length > 1) {
        $("a[id^='AltMedium']").each(function (index, item) {
            $(this).attr('style', 'display: none');
            $(this).attr('src', '');
            $(this).attr('alt', '');
            // unhighlight all the thumbs
            $(this).parent().attr('style', 'border: none;');
        });
        // hide all list items
        $('li.jqthumb').attr('style', 'display:none');
    }

    var doneAltMain = 'false';
    $("input[id^='HdnAltThumbImage']").each(function (index, item) {
        // are these alternatives for the currently selected variant?
        var thisAlt = $(this).attr("id").split('-');
        if (thisAlt != null && thisAlt != 'undefined' && thisAlt.length > 2) {
            if (variantKey == (thisAlt[2] + '-' + thisAlt[3])) {

                // there are alternatives - so do the main image first if not done yet...
                alternativesExist = true;

                var AltText = $('.product-details-img a.jqzoom').attr('alt');
                if (doneAltMain != 'true') {
                    var newMainAltImg = $('#HdnVariantThumbImage-' + variantKey).val();
                    if (newMainAltImg != null && newMainAltImg != 'undefined' && newMainAltImg != '') {
                        $('img#AltSmall-0').attr('src', newMainAltImg);
                        $('img#AltSmall-0').attr('style', 'display :inline');
                        $('img#AltSmall-0').attr('alt', AltText);
                    }
                    if (newHeroImg != null && newHeroImg != 'undefined' && newHeroImg != '') {
                        $('a#AltMedium-0').attr('href', newHeroImg);
                        $('a#AltMedium-0').attr('style', 'display: inline');
                        $('a#AltMedium-0').attr('alt', AltText);
                    }
                    else {
                        // mising hero image
                        $('a#AltMedium-0').attr('href', HeroImageMissingFile);
                        $('a#AltMedium-0').attr('style', 'display: inline');
                        $('a#AltMedium-0').attr('alt', AltText);
                    }
                    doneAltMain = 'true';
                }

                // now do this alternative...
                var thisAlt = $(this).attr("id").split('-');
                if (thisAlt != null && thisAlt != 'undefined' && thisAlt.length > 2) {
                    var thisNumber = thisAlt[1];
                    var thisUrl = $(this).val();
                    if (thisUrl != null && thisUrl != 'undefined' && thisUrl != '' && thisNumber != null && thisNumber != 'undefined' && thisNumber != '') {
                        $('img#AltSmall-' + (parseInt(thisNumber) + 1)).attr('src', thisUrl);
                        $('img#AltSmall-' + (parseInt(thisNumber) + 1)).attr('style', 'display :inline');
                        $('img#AltSmall-' + (parseInt(thisNumber) + 1)).attr('alt', AltText);
                        // do the medium alt
                        var thisAltHeroImg = $('#HdnAltHeroImage-' + thisNumber + '-' + thisAlt[2] + '-' + thisAlt[3]).val();
                        if (thisAltHeroImg != null && thisAltHeroImg != 'undefined' && thisAltHeroImg != '') {
                            $('a#AltMedium-' + (parseInt(thisNumber) + 1)).attr('href', thisAltHeroImg);
                            $('a#AltMedium-' + (parseInt(thisNumber) + 1)).attr('style', 'display :inline');
                            $('a#AltMedium-' + (parseInt(thisNumber) + 1)).attr('alt', AltText);
                        }
                        else {
                            // mising hero image
                            $('a#AltMedium-' + (parseInt(thisNumber) + 1)).attr('href', HeroImageMissingFile);
                            $('a#AltMedium-' + (parseInt(thisNumber) + 1)).attr('style', 'display :inline');
                            $('a#AltMedium-' + (parseInt(thisNumber) + 1)).attr('alt', AltText);
                        }
                    }
                }

            }
        }

    });

    // ensure alterntive images with missing image have correct img size
    $('.product-details-img .jqthumb img').each(function (index, item) {
        if ($(this).attr('src').search(/no_image/) != -1) {
        }
    });

    if (alternativesExist == true) {
        $('li.jqthumb').attr('style', 'display:inline-block');
        // highlight the first thumb
        if ($('a#AltMedium-0').attr('href') != '') {
            $('a#AltMedium-0').parent().attr('style', 'border: thin solid black;');
        }
    }

    //    // remove 'loading zoom' when there is no zoom image
    //    $('.jqzoom').mouseover(function () {
    //        if ($('.jqzoom').attr('href') == '') {
    //            $('.preload').remove();
    //        }
    //    });

};

// variant selected changed
commerce.ui.swatchify_range($(".product-options"), { change: function (eventObj) {
    if (eventObj.data === null)
        return;

    // show progress mouse cursor
    $("*").css("cursor", "progress");

    if (typeof eventObj.data.colour != 'undefined') {
        SetImages(eventObj.data.colour.id);
    }

    // update display of the variant details
    var options = {};
    options = $.extend({ async: true, success: function (data, status) {

        // update the display
        UpdateVariantDisplay(data, true);

        // update the product print link
        var productPrintBaseLink = $('#hdnProductPrintBaseLink').val();
        productPrintBaseLink = productPrintBaseLink + "?pid=" + pid;
        if (vid != null && vid != 'undefined' && vid != '') {
            productPrintBaseLink = productPrintBaseLink + "&vid=" + vid;
        }
        $('#ProductPrintLink').attr('href', productPrintBaseLink);

    },
        error: function (data, status) {
            // reset mouse cursor
            resetMouse();
            return false;
        }
    },
		 options);

    var pid = '';
    var vid = '';
    var daysCaption = $('#hdnDaysCaption').val();
    var selectedSwatchText = $('#hdnSelectedSwatchText').val();
    var requestSwatchPageId = $('#hdnRequestSwatchPageId').val();

    var quantity = $('.QtyDropDown');
    quantity = quantity.size() == 0 ? '1' : quantity.val();

    if (eventObj.data.id != null && eventObj.data.id != 'undefined') {
        pid = eventObj.data.product;
        vid = eventObj.data.id;
        commerce._callws($.extend({ url: '/SiteWebServices/products.asmx/GetBestPriceForProductDisplay', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify({ "productKey": eventObj.data.product, "variantKey": eventObj.data.id, "quantity": quantity, "daysCaption": daysCaption, "selectedSwatchText": selectedSwatchText, "requestSwatchPageId": requestSwatchPageId, fabricImageFormat: FabricImageFormat }) }, options));
    }
    else if (eventObj.data.product != null && eventObj.data.product != 'undefined') {
        pid = eventObj.data.product;
        commerce._callws($.extend({ url: '/SiteWebServices/products.asmx/GetBestPriceForProductDisplay', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify({ "productKey": eventObj.data.product, "variantKey": eventObj.data.product, "quantity": quantity, "daysCaption": daysCaption, "selectedSwatchText": selectedSwatchText, "requestSwatchPageId": requestSwatchPageId, fabricImageFormat: FabricImageFormat }) }, options));
    }
    else {
        var id = $("input[type='hidden'].product-key").val();
        var pr = commerce.product.find(id);
        if (pr == null) { return true; } // ..submit the form; we can't find the product!..
        pid = id;
        vid = pr.id;
        commerce._callws($.extend({ url: '/SiteWebServices/products.asmx/GetBestPriceForProductDisplay', type: 'POST', contentType: 'application/json; charset=utf-8', dataType: 'json', data: JSON.stringify({ "productKey": id, "variantKey": pr.id, "quantity": quantity, "daysCaption": daysCaption, "selectedSwatchText": selectedSwatchText, "requestSwatchPageId": requestSwatchPageId, fabricImageFormat: FabricImageFormat }) }, options));
    }
    return false;
}
});


// display alternatives
$('.jqthumb a').attr('style', 'display:inline-block');
if (alternativesExist == true) {
    $('li.jqthumb').attr('style', 'display:inline-block');
}


// handle close of basket item added section
$('#item-added-basket-close').click(function () {
    $('#item-added-basket').fadeOut('fast');
    return false;
});

// intercept add to basket click
commerce.ui.intercept($(".prodaddtobasket"));

// intercept add to wishlist click
commerce.ui.interceptWishLink($('#wishlist-link'));

// intercept add to giftlistlist click
commerce.ui.interceptGiftLink($('#giftlist-link'));


// handle email when back in stock submit click
commerce.ui.interceptStockEmail($('.btnStockEmail'));

commerce.ui.interceptStockMsgEmail($('.btnOOSMsgStockEmail'));


});

