// Indicator to whether we've got offers or not. This determines whether we do rollover processing
// or not, because if there is no offer on we'll have a blank navigation field. It is set to true automatically
// if there is a div called OfferDiv on the page.
var offer = false;
// List of temporary catagories which can be displayed
var displaySpecialCatagory = 'Christmas';
// Description of the catagory rollover on the navigation image
var specialCatagoryRolloverDesc = 'Examples of Christmas Cakes';
// The position of thumbnail scroll panel.
var scrollpos = 0;
// Default size of the white surround of the main picture.
var imageWhiteSurround = 10;
// Default size of the white surround of the thumbnails.
var thumbWhiteSurround = 5;
// Default size of all borders.
var bordersize = 2;
// The variable containing the currently selected thumb. Used when a new thumb has been selected, and the 
// border of the previous thumbnail needs to be switched to white.
var selectedThumb;
// The var that contains the scroll timer.
var scrollTimer;
// The var that contains the displayImage timer.
var displayImageTimer;
// The var that contains the thumbnail timer.
var thumbnailTimer;
// The var that contains the prices scroll timer.
var pricesScrollTimer;
// The var that contains the image load timer.
var imageLoadTimer;
// The time in milliseconds for the thumbnailBorder timer.
var imageTimerInterval = 200;
// The time in milliseconds for the image Loading timer.
var imageLoadingTimerInterval = 200;
// The time in milliseconds for the scrolling interval.
var scrollTimerInterval = 15;
// The speed of the scrolling in pixels.
var scrollSpeed;
// The time in milliseconds for the title images to remain on the screen before fading out.
var titleImageStaticTimerInterval = 25000;
// The var that contains the Timer that triggers the fade steps.
var titleImageFadeWaitTimer;
// The time in milliseconds for the fade timer to trigger;
var titleImageFadeTimerInterval = 50;
// Default directory of the webImagesDir
var webImagesDir = "webimages/";
// Default directory of the navigation directory
var navigationDir = "navigation/";     
// Top level directory structure
var topLevelDir = "pictures/";
// Default directory for the fading title images
var titleImagesDir = topLevelDir + "TitleImages/";   
// Default directory name of the images directory
var imageDir;
// The default shadow offset
var shadowOffset = 20;
// Max size, in pixels, of pictures.
//var maxImageSize = 350;
// Constants for image loading        
var imageNotLoaded = "Not Loaded";
var imageLoadFailure = "Failed";
var imageLoadSuccess = "Loaded";
// ID for splash popup that shows images are being loaded.
var splashID = "splashID";
// Current Display Image. This is used if the displayImage function has to be set up in a timer, because the image hasn't currently loaded.
var displayImageObj;
// Current Thumbnail. This is used if the calculateScrollPos function has to be set up in a timer, because the images haven't currently loaded.
var thumbImageObj;
// Default can't load image picture we can display if something goes wrong.
var unableToLoadImage = new Image();
unableToLoadImage.src=webImagesDir + "imageLoadFailed.jpg";
// Default can't load thumb picture we can display if something goes wrong.
var unableToLoadThumb = new Image();
unableToLoadThumb.src=webImagesDir + "thumbLoadFailed.jpg";
// Default can't find any images for this filter picture we display if necessary.
var noFilteredImagesToDisplay = new Image();
noFilteredImagesToDisplay.src=webImagesDir + "noFilteredImagesToDisplay.jpg";
// Default loading images splash screen.
var imageLoadSplash = new Image();
imageLoadSplash.src=webImagesDir + "imageLoadSplash.gif";
// image not loaded loop detector for displayImage so we don't loop indefinitely
var displayImageLoopCount = 0;
// thumbimage not loaded loop detector for calculateScrollPos so we don't loop indefinitely
var calcScrollLoopCount = 0;
// thumbimage not loaded loop detector for pricesScroll so we don't loop indefinitely
var pricesScrollLoopCount = 0;
// images not loaded loop detector for loadImages so we don't loop indefinitely
var imageLoadLoopCount = 0;
// Max loop var for image not loaded loop detector.
var imageMaxLoop = 50;
//Highlight for selected price table element
var highlightColour = "#FFFFB3";
//Highlight for catagory title rows in price table
var titleColour = "#BDFFC8";
// This variable is used to hold which prices table row has been selected.
var selectedTabRow;
// The hash that is associated with the URL of the page.
var hash;
// The subgroup that we're filtering on
var subGroup;

//Scroll Images
var leftScrollImage;
var largeLeftScrollImage;
var leftScrollGreyedImage;
var doubleLeftScrollImage;
var doubleLeftScrollGreyedImage;
var largeDoubleLeftScrollImage;

var rightScrollImage;
var largeRightScrollImage;
var rightScrollGreyedImage;
var doubleRightScrollImage;
var doubleRightScrollGreyedImage;
var largeDoubleRightScrollImage;

// The variable that detemines whether we are IE or not.
var isMicrosoftIE;

// mailto script variables. By putting this in the script area prevents spammers from getting address to send spam to.
var user = "info";
var domain = "wishcakes.co.uk";
var subject = "Internet Cake Enquiry";
var mailAddress = user + "@" + domain;
var mailLink = "mailto:" + mailAddress + "?subject=" + subject;

// initPage: This function is called when the page loads. This allows multiple functions to be called to set up the page at initialisation.
function initPage() {
    offer = isOfferPage();
    loadNavigation();
    hash = window.location.hash;
    document.pageID = initPage.arguments[0];
    
    // Set whether we are using MicroSoft IE browser or not.
    if ("Microsoft Internet Explorer" == navigator.appName) {
        isMicrosoftIE == true;
        scrollSpeed = 4;
    } else {
        isMicrosoftIE == false;
        scrollSpeed = 3;
    }
    
    // If page has an initload property, process relevant code.
    if (document.pageID) {
        if (document.pageID == "priceList") {
            createPriceListThumbTable();
        } else if (document.pageID == "prices") {
            imageLoadLoopCount = 0;
            if (hash) { 
               document.selectedPrice = hash.substr(1);
               loadPricesThumbTable();
            } else {
                document.selectedPrice = "";
                loadPricesThumbTable();
            }
        } else {
        
            loadScrollImages();
            // Check to see if we have a default filter in the code. If we do then we need to call the onclick method 
            // (which should be a call to setSubGroup) using the eval command. If we don't have a filter then run loadImages instead.
            // setSubGroup runs loadImages after setting up some defaults.
            var filterDiv = document.getElementById('defaultFilter');
            if (filterDiv) {
                // If we have a default filter, get the attributes and find the onclick method. Get this string and run eval against it
                // which will effectively be like the user has clicked the filter link themselves.
                var attrs = filterDiv.attributes;
                for (var i = 0; i < attrs.length; i++) {
                    if (attrs[i].name == "onclick") {
                        eval(attrs[i].nodeValue);   
                    }
                }
            } else {
                loadImages();
            }
        }
    } else {
        configureTitleAnimation();
    }
    
    // If we have an offer on, then we need to specify the title to assign to the image. By doing it this
    // way, it means when we have no offer and the nav element is blank we don't get hovers saying here are 
    // our offers.
    if (offer) {
        var offerNav = document.getElementById('Offer');
        offerNav.setAttribute("title", specialCatagoryRolloverDesc);
        // Reset any selected offer images. This is required because if you have selected the offer banner and
        // moved to another page, moved the mouse and then click back, the offer banner is selected even though
        // the mouse is nowhere near it.
        offerhover(false);
    }
    
    var mailtoDiv = document.getElementById('mailto')
    if (mailtoDiv) {
        mailtoDiv.innerHTML=mailAddress;
    }
}

// loadImages: This function preloads the images that map to the thumbnails. They are stored in a global array for later use.
//               It also generates the table that the thumbnails are put into which is stored in the thumbnail div.

function loadImages() {

    clearTimeout(imageLoadTimer);
    var imageDir = document.pageID;
    var mainImageDiv = document.getElementById("mainImageDiv");
    
    downloadThumbNails(imageDir);       
    downloadImages(imageDir);
    
    if ((thumbsLoaded() && imagesLoaded(document.imageArray)) || imageLoadLoopCount > imageMaxLoop) {            
        imageLoadLoopCount = 0;
        processImages(imageDir);
    } else {
        if (imageLoadLoopCount > 3) {
            displayLoadingPanel(mainImageDiv);
        }
        imageLoadLoopCount++;
        imageLoadTimer = setTimeout("loadImages()", imageLoadingTimerInterval);                
    }
}

// loadTitleImages: This function preloads the title images are used in the titlePage slideshow. 
//                  They are stored in a global array for later use.

function loadTitleImages() {

    clearTimeout(imageLoadTimer);
    
    downloadTitleImages();
    
    if ((imagesLoaded(document.catagory1) && 
        imagesLoaded(document.catagory2) &&
        imagesLoaded(document.catagory3) && 
        imagesLoaded(document.catagory4) && 
        imagesLoaded(document.catagory5)) || 
        imageLoadLoopCount > imageMaxLoop) {  
              
        imageLoadLoopCount = 0;
        runTitleAnimation();
    } else {
        imageLoadLoopCount++;
        imageLoadTimer = setTimeout("loadTitleImages()", imageLoadingTimerInterval);                
    }
}

function processImages() {

    // Get all the arguments for this function, that are the image names for this page.
    var thumbnaildiv = document.getElementById('thumbnails');
    var thumbsurrounddiv = document.getElementById('thumbsurround');
    var thumbdisplaydiv = document.getElementById('thumbDisplay');
    var mainImageDiv = document.getElementById("mainImageDiv");
    
    // Remove any previous thumbtab table. This is because we could be changing the filter and recreating a new set of 
    // thumbs without reloading the page.
    removeChildren(thumbnaildiv);
    
    removeLoadingPanel(mainImageDiv);
    
    thumbsurrounddiv.style.zIndex="99";
    thumbdisplaydiv.style.zIndex="98";
    // Create the shadow around the thumbnail div.
    createShadow(thumbsurrounddiv, thumbdisplaydiv);

    // create the table, and set the properties
    var thumbtab = document.createElement('table');
    thumbtab.setAttribute("id", "thumbtab");
    thumbtab.cellPadding=thumbWhiteSurround;
    thumbtab.align="center";
    thumbtab.style.position="absolute";

    // Create the Table Body
    var tabbody = document.createElement('tbody');
    thumbtab.appendChild(tabbody);
    // Create the Table Row
    var tabrow = document.createElement('tr');
    tabrow.setAttribute("id","thumbtabRow");
    tabbody.appendChild(tabrow);
    thumbnaildiv.appendChild(thumbtab);
    
    for (var i = 0; i < document.thumbArray.length; i++) {
        // Create the Table data element and add the thumbnail image. We do this first so that when the image loads we can 
        // calculate the maximum scroll width. If we set the thumbnail source before adding to the table, we don't get this image 
        // calculated in the maxScrollPos, so the last image isn't displayed (in IE).
        var tabdata = document.createElement('td');
        tabrow.appendChild(tabdata);
        tabdata.appendChild(document.thumbArray[i]); 
        tabdata.style.border = "solid white " + bordersize + "px";  
    }
    
    if (hash) {
        hash = hash.substr(1);
        for (var i = 0; i < document.thumbArray.length; i++) {
            if (document.thumbArray[i].id == hash) {
                // If a specific thumb has been chosen, then process this selected thumb
                processSelectedThumb(document.thumbArray[i]);
                // Now calculate the scroll position, so that we can display the thumbnail in the thumb table. If we don't do this, 
                // the user might have selected a thumb that is in a non displayed part of the thumb table.
                calculateScrollPos(document.thumbArray[i]);
            } 
        } 
        // Once we have processed the hash, we don't need it again until the next time a page is loaded. We need to remove it 
        // because this can cause problems with the filter process.
        hash = null;                      
    } else {
        processSelectedThumb(document.thumbArray[0]);
    }
}

// downloadImages: This function preloads the images that map to the thumbnails. They are stored in a global array for later use.
//               
function downloadImages(imageDir) {
    if (! document.imageArray) {
        document.imageArray = new Array();
       
        // Create Images and thumbnails and store them in their relative arrays.
        var count = 0;  
        for (var i=0; i < images.length; i=i+5) {
            if (images[i] == imageDir) { 
                if (isSubGroupImage(images[i+1])) { 
                    var image = new Image();
                    var imageName = images[i+2];
                    image.name=imageName;
                    image.loaded = imageNotLoaded;
                    image.onload=imageLoaded;
                    image.onerror=imageLoadError;
                    image.setAttribute("title", "Click for Price Information");     
                    image.linkReference='WishCakesPrices.htm#' + imageName;     
                    image.src=topLevelDir + imageDir + "/images/" + imageName;
                    document.imageArray[count] = image;
                    count++;
                }
            }
        }
    }
}

// downloadTitleImages: This function preloads the images that are used in the title page. They are stored in a global array for later use.
//                      All images have are transparent and will then be able to be faded in.
function downloadTitleImages() {

    if (! document.catagory1) {
        document.catagory1 = new Array();
        document.catagory2 = new Array();
        document.catagory3 = new Array();
        document.catagory4 = new Array();
        document.catagory5 = new Array();
       
        // Create Images and stores them in their relative arrays.
        for (var i=0; i < titleImages.length; i=i+3) {
            var catagory = titleImages[i];
            var imageDir = titleImages[i+1];
            var imageName = titleImages[i+2];
        
            var image = new Image();
            image.name=imageName;
            image.loaded = imageNotLoaded;
            image.onload=imageLoaded;
            image.onerror=imageLoadError;
            // Check to see what catagory this image is for. This if/else is to make the hover sentence make more
            // sense.
            if (imageDir == "Flowers" || imageDir == "Toppers" ) {
                image.setAttribute("title", "Click to see " + imageDir);    
            } else {
                image.setAttribute("title", "Click to see " + imageDir + " cake");
            }       
            image.linkReference="WishCakes" + imageDir + ".htm#" + imageName;
            image.onclick=switchToLinkPage;     
            image.src=titleImagesDir + catagory + "/" + imageName;
            image.style.opacity=".00";
            image.style.filter="alpha(opacity=0)";
            image.style.cursor = "pointer";
            
            if (catagory == "Catagory1") { 
                document.catagory1[document.catagory1.length] = image;
            } else if (catagory == "Catagory2") { 
                document.catagory2[document.catagory2.length] = image;
            } else if (catagory == "Catagory3") { 
                document.catagory3[document.catagory3.length] = image;
            } else if (catagory == "Catagory4") { 
                document.catagory4[document.catagory4.length] = image;
            } else if (catagory == "Catagory5") { 
                document.catagory5[document.catagory5.length] = image;
            } else {
            } 
        }
     }
}

// downloadThumbNails: This function preloads all the thumbnails. They are stored in a global array for later use.
// 
function downloadThumbNails(imageDir) {
    var count = 0;
    if (! document.thumbArray) {
        document.thumbArray = new Array();
        for (var i=0; i < images.length; i=i+5) {
            if (!imageDir || images[i] == imageDir) {
                if (isSubGroupImage(images[i+1])) { 
                    var thumbimage = new Image();
                    var imageName = images[i+2];
                    // Now set attributes on thumbimage.
                    thumbimage.setAttribute("id", imageName);                
                    thumbimage.loaded=imageNotLoaded;
                    // set the rollover function for each thumbnail.
                    thumbimage.onmouseover = thumbSelect;
                    thumbimage.setAttribute("title", "DoubleClick for Price Information");      
                    thumbimage.onload=imageLoaded;
                    thumbimage.style.cursor = "pointer";
                    thumbimage.onerror=thumbLoadError; 
                    thumbimage.ondblclick=switchToLinkPage;
                    thumbimage.linkReference='WishCakesPrices.htm#' + imageName;
                    thumbimage.src=topLevelDir + images[i] + "/thumbnails/" + imageName;
                       
                    document.thumbArray[count] = thumbimage;
                    count++;
                }
            }
        }
    }
}

function loadPricesThumbTable() {

    clearTimeout(imageLoadTimer);
    var selectedPrice = document.selectedPrice;
    var pricesTabDiv = document.getElementById("pricesTabDiv");
    
    downloadThumbNails();       
    
    if (thumbsLoaded() || imageLoadLoopCount > imageMaxLoop) {       
        imageLoadLoopCount = 0;
        createPricesThumbTable(selectedPrice);
    } else {
        if (imageLoadLoopCount > 3) {
            displayLoadingPanel(pricesTabDiv);
        }
        imageLoadLoopCount++;
        imageLoadTimer = setTimeout("loadPricesThumbTable()", imageLoadingTimerInterval);                
    }
}

// This method displays a splash panel indicating that images are being loaded. This is to show the user that when
// they are looking at a blank screen, things are being run in the background.
function displayLoadingPanel(parentDiv) {

    if (!document.showingSplash || document.showingSplash == "false") {
        var newdiv = document.createElement("div");
        newdiv.setAttribute("id", splashID);
        newdiv.appendChild(imageLoadSplash);
        
        var topstart = (parentDiv.clientHeight / 2) - (imageLoadSplash.height / 2);
        var leftstart = (parentDiv.clientWidth / 2) - (imageLoadSplash.width / 2);
        newdiv.style.top=topstart + "px";
        newdiv.style.left=leftstart + "px";
        newdiv.style.width=imageLoadSplash.width + "px";
        newdiv.style.position="relative";
        // set zindex to make sure that this is the top div in the parent div.
        newdiv.style.zIndex="99";
        
        parentDiv.appendChild(newdiv);
        document.showingSplash = true;             
    }
}

// This method removes the splash popup when the loading is complete.
function removeLoadingPanel(parentDiv) {

   var splashdiv = document.getElementById(splashID);
   if (splashdiv) {
       parentDiv.removeChild(splashdiv);
       document.showingSplash = false;             
   }
}


// createThumbTable: This function loads all the price list thumbnails requested into a table.
function createPricesThumbTable(selectedPrice) {

    var pricesTable = document.getElementById('pricesTable');
    var pricesTabBody = document.getElementById('pricesTableBody');
    var pricestabdiv = document.getElementById('pricesTabDiv');
    var pricesdiv = document.getElementById('pricesDiv');
    var count=0;
    selectedTabRow = null;
    removeLoadingPanel(pricestabdiv);

    pricesTable.className="pricesTabBorder"
    pricestabdiv.style.zIndex="98";
    pricesdiv.style.zIndex="97";
    // create the shadow around the image.
    if (document.pageID == "prices") {
        createShadow(pricestabdiv, pricesdiv);
    }

    var currentType = "";
    for (var i = 0; i < images.length; i=i+5) {
        // If the catagory type is a new one, then insert the title into the table. This splits the pricelist table
        // up into easier recognised sections.
        // If the catagory is * Offers, then we need to be selective about which one to display. All offers are listed in the
        // images.js, so we only want to display the one that is current on the site.
        // So we check that if the catagory has Offers in the name, we only want to display the images if the offer boolean 
        // is true AND the catagory name matches the offerCatagory variable. Otherwise ignore.
        if ((searchArray(specialCatagories, images[i]) && ! offer) ||
            (searchArray(specialCatagories, images[i]) && ! (displaySpecialCatagory == images[i]))) {
           //Nop - don't load these images into the prices table.
        } else {          
            if (images[i] != currentType) {
                var tabrow = document.createElement('tr'); 
                tabrow.className="pricesTab";
                pricesTabBody.appendChild(tabrow);
       
                // Create the Table data element and add the thumbnail image. 
                var tabdata1 = document.createElement('td');
                // Span the 3 columns with the cake catagory title
                tabdata1.colSpan="3";
                tabdata1.className="text24point pricesBorder textBlue";
                //tabdata1.className="pricesTitleText";
                tabdata1.style.backgroundColor=titleColour;
                tabrow.appendChild(tabdata1);
                tabdata1.innerHTML = images[i];
                currentType = images[i];
            }
            
            // Create the Table Row
            var tabrow = document.createElement('tr'); 
            tabrow.className="pricesTab";
            pricesTabBody.appendChild(tabrow);
       
            priceThumbProcess(i, tabrow, currentType, selectedPrice);
        }
    }
    if (selectedTabRow && document.pageID == "prices") {
        pricesScroll();
    }
}

// createPriceListThumbTable: This function loads all the price list thumbnails into a printable list.
function createPriceListThumbTable(selectedPrice) {

    clearTimeout(pricesScrollTimer);
    
    downloadThumbNails();        
    
    if (thumbsLoaded()) {
        pricesScrollLoopCount = 0;
        processPriceListTable();
    } else {
        if (pricesScrollLoopCount > imageMaxLoop) {            
            pricesScrollLoopCount = 0;
            processPriceListTable();
        } else {
            pricesScrollLoopCount++;
            pricesScrollTimer = setTimeout("createPriceListThumbTable()", imageLoadingTimerInterval);                
        }
    }
}    
    
function processPriceListTable() {    

    var pricesTabBody = document.getElementById('pricesTableBody');
    var priceListdiv = document.getElementById('priceListDiv');
    var pricesTable = document.getElementById('pricesTable');
    var count=0;
    selectedTabRow = null;

    var currentType = "";
    var newTabRow = 1;
    var tabrow;
    var totalTableHeight = 0;
    var blankRowRequired = false;
    // Last Blank Row. This indicates the last divide height, so we can keep working in intervals.
    // We need to set this to 363 initially because on page 1 we have the wishcakes title at the top.
    var lastBlankRow = 0;
    for (var i = 0; i < images.length; i=i+5) {
        // If the catagory type is a new one, then insert the title into the table. This splits the pricelist table
        // up into easier recognised sections.
        // If the catagory is * Offers, then we need to be selective about which one to display. All offers are listed in the
        // images.js, so we only want to display the one that is current on the site.
        // So we check that if the catagory has Offers in the name, we only want to display the images if the offer boolean 
        // is true AND the catagory name matches the offerCatagory variable. Otherwise ignore.
        if (searchArray(specialCatagories, images[i]) &&
           ! (searchArray(displaySpecialCatagory, images[i]) || ! offer)) {
           //Nop - don't load these images into the prices table.
        } else {
            if (images[i] != currentType) {
                var tabrow = document.createElement('tr'); 
                tabrow.className="pricesTab";
                pricesTabBody.appendChild(tabrow);
       
                // Create the Table data element and add the thumbnail image. 
                var tabdata1 = document.createElement('td');
                // Span the 3 columns with the cake catagory title
                tabdata1.colSpan="6";
                tabdata1.className="text24point pricesBorder textBlue";
                //tabdata1.className="pricesTitleText";
                tabdata1.style.backgroundColor=titleColour;
                tabrow.appendChild(tabdata1);
                tabdata1.innerHTML = images[i];
                currentType = images[i];
                newTabRow = 1;
            }
           
            // Create the Table Row when 2 entries have been written out.
            
            if (newTabRow == 1) {
                if (blankRowRequired) {
                    blankTabRow = document.createElement('tr'); 
                    blankTabRow.className="pricesTab";
                    pricesTabBody.appendChild(blankTabRow);        
                    newTabRow = 0;
                    // Create the Table data element and add the thumbnail image. 
                    var tabdata = document.createElement('td');
                    
                    tabdata.colSpan="6";
                    tabdata.className="text24point pricesBorder textBlue";
                    var blankThumbImage = new Image();
                    blankThumbImage.src=webImagesDir + "/blankThumbnail.jpg";
                    tabdata.appendChild(blankThumbImage);
                    blankTabRow.appendChild(tabdata);
                    lastBlankRow = pricesTable.clientHeight - (pricesTable.clientHeight % 1330);
                    blankRowRequired = false;
                }
                tabrow = document.createElement('tr'); 
                tabrow.className="pricesTab";
                pricesTabBody.appendChild(tabrow);
                newTabRow = 0;
            } else {
                newTabRow++;
            }
            priceThumbProcess(i, tabrow, currentType, "");
            totalTableHeight =+ pricesTable.clientHeight;
            
            if (totalTableHeight - lastBlankRow > 1330 && ! blankRowRequired) {
                //blankRowRequired = true;
            }
        }
    }
}
        
            
// priceThumbProcess: This function adds supplied image into the priceList table.
function priceThumbProcess(currentImage, tableRow, catagory, selectedImage) {
           
    // Create Images and thumbnails and store them in their relative arrays.  
    var thumbimage = new Image();
    thumbimage.style.border="0px";
    thumbimage.setAttribute("title", "Click to display larger image");  
    thumbimage.linkReference='WishCakes' + images[currentImage] + '.htm#' + images[currentImage+2];
    thumbimage.loaded=imageNotLoaded;
    thumbimage.onload=imageLoaded;
    thumbimage.onerror=thumbLoadError; 

    var anchor = document.createElement('a');
    anchor.href=thumbimage.linkReference;
    anchor.appendChild(thumbimage);

    // Create the Table data element and add the thumbnail image. 
    var tabdata1 = document.createElement('td');
    tabdata1.className="text24point pricesBorder textBlue";
    tableRow.appendChild(tabdata1);
    tabdata1.appendChild(anchor);

    // Now set attributes on thumbimage.
    thumbimage.src=topLevelDir + images[currentImage] + "/thumbnails/" + images[currentImage+2];
    var tabdata2 = document.createElement('td');
    if (images[currentImage+3] == "Prices on Request") {
    	tabdata2.className="text12point pricesBorder textBlue";
    } else {
    	tabdata2.className="text24point pricesBorder textBlue";
    }
    tableRow.appendChild(tabdata2);
    var cakePrice = images[currentImage+3].replace("£","&pound;");
    tabdata2.innerHTML = cakePrice;
     
    var tabdata3 = document.createElement('td');
    tabdata3.innerHTML = images[currentImage+4];
    tabdata3.className="text16point pricesBorder textBlue";
    tableRow.appendChild(tabdata3);
    
    if (images[currentImage+2] == selectedImage && document.pageID == "prices") {
        tabdata1.style.backgroundColor=highlightColour;
        tabdata2.style.backgroundColor=highlightColour;
        tabdata3.style.backgroundColor=highlightColour;
        selectedTabRow = tableRow;
    }
}

function pricesScroll() {
    if (thumbsLoaded()) {
        var priceScrollPos = 0;
        pricesScrollLoopCount = 0;
        var pricesTabDiv = document.getElementById('pricesTabDiv');
        if (selectedTabRow.offsetTop > pricesTabDiv.clientHeight) {
            priceScrollPos = selectedTabRow.offsetTop - (pricesTabDiv.clientHeight / 2); 
        }

        pricesTabDiv.scrollTop = priceScrollPos;   
    } else {
        if (pricesScrollLoopCount > imageMaxLoop) {            
            pricesScrollLoopCount = 0;
        } else {
            pricesScrollLoopCount++;
            pricesScrollTimer = setTimeout("pricesScroll()", imageTimerInterval);                
        }
    }
}

// Preload the scroll images into variables.
function loadScrollImages() {
    leftScrollImage = new Image();
    leftScrollImage.src = webImagesDir + scrollImages[0];

    largeLeftScrollImage = new Image();
    largeLeftScrollImage.src = webImagesDir + scrollImages[1];

    leftScrollGreyedImage = new Image();
    leftScrollGreyedImage.src = webImagesDir + scrollImages[2];
    
    rightScrollImage = new Image();
    rightScrollImage.src = webImagesDir + scrollImages[3];

    largeRightScrollImage = new Image();
    largeRightScrollImage.src = webImagesDir + scrollImages[4];
    //largeRightScrollImage.style.cursor = "pointer";

    rightScrollGreyedImage = new Image();
    rightScrollGreyedImage.src = webImagesDir + scrollImages[5];
    
    doubleLeftScrollImage = new Image();
    doubleLeftScrollImage.src = webImagesDir + scrollImages[6];
    
    doubleLeftScrollGreyedImage = new Image();
    doubleLeftScrollGreyedImage.src = webImagesDir + scrollImages[7];
    
    largeDoubleLeftScrollImage = new Image();
    largeDoubleLeftScrollImage.src = webImagesDir + scrollImages[8];
    
    doubleRightScrollImage = new Image();
    doubleRightScrollImage.src = webImagesDir + scrollImages[9];
    
    doubleRightScrollGreyedImage = new Image();
    doubleRightScrollGreyedImage.src = webImagesDir + scrollImages[10];
    
    largeDoubleRightScrollImage = new Image();
    largeDoubleRightScrollImage.src = webImagesDir + scrollImages[11];
}

// loadNavigation: This function is used to load the navigation images (user selected images) and store them in the relevant array.
function loadNavigation() {
    document.navArray = new Array();
    for (var i=0; i < navigationImages.length; i++) {
        var image = new Image();
        var id = navigationDir + navigationImages[i];
        image.src=id;
        image.className="navigationElement";
        image.setAttribute("id", id);
        document.navArray[i] = image;
    }
}

// highlightImage: This function is invoked when a user rolls the mouse over a navigation image/next|prev image button. We replace the src of the object with the
//                 select image. We store the original src value as a var on the image, so when the mouse rolls off we know what the original src is. 
//                 We only set the new src if the current src doesn't contain undefined (meaning image hasn't loaded yet) or 
//                 that the scroll image isn't greyed out.                 
function highlightImage() {
    var args = highlightImage.arguments;
    var currID = document.getElementById(args[0]);
    // Check that we're not dealing with a filter. We need to make sure that we don't highlight a selected filter. 
    if (document.filter && currID.name == document.filter[0]) {
      // Nop. Don't highlight the image of a selected filter. 
    } else { 
        if (currID.src.indexOf("undefined") < 0 && 
            currID.src.indexOf("Greyed") < 0) { 
            currID.osrc = currID.src;
            currID.src=args[1];
            currID.style.cursor="pointer";
        } else {
            currID.osrc = "undefined";
        }
        
        if (args[0] == "Offer" && ! offer) {
            currID.style.cursor="default";
        }
    }
}

// replaceImage: This function replaces the selected navigation image with the original image. We check that the src isn't
//               undefined (not loaded yet) or greyed (scroll is disabled as it at the end of the limit).
function replaceImage(navElement) { 
    // Check that we're not dealing with a filter. We need to make sure that we don't deselected a highlight filter. The cause of this is because we move
    // over it and it highlights, we then click to select, and then move the mouse off of the image. Instead of it remaining on the page select image it 
    // goes back to non highlighted title image. Normally this isn't an issue because a page select means that we've moved to a new html page, but filtering
    // is done via javascript. 
    if (document.filter && navElement.name == document.filter[0]) {
      // Nop. Don't reset the image of a selected filter. The filter will get deselected when another filter is selected.
    } else { 
        if (navElement.osrc) {
            if (navElement.osrc.indexOf("undefined") < 0 && 
                navElement.src.indexOf("Greyed") < 0) {
                navElement.src = navElement.osrc;
            }
        }
        
        navElement.style.cursor = "default";
    }
}

// scroll_left: This function shifts the thumbnail div left by a set value. It then sets a timer to scroll again after a set interval.
//              This method keeps running indefinitely until the stop_Scroll function is invoked, which removes the timer.
function scroll_Left() {  
    var thumbdiv = document.getElementById('thumbnails');
    var thumbsurrounddiv = document.getElementById('thumbsurround');
    var thumbtab = document.getElementById('thumbtab');
    // Set the maximum scroll value which is calculated as the width of all thumbs minus the width of the thumb display. This basically is 
    // the maximum visible left edge when the thumbs are scrolled max to the right.
    var maxScrollPos = thumbsurrounddiv.clientWidth - thumbtab.clientWidth;

    // Only scroll left if we're not at the left edge of the div.
    if (scrollpos < 0) {
        // if the scrollpos is the maximum right amount, then right scroll icon is greyed out. As we've moved back 
        // a bit we can now allow the right scroll to be un-greyed.
        document.getElementById('scrollLeft').style.cursor="pointer";
        if (scrollpos == maxScrollPos) {
            document.getElementById('scrollRight').src=rightScrollImage.src;
            document.getElementById('scrollRight').style.cursor="pointer";
        }

        scrollpos = scrollpos + scrollSpeed;  
        // If the scrollpos is at the left edge, then grey out the icon, otherwise change the image to a large scroll icon.
        if (scrollpos >= 0) {
            scrollpos = 0;
            document.getElementById('scrollLeft').src=leftScrollGreyedImage.src;
            document.getElementById('scrollLeft').style.cursor="default";
        } else {
            document.getElementById('scrollLeft').src=largeLeftScrollImage.src;
            document.getElementById('scrollLeft').style.cursor="pointer";
        }
        thumbdiv.style.left = scrollpos + "px"; 
        clearTimeout(scrollTimer);
        scrollTimer = setTimeout("scroll_Left()", scrollTimerInterval);                
    } 
}

// scroll_right: This function shifts the thumbnail div right by a set value. It then sets a timer to scroll again after a set interval.
//              This method keeps running indefinitely until the stop_Scroll function is invoked, which removes the timer.
function scroll_Right() {  
    var thumbdiv = document.getElementById('thumbnails');
    var thumbsurrounddiv = document.getElementById('thumbsurround');
    var thumbtab = document.getElementById('thumbtab'); 
    // Set the maximum scroll value which is calculated as the width of all thumbs minus the width of the thumb display. This basically is 
    // the maximum visible left edge when the thumbs are scrolled max to the right.
    var maxScrollPos = thumbsurrounddiv.clientWidth - thumbtab.clientWidth;

    if (scrollpos > maxScrollPos) {
        document.getElementById('scrollRight').style.cursor="pointer";
        if (scrollpos == 0) {
           document.getElementById('scrollLeft').src=leftScrollImage.src;
           document.getElementById('scrollLeft').style.cursor="pointer";
        }
        scrollpos = scrollpos - scrollSpeed;
        if (scrollpos <= maxScrollPos) {
            scrollpos = maxScrollPos;                    
            document.getElementById('scrollRight').src=rightScrollGreyedImage.src;
            document.getElementById('scrollRight').style.cursor="default";
        } else {
            document.getElementById('scrollRight').src=largeRightScrollImage.src;
            document.getElementById('scrollRight').style.cursor="pointer";
        }

        thumbdiv.style.left = scrollpos + "px";
        clearTimeout(scrollTimer);
        scrollTimer = setTimeout("scroll_Right()", scrollTimerInterval);                
    } 
}

// stop_Scroll: This removes any Timers on the scroll div. This means that the user has moved off the scroll icons.
function stop_Scroll() {  

    var thumbsurrounddiv = document.getElementById('thumbsurround');
    var thumbtab = document.getElementById('thumbtab'); 
    // Set the maximum scroll value which is calculated as the width of all thumbs minus the width of the thumb display. This basically is 
    // the maximum visible left edge when the thumbs are scrolled max to the right.
    var thumbsurrounddivWidth = thumbsurrounddiv.clientWidth;
    var thumbtabWidth = thumbtab.clientWidth;
    var maxScrollPos = thumbsurrounddivWidth - thumbtabWidth;

    if (scrollpos == 0) {
        document.getElementById('scrollLeft').src=leftScrollGreyedImage.src;
        document.getElementById('scrollLeft').style.cursor="default";
    } else {
        document.getElementById('scrollLeft').src=leftScrollImage.src;
        document.getElementById('scrollLeft').style.cursor="pointer";
    }

    if (scrollpos == maxScrollPos || thumbtabWidth < thumbsurrounddivWidth ) {
        document.getElementById('scrollRight').src=rightScrollGreyedImage.src;
        document.getElementById('scrollRight').style.cursor="default";
    } else {
        document.getElementById('scrollRight').src=rightScrollImage.src;
        document.getElementById('scrollRight').style.cursor="pointer";
    }             
    clearTimeout(scrollTimer);
}

// calculateScroll: This method is called when we need to specify a specfic thumb to display. We calculate the where the thumb is in relation to the 
// total table containing all the thumbs. Then we work out whether we have enough scroll width to display the thumb in the middle of the display, or 
// not i.e if the thumb is the last one in the table, we won't be able to centre it, as there are no other thumbs to display to its right. So in this 
// case we set the scrollpos to the maximum val. Similarly if the the thumb is one of the 1st few, then we need to set the scrollpos to the start of 
// the table.
function calculateScrollPos(thumbnail) {
    if (thumbnail) {
        thumbImageObj = thumbnail;
    } else {
        thumbnail = thumbImageObj;
    }
       
    if (thumbsLoaded()) {
        // var that counts the number of tries to load thumbs
        calcScrollLoopCount = 0;
        //The table that contains all the thumbs. This is inside the thumbnails div.
        var thumbtab = document.getElementById('thumbtab');
        // the div that is the visible portion of the thumbnails.
        var thumbsurrounddiv = document.getElementById('thumbsurround');
        // the div containing all the thumbs. This gets scrolled inside the visible div.
        var thumbdiv = document.getElementById('thumbnails');
        // The position of the centre of the selected thumb in relation to the div of all thumbs. 
        var thumbTabPos = (thumbnail.parentNode.offsetLeft + (thumbnail.width /2));
        // the width of the table containing the thumbs.
        var tabWidth = thumbtab.clientWidth;
        // The middle point of the visible div.
        if (thumbtab.clientWidth >= thumbsurrounddiv.clientWidth) {
            var midDisplay = thumbsurrounddiv.clientWidth /2;
            //The maximum scroll pos is the position we need to set the div of all the thumbs so we can display all the 
            // final thumbs in the table without needing to scroll. Because everything is calculated from the left edge of the 
            // div, the max scroll pos is the total with of the thumbs, minus the display div. This gives us our left edge.
            var maxScrollPos = thumbsurrounddiv.clientWidth - thumbtab.clientWidth;
        
            // if the remaining width from the selected thumb to the end of the thumbs is less then the mid point, it means
            // we can't display the selected thumb in the middle, because we'd end up with a massive white space in the right hand 
            // half of the div i.e we havn't got enough thumbs after the selected thumb to the end of the table. So we set
            // the scroll pos to maximum scroll pos i.e the user can't scroll right anymore.
            if (tabWidth - thumbTabPos < midDisplay) {
                scrollpos = maxScrollPos
            // If the selected thumb is less that the mid point, it means we haven't got enough thumbs earlier in the table
            // to display it in the centre. Therefore as it is one of the first few thumbs we need to scroll to the start
            // of the table i.e the user can't scroll left anymore.
            } else if (thumbTabPos < midDisplay) {
                scrollpos = 0;
            // finally if we reach here it means we can display the thumb in the centre of the div. So we need to set the scroll pos
            // to be the selected thumb position, minus half of the visible div. This calcs our left edge again. Everything is
            // a minus figure as we start at 0 and scroll the table left (when the user hits the right scroll bar we shuffle everything
            // to the left to mimic scrolling) and this means we hit negative values.
            } else {
                scrollpos = 0 - (thumbTabPos-midDisplay);
            }
            // Now set the scroll pos on the div.
            thumbdiv.style.left = scrollpos + "px";
        }
        // Finally call the stop_Scroll which checks to see if we need to display the greyed icons or not.
        stop_Scroll();
    } else {
        if (calcScrollLoopCount > imageMaxLoop) {            
            calcScrollLoopCount = 0;
        } else {
            calcScrollLoopCount++;
            thumbnailTimer = setTimeout("calculateScrollPos()", imageTimerInterval);                
        }
    }

}

// This function calculates whether all thumbs have loaded OK and returns either true or false.
function thumbsLoaded() {
    var loaded = true;
    if (! document.thumbArray) {
        loaded = false;
    } else {
        for (var i=0; i < document.thumbArray.length; i++) {
            if (document.thumbArray[i].loaded != imageLoadSuccess) {
                loaded = false;
            }
        }
    }
    
    return loaded;
}

// This function calculates whether all images have loaded OK and returns either true or false.
function imagesLoaded(imageArray) {
    var loaded = true;
    if (! imageArray) {
        loaded = false;
    } else {
        for (var i=0; i < imageArray.length; i++) {
            if (imageArray[i].loaded != imageLoadSuccess) {
                loaded = false;
            }
        }
    }
    
    return loaded;
}

//thumbSelect: This is the function called by the mouse rolling over the thumbnails.
function thumbSelect() {
    processSelectedThumb(this);
}

// processSelectedThumb: This is called when the user moves a mouse over one of the thumbnails. It first sets a previous selected thumbnail border to white. 
//                       Then it sets the current selected thumbnail border to black. Finally call the function to display the image.
function processSelectedThumb(thumbnail) {
    if (selectedThumb) {
        removeBorder(selectedThumb);
    }

    // Loop through the array of thumbs and choose the image that is in the same array position as the selected thumb.
    if (document.thumbArray.length == 0) {
        displayImageObj = noFilteredImagesToDisplay;
        displayImage();
        calcImageControls();
        stop_Scroll();
    } else {
        for (var i = 0; i < document.thumbArray.length; i++) {
            if (document.thumbArray[i].id == thumbnail.id) {
                clearTimeout(thumbnailTimer);
                clearTimeout(displayImageTimer);
                displayImageObj = document.imageArray[i];
                calcImageControls(thumbnail);
                displayImage();
                stop_Scroll();
            }
        } 
        
        setBorder(thumbnail);
        // If the selected thumb is the 1st one in the thumbnail listm, reset the scrollPos almost to the left edge and the scroll left.
        // This means that we set the thumbs as if the page had loaded and also get all the processing 
        // for greying out the scroll icons.
        if (document.thumbArray[0] == selectedThumb) {
            scrollpos = -1;
            scroll_Left();
        }
    }
}

// selectImage: This method is called by the arrows on either side of the main image. They are used to click the next or previous image without the 
//              need to use the scroll bar. This also controls the first/last buttons which position the selection at the beginning or end of the 
//              list of thumbnails.
function selectImage(direction) {

    var newDisplayThumb = null;
    
    if (direction == "first") {
        // Select the first image in the table.
        newDisplayThumb = document.thumbArray[0];
    } else if (direction == "last") {
        // Select the last image in the table.
        newDisplayThumb = document.thumbArray[document.thumbArray.length -1];
    } else {
        for (var i = 0; i < document.thumbArray.length; i++) {
            if (document.thumbArray[i].id == selectedThumb.id) { 
                if (direction == "next") {
                    // Select the next image in the table.
                    newDisplayThumb = document.thumbArray[i+1];
                    break;
                } else if (direction == "prev") {
                    // Select the prev image in the table.
                    newDisplayThumb = document.thumbArray[i-1];
                    break;
                } else {
                    // Shouldn't even get into here. But if you do, do nothing.
                }
            }
        }
    }

    if (newDisplayThumb != null) {
        processSelectedThumb(newDisplayThumb);
        calculateScrollPos(newDisplayThumb);
    }

}

// calcImageControls: This function is called to check to see if the image next/prev buttons need to be greyed or indeed switched back on. 
// If there are no thumbnails then we grey everything out.
function calcImageControls(currThumb) {
    
    // If there are thumbnails to process then work out which controls need to be greyed out and which one allowed to be active.
    // If there are no thumbnails (e.g filters with no matches) grey out everything.
    if (document.thumbArray.length > 0) {
        for (var i = 0; i < document.thumbArray.length; i++) {
            if (document.thumbArray[i].id == currThumb.id) { 
                // If the current thumb is last in the table, grey out next icon, otherwise un-grey the next icon.
                if (i >= document.thumbArray.length - 1) {
                    document.getElementById('imageRight').src=rightScrollGreyedImage.src;
                    document.getElementById('imageRight').style.cursor="default";
                    document.getElementById('imageLast').src=doubleRightScrollGreyedImage.src;
                    document.getElementById('imageLast').style.cursor="default";
                } else {
                    document.getElementById('imageRight').src=rightScrollImage.src;
                    document.getElementById('imageRight').style.cursor="pointer";
                    document.getElementById('imageLast').src=doubleRightScrollImage.src;
                    document.getElementById('imageLast').style.cursor="pointer";
                }
                
                // If the current thumb is first in the table, grey out prev icon, otherwise un-grey the prev icon.
                if (i <= 0) {
                    document.getElementById('imageLeft').src=leftScrollGreyedImage.src;
                    document.getElementById('imageLeft').style.cursor="default";
                    document.getElementById('imageFirst').src=doubleLeftScrollGreyedImage.src;
                    document.getElementById('imageFirst').style.cursor="default";
                } else {
                    document.getElementById('imageLeft').src=leftScrollImage.src;
                    document.getElementById('imageLeft').style.cursor="pointer";
                    document.getElementById('imageFirst').src=doubleLeftScrollImage.src;
                    document.getElementById('imageFirst').style.cursor="pointer";
                }
                break;
            }
        }
    } else {
        document.getElementById('imageRight').src=rightScrollGreyedImage.src;
        document.getElementById('imageRight').style.cursor="default";
        document.getElementById('imageLast').src=doubleRightScrollGreyedImage.src;
        document.getElementById('imageLast').style.cursor="default";
        document.getElementById('imageLeft').src=leftScrollGreyedImage.src;
        document.getElementById('imageLeft').style.cursor="default";
        document.getElementById('imageFirst').src=doubleLeftScrollGreyedImage.src;
        document.getElementById('imageFirst').style.cursor="default";
    }
}

// setBorder: This sets the the border of the selected thumb. It also sets the var selectedThumb to this thumb, so that we know which one to 
//            deselect when another thumb is selected.
function setBorder(currentThumb) {
    if (currentThumb) {
        var thumbdiv = currentThumb.parentNode;
        thumbdiv.style.border = "solid #C434A4 2px";
        selectedThumb = currentThumb;
    }
}

// removeBorder: This function sets the border to be white, which effectively removes it as the background is white.
function removeBorder(currentThumb) {
    var thumbdiv = currentThumb.parentNode;
    if (thumbdiv) {
        thumbdiv.style.border = "solid white 2px";
    }
}

// displayImage: This function checks that the image listed in displayImageObj var has been loaded correctly. If it has it then puts it into a div,
//               and displays it, creating the shadow in the process.
function displayImage()
{ 
    if (displayImageObj.loaded == imageLoadFailure) {
        displayImageObj = unableToLoadImage;
    }
    // If image hasn't loaded then check that we haven't tried more than the max number of times. 
    // If not then set the timer to try again in a short while.
    if (displayImageObj.loaded == imageNotLoaded) {
        if (displayImageLoopCount > imageMaxLoop) {
            displayImageObj.src = unableToLoadImage.src;
            displayImageLoopCount = 0;
        } else {
            displayImageLoopCount++;
            displayImageTimer = setTimeout("displayImage()", imageTimerInterval);                
        }
    } else {
        displayImageLoopCount = 0;
        var maindiv = document.getElementById('mainImageDiv');
        // remove all child elements. This removes the previous image and the old shadow.
        removeChildren(maindiv);
        var image = new Image();
        image.name=displayImageObj.src;
        image.src=displayImageObj.src;
        image.setAttribute("title", displayImageObj.title);
        image.linkReference=displayImageObj.linkReference;
        var anchor = document.createElement('a');
        anchor.href=image.linkReference;
        anchor.appendChild(image);
        var bordersSize = imageWhiteSurround + bordersize;
        var whitesize = imageWhiteSurround + "px";
        var divIdName = 'TopDiv';
        image.style.width = displayImageObj.width + "px";
        image.style.height = displayImageObj.height + "px";

        var picwidth = displayImageObj.width + (bordersSize * 2);
        var picheight = displayImageObj.height + (bordersSize * 2);
        image.style.border="solid white " + whitesize;
        
        // create the main image div, and set the style properties.
        var topdiv = document.createElement('div');
        topdiv.id = divIdName;  
        var topstart = (maindiv.clientHeight - picheight) /2;
        var leftstart = (maindiv.clientWidth - picwidth) /2;
        topdiv.style.top=topstart + "px";
        topdiv.style.left=leftstart + "px";
        topdiv.style.width=picwidth + "px";
        topdiv.style.height=picheight + "px";        
        topdiv.style.backgroundColor="white"
        topdiv.style.position="relative";
        //topdiv.className="image";
        // set zindex to make sure that this is the top div in the parent div.
        topdiv.style.zIndex="99";
        topdiv.style.border = "solid black " + bordersize + "px";
        maindiv.appendChild(topdiv);
        // create the shadow around the image.
        createShadow(topdiv, maindiv);
        topdiv.appendChild(anchor);     
    }
}

// createShadow: This function takes the div that the shadow is to be placed round, and the div that the shadow divs should be added to.
//               The shadow is offset a standard amount, and then each layer is slightly smaller than the previous, like a pyramid, and 
//               the colour gets darker, so it appears as though the shadow is lightening at the edges.
function createShadow(shadowDiv, parentDiv) {
           
    var color = new Array("#F8F8F8","#F4F4F4","#F0F0F0","#ECECEC","#E8E8E8","#E4E4E4","#E0E0E0","#DCDCDC","#D8D8D8","#D4D4D4","#D0D0D0","#CCCCCC","#C8C8C8","#C4C4C4","#C0C0C0");
    var colourBands = color.length; 
    var divWidth = shadowDiv.clientWidth;
    var divHeight = shadowDiv.clientHeight;
    var divTop = shadowDiv.offsetTop;
    var divLeft = shadowDiv.offsetLeft;
    var index = colourBands;
    for (var i=0; i < colourBands; i++) {
        var newdiv = document.createElement("div");
        var divIdName = "div" + i;
        newdiv.setAttribute("id", divIdName);
        newdiv.style.top=divTop + shadowOffset + i + "px";
        newdiv.style.left=divLeft + shadowOffset + i + "px";
        newdiv.style.width=divWidth -(i*2) + "px";
        newdiv.style.height=divHeight -(i*2) + "px";
        newdiv.style.backgroundColor=color[i];
        newdiv.className="shadow";
        parentDiv.appendChild(newdiv);                
    }
}

// removeChildren: This function removes all the children from a particular node. It loops through each child and removes it.
function removeChildren(deldiv) {
    var numChilds = deldiv.childNodes.length;
    var cnodes = deldiv.childNodes;
    for (var i=0; i < numChilds; i++) {
        var currChild = deldiv.firstChild;
        deldiv.removeChild(deldiv.childNodes[0]);
    }
}

function mailto() { 
    win = window.location=mailLink;
}

function imageLoadError() { 
    
    this.loaded = imageLoadFailure;
    this.src = unableToLoadImage.src;
}

function thumbLoadError() {
    this.loaded = imageLoadFailure;
    this.src = unableToLoadThumb.src;
}

// processThumbnail: This set the flag to say that this image has loaded OK.
function imageLoaded() {
    this.loaded = imageLoadSuccess;
}

// linkToPriceList: This small method is called when the thumbnails are doubleclicked. It switches the user to the relevant price details.
function switchToLinkPage() {
    document.location=this.linkReference;
}

// This function switches HTML page to the specified location
function switchLocation(location) {
    document.location=location;
}

// This switches the footer colour to a highlight
function footerHighlight(id) {
    var divid = document.getElementById(id);
    divid.style.color = "#D639B3";
    divid.style.cursor = "pointer";
}

// This switches the footer colour back to default
function footerNormal(id) {
    var divid = document.getElementById(id);
    divid.style.color = "#723CDF";
    divid.style.cursor = "default";
}

// A quick function to determine if we're running an offer.
function isOfferPage() {
    var result = false;
    var divid = document.getElementById("offerDiv");
    if (divid) {
        result = true;
    }
    return result;
}

// When true, this sets the cursor when we have an offer, to make the image look like a link. Otherwise we reset
// the pointer back.
function offerhover(value) {
    var divid = document.getElementById("offerDiv");
    if (divid) {
        var offerPic = document.getElementById("offer");
        if (offerPic) {
            if (value == "true") {
                divid.style.cursor = "pointer";
                offerPic.src = webImagesDir + "offerBannerSelected.gif";
            } else {
                divid.style.cursor = "default";
                offerPic.src = webImagesDir + "offerBanner.gif";
            }
        }
    }
}

// This function decides whether to allow the offer navigation element to sent the request through to
// the offer page.
function offerWebsite() {
    switchLocation('WishCakes' + displaySpecialCatagory + '.htm');
}

// If we are using the offer page we need to map the new images to the image map areas, otherwise
// the offer image obscures the new image underneath even though the banner is transparent.
function setOfferImageMaps(image) {
            
    var divid = document.getElementById("offerDiv");
    if (divid) {
        if (image.src.indexOf("Catagory2") > 0) {
            var area2 = document.getElementById("catagory2map");
            if (area2) {
                area2.setAttribute("title", image.title);
                area2.linkReference=image.linkReference;
                area2.onclick=switchToLinkPage;
                area2.style.cursor = "pointer";
            }
        } else if (image.src.indexOf("Catagory3") > 0) {
            var area3 = document.getElementById("catagory3map");
            if (area3) {
                area3.setAttribute("title", image.title);
                area3.linkReference=image.linkReference;
                area3.onclick=switchToLinkPage;
                area3.style.cursor = "pointer";
            }
        } else if (image.src.indexOf("Catagory5") > 0) {
            var area5 = document.getElementById("catagory5map");
            if (area5) {
                area5.setAttribute("title", image.title);
                area5.linkReference=image.linkReference;
                area5.onclick=switchToLinkPage;
                area5.style.cursor = "pointer";
            }
        } else {
            // Nothing to do.               
        }
    }
}

// This function searches an array for a value and returns either true or false if the array contains it.
function searchArray(Array, string) {
    var result = false;
    for (var i=0; i < Array.length; i++) {
        if (Array[i] == string) {
            result = true;
            break;
        }
    }
    return result;
}

// This function returns the current year for the copyright statement in the HTML.
function getYear() {
    return new Date().getFullYear();
}

// This setups up the animation for the picture fades on the title screen.
function configureTitleAnimation() {

    var mainPictureDiv = document.getElementById("titlePageImageDiv");
    if (mainPictureDiv) {

        var blankTitleImage = new Image();
        blankTitleImage.src=webImagesDir + "blankTitleImage.jpg";
        blankTitleImage.style.zIndex="90";
        mainPictureDiv.appendChild(blankTitleImage);

        loadTitleImages();
        var titleImage1 = document.createElement('div');
        titleImage1.setAttribute("id", "titleImage1");
        titleImage1.className="titleImage1";
        titleImage1.style.zIndex="96";
        var titleImage2 = document.createElement('div');
        titleImage2.setAttribute("id", "titleImage2");
        titleImage2.className="titleImage2";
        titleImage2.style.zIndex="96";
        var titleImage3 = document.createElement('div');
        titleImage3.setAttribute("id", "titleImage3");
        titleImage3.className="titleImage3";
        titleImage3.style.zIndex="96";
        var titleImage4 = document.createElement('div');
        titleImage4.setAttribute("id", "titleImage4");
        titleImage4.className="titleImage4";
        titleImage4.style.zIndex="95";
        var titleImage5 = document.createElement('div');
        titleImage5.setAttribute("id", "titleImage5");
        titleImage5.className="titleImage5";
        titleImage5.style.zIndex="97";

        for (var i = 0; i < document.catagory1.length; i++) {
            document.catagory1[i].style.position="absolute";
            document.catagory1[i].style.zIndex="95";
            titleImage1.appendChild(document.catagory1[i]);
        }

        for (var i = 0; i < document.catagory2.length; i++) {
            document.catagory2[i].style.position="absolute";
            document.catagory2[i].style.zIndex="95";
            titleImage2.appendChild(document.catagory2[i]);
        }
        
        for (var i = 0; i < document.catagory3.length; i++) {
            document.catagory3[i].style.position="absolute";
            document.catagory3[i].style.zIndex="95";
            titleImage3.appendChild(document.catagory3[i]);
        }
        
        for (var i = 0; i < document.catagory4.length; i++) {
            document.catagory4[i].style.position="absolute";
            document.catagory4[i].style.zIndex="95";
            titleImage4.appendChild(document.catagory4[i]);
        }
        
        for (var i = 0; i < document.catagory5.length; i++) {
            document.catagory5[i].style.position="absolute";
            document.catagory5[i].style.zIndex="95";
            titleImage5.appendChild(document.catagory5[i]);
        }
    
        var image1 = getNextImage(null, document.catagory1);
        image1.style.opacity="1.0";
        image1.style.filter="alpha(opacity=100)";
        image1.style.zIndex="97";
        
        var image2 = getNextImage(null, document.catagory2);
        image2.style.opacity="1.0";
        image2.style.filter="alpha(opacity=100)";
        image2.style.zIndex="97";
        if (offer) {
            // Check to see if we need to set offerImage maps - only need to do this for top right, centre
            // and bottom right.
            setOfferImageMaps(image2);
        }
        
        var image3 = getNextImage(null, document.catagory3);
        image3.style.opacity="1.0";
        image3.style.filter="alpha(opacity=100)";
        image3.style.zIndex="97";
        if (offer) {
            // Check to see if we need to set offerImage maps - only need to do this for top right, centre
            // and bottom right.
            setOfferImageMaps(image3);
        }
        
        var image4 = getNextImage(null, document.catagory4);
        image4.style.opacity="1.0";
        image4.style.filter="alpha(opacity=100)";
        image4.style.zIndex="97";
        
        var image5 = getNextImage(null, document.catagory5);
        image5.style.opacity="1.0";
        image5.style.filter="alpha(opacity=100)";
        image5.style.zIndex="97";
        if (offer) {
            // Check to see if we need to set offerImage maps - only need to do this for top right, centre
            // and bottom right.
            setOfferImageMaps(image5);
        }
        
        mainPictureDiv.appendChild(titleImage1);
        mainPictureDiv.appendChild(titleImage2);
        mainPictureDiv.appendChild(titleImage3);
        mainPictureDiv.appendChild(titleImage4);
        mainPictureDiv.appendChild(titleImage5);
    }
}   
    
// This function is triggered when the title images have been loaded.
function runTitleAnimation() {
    
    var titleImage1 = document.getElementById("titleImage1");
    var image1 = titleImage1.firstChild;    
    var titleImage2 = document.getElementById("titleImage2");
    var image2 = titleImage2.firstChild;    
    var titleImage3 = document.getElementById("titleImage3");
    var image3 = titleImage3.firstChild;    
    var titleImage4 = document.getElementById("titleImage4");
    var image4 = titleImage4.firstChild;    
    var titleImage5 = document.getElementById("titleImage5");
    var image5 = titleImage5.firstChild;    
    
    var imageLoadTimer1 = setTimeout(function() {setNewTitleImages("Catagory1", document.catagory1, image1);}, 5000);
    var imageLoadTimer2 = setTimeout(function() {setNewTitleImages("Catagory2", document.catagory2, image2);}, 10000);
    var imageLoadTimer3 = setTimeout(function() {setNewTitleImages("Catagory3", document.catagory3, image3);}, 15000);
    var imageLoadTimer4 = setTimeout(function() {setNewTitleImages("Catagory4", document.catagory4, image4);}, 20000);
    var imageLoadTimer5 = setTimeout(function() {setNewTitleImages("Catagory5", document.catagory5, image5);}, 25000);
}
    
// This function is called via the timer to trigger the new image updates.
function setNewTitleImages(catagory, catagoryArray, image) {    

    var mainPictureDiv = document.getElementById("titlePageImageDiv");
    var newImage = getNextImage(image, catagoryArray);
    
    fadeTitleImages(image, newImage);
    
    var imageLoadTimer = setTimeout(function() {setNewTitleImages(catagory, catagoryArray, newImage);}, titleImageStaticTimerInterval);
    
}

// This function fades one image by changing its opacity and fades in another.
function fadeTitleImages(fadeOutImage, fadeInImage) {
    
    fadeOutOpacity = fadeOutImage.style.opacity * 100;
    fadeInOpacity = fadeInImage.style.opacity * 100;
   
    if (fadeOutOpacity > 0) {
        fadeOutOpacity = fadeOutOpacity - 2;
        fadeOutImage.style.opacity = fadeOutOpacity / 100;
        fadeOutImage.style.filter="alpha(opacity=" + (fadeOutOpacity) + ")";
    
        fadeInOpacity = fadeInOpacity + 2;
        fadeInImage.style.opacity = fadeInOpacity / 100;
        fadeInImage.style.filter="alpha(opacity=" + (fadeInOpacity) + ")";
        if (fadeOutOpacity > 0) {
            if (offer) {
                //Check to see if we need to set offerImage maps
                setOfferImageMaps(fadeInImage);
            }
            titleImageFadeWaitTimer = setTimeout(function() {fadeTitleImages(fadeOutImage, fadeInImage);}, titleImageFadeTimerInterval);
        } else {
            fadeInImage.style.zIndex="97";
            fadeOutImage.style.zIndex="95";
        }
    }
}

// This function gets the next image from the array.
function getNextImage(currentImage, imageArray) {

    var nextImage = null;
    
    if (currentImage == null) {
        nextImage = imageArray[0];
    } else {
        for (var i = 0; i < imageArray.length && nextImage == null; i++) {
            if (imageArray[i].name == currentImage.name) {
                if (imageArray.length == i + 1) {
                    nextImage = imageArray[0];
                } else {
                    nextImage = imageArray[i + 1];
                }
            }
        }
    } 
    
    return nextImage;
}

// This function checks to see if whether we should display the image. It checks whether we have a subGroup defined. If not, 
// we display the image. If we do, we check to see if the subgroup is listed in the images list of valid subgroups. 
// If it is we display the image.
function isSubGroupImage(subGroups) {
    var result = false;
    if (this.subGroup) {
        var subgroups = new Array();
        // Split the subGroupString into individual elements
        splitSubgroups = subGroups.split('-'); 
        // Loop through each subgroup checking to see if the subGroup we're filtering on is listed.
        for (var i = 0; i < splitSubgroups.length && result == false; i++) {
            if (this.subGroup == "all" || splitSubgroups[i].toLowerCase() == "all" || splitSubgroups[i] == this.subGroup) {
                result = true;     
            }
        }
    } else {
        result = true;
    }
    return result;
}

// The setter function that filter options on the webpage use to select the image filtering. 
// We then run loadImages which will filter the images for this subgroup.
function setSubGroup(newSubGroup, filterName, pageSelectImage, pageDeSelectImage) {
    if  (this.subGroup && this.subGroup == newSubGroup) {
        // If the filter is the same as the previous one, do nothing.
    } else {    
        this.subGroup = newSubGroup;
        
        // If we have a filter already registered, reset the image back to the non selected image.
        // If we don't have a filter registed, set one up ready for use.
        if (document.filter) {
            var oldFilterImage = document.getElementById(document.filter[0]);
            oldFilterImage.src=document.filter[1];
        } else {
            document.filter = new Array();  
        }
        
        // set the newly selected filter with the correct image
        var newFilter = document.getElementById(filterName);
        if (newFilter) {
            newFilter.src = pageSelectImage;
            
            // Store this info away so we can deselect the image when a new filter is selected. 
            document.filter[0] = filterName;
            document.filter[1] = pageDeSelectImage;
            
            document.thumbArray = null;
            document.imageArray = null;
            
            // Recreate the valid images
            loadImages();
         }
    }
}