﻿// THESE FUNCTIONS PREPARE AND DRAW THE MODEL AND FABRIC LISTS, AND SET/CHECK GENERAL VARIABLES

jQuery.noConflict();

// CHECK LANGUAGE FOR CURRENT CULTURE
var currentCulture = "";

if (currentLanguage == "de") {
    currentCulture = "de_DE";
}
else if (currentLanguage == "fr") {
    currentCulture = "fr_BE";
}
else if (currentLanguage == "nl") {
    currentCulture = "nl_BE";
}
else if (currentLanguage == "sv") {
    currentCulture = "sv_SE";
}
else {
    currentCulture = "en_GB";
}


// VARIABLE OF CURRENT URL
var currentUrl = window.location.href.toString();


// FIND OUT IF CURRENT PAGE IS THE RECOMMENDATION PAGE, AND SET IT IN A VARIABLE ------------------------------

var isRecommendationPage = "";
function checkIsRecommendationPage() { // Function is called from the model list drawing function
    var htmlCode = document.body.innerHTML.toString();
    if (htmlCode.match("Product recommendations") == "Product recommendations" || htmlCode.match("Recommandations de produit") == "Recommandations de produit" || htmlCode.match("Productaanbevelingen") == "Productaanbevelingen" || htmlCode.match("Produktempfehlungen") == "Produktempfehlungen") {
        isRecommendationPage = "Yes";
    }
}


// DIVIDE PRODUCT NAME ON PRODUCT PAGE IN MAIN (MODEL) AND SUB (FABRIC) NAMES FOR NICER LAYOUT + ADD "COVER FOR"
var mainProdName = "";
var subProdName = "";

function displayMainSubProdName() {
    if (jQuery("div.ProductDetails").length) { // ONLY ON PRODUCT PAGES
        var orgProdNameContainer = jQuery("h1"); // ORIGINAL H1
        var orgProdName = orgProdNameContainer.text();  // ORIGINAL (COMPLETE) PRODUCT NAME
        var prodNameDividerPosition = orgProdName.indexOf(" - ");   // CHECK WHERE PROD NAME IS DIVIDED BETWEEN MODEL AND FABRIC
        if (prodNameDividerPosition != -1) { // ONLY CREATE SUB NAMES ETC FOR PRODUCTS WITH A FABRIC TYPE
            var prodNameSecondHalf = orgProdName.substr(prodNameDividerPosition);   // EVERYTHING AFTER & INCL. DIVIDER 
            mainProdName = orgProdName.replace(prodNameSecondHalf, "")  // MAIN PROD NAME (MODEL)
            subProdName = prodNameSecondHalf.replace(" - ", "");    // SUB PROD NAME (FABRIC)

            orgProdNameContainer.text(mainProdName); // PUT MODEL NAME IN H1 
            var coverText = "";
            if (currentLanguage == "en") { coverText = "Cover for"; }
            if (currentLanguage == "de") { coverText = "Bezug für"; }
            if (currentLanguage == "fr") { coverText = "Housse pour"; }
            if (currentLanguage == "nl") { coverText = "Hoes voor"; }
            if (currentLanguage == "sv") { coverText = "Överdrag för"; }

            // MATCH AGAINST NON-COVER PRODUCTS (METRE & FOULARD)
            var nonCoverName = mainProdName.toUpperCase().match(/FABRIC|METERWARE|TISSU|STOFFEN|TYG|FOULARD|THROW/);
            if (nonCoverName == null) {
                orgProdNameContainer.prepend(coverText + " "); // WRITE "COVER FOR" IF A COVER
            }

            orgProdNameContainer.after("<h2 id='SubProdName'></h2>"); // CREATE H2
            jQuery("#SubProdName").text(subProdName);    // PUT FABRIC NAME IN H2
        }
        orgProdNameContainer.show();    // SHOW H1 (HIDDEN IN CSS)
        jQuery("#SubProdName").show();   // MAKE SURE H2 IS DISPLAYED (HIDDEN IN CSS)
    }
}

// FUNCTION FOR TRANSFORMING A REAL FABRIC NAME INTO IMAGE NAME
function fabricNameToImageName(fabricName) {

    var imageName = fabricName.toLowerCase();

    // DELETE "-" FROM RE-COVER
    imageName = imageName.replace(/-/g, "");

    // FIRST LETTER TO UPPER CASE
    imageName = imageName.charAt(0).toUpperCase() + imageName.substr(1);

    // FIND OUT NUMBER OF SPACES IN NAME
    var numberOfSpaces = imageName.length - imageName.replace(/ /g, "").length;

    // SUBSTITUTE ALL SPACES AND TURN FOLLOWING LETTER INTO UPPERCASE
    for (i = 0; i < numberOfSpaces; i++) {
        var spacePosition = imageName.indexOf(" ");
        imageName = imageName.replace(" ", "");
        imageName = imageName.substr(0, spacePosition) + imageName.charAt(spacePosition).toUpperCase() + imageName.substr(spacePosition + 1);
    }

    return (imageName);
}

// RENDER FABRIC POPUP CONTAINER
function renderFabricPopup(fabricImageName, imageType, fabricName) {

    var fabricPopupCode = '<div id="FabricPopup">';
    fabricPopupCode += '<div id="FabricPopupBg"></div>';
    fabricPopupCode += '<div id="FabricPopupContent">';
    fabricPopupCode += '<div id="FabricPopupClose"><a onclick="closeFabricPopup();" class="CloseFabricPopup">';
    fabricPopupCode += '&nbsp;<img src="/WebRoot/Store/Shops/62005383/MediaGallery/images/misc/close-popup.gif" alt="X" /></a></div>';
    fabricPopupCode += '<div id="FabricPopupImage"><img src="/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/fabric-popup/';
    fabricPopupCode += fabricImageName + '.' + imageType + '" alt="' + fabricName + '" />&nbsp;</div>';
    fabricPopupCode += '</div></div>';
    return fabricPopupCode;

}

// WRITE FABRIC CLOSEUPLINK
function autoFabricLink() {

    // MATCH AGAINST FABRIC BY THE METRE PRODUCTS
    var fabricByTheMetreName = mainProdName.toUpperCase().match(/FABRIC|METERWARE|TISSU|STOFFEN|TYG/);

    // EXECUTE ON PRODUCT PAGE BUT NOT FOR FABRIC BY THE METRE PRODUCTS
    if ((jQuery("div.ProductDetails").length) && (fabricByTheMetreName == null)) { 


        var fabricPopupName = subProdName;
        var fabricPopupId = fabricNameToImageName(subProdName);

        var fabricLinkCode = "";
        fabricLinkCode += '<a id="FabricLink" onclick="openFabricPopup();"><b>';

        if (currentLanguage == "de") { fabricLinkCode += 'Nahaufnahme des Stoffe'; }
        else if (currentLanguage == "fr") { fabricLinkCode += 'Close-up de tissu'; }
        else if (currentLanguage == "nl") { fabricLinkCode += 'Close-up van stof'; }
        else if (currentLanguage == "sv") { fabricLinkCode += 'Närbild av tyg'; }
        else { fabricLinkCode += 'Close-up of fabric'; }

        fabricLinkCode += '</b></a>';

        fabricLinkCode += renderFabricPopup(fabricPopupId, "jpg", fabricPopupName);

        jQuery("#SubProdName").next().next().append(fabricLinkCode);



    }
    
    // CHANGE THE PRODUCT CLOSE UP TEXT CLOSE
    if (jQuery("div.ProductDetails").length) {
        var productCloseUpText = "";
        if (currentLanguage == "de") { productCloseUpText = 'Nahaufnahme des Produkts'; }
        else if (currentLanguage == "fr") { productCloseUpText = 'Close-up de produit'; }
        else if (currentLanguage == "nl") { productCloseUpText = 'Close-up van produkt'; }
        else if (currentLanguage == "sv") { productCloseUpText = 'Närbild av produkt'; }
        else { productCloseUpText = 'Close-up of product'; }

        jQuery("div.TopSmallPadding a").text(productCloseUpText);        

    }
}

// OPENS THE FABRIC POPUP 
function openFabricPopup() {
    jQuery("#FabricPopupContent").hide();
    jQuery("#FabricPopup").fadeIn("fast", function() {
    jQuery("#FabricPopupContent").fadeIn("fast");        
    });
}

// CLOSES THE FABRIC POPUP 
function closeFabricPopup() {
    jQuery("#FabricPopup").hide();
}


// FIND TO WHICH MODEL IN A FAMILY A CERTAIN PRODUCT NUMBER BELONGS
function findModel(modelFamily, articleNumber) {

    var tempArray = [];
    eval("tempArray = " + modelFamily + "Family");

    for (var i = 0; i < tempArray.length; i++) {

        //jQuery("#testContainer").append("i" + i + "<br>");

        for (var k = 1; k < tempArray[i].length; k++) {
            //jQuery("#testContainer").append("i" + i + " k" + k + " " + tempArray[i][k].fabricArticleNumber + "<br>");        
            if (tempArray[i][k].fabricArticleNumber == articleNumber) {
                return tempArray[i][0].modelName;
            }
        }
    }
    jQuery("#SofaWithoutCoverBanner").after("<div>" + "could not find article no." + "</div>");    
    return "could not find article no.";
}



// AUTO MATCH THE FABRIC LIST TO BE DISPLAYED
function autoMatchModel() {
    //alert("automatch start");
    if (jQuery("div.ProductDetails").length && currentPageIsBargainCorner == false) {
        var productPosition = currentUrl.indexOf("/Products/");
        var currentProductId = currentUrl.substr(productPosition);
        currentProductId = currentProductId.replace("/Products/", "")
        var ampersandPosition = currentProductId.indexOf("&");
        if (ampersandPosition != -1) {
            var argumentString = currentProductId.substr(ampersandPosition);
            currentProductId = currentProductId.replace(argumentString, "");
        }
        //alert(currentProductId);

        var fabricListUrl = "/WebRoot/Store/Shops/62005383/MediaGallery/scripts/fabric-lists/" + familyToShow + "-fabrics.js";
        //alert("fabricListUrl: " + fabricListUrl);
        
        // LOAD THE GENERAL FABRIC INFORMATION AND THEN THE CURRENT FAMILY FABRIC INFORMATION
        jQuery.getScript("/WebRoot/Store/Shops/62005383/MediaGallery/scripts/fabric-lists/fabric-information.js", function() {
            jQuery.getScript(fabricListUrl, function() {
                //alert(fabricListUrl + ' load was performed.');
                //alert(familyToShow + " " + currentProductId);
                var currentModel = findModel(familyToShow, currentProductId);

                //alert("current model: " + currentModel);
                drawFabricList(currentModel);
            });
        });
    }
}


// FUNCTION FOR EXPLICITLY DRAWING A FABRIC LIST ANYWHERE
function drawManualFabricList(family, modelToShow) {

    var fabricListUrl = "/WebRoot/Store/Shops/62005383/MediaGallery/scripts/fabric-lists/" + family + "-fabrics.js";

    // LOAD THE GENERAL FABRIC INFORMATION AND THEN THE CURRENT FAMILY FABRIC INFORMATION
    jQuery.getScript("/WebRoot/Store/Shops/62005383/MediaGallery/scripts/fabric-lists/fabric-information.js", function() {
        jQuery.getScript(fabricListUrl, function() {
            drawFabricList(modelToShow);
        });
    });

}







// AUTOMATICALLY WRITE MODEL FAMILY
var familyToShow = "";
function autoMatchModelFamily() {
    if (jQuery("div.ProductDetails").length) { // ONLY DO ON PRODUCT PAGES
        if (mainProdName.toUpperCase().match("EKTORP") != null) {familyToShow = "ektorp"; }
        if (mainProdName.toUpperCase().match(/JENNYLUND|IKEA PS|POÄNG|KLAPPSTA|TULLSTA/) != null) {familyToShow = "armchair"; }
        if (mainProdName.toUpperCase().match("EKESKOG") != null) { familyToShow = "ekeskog"; }
        if (mainProdName.toUpperCase().match("HAGALUND") != null) { familyToShow = "hagalund"; }
        if (mainProdName.toUpperCase().match("GÖTEBORG") != null) { familyToShow = "goteborg"; }
        if (mainProdName.toUpperCase().match("KLIPPAN") != null) { familyToShow = "klippan"; }
        if (mainProdName.toUpperCase().match(/HRH|HKH|SAR|ZKH/) != null) { familyToShow = "royal"; }
        if (mainProdName.toUpperCase().match("LILLBERG") != null) { familyToShow = "lillberg"; }
        if (mainProdName.toUpperCase().match("STRÖMSTAD") != null) { familyToShow = "stromstad"; }
        if (mainProdName.toUpperCase().match("KRAMFORS") != null) { familyToShow = "kramfors"; }
        if (mainProdName.toUpperCase().match("NIKKALA") != null) { familyToShow = "nikkala"; }
        if (mainProdName.toUpperCase().match("TOMELILLA") != null) { familyToShow = "tomelilla"; }
        if (mainProdName.toUpperCase().match("TYLÖSAND") != null) { familyToShow = "tylosand"; }                        
        if (mainProdName.toUpperCase().match("BEDDINGE") != null) { familyToShow = "beddinge"; }  
        if (mainProdName.toUpperCase().match("KARLANDA") != null) { familyToShow = "karlanda"; }  
        if (mainProdName.toUpperCase().match("KARLANDA") != null && mainProdName.toUpperCase().match(/LONG|LANG|LÅNG/) != null) { familyToShow = "karlandaLongSkirt"; }
        if (mainProdName.toUpperCase().match("KARLSTAD") != null) { familyToShow = "karlstad"; }
        if (mainProdName.toUpperCase().match("KARLSTAD") != null && mainProdName.toUpperCase().match(/LONG|LANG|LÅNG/) != null) { familyToShow = "karlstadLongSkirt"; }
        if (mainProdName.toUpperCase().match(/CUSHION|KISSEN|COUSSIN|KUSSEN|KUDD/) != null) {familyToShow = "cushion"; }
        if (mainProdName.toUpperCase().match("45X15") != null) { familyToShow = "cushion"; } // EKTORP NECK ROLL
        if (mainProdName.toUpperCase().match(/THROW|FOULARD|LÖST ÖVERDRAG/) != null) { familyToShow = "throw"; }

        if (mainProdName.toUpperCase().match(/FABRIC|METERWARE|TISSU|STOFFEN|TYG/) != null) { familyToShow = "fabricByTheMetre"; }

        if (familyToShow != "" && familyToShow != "fabricByTheMetre") { // ONLY SHOW MODEL LIST IF THE FAMILY MATCHED IS NOT EMPTY OR FABRIC BY THE METRE
            drawModelList(familyToShow);
        }
    }
}


// MODEL ARRAY PREPARATION FUNCTION -------------------------------------------------------
// This is to give the model array variables the proper form

function prepareModelArray(arrayName) {
    var tempArray = [];
    for (i = 1; i <= 30; i++) { // The number 30 is simply a number higher than the largest model map
        tempArray[i] = { "modelNameEnglish": "", "modelNameDutch": "", "modelNameFrench": "", "modelNameGerman": "", "modelNameSwedish": "", "modelImageNumber": "", "modelArticleNumber": "", "modelCategoryPath": "" };
    }
    eval(arrayName + " = tempArray"); // Write the temporary array to the current family array
}


// DRAWS THE MODEL LIST
function drawModelList(familyName) {

    checkIsRecommendationPage(); //Check if the current page is the product recommendation email page

    if (isRecommendationPage != "Yes") { // Only execute funcion if current page is not recommendation page

        familyName = familyName.substr(0, 1).toLowerCase() + familyName.substr(1);  // Corrects the family name if written with uppercase first letter in the html code
        familyName = familyName + "Models"; // Make the family name match the array name

        prepareModelArray(familyName); // Prepare the model array of the current family
        eval("load_" + familyName + "()"); // Load the model article numbers into the current model array

        var currentFamily = []; // Create a temporary array to use in the loop below
        eval("currentFamily = " + familyName); // Load the current model info into the temporary array


        var modelListCode = "";
        modelListCode += '<div style="font-size: 11px; border-top: 2px solid black; border-bottom: 0px solid black; padding: 2px 0px 2px 10px; margin-top: 15px; text-align: left;">';  // Write the header div

        // The header text
        if (currentLanguage == "de") {
            modelListCode += 'Modellen unt wohnaccessoires';
        }
        else if (currentLanguage == "fr") {
            modelListCode += 'modèles et accessoires';
        }
        else if (currentLanguage == "nl") {
            modelListCode += 'modellen en woonaccessoires';
        }
        else if (currentLanguage == "sv") {
            modelListCode += 'modeller och tillbehör';
        }
        else {
            modelListCode += 'models and accessories';
        }

        modelListCode += '</div>';  // End the header div

        modelListCode += '<div class="ModelList">';  // Write the container div

        for (i = 1; i < currentFamily.length; i++) { // Loop through the models in the family array
            if (currentFamily[i].modelNameEnglish === "") {  // Quit drawing when reaching the end of the list of defined models in the current family 
                break;
            }
            else {

                var currentModelName = "";
                var currentModelNameContainerId = ""; //Create the variable that is used to store the id for the mouseover name effect container;

                // Check language for correct model name
                if (currentLanguage == "de") {
                    currentModelName = currentFamily[i].modelNameGerman;
                }
                else if (currentLanguage == "fr") {
                    currentModelName = currentFamily[i].modelNameFrench;
                }
                else if (currentLanguage == "nl") {
                    currentModelName = currentFamily[i].modelNameDutch;
                }
                else if (currentLanguage == "sv") {
                    currentModelName = currentFamily[i].modelNameSwedish;
                }
                else {
                    currentModelName = currentFamily[i].modelNameEnglish;
                }


                // The anchor tag
                //modelListCode += '<span style="white-space: nowrap"><a href="/epages/62005383.sf/' + currentCulture;
                modelListCode += '<span style="white-space: nowrap"><a href="http://www.savemysofa.com/epages/62005383.sf/' + currentCulture;

                if (currentFamily[i].modelArticleNumber === "") { // If the model map is really a category map, link to category instead
                    modelListCode += '/?ObjectPath=/Shops/62005383/Categories/';
                    modelListCode += currentFamily[i].modelCategoryPath;
                }
                else {
                    if (currentFamily[i].modelImageNumber === "") {
                        currentFamily[i].modelImageNumber = currentFamily[i].modelArticleNumber; // If a link to a model, use article number as image number if no other image number is specified
                    }
                    modelListCode += '/?ObjectPath=/Shops/62005383/Products/';
                    modelListCode += currentFamily[i].modelArticleNumber;
                }
                modelListCode += '">';

                currentModelNameContainerId = currentFamily[i].modelImageNumber; // The mouseover model name container will be referenced through the image number

    
                // The image tag
                modelListCode += '<img src="/WebRoot/Store/Shops/62005383/MediaGallery/images/products/small/' + currentFamily[i].modelImageNumber + '.jpg"';
                modelListCode += 'alt="' + currentModelName + '" ';
                modelListCode += 'title=""  onmouseover="showFabricName(\'' + currentModelNameContainerId + '\')" onmouseout="hideFabricName(\'' + currentModelNameContainerId + '\')"></a>';


                modelListCode += '<span style="position: absolute;">';
                modelListCode += '<span id="' + currentModelNameContainerId + '" class="NameContainer">';
                modelListCode += '<div style="border: 1px solid white;">';
                modelListCode += '<table cellspacing="0" style="width: 100%;"><tr><td style="font-weight: normal; font-size: 11px; line-height: 13px; color: #000; padding: 2px 1px 2px 1px; vertical-align: middle; height: 35px; text-align: center; border: 1px solid black;">';
                modelListCode += currentModelName;
                modelListCode += '</td></tr></table>';
                modelListCode += '</div>';
                modelListCode += '</span>';
                modelListCode += '</span>';
                modelListCode += '</span> ';
            }
        }
        modelListCode += '</div>';


        jQuery(document).ready(function() {
            jQuery("div.ProductDetails").append("<div id='ListContainer'></div>"); 
            jQuery("#ListContainer").append(modelListCode);
        });
    }
}



// THE FUNCTION FOR DRAWING THE FABRIC LIST ---------------------------------------------
function drawFabricList(modelName) {

    if (isRecommendationPage != "Yes") { // Only execute function if current page is not recommendation page
        var currentModel = []; // Create a temporary array to use in the loop below
        eval("currentModel = " + modelName + "Fabrics"); // Load the current model info into the temporary array

        var fabricListCode = "";

        fabricListCode += '<div style="font-size: 11px; border-top: 2px solid black; border-bottom: 0px solid black; padding: 2px 0px 2px 10px; margin-top: 15px; ">';  // Write the header div

        // The header text
        if (currentLanguage == "de") {
            fabricListCode += 'Stoffe';
        }
        else if (currentLanguage == "fr") {
            fabricListCode += 'tissu';
        }
        else if (currentLanguage == "nl") {
            fabricListCode += 'stoffen';
        }
        else if (currentLanguage == "sv") {
            fabricListCode += 'tyger';
        }
        else {
            fabricListCode += 'fabrics';
        }

        fabricListCode += '</div>';  // End the header div
        fabricListCode += '<div class="FabricList">';  // Write the container div

        for (var i = 1; i < fabricInformation.length; i++) { // Loop through the fabrics in the predefined fabric order array
            for (var k = 1; k < currentModel.length; k++) { // Loop through the model fabrics to find the corresponding one, if it exists
                if ((currentModel[k].fabricId == fabricInformation[i].fabricId) && (currentModel[k].fabricId != undefined) && (currentModel[k].fabricArticleNumber != "")) { // If found, write the fabric link + image and then exit loop


                    //Check for first fabric on 2nd row - if so, insert break
                    if (currentModel[k].fabricId.match("PalermoGardeniaWhite") != null) {
                        fabricListCode += '<br /><br />';
                    }

                    //Check for first fabric on 3rd row - if so, insert break
                    if (currentModel[k].fabricId.match("LisbonWhisperWhite") != null) {
                        fabricListCode += '<br /><br />';
                    }
                    //Check for first fabric on 4th row - if so, insert break
                    else if (currentModel[k].fabricId.match("LisbonSafari") != null) {
                        fabricListCode += '<br />';
                    }
                    //Check for first fabric on 5th row - if so, insert break
                    else if (currentModel[k].fabricId.match("ParisAntiqueWhite") != null) {
                    fabricListCode += '<br /><br />';
                    }
                    //Check for first fabric on 6th row - if so, insert break
                    else if (currentModel[k].fabricId.match("ParisWarmSand") != null) {
                        fabricListCode += '<br />';
                    }
                    //Check for first fabric on 7th row - if so, insert break
                    else if (currentModel[k].fabricId.match("MonacoCloud") != null) {
                        fabricListCode += '<br /><br />';
                    }
                    //Check for first fabric on 8th row - if so, insert break
                    else if (currentModel[k].fabricId.match("BolognaSwan") != null) {
                        fabricListCode += '<br />';
                    }                    
                    
            
                    
                    // The anchor tag
                    fabricListCode += '<a href="http://www.savemysofa.com/epages/62005383.sf/' + currentCulture + '/?ObjectPath=/Shops/62005383/Products/';
                    fabricListCode += currentModel[k].fabricArticleNumber + '">';

                    // The image tag
                    fabricListCode += '<img src="/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/small/';
                    fabricListCode += fabricInformation[i].fabricId + '.jpg" alt="' + fabricInformation[i].fabricName + ' thumbnail" title="" onmouseover="showFabricName(\'' + fabricInformation[i].fabricId + '\')" onmouseout="hideFabricName(\'' + fabricInformation[i].fabricId + '\')"></a>';

                    // The fabric name containers

                    var originalFabricDisplayName = fabricInformation[i].fabricName;
                    var newFabricDisplayName = originalFabricDisplayName.replace(" ", "<br>");

                    fabricListCode += '<span style="position: absolute;">';
                    fabricListCode += '<span id="' + fabricInformation[i].fabricId + '" style="border: 1px solid white; width: 88px; position: absolute; bottom: 2px; left: -79px; display: none;">';
                    fabricListCode += '<span style="font-weight: normal; font-size: 11px; line-height: 13px; color: #000; padding: 2px 0px 2px 0px; display: block; white-space: nowrap; text-align: center; background: #fff; border: 1px solid black;">';
                    fabricListCode += newFabricDisplayName;
                    fabricListCode += '</span>';
                    fabricListCode += '</span>';
                    fabricListCode += '</span> ';
                    break;


                }
            }
        }
        fabricListCode += '</div>';

        jQuery(document).ready(function() {
            if (jQuery("#ListContainer").parent().html() == null) { // FOR FABRIC BY THE METRE, PAGES WHICH HAVE NO MODEL LIST
                jQuery("div.ProductDetails").append("<div id='ListContainer'></div>");
            }
            jQuery("#ListContainer").append(fabricListCode);
        });
    }
}




function showFabricName(fabricNameContainer) {
    document.getElementById(fabricNameContainer).style.opacity = 0;
    document.getElementById(fabricNameContainer).style.filter = "alpha(opacity=0)";
    document.getElementById(fabricNameContainer).style.display = "block";
    fadeInFabricName(fabricNameContainer, 0);
}

function hideFabricName(fabricNameContainer) {
    document.getElementById(fabricNameContainer).style.display = "none";
    // fadeOutFabricName(fabricNameContainer, 10);

}

function fadeOutFabricName(element, value) {
    document.getElementById(element).style.opacity = value / 10;
    document.getElementById(element).style.filter = "alpha(opacity=" + value * 10 + ")";
    value = value - 2;
    if (value > 0) {
        setTimeout('fadeOutFabricName("' + element + '", ' + value + ')', 5);
    }
    else {
        document.getElementById(element).style.display = "none";
    }
}


function fadeInFabricName(element, value) {
    document.getElementById(element).style.opacity = value / 10;
    document.getElementById(element).style.filter = "alpha(opacity=" + value * 10 + ")";
    value++;
    if (value <= 10) {
        setTimeout('fadeInFabricName("' + element + '", ' + value + ')', 15);
    }

}


// HIDE "CUSTOMERS WHO BOUGHT THIS ALSO BOUGHT" FUNCTIONALITY -------------------------------------------------------

jQuery(document).ready(function() {
    if (jQuery("table.CrossellingCount").html() != null) {
        jQuery("table.CrossellingCount").hide();
        jQuery("table.CrossellingCount").prev("h2").hide();
        jQuery("table.CrossellingCount").next(".TaxAndShippingInfo").hide();
    }
});



// FABRIC SAMPLE BANNER -------------------------------------------------------

function initiateFabricSampleBanner() {

    // ONLY EXECUTE IF BANNER CONTAINER EXISTS
    if (jQuery("#FabricSampleBanner").length) {

        // TEXT ON BANNER THE SAME AS LINK TEXT
        var displayText = jQuery("#FabricSampleBanner a").text();

        // DISPLAY THE TEXT WITH SHADOW
        jQuery("#FabricSampleBanner a").after("<span class='Shadow1'>" + displayText + "</span>");
        jQuery("#FabricSampleBanner a").after("<span class='Shadow2'>" + displayText + "</span>");
        jQuery("#FabricSampleBanner a").after("<span class='Shadow3'>" + displayText + "</span>");
        jQuery("#FabricSampleBanner a").after("<span class='Shadow4'>" + displayText + "</span>");
        jQuery("#FabricSampleBanner a").after("<span class='Front'>" + displayText + "</span>");

        // BANNER LINK SAME AS ANCHOR HREF (ANCHOR IS FOR SEARCH ENGINES)
        var bannerLink = jQuery("#FabricSampleBanner a").attr("href");
        jQuery("#FabricSampleBanner").bind("click", function() {
            window.location = bannerLink;
        });

        // START ANIMATING
        animateFabricSampleBanner(1);
    }
}

//FUNCTION FOR ANIMATING IMAGES IN FABRIC SAMPLE BANNER
function animateFabricSampleBanner(imageToShowNumber) {

    // SET THE VARIABLES
    var totalNumberOfImages = jQuery("#FabricSampleBanner img").length;
    var imageToHideNumber = 0;
    if (imageToShowNumber == 1) {
        imageToHideNumber = totalNumberOfImages;
    }
    else {
        imageToHideNumber = imageToShowNumber - 1
    }

    // SET IMAGE TO BE SHOWN AS A JQUERY VARIABLE
    var imageToShow = jQuery("#FabricSampleBanner img:eq(" + (imageToShowNumber - 1) + ")");

    // DECREASE Z-INDEX BY ONE FOR ALL IMAGES AND THEN
    // HIDE ACTIVE IMAGE, SET Z-INDEX TO 99 AND THEN FADE IN
    jQuery("#FabricSampleBanner img").each(function() {
        var currentZIndex = jQuery(this).css("z-index");
        imageToShow.hide();
        jQuery(this).css("z-index", (currentZIndex - 1));
        imageToShow.css("z-index", "99");
        imageToShow.fadeIn("slow");
    });

    // SELECT NEXT IMAGE TO SHOW
    imageToShowNumber++;
    if (imageToShowNumber > totalNumberOfImages) {
        imageToShowNumber = 1;
    }

    // RUN ITSELF IN THREE SECONDS WITH NEW IMAGE TO FADE IN
    setTimeout("animateFabricSampleBanner(" + imageToShowNumber + ")", 3000);
}

//FUNCTION FOR DISPLAYING SOFA WITHOUT COVER BANNER CORRECTLY ( AS A TABLE)
function initiateSofaWithoutCoverBanner() {
    if (jQuery("#SofaWithoutCoverBanner").length) {
        jQuery("#SofaWithoutCoverBanner").wrapInner("<table><tr><td></td></tr></table>");
    }
}



// FUNCTION FOR ANIMATING IMAGES IN START PAGE BANNER
function animateStartPageBanner(imageToShowNumber) {
    if (jQuery("#StartPageBanner").length) {
        // SET THE VARIABLES
        var totalNumberOfImages = jQuery("#StartPageBanner img").length;
        var imageToHideNumber = 0;
        if (imageToShowNumber == 1) {
            imageToHideNumber = totalNumberOfImages;
        }
        else {
            imageToHideNumber = imageToShowNumber - 1
        }

        // SET IMAGE TO BE SHOWN AS A JQUERY VARIABLE
        var imageToShow = jQuery("#StartPageBanner img:eq(" + (imageToShowNumber - 1) + ")");

        // DECREASE Z-INDEX BY ONE FOR ALL IMAGES AND THEN
        // HIDE ACTIVE IMAGE, SET Z-INDEX TO 99 AND THEN FADE IN
        jQuery("#StartPageBanner img").each(function() {
            var currentZIndex = jQuery(this).css("z-index");
            imageToShow.hide();
            jQuery(this).css("z-index", (currentZIndex - 1));
            imageToShow.css("z-index", "99");
            imageToShow.fadeIn("slow");
        });

        // SELECT NEXT IMAGE TO SHOW
        imageToShowNumber++;
        if (imageToShowNumber > totalNumberOfImages) {
            imageToShowNumber = 1;
        }

        // RUN ITSELF IN THREE SECONDS WITH NEW IMAGE TO FADE IN
        setTimeout("animateStartPageBanner(" + imageToShowNumber + ")", 3500);
    }
}

// IS CURRENT PAGE BARGAIN CORNER? MATCH URL OR BREADCRUMBS
var currentPageIsBargainCorner = false;
function checkIsBargainCorner() {
    var breadcrumbText = jQuery("div.ContentAreaWrapper h3:first").text();
    if (currentUrl.match(/BargainCorner|2635020/) != null) {
        currentPageIsBargainCorner = true;
    }
    else if (breadcrumbText.match(/bargain|koopjeshoek|schnäppchenecke|affaires|fyndhörna/i) != null) {
        currentPageIsBargainCorner = true;
    }
}

function displayBargainCornerPage() {
    if (currentPageIsBargainCorner == true) {
        jQuery(".ProductListHead, .ListItemProductContainer, .ProductListFoot, .SearchMask").show();
        jQuery("#ListContainer").hide();
        jQuery(".ProductListHead").css("border-top", "1px solid black").css("border-bottom", "1px solid black");
        jQuery(".ListItemProductContainer").css("width", "auto").css("border-bottom", "1px solid #ccc");
        jQuery(".ListItemProductContainer").css("padding", "5px 0");
        jQuery("h3.Headline a").css("font-weight", "bold");
        jQuery("div.Description").hide();
        jQuery(".SearchMask .Separator").css("height", "0px");
        jQuery("td.Links a, td.Links br").hide();
        jQuery(".InfoArea .ImageArea").css("height", "65px").css("min-height", "65px");
        jQuery(".Pager").css("display", "block");
        jQuery(".SearchString, .SearchIcon").hide();
        jQuery("i.ProductOnStockIcon").parent().hide();
    }
}


//fabricNameToImageName


// OUR FABRICS PAGE
function displayOurFabricsPage() {
    if (jQuery("div.FabricInfo").length) {

        jQuery(".FabricInfoList span.FabricInfoImage").each(function () {
            var fabricName = jQuery(this).text();
            var popupFabricName = fabricName.replace(" ", "<br>");
            var fabricImageName = fabricNameToImageName(fabricName);
            var fabricImageCode = "";

            fabricImageCode += '<img src="/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/small/';
            fabricImageCode += fabricImageName;
            fabricImageCode += '.jpg" alt="';
            fabricImageCode += fabricName + '" ';
            fabricImageCode += 'onclick="showFabricInfoPopup(\'' + fabricImageName + '\', \'jpg\', \'' + fabricName + '\')" ';
            fabricImageCode += 'onmouseover="showFabricLabel(\'' + fabricImageName + '\')" ';
            fabricImageCode += 'onmouseout="hideFabricLabel(\'' + fabricImageName + '\')" />';
            fabricImageCode += '';
            fabricImageCode += '';

            fabricImageCode += '<span class="FabricLabelWrapper">';
            fabricImageCode += '<span class="FabricLabelContainer" id="' + fabricImageName + '" >';
            fabricImageCode += '<span class="FabricLabel" >';
            fabricImageCode += popupFabricName;
            fabricImageCode += '</span>';
            fabricImageCode += '</span>';
            fabricImageCode += '</span> ';

            jQuery(this).parent().append(fabricImageCode);
        });

        // PUT CLICK FOR CLOSE-UP MESSAGE
        var clickForCloseUpMessage = "";
        if (currentLanguage == "de") { clickForCloseUpMessage = 'Nahaufnahme des Stoffe'; }
        else if (currentLanguage == "fr") { clickForCloseUpMessage = 'Close-up de tissu'; }
        else if (currentLanguage == "nl") { clickForCloseUpMessage = 'Close-up van stof'; }
        else if (currentLanguage == "sv") { fabriclickForCloseUpMessagecLinkCode = '(klicka för närbild av tyget)'; }
        else { clickForCloseUpMessage = '(click for close-up of fabric)'; }
        jQuery("div.FabricInfoList").append("<span class='FabricListHeader'>" + clickForCloseUpMessage + "</span>");

        //SET LOADER IMAGE
        jQuery("div.FabricInfo:first").append(renderFabricPopup("loader", "gif", "Loading..."));
    }
}

function showFabricInfoPopup(fabricImageName, imageType, fabricName) {

    var imageFolder = "/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/fabric-popup/";
    var imageSrc = imageFolder + fabricImageName + "." + imageType;

    jQuery("div#FabricPopupImage img").attr("src", imageFolder + "loader.gif");
    jQuery("div#FabricPopupImage img").attr("alt", "Loading...");

    jQuery("div#FabricPopupImage img").attr("src", imageSrc);
    jQuery("div#FabricPopupImage img").attr("alt", fabricName);
    jQuery("div#FabricPopup").fadeIn("slow");
}

function showFabricLabel(labelId) {
    jQuery("#" + labelId).fadeIn(150);
}

function hideFabricLabel(labelId) {
    jQuery("#" + labelId).hide();
}

jQuery(document).ready(function () {

    jQuery("#SofaWithoutCoverBanner").after("<div id='testContainer' style='color: white'></div>");
    checkIsBargainCorner();
    displayMainSubProdName();
    autoMatchModelFamily();
    autoFabricLink();
    autoMatchModel();
    initiateFabricSampleBanner();
    initiateSofaWithoutCoverBanner();
    animateStartPageBanner(1);
    displayBargainCornerPage();
    displayOurFabricsPage();

});