﻿// THESE FUNCTIONS PREPARE AND DRAW THE MODEL AND FABRIC LISTS, AND SET/CHECK GENERAL VARIABLES

//jQuery.noConflict();

// VARIABLE OF CURRENT URL
var currentUrl = window.location.href.toString();

// TEST CONDITION
var isTest = false;
if (currentUrl.match("test=true")) {
    isTest = true;
}

// GLOBAL VARIABLES -----------------
var mainProdName = "";
var subProdName = "";
var currentFabricId = "";
var currentModelNumber = "";
var currentFabricNumber = "";
var currentProductNumber = "";
var currentModelFamily = "";
var currentCatType = "";
var standardFabricNumber = "817-08";
var isBargainCornerPage = false;

// FUNCTION FOR EXTRACTING MODEL AND FABRIC NUMBERS ON PRODUCT PAGES
function getModelNumbers() {
    if (jQuery("div.ProductDetails").length) {

        // FIRST TRY MATCHING THROUGH URL
        if (currentUrl.match(/product/gi) != null) {
            var productPosition = currentUrl.indexOf("/Products/");
            currentProductNumber = currentUrl.substr(productPosition);
            currentProductNumber = currentProductNumber.replace("/Products/", "");
            // DELETE BARGAIN CORDER PREFIX
            currentProductNumber = currentProductNumber.replace(/BE-|SE-/i, "");
            var firstHyphenPosition = currentProductNumber.indexOf("-");

            currentModelNumber = currentProductNumber.substr(0, firstHyphenPosition);
            currentFabricNumber = currentProductNumber.substr(firstHyphenPosition + 1);
        }

        // IF NOT THEN TRY TO GET PROD NR FROM MAIN IMAGE (THIS IS WHEN SWITCHING LANGUAGES ON A PRODUCT PAGE OR WHEN ADDING TO CART)
        else {
            var prodImg = jQuery("#ProductSlideshow img:first");

            if (prodImg.length) {
                var mainProdImageUrl = prodImg.attr("src");
                // alert(mainProdImageUrl);

                // DO NOT WRITE LIST IF THERE IS NO REAL IMAGE

                // THIS NEED TO BE FIXED FOR MODEL/FABRIC NUMBERS
                var mainProdImageUrlLength = mainProdImageUrl.length;
                currentProductNumber = mainProdImageUrl.substr(mainProdImageUrlLength - 20);
                var productIdPosition = currentProductNumber.search(/_[\d]{3}/);

                currentProductNumber = currentProductNumber.substr(productIdPosition + 1).replace(".jpg", ""); ;
                currentModelNumber = currentProductNumber.substr(0, 3);
                currentFabricNumber = currentProductNumber.substr(4);
            }
        }

        // IF STATIC PRODUCT, CHANGE TO STANDARD FABRIC NUMBER
        if (isStaticProduct(currentModelNumber)) {
            currentFabricNumber = "000-00";
        }

        //alert(currentProductNumber + " " + currentModelNumber + " " + currentFabricNumber);

    }
}


// DEFINING GENERIC PRODUCTS THAT DO NOT HAVE FAMILY NAME
function isGenericProduct(prodNumber) {
    if (prodNumber.match(/101|102|104|105|108|682|686|200|205|210|225/)) {
        return true;
    }
    else {
        return false;
    }
}


// DEFINING STATIC PRODUCTS (THAT DO NOT COME IN VARIOUS FABRICS)
function isStaticProduct(prodNumber) {
    if (prodNumber.match(/601|602|603|606|607|715|716|717/)) {
        return true;
    }
    else {
        return false;
    }
}

// DEFINING PRODUCTS THAT ARE NOT COVERS
function isCoverProduct(prodNumber) {
    if (prodNumber.match(/601|602|603|606|607|715|716|717|900|683|684|685/)) {
        return false;
    }
    else {
        return true;
    }
}


// CHECK WHAT CURRENT CAT TYPE
function checkCatType() {
    if (jQuery("div.ProductDetails").length) { // ONLY DO ON PRODUCT PAGES
        var breadCrumbText = jQuery(".BreadcrumbItem").text();
        if (breadCrumbText.match(/sof|faut/i)) { currentCatType = "sofas"; }
        else if (breadCrumbText.match(/cush|kiss|couss|kuss|kudd/i)) { currentCatType = "cushions"; }
        else if (breadCrumbText.match(/pad|stuhl|carreau|stoel|stol/i)) { currentCatType = "chairs"; }
        else if (breadCrumbText.match(/metre|meter|métre/i)) { currentCatType = "fabrics"; }
    }
}

// DIVIDE PRODUCT NAME ON PRODUCT PAGE IN MAIN (MODEL) AND SUB (FABRIC) NAMES FOR NICER LAYOUT + ADD "COVER FOR"
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 = "Slipcover for"; }
            if (currentLanguage == "de") { coverText = "Bezug für"; }
            if (currentLanguage == "fr") { coverText = "Housse pour"; }
            if (currentLanguage == "nl") { coverText = "Hoes voor"; }
            if (currentLanguage == "sv") { coverText = "Klädsel till"; }

            // MATCH AGAINST NON-COVER PRODUCTS 
            if (isCoverProduct(currentModelNumber)) {
                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)
        currentFabricId = fabricNameToImageName(subProdName);
        if (currentFabricId == "") {
            currentFabricId = "NotDefined";
        }
    }
}

// FUNCTION FOR TRANSFORMING A REAL FABRIC NAME INTO IMAGE NAME
function fabricNameToImageName(fabricName) {

    var imageName = fabricName.toLowerCase();

    // DELETE "-" FROM RE-COVER
    imageName = imageName.replace(/re-cover/g, "recover");

    // 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/medium/';
    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 fabricLinkCode = "";
        fabricLinkCode += '<a id="FabricLink" onclick="openFabricPopup();">';

        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 += '</a><div class="ClearBoth"></div>';

        fabricLinkCode += renderFabricPopup(currentFabricId, "jpg", subProdName);

        jQuery("table.FullSize .TableLayoutRow > td:first").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();
}



// AUTO MATCH THE FABRIC LIST TO BE DISPLAYED
function autoMatchModel() {

    if (jQuery("div.ProductDetails").length && isBargainCornerPage == false && !isStaticProduct(currentModelNumber)) {
            drawFabricList(currentModelNumber);
    }
}


// FUNCTION FOR EXPLICITLY DRAWING A FABRIC LIST ANYWHERE
function drawManualFabricList(modelToShow) {
    drawFabricList(modelToShow);
}

// AUTOMATICALLY WRITE MODEL FAMILY
var familyToShow = "";

var isPartOfSofaFamily = false;
function autoMatchModelFamily() {
    if (jQuery("div.ProductDetails").length) { // ONLY DO ON PRODUCT PAGES

        // CHECK IF PRODUCT IS PART OF SOFA FAMILY (FOR MIX & MATCH)
        
        if (currentCatType == "sofas") {
            isPartOfSofaFamily = true;
        }

        if (mainProdName.match(/BARKABY/i)) { familyToShow = "armchair"; currentModelFamily = "barkaby"; }
        if (mainProdName.match(/BÖRJE/i)) { familyToShow = "borje"; currentModelFamily = "borje"; }
        if (mainProdName.match(/EKTORP/i)) { familyToShow = "ektorp"; currentModelFamily = "ektorp"; }
        if (mainProdName.match(/HARRY/i)) { familyToShow = "harry"; currentModelFamily = "harry"; }
        if (mainProdName.match(/HENRIKSDAL/i)) { familyToShow = "henriksdal"; currentModelFamily = "henriksdal"; }
        if (mainProdName.match(/IVAR/i)) { familyToShow = "ivar"; currentModelFamily = "ivar"; }
        if (mainProdName.match(/JENNYLUND/i)) { familyToShow = "armchair"; currentModelFamily = "jennylund"; }
        if (mainProdName.match(/KAUSTBY/i)) { familyToShow = "kaustby"; currentModelFamily = "kaustby"; }
        if (mainProdName.match(/KLAPPSTA/i)) { familyToShow = "armchair"; currentModelFamily = "klappsta"; }
        if (mainProdName.match(/TULLSTA/i)) { familyToShow = "armchair"; currentModelFamily = "tullsta"; }
        if (mainProdName.match(/EKESKOG/i)) { familyToShow = "ekeskog"; currentModelFamily = "ekeskog"; }
        if (mainProdName.match(/HAGALUND/i)) { familyToShow = "hagalund"; currentModelFamily = "hagalund"; }
        if (mainProdName.match(/GÖTEBORG/i)) { familyToShow = "goteborg"; currentModelFamily = "goteborg"; }
        if (mainProdName.match(/KLIPPAN/i)) { familyToShow = "klippan"; currentModelFamily = "klippan"; }
        if (mainProdName.match(/LILLBERG/i)) { familyToShow = "lillberg"; currentModelFamily = "lillberg"; }
        if (mainProdName.match(/LYCKSELE/i)) { familyToShow = "lycksele"; currentModelFamily = "lycksele"; }
        if (mainProdName.match(/IKEA PS/i)) { familyToShow = "armchair"; currentModelFamily = "ps"; }
        if (mainProdName.match(/POÄNG/i)) { familyToShow = "armchair"; currentModelFamily = "poang"; }
        if (mainProdName.match(/STRÖMSTAD/i)) { familyToShow = "stromstad"; currentModelFamily = "stromstad"; }
        if (mainProdName.match(/KRAMFORS/i)) { familyToShow = "kramfors"; currentModelFamily = "kramfors"; }
        if (mainProdName.match(/NIKKALA/i)) { familyToShow = "nikkala"; currentModelFamily = "nikkala"; }
        if (mainProdName.match(/TOMELILLA/i)) { familyToShow = "tomelilla"; currentModelFamily = "tomelilla"; }
        if (mainProdName.match(/TYLÖSAND/i)) { familyToShow = "tylosand"; currentModelFamily = "tylosand"; }
        if (mainProdName.match(/BEDDINGE/i)) { familyToShow = "beddinge"; currentModelFamily = "beddinge"; }
        if (mainProdName.match(/KARLANDA/i)) { familyToShow = "karlanda"; currentModelFamily = "karlanda"; }
        if (mainProdName.match(/KIVIK/i)) { familyToShow = "kivik"; currentModelFamily = "kivik"; }
        if (mainProdName.match(/KARLSTAD/i)) { familyToShow = "karlstad"; currentModelFamily = "karlstad"; }
        if (mainProdName.match(/MYSINGE/i)) { familyToShow = "mysinge"; currentModelFamily = "mysinge"; }
        if (mainProdName.match(/FRAME|STRUCT|GESTELL|STOMM|BACK|RUG|DOS|RÜCK|RYGG/i)) { isPartOfSofaFamily = true } // ADD-ON STRUCTURAL STUFF, LIKE BACK CUSHIONS
        if (mainProdName.match(/CUSHION|KISSEN|COUSSIN|KUSSEN|KUDD/i) && isPartOfSofaFamily == false) { familyToShow = "cushionCover"; }
        if (mainProdName.match(/IKEA/i) && mainProdName.match(/CUSHION|KISSEN|COUSSIN|KUSSEN|KUDD/i) && isPartOfSofaFamily == false) { familyToShow = "forIkeaCushion"; }
        if (mainProdName.match(/45X15/i)) { familyToShow = "forIkeaCushion"; } // EKTORP NECK ROLL
        if (mainProdName.match(/PAD|STUHLKISSEN|CARREAU|STOELKUSSEN|DYNA/i)) { familyToShow = "chairpad"; }
        if (mainProdName.match(/INNE|INTÉRIEUR/i)) { familyToShow = "innerCushion"; }
        if (mainProdName.match(/THROW|FOULARD|LÖST ÖVERDRAG/i)) { familyToShow = "throw"; }
        if (mainProdName.match(/FABRIC|METERWARE|TISSU|STOFFEN|TYG/i)) { familyToShow = "fabricByTheMetre"; }
        if (familyToShow != "" && familyToShow != "fabricByTheMetre") { // ONLY SHOW MODEL LIST IF THE FAMILY MATCHED IS NOT EMPTY OR FABRIC BY THE METRE
            //alert(familyToShow + currentModelFamily);
            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": "", "modelSubType": "", "modelArticleNumber": "" };
    }
    eval(arrayName + " = tempArray"); // Write the temporary array to the current family array
}


// DRAWS THE MODEL LIST
function drawModelList(familyName) {

    // ONLY DRAW MODEL LIST IF A FABRIC IS CURRENTLY DEFINED
    if (currentFabricNumber != "" && !isBargainCornerPage) {

        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 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 {

                // DO NOT WRITE OUT HEADER DEFINITION ITEM
                if (currentFamily[i].modelArticleNumber != "familyBoxHeader") {

                    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;
                    }


                    // MODEL LINK HREF
                    var modelLinkHref = "?ObjectPath=/Shops/62005383/Products/" + currentFamily[i].modelArticleNumber + "-" + currentFabricNumber;




                    modelListCode += "<div class='ModelContainer " + currentFamily[i].modelSubType + "'>";
                    modelListCode += "<a class='ImageContainer' href='" + modelLinkHref + "'>";

                    var modelImageSrc = "/WebRoot/Store/Shops/62005383/MediaGallery/images/products/small/IKEA_";

                    // DO NOT ADD FAMILY NAME FOR GENERIC PRODUCTS
                    if (isGenericProduct(currentFamily[i].modelArticleNumber) == false) {
                        // IF IKEA MODEL, USE IKEA FAMILY NAME
                        if (currentModelName.match(/IKEA/) != null) {
                            var modelImageFamilyName = currentModelName.replace("IKEA ", "");
                            modelImageFamilyName = modelImageFamilyName.substr(0, modelImageFamilyName.indexOf(" "));
                            modelImageFamilyName = modelImageFamilyName.toLowerCase().replace(/å|ä/, "a").replace("ö", "o");
                            modelImageSrc = modelImageSrc + modelImageFamilyName + "_";

                        }
                        // IF NOT IKEA MODEL, USE GENERAL FAMILY NAME
                        else {
                            modelImageSrc = modelImageSrc + currentModelFamily + "_";
                        }



                    }

                    // PUT SRC IN TITLE AND ADD SRC AFTER TO MAKE ERROR CORRECTION POSSIBLE
                    modelImageSrc = modelImageSrc + currentFamily[i].modelArticleNumber + "-" + currentFabricNumber + ".jpg";
 
                    modelListCode += "<img class='ModelImage' title='" + modelImageSrc + "' ";
                    modelListCode += "alt='" + currentModelName + "' />";
                    modelListCode += "</a>";


                    //THE NAME HOVER CONTAINERS
                    modelListCode += "<div class='ModelNameContainer'>";
                    modelListCode += "<span>";
                    modelListCode += currentModelName;
                    modelListCode += "</span>";
                    modelListCode += "</div>";

                    modelListCode += "</div>";

                }

            }
        }

        // CLOSE DIV WITH CLEARING
        modelListCode += '<div style="clear:both"></div></div>';

        jQuery(".NavBarRight .SizeContainer").html(modelListCode);


        // CHECK FOR SUBTYPES AND ORGANIZE MODELS

        // MIX & MATCH
        if (jQuery(".ModelList .MixAndMatch").length) {
            var subTypeHeader_MixAndMatch = "";
            if (currentLanguage == "de") { subTypeHeader_MixAndMatch = "mix & match" }
            else if (currentLanguage == "fr") { subTypeHeader_MixAndMatch = "mix & match" }
            else if (currentLanguage == "nl") { subTypeHeader_MixAndMatch = "mix & match" }
            else if (currentLanguage == "sv") { subTypeHeader_MixAndMatch = "mix & match" }
            else { subTypeHeader_MixAndMatch = "mix & match" }
            jQuery(".ModelList").append("<div id='SubType_MixAndMatch' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_MixAndMatch + "</div></div>");
            jQuery("#SubType_MixAndMatch").append(jQuery(".ModelList .MixAndMatch").detach());
        }

        // FOR BUILD IN
        if (jQuery(".ModelList .ForBuildIn").length) {
            var subTypeHeader_ForBuildIn = "";
            if (currentLanguage == "de") { subTypeHeader_ForBuildIn = "anbauteil" }
            else if (currentLanguage == "fr") { subTypeHeader_ForBuildIn = "élément complémentaire" }
            else if (currentLanguage == "nl") { subTypeHeader_ForBuildIn = "voor aanbouw" }
            else if (currentLanguage == "sv") { subTypeHeader_ForBuildIn = "för påbyggnad" }
            else { subTypeHeader_ForBuildIn = "for add-on" }
            jQuery(".ModelList").append("<div id='SubType_ForBuildIn' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_ForBuildIn + "</div></div>");
            jQuery("#SubType_ForBuildIn").append(jQuery(".ModelList .ForBuildIn").detach());
        }

        // SOFABED
        if (jQuery(".ModelList .Sofabed").length) {
            var subTypeHeader_Sofabed = "";
            if (currentLanguage == "de") { subTypeHeader_Sofabed = "bettsofas" }
            else if (currentLanguage == "fr") { subTypeHeader_Sofabed = "convertibles" }
            else if (currentLanguage == "nl") { subTypeHeader_Sofabed = "slaapbanken" }
            else if (currentLanguage == "sv") { subTypeHeader_Sofabed = "bäddsoffor" }
            else { subTypeHeader_Sofabed = "sofabeds" }
            jQuery(".ModelList").append("<div id='SubType_Sofabed' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_Sofabed + "</div></div>");
            jQuery("#SubType_Sofabed").append(jQuery(".ModelList .Sofabed").detach());
        }
        
        // LONG SKIRT
        if (jQuery(".ModelList .Long").length) {
            var subTypeHeader_Long = "";
            if (currentLanguage == "de") { subTypeHeader_Long = "lang" }
            else if (currentLanguage == "fr") { subTypeHeader_Long = "longue" }
            else if (currentLanguage == "nl") { subTypeHeader_Long = "lang" }
            else if (currentLanguage == "sv") { subTypeHeader_Long = "lång" }
            else { subTypeHeader_Long = "long" }
            jQuery(".ModelList").append("<div id='SubType_Long' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_Long + "</div></div>");
            jQuery("#SubType_Long").append(jQuery(".ModelList .Long").detach());
        }

        // FOR LEATHER SOFAS
        if (jQuery(".ModelList .ForLeatherSofa").length) {
            var subTypeHeader_ForLeatherSofa = "";
            if (currentLanguage == "de") { subTypeHeader_ForLeatherSofa = "für ledersofas" }
            else if (currentLanguage == "fr") { subTypeHeader_ForLeatherSofa = "pour canapés cuir" }
            else if (currentLanguage == "nl") { subTypeHeader_ForLeatherSofa = "voor leder sofas" }
            else if (currentLanguage == "sv") { subTypeHeader_ForLeatherSofa = "till lädersoffor" }
            else { subTypeHeader_ForLeatherSofa = "for leather sofas" }
            jQuery(".ModelList").append("<div id='SubType_ForLeatherSofa' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_ForLeatherSofa + "</div></div>");
            jQuery("#SubType_ForLeatherSofa").append(jQuery(".ModelList .ForLeatherSofa").detach());
        }

        // FOR IKEA CUSHIONS
        if (jQuery(".ModelList .ForIkeaCushion").length) {
            var subTypeHeader_ForIkeaCushion = "";
            if (currentLanguage == "de") { subTypeHeader_ForIkeaCushion = "für IKEA kissen" }
            else if (currentLanguage == "fr") { subTypeHeader_ForIkeaCushion = "coussins pour IKEA" }
            else if (currentLanguage == "nl") { subTypeHeader_ForIkeaCushion = "voor IKEA kussens" }
            else if (currentLanguage == "sv") { subTypeHeader_ForIkeaCushion = "för IKEA-kuddar" }
            else { subTypeHeader_ForIkeaCushion = "for IKEA cushions" }
            jQuery(".ModelList").append("<div id='SubType_ForIkeaCushion' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_ForIkeaCushion + "</div></div>");
            jQuery("#SubType_ForIkeaCushion").append(jQuery(".ModelList .ForIkeaCushion").detach());
        }

        // ARMCHAIRS
        if (jQuery(".ModelList .Armchair").length) {
            var subTypeHeader_Armchair = "";
            if (currentLanguage == "de") { subTypeHeader_Armchair = "für IKEA kissen" }
            else if (currentLanguage == "fr") { subTypeHeader_Armchair = "coussins pour IKEA" }
            else if (currentLanguage == "nl") { subTypeHeader_Armchair = "voor IKEA kussens" }
            else if (currentLanguage == "sv") { subTypeHeader_Armchair = "för IKEA-kuddar" }
            else { subTypeHeader_Armchair = "for IKEA cushions" }
            jQuery(".ModelList").append("<div id='SubType_Armchair' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_Armchair + "</div></div>");
            jQuery("#SubType_Armchair").append(jQuery(".ModelList .Armchair").detach());
        }

        // STANDARD (LAST BUT APPEARS FIRST)
        if (jQuery(".ModelList > div.ModelContainer").length) {
            var subTypeHeader_Standard = "";
            if (currentLanguage == "de") { subTypeHeader_Standard = "wählen sie ihr modell" }
            else if (currentLanguage == "fr") { subTypeHeader_Standard = "choisissez votre modèle" }
            else if (currentLanguage == "nl") { subTypeHeader_Standard = "kies uw model" }
            else if (currentLanguage == "sv") { subTypeHeader_Standard = "välj din modell" }
            else { subTypeHeader_Standard = "choose your model" }
            jQuery(".ModelList").prepend("<div id='SubType_Standard' class='SubType'><div class='SubTypeHeader'>" + subTypeHeader_Standard + "</div></div>");
            jQuery("#SubType_Standard").append(jQuery(".ModelList > div.ModelContainer").detach());
        }


        // INSERT CLEAR DIV AT THE END OF EACH CONTAINER
        jQuery(".SubType").append("<div class='ClearBoth'></div>");


        // NONEXISTING IMAGES ARE TO BE SUBSTITUTED WITH B/W GENERIC IMAGES
        // BIND ERROR EVENT TO EVERY IMAGE, THEN ASSIGN SRC
        jQuery(".ModelList img").each(function () {
            jQuery(this).error(function () {

                // ON ERROR, GET B/W IMAGE SRC FROM HREF
                var thisLinkHref = jQuery(this).parent().attr("href");
                var thisModelText = jQuery(this).parent().next().find("span").text();
                var newModelImgSrc = makeBwModelImageSrc(thisLinkHref, thisModelText);
                jQuery(this).attr("src", newModelImgSrc);

                // NOW CREATE DUPLICATE AND REMOVE SELF TO AVOID PLATFORM INTERCEPT
                var clonedImageCode = "<img src='" + jQuery(this).attr('src') + "' alt='" + jQuery(this).attr('alt') + "' title='' />";
                jQuery(this).after(clonedImageCode);
                jQuery(this).remove();

            });
            jQuery(this).attr("src", jQuery(this).attr("title"));
            jQuery(this).attr("title", "");
        });
    }
}


// FUNCTION FOR MAKING B/W MODEL IMAGE SRC FROM MODEL LINK HREF
function makeBwModelImageSrc(linkHref, imgTxt) {
    var newModelImgSrc = linkHref;
    var productPosition = newModelImgSrc.indexOf("/Products/");

    newModelImgSrc = newModelImgSrc.substr(productPosition).replace("/Products/", "");
    var firstHyphenPosition = newModelImgSrc.indexOf("-");
    var thisModelNumber = newModelImgSrc.substr(0, firstHyphenPosition);
    var modelImageFamilyName = "";
    



        // GET FAMILY NAME FROM THIS MODEL NAME TEXT IF IKEA MODEL
        if (imgTxt.match(/IKEA/)) {
            modelImageFamilyName = imgTxt.replace("IKEA ", "");
            modelImageFamilyName = modelImageFamilyName.substr(0, modelImageFamilyName.indexOf(" "));
            modelImageFamilyName = modelImageFamilyName.toLowerCase().replace(/å|ä/, "a").replace("ö", "o");
            modelImageFamilyName = modelImageFamilyName + "_";

        }
        // IF NOT IKEA MODEL, USE GENERAL FAMILY NAME
        else {
            // modelImageFamilyName = currentModelFamily + "_";
        }


    newModelImgSrc = "/WebRoot/Store/Shops/62005383/MediaGallery/images/products/small/" + "IKEA_" + modelImageFamilyName + thisModelNumber + ".jpg";
    return (newModelImgSrc);

}


// THE FUNCTION FOR DRAWING THE FABRIC LIST ---------------------------------------------


function drawFabricList(modelNumber) {

    jQuery("body").append("<div id='FabricSamplePopupBg' onclick='closeFabricSamplePopup();'></div>"); //Write the sample popup background
    jQuery("body").append("<div id='FabricSamplePopupContent'></div>"); //Write the sample popup container

    var fabricListCode = "";
    fabricListCode += "<div id='FabricList'>";
    fabricListCode += "<div id='FabricListHeader'>";  // Write the header div

    if (currentLanguage == "de") { fabricListCode += "wählen sie ihren stoff" }
    else if (currentLanguage == "fr") { fabricListCode += "choisissez votre tissu" }
    else if (currentLanguage == "nl") { fabricListCode += "kies uw stof" }
    else if (currentLanguage == "sv") { fabricListCode += "välj ditt tyg" }
    else { fabricListCode += "choose your fabric" }

    fabricListCode += "</div>";

    for (var i = 1; i < fabricMatrix.length; i++) { // LOOP THROUGH THE FABRICS IN THE PREDEFINED FABRIC ORDER ARRAY

        // WRITE FABRIC FAMILY NAME
        if (fabricMatrix[i].fabricFamilyEn != null) {

            if (currentLanguage == "de") {
                currentFabricFamilyName = fabricMatrix[i].fabricFamilyDe;
            }
            else if (currentLanguage == "fr") {
                currentFabricFamilyName = fabricMatrix[i].fabricFamilyFr;
            }
            else if (currentLanguage == "nl") {
                currentFabricFamilyName = fabricMatrix[i].fabricFamilyNl;
            }
            else if (currentLanguage == "sv") {
                currentFabricFamilyName = fabricMatrix[i].fabricFamilySv;
            }
            else {
                currentFabricFamilyName = fabricMatrix[i].fabricFamilyEn;
            }
            fabricListCode += "<div class='SampleContainer'><span class='FabricFamilyName'>" + currentFabricFamilyName + "</span></div>";
        }
        // CHECK FOR BLANK SPACES
        else if (fabricMatrix[i].fabricNumber.match("EMPTY-SPACE") != null) {
            fabricListCode += '<div class="SampleContainer"></div>';
        }

        else {

            // THE FABRIC DESCRIPTION OF THE CURRENTLY VISIBLE PRODUCT
            if (currentFabricId == fabricMatrix[i].fabricId) {
                var currentFabricDescription = "";

                if (currentLanguage == "de") {
                    currentFabricDescription = fabricMatrix[i].fabricTextDe;
                }
                else if (currentLanguage == "fr") {
                    currentFabricDescription = fabricMatrix[i].fabricTextFr;
                }
                else if (currentLanguage == "nl") {
                    currentFabricDescription = fabricMatrix[i].fabricTextNl;
                }
                else if (currentLanguage == "sv") {
                    currentFabricDescription = fabricMatrix[i].fabricTextSv;
                }
                else {
                    currentFabricDescription = fabricMatrix[i].fabricTextEn;
                }
                // PUT FABRIC DESCRIPTION IN
                jQuery(".InfoArea .FullSize div:eq(1)").addClass("ProductDescription").before("<div class='FabricDescription'>" + currentFabricDescription + "</div>");
            }

            fabricListCode += '<div class="SampleContainer">';
            fabricListCode += '<a class="ImageContainer" href="?ObjectPath=/Shops/62005383/Products/';
            fabricListCode += modelNumber + "-" + fabricMatrix[i].fabricNumber + '">';
            fabricListCode += '<img class="Sample" src="http://www.savemysofa.com/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/small/';
            fabricListCode += fabricMatrix[i].fabricId + '.jpg" alt="' + fabricMatrix[i].fabricName + ' thumbnail" title="" >';
            fabricListCode += '</a>';
            fabricListCode += '<div class="SampleZoom" onclick="openFabricSamplePopup(\'' + fabricMatrix[i].fabricId + '\');">';
            fabricListCode += '</div>';

            var originalFabricDisplayName = fabricMatrix[i].fabricName;
            var newFabricDisplayName = originalFabricDisplayName.replace(" ", "<br>");

            //THE NAME HOVER CONTAINERS
            fabricListCode += '<div class="SampleNameContainer">';
            fabricListCode += '<span>';
            fabricListCode += newFabricDisplayName;
            fabricListCode += '</span>';
            fabricListCode += '</div>';

            fabricListCode += '</div>';
        }
    }

    fabricListCode += '</div>';

    if (!jQuery("#ListContainer").length) { // FOR FABRIC BY THE METRE, PAGES WHICH HAVE NO MODEL LIST
        jQuery("div.ProductDetails").append("<div id='ListContainer'></div>");
    }
    jQuery("#ListContainer").append(fabricListCode);

    // LOOP FOR INSERTING ROW SPACES WITH DATA FROM FABRIC INFORMATION SCRIPT
    for (var j = 0; j < rowSpacerAfterLines.length; j++) {
        var insertRowSpacerAfterElement = (rowSpacerAfterLines[j] * 11) - 1;
        jQuery(".SampleContainer:eq(" + insertRowSpacerAfterElement + ")").after("<div class='RowSpacer'></div>");
    }
}



function openFabricSamplePopup(fabricName) {
    jQuery("#FabricSamplePopupBg").fadeTo("fast",0.8);
    var fabricSamplePopupCode = "";
    fabricSamplePopupCode += "<div class='ClosePopup'><a onclick='closeFabricSamplePopup();'><img src='/WebRoot/Store/Shops/62005383/MediaGallery/images/misc/close-popup.gif' alt='X'></a></div>";
    fabricSamplePopupCode += "<div class='PopupImageContainer'><img src='/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/medium/" + fabricName + ".jpg' alt='' /></div>";

    jQuery("#FabricSamplePopupContent").html(fabricSamplePopupCode);
    jQuery("#FabricSamplePopupContent").fadeIn("fast");
}

function closeFabricSamplePopup() {
    jQuery("#FabricSamplePopupBg").fadeOut("fast");
    jQuery("#FabricSamplePopupContent").fadeOut("fast");
}



// 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) {

        // 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(1300);
    });

    // 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 + ")", 5850);
}


//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(1000);
        });

        // SELECT NEXT IMAGE TO SHOW
        imageToShowNumber++;
        if (imageToShowNumber > totalNumberOfImages) {
            imageToShowNumber = 1;
        }

        // RUN ITSELF AFTER INTERVAL WITH NEW IMAGE TO FADE IN
        setTimeout("animateStartPageBanner(" + imageToShowNumber + ")", 4800);
    }
}

// IS CURRENT PAGE BARGAIN CORNER? MATCH URL OR BREADCRUMBS

function checkIsBargainCorner() {
    var breadcrumbText = jQuery(".ContentAreaWrapper h3:first").text();
    if (breadcrumbText.match(/bargain|koopjeshoek|schnäppchenecke|affaires|fyndhörna/i)) {
        isBargainCornerPage = true;
    }

    
}

function displayBargainCornerPage() {
    if (isBargainCornerPage == true) {
        jQuery(".PagerSizeContainer").show();
        //jQuery(".CategoryList h1:first").hide();

        // CATEGORY LISTING BROKEN IMAGE FIX

        if (jQuery(".CategoryList").length) {

            jQuery(".ProductSmallImage").each(function () {
                var bargainListImageSrc = jQuery(this).attr("src");
                var bargainListImageAlt = jQuery(this).attr("alt");

                jQuery(this).after("<img alt='" + bargainListImageAlt + "' title='" + bargainListImageAlt + "' class='BargainImgClone' />");

                jQuery(this).next().error(function () {

                    var newBargainListImageSrc = bargainListImageSrc.replace(/-\d{3}-.{2}/i, "");
                    jQuery(this).prev().attr("src", newBargainListImageSrc);
                    jQuery(this).remove();
                });

                //GIVE SRC TO CLONED IMAGE
                jQuery(this).next().attr("src", bargainListImageSrc);
            });
        }

        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/medium/";
    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();
}

function hideSwedishBargainCorner() {
    if (currentLanguage == "sv") {
        jQuery(".CategoriesTreeBox a").each(function () {
            if (jQuery(this).text().match(/fynd/i) != null) {
                jQuery(this).closest("li").hide();
            }
        });
    }
}

// FUNCTION FOR RENDERING MODEL FAMILY BOXES ON CATEGORY PAGE
function renderModelFamilyBoxes() {
    if (jQuery("#ModelFamilyBoxContainer").length) {

        // THE HEADER NAME
        var familyBoxHeader = "";

        jQuery("#ModelFamilyBoxContainer").append("<div class='ClearBoth'></div>");

        jQuery("#ModelFamilyBoxContainer .ModelFamily").each(function () {
            //GET FAMILY NAME, DELETE WHITESPACE
            var familyName = jQuery(this).text().replace(/\W/g, "");
            var familyArrayName = familyName + "Models";
            prepareModelArray(familyArrayName);

            eval("load_" + familyArrayName + "()");

            var currentFamily = [];
            eval("currentFamily = " + familyArrayName);


            var familyModelQuantity = currentFamily.length;
            //        alert(familyModelQuantity);

            jQuery(this).wrap("<div class='FamilyPositioner'></div>");
            jQuery(this).html("<div class='TextWrapper'><h3></h3></div>");

            for (var i = 1; familyModelQuantity; i++) {
                if (currentFamily[i].modelNameEnglish == "") {
                    break;
                }

                else if (currentFamily[i].modelArticleNumber == "101" && (i > 2)) {
                    // DO NOT INCLUDE GENERAL CUSHIONS, BUT DO INCLUDE IF IT IS CUSHION CAT (WHEN 101 IS FIRST ITEM)
                }
                // IF HEADER FOR BOX IS SPECIFIED, PUT IT IN VAR
                else if (currentFamily[i].modelArticleNumber == "familyBoxHeader") {

                    if (currentLanguage == "de") {
                        familyBoxHeader = currentFamily[i].modelNameGerman;
                    }
                    else if (currentLanguage == "fr") {
                        familyBoxHeader = currentFamily[i].modelNameFrench;
                    }
                    else if (currentLanguage == "nl") {
                        familyBoxHeader = currentFamily[i].modelNameDutch;
                    }
                    else if (currentLanguage == "sv") {
                        familyBoxHeader = currentFamily[i].modelNameSwedish;
                    }
                    else {
                        familyBoxHeader = currentFamily[i].modelNameEnglish;
                    }
                }
                else {

                    // CHECK LANGUAGE FOR CORRECT MODEL NAME
                    var currentModelName = "";
                    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;
                    }

                    var literalFamilyName = "";


                    // GET RID OF IKEA & FAMILY NAME
                    currentModelName = currentModelName.replace("IKEA ", "");

                    // DO NOT GET RID OF MODEL FAMILY NAMES FOR FAMILY BOX WITH PROPER NAME
                    if (familyBoxHeader == "") {
                        literalFamilyName = currentModelName.substr(0, currentModelName.indexOf(" "))
                        currentModelName = currentModelName.substr(currentModelName.indexOf(" ") + 1);
                    }

                    // MAKE FIRST LETTER UPPERCASE
                    currentModelName = currentModelName.charAt(0).toUpperCase() + currentModelName.substr(1);


                    var modelCode = "";
                    modelCode += "<a href='?ObjectPath=/Shops/62005383/Products/" + currentFamily[i].modelArticleNumber;

                    // CHECK IF PRODUCT COMES IN COLORS, ADD CORRECT ENDING
                    if (isStaticProduct(currentFamily[i].modelArticleNumber)) {
                        modelCode += "-000-00'>";
                    }
                    // DEFAULT PRODUCT FABRIC
                    else {
                        modelCode += "-" + standardFabricNumber + "'>";
                    }

                    modelCode += currentModelName;
                    modelCode += "</a>";
                    modelCode += "";

                    jQuery(this).find(".TextWrapper").append(modelCode);
                    jQuery(this).css("background", "#fff url(/WebRoot/Store/Shops/62005383/MediaGallery/images/categories/" + familyName + "_box.jpg) right top no-repeat");

                }
            }

            // INSERT REAL FAMILY NAME AS HEADER, BUT CORRECT FOR SPECIAL CASES


            var headerText = "";
            if (familyBoxHeader != "") {
                jQuery(this).find("h3").html(familyBoxHeader);
            }
            else {
                jQuery(this).find("h3").html("IKEA " + literalFamilyName);
            }

            //            // CHANGE LITERAL FAMILY NAME FOR "SEE ALL..." WHEN IT IS ARMCHAIRS
            //            literalFamilyName = literalFamilyName.replace(/armchairs/i, "armchair");
            //            literalFamilyName = literalFamilyName.replace(/fauteuils/i, "fauteuil");
            //            literalFamilyName = literalFamilyName.replace(/sessel/i, "Sessel");
            //            literalFamilyName = literalFamilyName.replace(/fåtöljer/i, "fåtölj");


            if (jQuery(this).find("a").length > 5) {
                // CHECK LANGUAGE FOR CORRECT FAMILY NAME
                var seeAllModelsText = "";
                if (currentLanguage == "de") {
                    seeAllModelsText = "(Alle Modelle...)";
                }
                else if (currentLanguage == "fr") {
                    seeAllModelsText = "(Voir tous les modèles...)";
                }
                else if (currentLanguage == "nl") {
                    seeAllModelsText = "(Zie alle modellen...)";
                }
                else if (currentLanguage == "sv") {
                    seeAllModelsText = "(Se alla modeller...)";
                }
                else {
                    seeAllModelsText = "(See all models...)";
                }
                jQuery(this).find(".TextWrapper").append("<span>" + seeAllModelsText + "</span>");
                jQuery(this).find("a:gt(3)").wrapAll("<div class='HiddenLinks'></div>");
            }
        });

        // BIND TO SHOW ALL LINKS FOR BOX ON MOUSEOVER

        jQuery("#ModelFamilyBoxContainer .ModelFamily").bind("mouseenter", function () {
            if (jQuery(this).find(".HiddenLinks").length) {
                jQuery("#ModelFamilyBoxContainer .HiddenLinks, #ModelFamilyBoxContainer span").clearQueue();
                jQuery(this).css("z-index", "100");
                jQuery(this).parent().css("z-index", "100");
                jQuery(this).find(".HiddenLinks").slideDown("fast", function () {
                    jQuery(this).css("height", "");
                });
                jQuery(this).find("span").slideUp("fast", function () {
                    jQuery(this).css("height", "");
                });
            }
        });

        jQuery("#ModelFamilyBoxContainer .ModelFamily").bind("mouseleave", function () {
            if (jQuery(this).find(".HiddenLinks").length) {
                jQuery("#ModelFamilyBoxContainer .HiddenLinks, #ModelFamilyBoxContainer span").clearQueue();
                jQuery(this).find(".HiddenLinks").slideUp("fast", function () {
                    jQuery(this).css("height", "");
                    jQuery(this).closest(".ModelFamily").css("z-index", "");
                    jQuery(this).closest(".FamilyPositioner").css("z-index", "");
                });
                jQuery(this).find("span").slideDown("fast", function () {
                    jQuery(this).css("height", "");
                });
            }
        });
    }
}

function fixTopMenu() {
    
    // GET 5 FIRST CATEGORY LINKS
    jQuery(".NavBarLeft .CategoriesTreeBox li:lt(5) a:last-child").each(function () {
        var topLinkCode = "<li><a href='" + jQuery(this).attr("href") + "' class='TopLink'>" + jQuery(this).text() + "</a>";
        jQuery("#TopLinkContainer").append(topLinkCode);
        jQuery(this).closest("li").remove();
    });
}


function fixLeftColumn() {

    // FIX CURRENCY CONTAINER
    var currencyLabel = "";
    if (currentLanguage == "de") { currencyLabel = "Währung: " }
    else if (currentLanguage == "fr") { currencyLabel = "Monnaie: " }
    else if (currentLanguage == "nl") { currencyLabel = "Valuta: " }
    else if (currentLanguage == "sv") { currencyLabel = "Valuta: " }
    else if (currentLanguage == "en") { currencyLabel = "Currency: " }

    if (currencyLabel != "") {
        jQuery(".Coins").prepend("<span>" + currencyLabel + "</span>");
    }

    jQuery(".Coins a:eq(0)").addClass("Euro");
    jQuery(".Coins a:eq(1)").addClass("Pound");
    jQuery(".Coins a:eq(2)").addClass("Kronor");
    jQuery(".Coins").append("<div class='ClearBoth'></div>");
}

function fixProductPage() {
    if (jQuery(".ProductDetails").length) {
        
        // MOVE HEADER
        //jQuery(".ProductDetails").prepend(jQuery(".InfoArea h1").detach());


        // CREATE PURCHASE BLOCK
        jQuery(".FullSize .Price, .FullSize .TaxAndShippingInfo, .FullSize .Links").wrapAll("<div id='PurchaseBlock'></div>");

        // FIX IMAGE COLUMN SIZE
        jQuery(".FullSize .TableLayoutRow > td:first").removeClass("PaddingRight").css("width", "285px");

        // FIX THE FABRIC LINK AND FABRIC IMAGE (NOT ON FABRIC BY THE METRE)
        if (!currentCatType.match(/fabrics/i) && !isStaticProduct(currentModelNumber)) {
            jQuery("table.FullSize .TableLayoutRow > td:first").append("<div id ='CurrentImageWrapper'></div>");
            var currentFabricImageSrc = "/WebRoot/Store/Shops/62005383/MediaGallery/images/fabrics/medium/" + currentFabricId + ".jpg";
            var currentFabricImageAlt = jQuery("#SubProdName").text();
            var currentFabricImageCode = "<img id='CurrentFabricImage' src='" + currentFabricImageSrc + "' alt='" + currentFabricImageAlt + "' title='" + currentFabricImageAlt + "' />";
            jQuery("#CurrentImageWrapper").append(currentFabricImageCode);
        }

        // FIX "STARS" IN DESCRIPTION AND MAKE THEM INTO BULLET POINTS
        if (!jQuery(".ProductDescription").length) {
            jQuery(".InfoArea .FullSize div:eq(1)").addClass("ProductDescription");
        }

        var prodText = jQuery(".ProductDescription").text();
        if (prodText.match(/\*/) != null) {
            prodText = "<ul>" + prodText.replace(/\*/g, "</li><li>") + "</li></ul>";
            // GET RID OF FIRST </LI>
            prodText = prodText.replace("</li>", "");
            jQuery(".ProductDescription").html(prodText);
        }

        // ADD "MEASUREMENTS" LINK AND TEXT AS LAST BULLET POINT
        // ONLY DO ON SOFAS AND CHAIRS, + NOT ON CUSHIONS ETC

        if (currentCatType.match(/sofas|chairs/i) && !isGenericProduct(currentModelNumber)) {

            // VARS
            var measuresTextStart = "";
            var measuresLinkText = "";
            var measuresTextEnd = "";

            if (currentLanguage == "de") {
                measuresTextStart = "Nicht sicher, ob Sie ein " + currentModelFamily.toUpperCase() + " haben? Kontrollieren Sie der ";
                measuresLinkText = "Abmessungen";
                measuresTextEnd = "!";
            }
            else if (currentLanguage == "fr") {
                measuresTextStart = "Vous ne savez pas si vous avez un " + currentModelFamily.toUpperCase() + "? Vérifier les ";
                measuresLinkText = "dimensions";
                measuresTextEnd = "!";
            }
            else if (currentLanguage == "nl") {
                measuresTextStart = "Niet zeker of u een " + currentModelFamily.toUpperCase() + " heeft? Controleer de ";
                measuresLinkText = "afmetingen";
                measuresTextEnd = "!";
            }
            else if (currentLanguage == "sv") {
                measuresTextStart = "Osäker på om det är en " + currentModelFamily.toUpperCase() + " du har? Ta en titt på ";
                measuresLinkText = "måtten";
                measuresTextEnd = "!";
            }
            else {
                measuresTextStart = "Unsure if " + currentModelFamily.toUpperCase() + " is the correct model? Have a look at the ";
                measuresLinkText = "measures";
                measuresTextEnd = "!";
            }

            // CREATE CODE SNIPPET
            var measuresCode = "";
            measuresCode += "<li>" + measuresTextStart + " ";
            measuresCode += "<a href='/WebRoot/Store/Shops/62005383/MediaGallery/documents/model-details-" + currentCatType + ".pdf' target='_blank'>";
            measuresCode += measuresLinkText;
            measuresCode += "</a>";
            measuresCode += measuresTextEnd + "</li>";

            // APPEND TO LIST
            jQuery(".ProductDescription ul").append(measuresCode);

        }

        // INSERT FLEX TEXT
        var flexText = "";
        var flexTextEmail = "<a href='mailto:services@savemysofa.com'>services@savemysofa.com</a>";

        if (currentLanguage == "en") {
            flexText += "It's all in the details! If you would like to have the piping in a different color or frame and cushion covers in different fabrics, ";
            flexText += "contact us at " + flexTextEmail + " and we will solve the details.";
        }
        else if (currentLanguage == "de") {
            flexText += "Möchten Sie z.B. die Paspel in einer anderen Farbe oder Rahmen- und Kissenbezüge in verschiedenen Stoffen haben? ";
            flexText += "Kontaktieren Sie uns unter " + flexTextEmail + " und wir lösen die Details!";
        }
        else if (currentLanguage == "fr") {
            flexText += "Les détails font la différence! Si vous aimeriez avoir la tuyauterie dans une couleur différente ou un cadre et des housses de coussin en différents tissus, ";
            flexText += "contactez nous aux " + flexTextEmail + ". Nous allons résoudre tous les détails.";
        }
        else if (currentLanguage == "nl") {
            flexText += "Het zijn de details die het verschil maken! Wil je graag de sierbiezen in een contrasterende stof of frame en kussenhoezen in verschillende stoffen? ";
            flexText += "We helpen je er graag mee. Contacteer ons op " + flexTextEmail + ".";
        }
        else if (currentLanguage == "sv") {
            flexText += "Det är detaljerna som gör det! Vill du t. ex. ha passpoal i avvikande tyg, eller stom- och kuddklädslar i olika tyger? ";
            flexText += "Kontakta oss på " + flexTextEmail + " så löser vi detaljerna.";
        }
        jQuery(".FabricDescription").after("<div id='FlexText'>" + flexText + "</div>");


        // RENDER NEW IMAGE INSTEAD OF PLATFORM IMAGE VIEWER
        var prodImage = jQuery("#ProductSlideshow img:first");

        if (prodImage.length) {

            // GET ORIGINAL IMG SRC
            var prodImageSrc = jQuery(prodImage).attr("src");

            // INSERT NEW IMAGE W/ WRAPPER
            var newProdImageCode = "<div class='NewProdImageWrapper'><img id='NewProdImage' alt='' /></div>";
            jQuery(".ProductDetails td.AlignTop:first").prepend(newProdImageCode);

            // IF IMAGE DOES NOT EXIST, GET GENERIC IMAGE INSTEAD
            jQuery("#NewProdImage").error(function () {

                var newProdImgSrc = "";

                // DO NOT INCLUDE MODEL NAME FOR GENERIC PRODUCTS
                if ((currentModelFamily != "") && isGenericProduct(currentModelNumber) == false) {
                    newProdImgSrc = currentModelFamily + "_";
                }
                newProdImgSrc = "/WebRoot/Store/Shops/62005383/MediaGallery/images/products/medium/" + "IKEA_" + newProdImgSrc + currentModelNumber + ".jpg";
                jQuery("#NewProdImage").attr("src", newProdImgSrc);

                // SHOW NEW IMAGE, HIDE STANDARD ONE
                jQuery(".NewProdImageWrapper").css("width", "auto").css("height", "auto");
                jQuery(".NewProdImageWrapper").parent().addClass("HideStdImage");
            });

            // SET NEW IMAGE SRC TO EXECUTE ERROR FUNCTION ABOVE
            jQuery("#NewProdImage").attr("src", prodImageSrc);
        }


        if (isTest) {

        }

        // ADD FABRIC SAMPLE BUTTON
        var orderSampleText = "";
        if (currentLanguage == "en") { orderSampleText = "Order free fabric samples &raquo;"; }
        if (currentLanguage == "de") { orderSampleText = "Kostenfrei Stoffproben &raquo;"; }
        if (currentLanguage == "fr") { orderSampleText = "Echantillons de tissu gratuits &raquo;"; }
        if (currentLanguage == "nl") { orderSampleText = "Gratis stofstaal &raquo;"; }
        if (currentLanguage == "sv") { orderSampleText = "Beställ gratis tygprover &raquo;"; }
        jQuery("#PurchaseBlock").append("<div id='OrderSampleLinkContainer'><a href='?ViewObjectID=549169'>" + orderSampleText + "</a></div>");

        // MOVE FACEBOOK - TWITTER UP TO BUY BUTTON
        jQuery("#PurchaseBlock").after("<div id='SocialMediaContainer'></div>");
        jQuery("#SocialMediaContainer").append(jQuery("#ShowFacebookButtons").detach());
        jQuery("#SocialMediaContainer").append(jQuery("#ShowTwitterButtons").detach());
        jQuery("#SocialMediaContainer").append("<div style='clear:both;'></div>");

        // ADD COLOR WARNING TEXT FOR FABRIC IMAGES
        if (currentFabricId != "NotDefined") {
            var colorWarningCode = "";
            if (currentLanguage == "en") { colorWarningCode = "Fabric color may be slightly different from the picture."; }
            if (currentLanguage == "de") { colorWarningCode = "Es ist möglich das die Farbe des Produktes auf der Webseite leicht von der tatsächlichen Farbe abweicht."; }
            if (currentLanguage == "fr") { colorWarningCode = "La couleur de tissu peut être légèrement différent de l'image."; }
            if (currentLanguage == "nl") { colorWarningCode = "De kleur van de stof kan enigszins afwijken van de foto."; }
            if (currentLanguage == "sv") { colorWarningCode = "Tygets färg kan skilja sig något från bilden."; }
            jQuery("#CurrentImageWrapper").after("<div id='ColorWarning'>" + colorWarningCode + "</div>");
        }
    }
}


jQuery(document).ready(function () {
    checkCatType();
    fixTopMenu();
    fixLeftColumn();
    getModelNumbers();
    jQuery("#SofaWithoutCoverBanner").after("<div id='testContainer' style='color: white'></div>");
    checkIsBargainCorner();
    displayMainSubProdName();
    //autoFabricLink();
    autoMatchModel();
    autoMatchModelFamily();
    initiateFabricSampleBanner();
    initiateSofaWithoutCoverBanner();
    animateStartPageBanner(1);
    displayBargainCornerPage();
    displayOurFabricsPage();
    hideSwedishBargainCorner();
    renderModelFamilyBoxes();
    fixProductPage();
});

jQuery(window).load(function () {

});

