var carouselLeft = 0;
var carouselFx = null;
var shoppingListFx = null;
var shoppingListSlideState = 'out';
var spread = 0; //default
var spreadWidth = 860; //a page is 430px wide, so a spread width is 860px
var totalSpreadsLoaded = 0; //default
var lastSpread = 0;
var insertLastSpread = 0;
var shoppingListTimer = null;
var updateQtyTimer = null;
var productTips = null;
var postcodeSearch = '';
var store_id = '';
var store_name = '';
var store_city = '';
var store_suburb = '';
var catalogue_id = '';
var insert_id = '';
var promotion_id = '';
var selectNewStoreMessage = '';
var catalogue_title = '';
var catalogue_name = '';
var downloadSession = false;

window.addEvent("domready", initCatalogueInformation);

function initCatalogueInformation() {
    action('catalogue', 'catalogue-init', {}, function(response) {
        if (response.store_id && response.catalogue_id) {
            if( response.download )
                downloadSession = response.download;
            else
                downloadSession = false;
            store_id = response.store_id;
            store_name = response.store_name;
            store_city = response.store_city;
            store_postcode = response.store_postcode;
            $('yourLocalStore').setStyle('display', '');
            $('changeStoreButton').setStyle('display', '');
            if ($('storeNameSpan')) {
                $('storeNameSpan').set('html', response.store_name);
            }
            if ($('storeAddressSpan')) {
                $('storeAddressSpan').set('html', ', ' + response.store_address);
            }
            if ($('storePhoneSpan')) {
                $('storePhoneSpan').set('html', 'p: ' + response.store_phone);
            }
            if ($('welcomeBackSpan')) {
                $('welcomeBackSpan').set('html', 'Welcome Back!');
            }
            catalogue_id = response.catalogue_id;
            catalogue_title = response.catalogue_title;
            catalogue_name = response.catalogue_name;
            if (response.insert_id != undefined) {
                insert_id = response.insert_id;
                                insertLastSpread = response.insertLastSpread;
            }
            if (response.promotion_id) {
                promotion_id = response.promotion_id;
            }
            spread = response.startSpread;
                        if (response.insertLastSpread != undefined) {
                            insertLastSpread = response.insertLastSpread;
                        }
            lastSpread = response.lastSpread;
        } else {
            if (response.postcodeSearch && response.selectNewStore) {
                postcodeSearch = response.postcodeSearch;
                selectNewStoreMessage = response.selectNewStoreMessage;
            }
        }
        if( !downloadSession )
            initCatalogue();
    });
}
function initCatalogue() {
    if (store_id != '' && store_id != 0 && catalogue_id != '' && catalogue_id != 0 && !downloadSession) {
        if (pageTracker) {
            pageTracker._trackPageview('/store/load/' + store_postcode + '/' + store_id + '/' + store_name + ', ' + store_city + '/catalogue/' + catalogue_id);
            pageTracker._trackPageview('/catalogue/load/' + catalogue_id);
            var leftPageNo = spread * 2;
            var rightPageNo = leftPageNo + 1;
            pageTracker._trackPageview('/catalogue/' + catalogue_id + '/page/' + leftPageNo + '-' + rightPageNo);
        }
        setupCatalogueContainer();
        setupPreviousAndNextButtonEvents();
        setupCataloguePages();
        carouselFx = new Fx.Tween($('carousel'), {
            'duration': 'short'
        });
        setupShoppingListTool();
        setupChangeStoreButton();
    } else {
        if (postcodeSearch != '') {
            popStoreLocatorResults(postcodeSearch);
        } else {
            popStoreLocator(true);
        }
    }
}


function setupChangeStoreButton() {
    if ($('changeStoreButton')) {
        $('changeStoreButton').removeEvents('click');
        $('changeStoreButton').addEvent('click', function(event) {
            event.preventDefault();
        });
        $('changeStoreButton').addEvent('click', popStoreLocator);
    }
}

function setupCatalogueContainer() {
    if (!$('catalogueWrapper')) {
        $('catalogueContainer').adopt(new Element('div', {'id': 'catalogueWrapper'}));

        // PREV LINK
        if (!$('prevLinkContainer')) {
            $('catalogueWrapper').adopt(new Element('div', {'id': 'prevLinkContainer', 'class': 'prevLinkContainer'}));

            if (!$('prevLink')) {
                var image_html = '<img src="'+baseUrl+'/assets/images/core/previous_button.gif" alt="previous" />';
                $('prevLinkContainer').adopt(new Element('a', {'id': 'prevLink', 'href': '#', 'html': image_html}));
            }

            $('prevLinkContainer').setStyles({
                'position': 'absolute',
                'top': ($('catalogueWrapper').getTop() + 200) + 'px',
                'left': '15px',
                'z-index': '10'
            });
        }

        // CATALOGUE CONTAINER
        if (!$('catalogueSpreadViewContainer')) {
            $('catalogueWrapper').adopt(new Element('div', {'id': 'catalogueSpreadViewContainer', 'class': 'catalogueSpreadViewContainer'}));

            if (!$('catalogueSpreadViewer')) {
                $('catalogueSpreadViewContainer').adopt(new Element('div', {'id': 'catalogueSpreadViewer', 'class': 'catalogueSpreadViewer'}));

                if (!$('carousel')) {
                    if (spread == 0 || spread == (lastSpread + insertLastSpread)) {
                        var defaultSpreadWidth = spreadWidth * 2;
                    } else {
                        var defaultSpreadWidth = spreadWidth * 3;
                    }
                    $('catalogueSpreadViewer').adopt(new Element('div', {'id': 'carousel', 'class': 'carousel', 'style': 'width: ' + defaultSpreadWidth + 'px; left: 0px;'}));
                }
            }
            $('catalogueSpreadViewContainer').setStyles({
                'position': 'absolute'
            });
        }

        // NEXT LINK
        if (!$('nextLinkContainer')) {
            $('catalogueWrapper').adopt(new Element('div', {'id': 'nextLinkContainer', 'class': 'nextLinkContainer'}));

            if (!$('nextLink')) {
                var image_html = '<img src="'+baseUrl+'/assets/images/core/next_button.gif" alt="next" />';
                $('nextLinkContainer').adopt(new Element('a', {'id': 'nextLink', 'href': '#', 'html': image_html}));
            }

            $('nextLinkContainer').setStyles({
                'position': 'absolute',
                'top': ($('catalogueWrapper').getTop() + 200) + 'px',
                'left': ($('catalogueWrapper').getWidth() + 32) + 'px',
                'z-index': '10'
            });
        }

        // NAVIGATION BAR
        if (!$('navBarContainer')) {
            $('catalogueWrapper').adopt(new Element('div', {'id': 'navBarContainer', 'class': 'navBarContainer', 'style': 'width: 134px;'}));

            if (!$('prevNavButtonContainer')) {
                $('navBarContainer').adopt(new Element('div', {'id': 'prevNavButtonContainer', 'class': 'prevNavButtonContainer'}));

                if (!$('prevNavButton')) {
                    $('prevNavButtonContainer').adopt(new Element('input', {'id': 'prevNavButton', 'type': 'image', 'src': baseUrl + '/assets/images/core/prev_nav_button.gif'}));

                    $('prevNavButton').addEvent('click', function(event) {
                        event.preventDefault();
                    });
                }
            }

            if (!$('pageNumbersContainer')) {
                $('navBarContainer').adopt(new Element('div', {'id': 'pageNumbersContainer', 'class': 'pageNumbersContainer'}));

                if (!$('leftPageNumber')) {
                    $('pageNumbersContainer').adopt(new Element('div', {'id': 'leftPageNumber', 'class': 'leftPageNumber'}));
                }

                if (!$('rightPageNumber')) {
                    $('pageNumbersContainer').adopt(new Element('div', {'id': 'rightPageNumber', 'class': 'rightPageNumber'}));
                }

                if (!$('totalPageNumber')) {
                    $('pageNumbersContainer').adopt(new Element('div', {'id': 'totalPageNumber', 'class': 'totalPageNumber'}));
                }
            }

            if (!$('nextNavButtonContainer')) {
                $('navBarContainer').adopt(new Element('div', {'id': 'nextNavButtonContainer', 'class': 'nextNavButtonContainer'}));

                if (!$('nextNavButton')) {
                    $('nextNavButtonContainer').adopt(new Element('input', {'id': 'nextNavButton', 'type': 'image', 'src': baseUrl + '/assets/images/core/next_nav_button.gif'}));

                    $('nextNavButton').addEvent('click', function(event) {
                        event.preventDefault();
                    });
                }
            }

            $('navBarContainer').setStyles({
                'position': 'absolute',
                'top': ($('catalogueContainer').getHeight() - $('navBarContainer').getHeight() - 12) + 'px',
                'left': (($('catalogueContainer').getWidth() - $('navBarContainer').getWidth()) / 2) + 'px'
            });
        }
    }
}
function setupPreviousAndNextButtonEvents() {
    if ($('prevLink')) {
        $('prevLink').removeEvents("click");
        $('prevLink').addEvent("click", function(event) {
            event.preventDefault();
        });
        $('prevLink').addEvent("click", prevSpread);
        $('prevNavButton').addEvent('click', prevSpread);
    }

    if ($('nextLink')) {
        $('nextLink').removeEvents("click");
        $('nextLink').addEvent("click", function(event) {
            event.preventDefault();
        });
        $('nextLink').addEvent("click", nextSpread);
        $('nextNavButton').addEvent('click', nextSpread);
    }
}

function setupCataloguePages() {
    if ($('carousel')) {
        //hide carousel from view first
        $('carousel').setStyle('display', 'none');
    }

    var leftPageNo = spread * 2;
    if (leftPageNo != 0) {
        $('leftPageNumber').set('html', leftPageNo);
    } else {
        $('leftPageNumber').set('html', '');
    }
    var rightPageNo = leftPageNo + 1;
    if ((lastSpread + insertLastSpread) != 0 && lastSpread != '' && rightPageNo != (((lastSpread + insertLastSpread) * 2) + 1)) {
        $('rightPageNumber').set('html', rightPageNo);
        $('totalPageNumber').set('html', '/ ' + ((lastSpread + insertLastSpread) * 2));
    } else {
        $('rightPageNumber').set('html', '');
    }
    //left page
    createPage(leftPageNo);

    //right page
    createPage(rightPageNo);

    if (spread != (lastSpread + insertLastSpread)) {
        var leftNextCachePageNo = leftPageNo + 2;
        var rightNextCachePageNo = leftPageNo + 3;
        //left page
        createPage(leftNextCachePageNo);

        //right page
        createPage(rightNextCachePageNo);
    }
    if (spread != 0) {
        var leftPrevCachePageNo = leftPageNo - 2;
        var rightPrevCachePageNo = leftPageNo - 1;
        var inject = true;
        //right page - we're doing right first so that we can later inject the left page to the top of the carousel
        createPage(rightPrevCachePageNo, inject);

        //left page
        createPage(leftPrevCachePageNo, inject);
    }
    if (spread != 0 && spread != (lastSpread + insertLastSpread)) {
        totalSpreadsLoaded = 3;
        defaultSpreadLeft = spreadWidth * -1
    } else if (spread != 0 || spread != (lastSpread + insertLastSpread)) {
        totalSpreadsLoaded = 2;
        defaultSpreadLeft = 0;
    } else {
        totalSpreadsLoaded = 1;
        defaultSpreadLeft = 0;
    }

    //set carousel width
    $('carousel').setStyle('width', (totalSpreadsLoaded * spreadWidth) + 'px');

    //set carousel position
    $('carousel').setStyle('left', defaultSpreadLeft + 'px');

    if ($('carousel')) {
        //set carousel to display!
        $('carousel').setStyle('display', '');
    }

    //Increment backend Spread View count
    action('catalogue', 'increment-spread-view', {'spread': spread}, function(response) {});
}

function popStoreLocator(forceOpen) {
    if (forceOpen == true) {
        forceOpen = true;
    } else {
        forceOpen = false;
    }
    TB_show('<img src="' + baseUrl + '/assets/images/core/store_locator.gif" border="0" style="border: none !important; margin: 0 !important; padding-top:2px" alt="Mitre 10 Store Locator" />', baseUrl + '/store/locator?TB_JSON=true&height=271&width=467', false, forceOpen, true);
}

function locateStore() {
    if ($('searchTermTxt') ) {
        if ($('searchTermTxt').value != '' && $('searchTermTxt').value != 'Suburb or Postcode') {
            if ($('searchTermTxt').value.length >= 3) {
                var searchTerm = $('searchTermTxt').value;
                if (searchTerm != '') {
                    TB_show('<img src="' + baseUrl + '/assets/images/core/store_locator_search_results.gif" border="0" style="border: none !important; margin: 0 !important;" alt="Mitre 10 Store Locator Search Results" />', baseUrl + '/store/locate?searchTerm=' + searchTerm + '&TB_JSON=true&height=740&width=570&catalogue_id=' + force_catalogue_id, false, true);
                } else {
                    alert('You have entered invalid search terms. Please enter a Suburb Name OR a Postcode');
                }
            } else {
                alert('To narrow your search results better, please at least enter three characters for the search term');
            }
        } else {
            alert('To find your nearest Mitre 10 store, please enter at least a Suburb name OR a Postcode for best results.');
        }
    }
    return false;
}

function popStoreLocatorResults(postcode) {
    TB_show('<img src="' + baseUrl + '/assets/images/core/store_locator_search_results.gif" border="0" style="border: none !important; margin: 0 !important;" alt="Mitre 10 Store Locator Search Results" />', baseUrl + '/store/locate?searchTerm=' + postcode + '&TB_JSON=true&height=740&width=570&catalogue_id=' + force_catalogue_id, false, true);
    if (selectNewStoreMessage != '') {
        alert(selectNewStoreMessage);
    }
    return false;
}

function selectStore(selected_store_id) {

    if (force_catalogue_id == undefined)
        force_catalogue_id = null;

    action('store', 'select', {
        'store_id': selected_store_id,
        'catalogue' : parseInt(force_catalogue_id)
    }, function(response) {
        if ((response.store_id != undefined && store_id != response.store_id) || (response.catalogue_id != undefined && catalogue_id != response.catalogue_id)) {
            store_id = response.store_id;
            store_name = response.store_name;
            store_city = response.store_city;
            store_postcode = response.store_postcode;
            $('yourLocalStore').setStyle('display', '');
            $('changeStoreButton').setStyle('display', '');
            if ($('storeNameSpan')) {
                $('storeNameSpan').set('html', response.store_name);
            }
            if ($('storeAddressSpan')) {
                $('storeAddressSpan').set('html', ', ' + response.store_address);
            }
            if ($('storePhoneSpan')) {
                $('storePhoneSpan').set('html', 'p: ' + response.store_phone);
            }
            catalogue_id = response.catalogue_id;
            catalogue_title = response.catalogue_title;
            catalogue_name = response.catalogue_name;
            if (response.insert_id != undefined) {
                insert_id = response.insert_id;
            }
            if (response.promotion_id) {
                promotion_id = response.promotion_id;
            }
            spread = response.startSpread;
                        if (response.insertLastSpread != undefined) {
                            insertLastSpread = response.insertLastSpread;
                        }
            lastSpread = response.lastSpread;
            resetCataloguePages();
            //Google Analytics - send trackPageView
            /*if (pageTracker) { // THIS HAS BEEN MOVED TO initCatalogue() FUNCTION
                pageTracker._trackPageview('/store/load/' + store_id + ' - ' + response.store_name + ', ' + response.store_city + ' ' + response.store_postcode + ' - ' + response.store_name + ', ' + response.store_city + ' ' + response.store_postcode + '/catalogue/' + catalogue_id + '_' + catalogue_name);
                                pageTracker._trackPageview('/catalogue/load/' + catalogue_id + '_' + catalogue_name);
                var leftPageNo = spread * 2;
                var rightPageNo = leftPageNo + 1;
                pageTracker._trackPageview('/catalogue/' + catalogue_id + '/page/' + leftPageNo + '-' + rightPageNo);
            }//*/
            TB_remove();
            initCatalogue();
        } else if (response.store_id == store_id && response.catalogue_id == catalogue_id) {
            TB_remove();
        } else {
            eval(response.javascript);
        }
    });
}


function setupShoppingListTool() {
    if (!$('shoppingListToolWrapper')) {
        //SHOPPING LIST CONTAINER
        $('catalogueContainer').adopt(new Element('div', {'id': 'shoppingListToolWrapper', 'class': 'shoppingListToolWrapper', 'style': 'position: absolute; top: 0;'}));

        //SHOPPING LIST HANDLE (OPEN/CLOSE)
        if (!$('shoppingListToolHandleContainer')) {
            $('shoppingListToolWrapper').adopt(new Element('div', {'id': 'shoppingListToolHandleContainer', 'class': 'shoppingListToolHandleContainer'}));

            if (!$('shoppingListToolHandleLink')) {
                if (Browser.Engine.trident) {
                    $('shoppingListToolHandleContainer').adopt(new Element('a', {'id': 'shoppingListToolHandleLink_open', 'href': '#', 'html': '<img src="' + baseUrl + '/assets/images/core/shopping_list_tab_ie.gif" border="0" alt="Open Shopping List" />'}));
                }
                else {
                    $('shoppingListToolHandleContainer').adopt(new Element('a', {'id': 'shoppingListToolHandleLink_open', 'href': '#', 'html': '<img src="' + baseUrl + '/assets/images/core/shopping_list_tab.png" border="0" alt="Open Shopping List" />'}));
                }
            }
            $("shoppingListToolHandleContainer").addEvent("click", function(event) {
                event.preventDefault();
            });
            $('shoppingListToolHandleContainer').addEvent('click', slideShoppingListTool);
        }

        //SHOPPING LIST CONTENT
        if (!$('shoppingListToolContentContainer')) {
            $('shoppingListToolWrapper').adopt(new Element('div', {'id': 'shoppingListToolContentContainer', 'class': 'shoppingListToolContentContainer'}));

            //SHOPPING LIST HEADER IMAGE ('My Shopping List')
            if (!$('shoppingListToolHeaderImage')) {
                $('shoppingListToolContentContainer').adopt(new Element('div', {'id': 'shoppingListToolHeaderImage', 'class': 'shoppingListToolHeaderImage', 'html': '<img src="' + baseUrl + '/assets/images/core/my_pre_shopping_list.gif" width="259" height="73" border="0" alt="My Pre-Shopping List" />'}));
            }

            //SHOPPING LIST HEADER
            if (!$('shoppingListToolHeader')) {
                $('shoppingListToolContentContainer').adopt(new Element('div', {'id': 'shoppingListToolHeader', 'class': 'shoppingListToolHeader'}));
            }

            //SHOPPING LIST CONTENT
            if (!$('shoppingListToolContent')) {
                $('shoppingListToolContentContainer').adopt(new Element('div', {'id': 'shoppingListToolContent', 'class': 'shoppingListToolContent'}));
            }

            //SHOPPING LIST TOTALS CONTAINER
            if (!$('shoppingListToolTotalContainer')) {
                $('shoppingListToolContentContainer').adopt(new Element('div', {'id': 'shoppingListToolTotalContainer', 'class': 'shoppingListToolTotalContainer'}));

                if (!$('shoppingListTotalDiv')) {
                    $('shoppingListToolTotalContainer').adopt(new Element('div', {'id': 'shoppingListTotalDiv', 'class': 'shoppingListTotalDiv', 'html': 'Total: '}));

                    if (!$('shoppingListTotalSpan')) {
                        $('shoppingListTotalDiv').adopt(new Element('span', {'id': 'shoppingListTotalSpan'}));
                    }
                }

                if (!$('shoppingListDiscountDiv') && promotion_id != '' && promotion_id != 0) {
                    $('shoppingListToolTotalContainer').adopt(new Element('div', {'id': 'shoppingListDiscountDiv', 'class': 'shoppingListDiscountDiv', 'html': 'Promotional discount: '}));

                    if (!$('shoppingListDiscountSpan')) {
                        $('shoppingListDiscountDiv').adopt(new Element('span', {'id': 'shoppingListDiscountSpan'}));
                    }
                }

                if (!$('shoppingListGrandTotalDiv')) {
                    $('shoppingListToolTotalContainer').adopt(new Element('div', {'id': 'shoppingListGrandTotalDiv', 'class': 'shoppingListGrandTotalDiv', 'html': 'SHOPPING LIST TOTAL: '}));

                    if (!$('shoppingListGrandTotalSpan')) {
                        $('shoppingListGrandTotalDiv').adopt(new Element('span', {'id': 'shoppingListGrandTotalSpan'}));
                    }
                }
            }

            //SHOPPING LIST BUTTONS CONTAINER
            if (!$('shoppingListToolButtonsContainer')) {
                $('shoppingListToolContentContainer').adopt(new Element('div', {'id': 'shoppingListToolButtonsContainer', 'class': 'shoppingListToolButtonsContainer'}));

                if (!$('sendToFriendButton')) {
                    $('shoppingListToolButtonsContainer').adopt(new Element('input', {'type': 'image', 'src': baseUrl + '/assets/images/core/send_to_friend_button.gif', 'id': 'sendToFriendButton', 'style': 'position: relative;'}));
                }
                $('sendToFriendButton').addEvent('click', popSendToFriend);

                if (!$('printShoppingListButton')) {
                    $('shoppingListToolButtonsContainer').adopt(new Element('input', {'type': 'image', 'src': baseUrl + '/assets/images/core/print_list_button.gif', 'id': 'printShoppingListButton', 'style': 'position: relative;'}));
                }
                $('printShoppingListButton').addEvent('click', popPrintableShoppingList);
            }
        }

        getShoppingListHeading();
        updateShoppingList();

        //POSITION THE SHOPPING LIST
        $('shoppingListToolWrapper').setStyles({
            'position': 'absolute',
            'margin-left': '42px', //mmmmmm
            'z-index': '5'
        });

        //BRIEFLY SHOW THE SHOPPING LIST AND THEN HIDE
        slideShoppingListTool('in');
        delayedSlideShoppingListTool(1000);

    }
}

function slideShoppingListTool(mode) {
    if ($('shoppingListToolWrapper')) {
        if (shoppingListFx == null) {
            shoppingListFx = new Fx.Tween($('shoppingListToolWrapper'), {
                'duration': '333'
            });
        }

        var shoppingListToolWrapperInStateLeft = $('catalogueContainer').getLeft() + $('catalogueContainer').getWidth() - $('shoppingListToolWrapper').getWidth() - $('catalogueWrapper').getLeft();
        var shoppingListToolWrapperOutStateLeft = $('catalogueContainer').getLeft() + $('catalogueContainer').getWidth() - $('shoppingListToolWrapper').getWidth() + $('shoppingListToolContentContainer').getWidth() - $('catalogueWrapper').getLeft();
        shoppingListFx.removeEvents('complete');

        if (shoppingListTimer != null) {
            clearTimeout(shoppingListTimer);
        }
        shoppingListFx.addEvent('complete', slideShoppingListToolCompleted);
        if (shoppingListSlideState != mode) {
            switch (mode) {
                case 'in':
                    bringShoppingListToolToFront();
                    shoppingListFx.start('left', shoppingListToolWrapperInStateLeft + 'px');
                    break;
                case 'out':
                    shoppingListFx.start('left', shoppingListToolWrapperOutStateLeft + 'px');
                    break;
                case 'in then out':
                    bringShoppingListToolToFront();
                    shoppingListFx.start('left', shoppingListToolWrapperInStateLeft + 'px');
                    break;
                default:
                    if (shoppingListSlideState == 'in') {
                        //$('shoppingListToolContentContainer').removeEvents('mouseout');
                        shoppingListFx.start('left', shoppingListToolWrapperOutStateLeft + 'px');
                    } else {
                        bringShoppingListToolToFront();
                        shoppingListFx.start('left', shoppingListToolWrapperInStateLeft + 'px');
                    }
                    break;
            }
        }
    }
}

function getShoppingListHeading() {
    action('shopping-list', 'list-header', {}, function(response) {
        $('shoppingListToolHeader').set('html', response.contentHTML);
    });
}
function updateShoppingList() {
    action('shopping-list', 'list', {}, function(response) {
        $('shoppingListToolContent').set('html', response.contentHTML);
                if (response.subtotal != '$0.00' && response.subtotal != '$ 0.00') {
                    $('shoppingListTotalSpan').set('html', response.subtotal);
                } else {
                    if (response.contentHTML == '') {
                        $('shoppingListTotalSpan').set('html', '$ 0.00');
                    } else {
                        $('shoppingListTotalSpan').set('html', 'See in store*');
                    }
                }
        if (response.discountTotal != undefined) {
            $('shoppingListDiscountSpan').set('html', response.discountTotal);
        }
                if (response.miscMessage != '') {
                    if (!$('miscMessage')) {
                        var miscMessageElt = new Element('div', {'id': 'miscMessage', 'class': 'miscMessage'});
                        miscMessageElt.injectAfter('shoppingListGrandTotalSpan');
                        $('miscMessage').set('html', response.miscMessage);
                    }
                    $('miscMessage').set('html', response.miscMessage);
                } else {
                    if ($('miscMessage')) {
                        $('miscMessage').dispose();
                    }
                }
                if (response.grandTotal != '$0.00' && response.grandTotal != '$ 0.00') {
                    $('shoppingListGrandTotalSpan').set('html', response.grandTotal);
                } else {
                    if (response.contentHTML == '') {
                        $('shoppingListGrandTotalSpan').set('html', '$ 0.00');
                    } else {
                        $('shoppingListGrandTotalSpan').set('html', 'See in store*');
                    }
                }
    });
}

function delayedSlideShoppingListTool(delayTime) {
    if (shoppingListTimer != null) {
        clearTimeout(shoppingListTimer);
    }
    var timeMS = 666;
    var paramType = typeof delayTime;
    if (paramType == 'number') {
        timeMS = delayTime;
    }
    shoppingListTimer = setTimeout('slideShoppingListTool();', timeMS);
}

function slideShoppingListToolCompleted() {
    if (shoppingListSlideState == 'out') {
        if (Browser.Engine.trident) {
            var closeButton = new Element('a', {'id': 'shoppingListToolHandleLink_close', 'href': '#', 'html': '<img src="' + baseUrl + '/assets/images/core/shopping_list_tab_close_ie.gif" border="0" alt="Close Shopping List" id="shoppingListToolHandleLink_close_img" />'});
        }
        else {
            var closeButton = new Element('a', {'id': 'shoppingListToolHandleLink_close', 'href': '#', 'html': '<img src="' + baseUrl + '/assets/images/core/shopping_list_tab_close.png" border="0" alt="Close Shopping List" id="shoppingListToolHandleLink_close_img" />'});
        }
        closeButton.replaces($('shoppingListToolHandleLink_open'));
        shoppingListSlideState = 'in';
    } else {
        bringShoppingListToolToBack();
        if (Browser.Engine.trident) {
            var openButton = new Element('a', { 'id': 'shoppingListToolHandleLink_open', 'href': '#', 'html': '<img src="' + baseUrl + '/assets/images/core/shopping_list_tab_ie.gif" border="0" alt="Open Shopping List" id="shoppingListToolHandleLink_open_img" />'});
        }
        else {
            var openButton = new Element('a', { 'id': 'shoppingListToolHandleLink_open', 'href': '#', 'html': '<img src="' + baseUrl + '/assets/images/core/shopping_list_tab.png" border="0" alt="Open Shopping List" id="shoppingListToolHandleLink_open_img" />'});
        }
        openButton.replaces($('shoppingListToolHandleLink_close'));
        shoppingListSlideState = 'out';
    }
}

function bringShoppingListToolToBack() {
    if (Browser.Engine.trident) {
        $('shoppingListToolWrapper').setStyle('filter', "none");
        $('shoppingListToolWrapper').setStyle('background-image', 'none');
    } else {
        $('shoppingListToolWrapper').setStyle('background', 'none');
    }
    $('shoppingListToolWrapper').setStyle('z-index', '5');
}
function bringShoppingListToolToFront() {
    if (Browser.Engine.trident) {
        //$('shoppingListToolWrapper').setStyles({
        //    'background-image': 'none',
        //    'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + baseUrl + "/assets/images/core/shopping_list_bkg.png', sizingMethod='crop')"
        //});
        $('shoppingListToolWrapper').setStyle('background', 'transparent url(' + baseUrl + '/assets/images/core/shopping_list_bkg_ie.gif) no-repeat scroll right center');
    } else {
        $('shoppingListToolWrapper').setStyle('background', 'transparent url(' + baseUrl + '/assets/images/core/shopping_list_bkg.png) no-repeat scroll right center');
    }
    $('shoppingListToolWrapper').setStyle('z-index', '20');
}

function action( controller, action, params, onCompleteFunction ) {
    var url = baseUrl + "/" + controller + "/" + action + "/format/json";
    var request = new Request.JSON({
        url: url,
        onComplete: onCompleteFunction
    }).post(params);
}

function locateStoreCompleted(response) {
    alert("action completed!");
}

function spreadLoaded(spreadno) {
    var leftPageNo = spreadno * 2;
    return pageCreated(leftPageNo);
}

function nextSpread() {
    var oldSpread = spread;
    if (spread < (lastSpread + insertLastSpread)) {
        spread++;
        var leftPageNo = spread * 2;
        var rightPageNo = (spread * 2) + 1;
        //Google Analytics - send trackPageView
        if (pageTracker) {
            pageTracker._trackPageview('/catalogue/' + catalogue_id + '/page/' + leftPageNo + '-' + rightPageNo);
        }
        //Increment backend Spread View count
        action('catalogue', 'increment-spread-view', {'spread': spread}, function(response) {});
        if (leftPageNo > 0) {
            $('leftPageNumber').set('html', leftPageNo);
        } else {
            $('leftPageNumber').set('html', '');
        }
        if ((lastSpread + insertLastSpread) != 0 && lastSpread != '' && rightPageNo != (((lastSpread + insertLastSpread) * 2) + 1)) {
            $('rightPageNumber').set('html', rightPageNo);
            $('totalPageNumber').set('html', '/ ' + ((lastSpread + insertLastSpread) * 2));
        } else {
            $('rightPageNumber').set('html', '');
        }
        if (spread+1 <= (lastSpread + insertLastSpread)) {
            var newLeftPageNo = ((spread+1) * 2);
            var newRightPageNo = ((spread+1) * 2) + 1;
            if (!$('carouselItem_' + newLeftPageNo) && !$('carouselItem_' + newRightPageNo)) {

                // Build new cached left page
                createPage(newLeftPageNo);

                // Build new cached right page
                createPage(newRightPageNo);

                totalSpreadsLoaded += 2;
                $('carousel').setStyle('width', ($('carousel').getStyle('width').toInt() + spreadWidth) + 'px');
            }
        }
    }
    var firstLoadedSpread = 0;
    for (var i = 0; i < (lastSpread + insertLastSpread); i++) {
        if (spreadLoaded(i)) {
            firstLoadedSpread = i;
            break;
        }
    }
    carouselFx.start("left", ((oldSpread - firstLoadedSpread) * spreadWidth * -1) + 'px', ((spread - firstLoadedSpread) * spreadWidth * -1) + 'px');
    return false;
}

function jumpSpread() {
    spread++;
    var leftPageNo = spread * 2;
    var rightPageNo = (spread * 2) + 1;
    if (leftPageNo > 0) {
        $('leftPageNumber').set('html', leftPageNo);
    } else {
        $('leftPageNumber').set('html', '');
    }
    if ((lastSpread + insertLastSpread) != 0 && lastSpread != '' && rightPageNo != (((lastSpread + insertLastSpread) * 2) + 1)) {
        $('rightPageNumber').set('html', rightPageNo);
        $('totalPageNumber').set('html', '/ ' + ((lastSpread + insertLastSpread) * 2));
    } else {
        $('rightPageNumber').set('html', '');
    }
    if (spread-1 == 0) {
        $('prevLink').addEvent("click", prevSpread);
        $("prevNavButton").addEvent("click", prevSpread);
    }
    if (spread == lastSpread) {
        $('nextLink').removeEvent("click", nextSpread);
        $("nextNavButton").removeEvent("click", nextSpread);
    } else {
        var newLeftPageNo = ((spread+1) * 2);
        var newRightPageNo = ((spread+1) * 2) + 1;
        if (!$('carouselItem_' + newLeftPageNo) && !$('carouselItem_' + newRightPageNo)) {

            // Build new cached left page
            createPage(newLeftPageNo);

            // Build new cached right page
            createPage(newRightPageNo);

            totalSpreadsLoaded += 2;
            $('carousel').setStyle('width', ($('carousel').getStyle('width').toInt() + spreadWidth) + 'px');
        }
    }
    var firstLoadedSpread = 0;
    for (var i = 0; i < lastSpread; i++) {
        if (spreadLoaded(i)) {
            firstLoadedSpread = i;
            break;
        }
    }
    carouselFx.start("left", (((spread - 1) - firstLoadedSpread) * spreadWidth * -1) + 'px', ((spread - firstLoadedSpread) * spreadWidth * -1) + 'px');
    return false;
}


function pageCreated(page) {
    if ($('carouselItem_' + page)) {
        return true;
    }
    return false;
}

function createPage(page, inject) {
    if (!pageCreated(page)) {
        var newPage = new Element('div', {
            'class': 'carouselItem',
            'id': 'carouselItem_' + page
        });
        if (inject) {
            newPage.inject($('carousel'), 'top');
        } else {
            $('carousel').adopt(newPage);
        }
    }
    fillPage(page);
}

function pageFilled(page) {
    if ($('carouselItem_' + page).get('html') != '') {
        return true;
    }
    return false;
}

function fillPage(page) {
    if (!pageFilled(page)) {
        action('catalogue', 'page', {
            'page': page
        }, function(response) {
            $('carouselItem_' + page).set('html', response.pageContent);
            if (lastSpread != response.lastSpread) {
                lastSpread = response.lastSpread;
                setupCataloguePages();
            }
            TB_init();
            initTips();
        });
    }
}

function initTips() {
    //clear any stuck tips
    productTips = new Tips($$('.productTips'), {
        'className': 'tooltips',
        'onShow': function(tip) {
            tip.fade('hide');
            tip.fade(0.8);
        },
        'onHide': function(tip) {
            tip.fade(0);
        }
    });
}

function resetCataloguePages() {
    if ($('carousel')) {
        $('carousel').empty();
    }
}

function prevSpread() {
    var oldSpread = spread;
    if (spread > 0) {
        spread--;
        var leftPageNo = spread * 2;
        var rightPageNo = (spread * 2) + 1;
        //Google Analytics - send trackPageView
        if (pageTracker) {
            pageTracker._trackPageview('/catalogue/' + catalogue_id + '/page/' + leftPageNo + '-' + rightPageNo);
        }
        //Increment backend Spread View count
        action('catalogue', 'increment-spread-view', {'spread': spread}, function(response) {});
        if (leftPageNo > 0) {
            $('leftPageNumber').set('html', leftPageNo);
        } else {
            $('leftPageNumber').set('html', '');
        }
        if ((lastSpread + insertLastSpread) != 0 && lastSpread != '' && rightPageNo != (((lastSpread + insertLastSpread) * 2) + 1)) {
            $('rightPageNumber').set('html', rightPageNo);
            $('totalPageNumber').set('html', '/ ' + ((lastSpread + insertLastSpread) * 2));
        } else {
            $('rightPageNumber').set('html', '');
        }
        if (spread-1 >= 0) {
            var newLeftPageNo = ((spread-1) * 2);
            var newRightPageNo = ((spread-1) * 2) + 1;
            if (!$('carouselItem_' + newLeftPageNo) && !$('carouselItem_' + newRightPageNo)) {
                var inject = true;
                // Build new cached right page
                createPage(newRightPageNo, inject);

                // Build new cached left page
                createPage(newLeftPageNo, inject);

                totalSpreadsLoaded += 2;
                $('carousel').setStyle('width', ($('carousel').getStyle('width').toInt() + spreadWidth) + 'px');
            }
        }
    }
    var firstLoadedSpread = 0;
    for (var i = 0; i < (lastSpread + insertLastSpread); i++) {
        if (spreadLoaded(i)) {
            firstLoadedSpread = i;
            break;
        }
    }
    carouselFx.start("left", ((oldSpread - firstLoadedSpread) * spreadWidth * -1) + 'px', ((spread - firstLoadedSpread) * spreadWidth * -1) + 'px');
    return false;
}

function addItemToShoppingList(product_id, product_name) {
    if (pageTracker) {
        pageTracker._trackPageview('/shopping-list/add/product/' + product_id + ' - ' + product_name);
        pageTracker._trackPageview('/' + catalogue_id + '/shopping-list/add/product/' + product_id + ' - ' + product_name);
    }
    action('shopping-list', 'add-item', {
        'product_id': product_id
    }, function(response) {
        $('shoppingListToolContent').set('html', response.contentHTML);
                if (response.subtotal != '$0.00' && response.subtotal != '$ 0.00') {
                    $('shoppingListTotalSpan').set('html', response.subtotal);
                } else {
                    if (response.contentHTML == '') {
                        $('shoppingListTotalSpan').set('html', '$ 0.00');
                    } else {
                        $('shoppingListTotalSpan').set('html', 'See in store*');
                    }
                }
        if (response.discountTotal != undefined) {
            $('shoppingListDiscountSpan').set('html', response.discountTotal);
        }
                if (response.grandTotal != '$0.00' && response.grandTotal != '$ 0.00') {
                    $('shoppingListGrandTotalSpan').set('html', response.grandTotal);
                } else {
                    if (response.contentHTML == '') {
                        $('shoppingListGrandTotalSpan').set('html', '$ 0.00');
                    } else {
                        $('shoppingListGrandTotalSpan').set('html', 'See in store*');
                    }
                }
                if (response.miscMessage != '') {
                    if (!$('miscMessage')) {
                        var miscMessageElt = new Element('div', {'id': 'miscMessage', 'class': 'miscMessage'});
                        miscMessageElt.injectAfter('shoppingListGrandTotalSpan');
                        $('miscMessage').set('html', response.miscMessage);
                    }
                    $('miscMessage').set('html', response.miscMessage);
                } else {
                    if ($('miscMessage')) {
                        $('miscMessage').dispose();
                    }
                }
        slideShoppingListTool('in');
        TB_remove();
        delayedSlideShoppingListTool(666);
    });
}

function removeItemFromShoppingList(product_id) {
    if (confirm('Are you sure you want to remove this product from the shopping list?')) {
        action('shopping-list', 'remove-item', {
            'product_id': product_id
        }, function(response) {
            $('shoppingListToolContent').set('html', response.contentHTML);
                        if (response.subtotal != '$0.00' && response.subtotal != '$ 0.00') {
                            $('shoppingListTotalSpan').set('html', response.subtotal);
                        } else {
                            if (response.contentHTML == '') {
                                $('shoppingListTotalSpan').set('html', '$ 0.00');
                            } else {
                                $('shoppingListTotalSpan').set('html', 'See in store*');
                            }
                        }
            if (response.discountTotal != undefined) {
                $('shoppingListDiscountSpan').set('html', response.discountTotal);
            }
                        if (response.grandTotal != '$0.00' && response.grandTotal != '$ 0.00') {
                            $('shoppingListGrandTotalSpan').set('html', response.grandTotal);
                        } else {
                            if (response.contentHTML == '') {
                                $('shoppingListGrandTotalSpan').set('html', '$ 0.00');
                            } else {
                                $('shoppingListGrandTotalSpan').set('html', 'See in store*');
                            }
                        }
                        if (response.miscMessage != '') {
                            if (!$('miscMessage')) {
                                var miscMessageElt = new Element('div', {'id': 'miscMessage', 'class': 'miscMessage'});
                                miscMessageElt.injectAfter('shoppingListGrandTotalSpan');
                                $('miscMessage').set('html', response.miscMessage);
                            }
                            $('miscMessage').set('html', response.miscMessage);
                        } else {
                            if ($('miscMessage')) {
                                $('miscMessage').dispose();
                            }
                        }
            TB_remove();
        });
    }
}

function allowNumbersOnly(element) {
    var re = /^[0-9]+$/;
    if (!re.test(element.value))    {
        element.value = element.value.replace(/[^0-9]/g,"");
    }
}

function updateQty(element, product_id) {
    if (updateQtyTimer != null) {
        clearTimeout(updateQtyTimer);
    }
    if (element.value != '') {
        updateQtyTimer = setTimeout("updateItemQtyInShoppingList(" + product_id + ", " + element.value + ");", 500);
    }
}

function updateItemQtyInShoppingList(product_id, qty) {
    if (qty > 0 || (qty < 1 && confirm('Setting the quantity to 0 will remove the product from your shopping list. Are you sure you want to do this?'))) {
        if ($('item_' + product_id + '_qty')) {
            $('item_' + product_id + '_qty').blur();
        }
        action('shopping-list', 'update-item', {
            'product_id': product_id,
            'qty': qty
        }, function(response) {
            $('shoppingListToolContent').set('html', response.contentHTML);
            if ($('item_' + product_id + '_qty')) {
                $('item_' + product_id + '_qty').focus();
            }
                        if (response.subtotal != '$0.00' && response.subtotal != '$ 0.00') {
                            $('shoppingListTotalSpan').set('html', response.subtotal);
                        } else {
                            if (response.contentHTML == '') {
                                $('shoppingListTotalSpan').set('html', '$ 0.00');
                            } else {
                                $('shoppingListTotalSpan').set('html', 'See in store*');
                            }
                        }
            if (response.discountTotal != undefined) {
                $('shoppingListDiscountSpan').set('html', response.discountTotal);
            }
                        if (response.grandTotal != '$0.00' && response.grandTotal != '$ 0.00') {
                            $('shoppingListGrandTotalSpan').set('html', response.grandTotal);
                        } else {
                            if (response.contentHTML == '') {
                                $('shoppingListGrandTotalSpan').set('html', '$ 0.00');
                            } else {
                                $('shoppingListGrandTotalSpan').set('html', 'See in store*');
                            }
                        }
            TB_remove();
        });
    } else {
        if ($('item_' + product_id + '_qty')) {
            $('item_' + product_id + '_qty').blur();
        }
        updateShoppingList();
    }
}

function popSendToFriend() {
    TB_show('Send To a Friend', baseUrl + '/shopping-list/send-to-friend?TB_JSON=true&height=260&width=370', false, false);
}

function popPrintableShoppingList() {
    var printableShoppingList = window.open(baseUrl + '/shopping-list/printable-list/', 'name', 'height=850,width=600');
    if (window.focus) {
        printableShoppingList.focus();
    }
    return false;
}

function popTermsAndConditions() {
    window.open(baseUrl + '/index/terms/', 'name', 'height=700,width=600,scrollbars=1');
}


function sendShoppingList() {
    //TODO validation
    if ($('sender_name') && $('sender_name').value != ''
     && $('sender_email') && $('sender_email').value != ''
     && $('friend_name') && $('friend_name').value != ''
     && $('friend_email') && $('friend_email').value != ''
    ) {
        $('sendToFriendLoadingIcon').setStyle('display', 'inline');
        action('shopping-list', 'send-list', {
            'sender_name': $('sender_name').value,
            'sender_email': $('sender_email').value,
            'friend_name': $('friend_name').value,
            'friend_email': $('friend_email').value,
            'message': $('message').value
        }, function(response) {
            $('sendToFriendContainer').setStyle('display', 'none');
            $('sentToFriendContainer').setStyle('display', 'block');
            if (pageTracker) {
                pageTracker._trackPageview('/shopping-list/send/store/' + store_postcode + '/' + store_id + '/' + store_name + ', ' + store_city);
                pageTracker._trackPageview('/' + catalogue_id + '/shopping-list/send/store/' + store_postcode + '/' + store_id + '/' + store_name + ', ' + store_city);
                pageTracker_ecommerce._trackPageview('/' + catalogue_id + '/shopping-list/send/store/' + store_postcode + '/' + store_id + '/' + store_name + ', ' + store_city);
                pageTracker_ecommerce._addTrans(
                    response.order_id,            // Order ID - Session ID
                    response.affiliation,        // Affiliation - Store ID
                    response.total,                // Total - Shopping List Grand Total
                    response.tax,                // Tax - -
                    response.shipping,            // Shipping - -
                    response.city,                // City - Postcode searched (or if not logged, Store's postcode)
                    response.state,                // State - State of store
                    response.country            // Country - -
                );
                for (var item in response.shoppingList) {
                    pageTracker_ecommerce._addItem(
                        response.order_id,                    // Order ID - Session ID
                        item,                                // SKU/Code - Product ID
                        response.shoppingList[item].name,    // Product Name
                        'Catalogue',                        // Category - Catalogue
                        response.shoppingList[item].price,    // Item Price
                        response.shoppingList[item].qty        // Item Quantity
                    );
                }
                pageTracker_ecommerce._trackTrans();
            }
        });
    }
}

function selectSuburb(postcode) {
    TB_show('<img src="' + baseUrl + '/assets/images/core/store_locator_search_results.gif" border="0" style="border: none !important; margin: 0 !important;" alt="Mitre 10 Store Locator Search Results" />', baseUrl + '/store/locate?searchTerm=' + postcode + '&TB_JSON=true&height=740&width=570', false, true);
}

function productZoomView(product_id, catalogue_id) {
        var cid;
        if (catalogue_id != undefined) {
            cid = '&cid=' + catalogue_id;
        } else {
            cid = '';
        }
    TB_show(catalogue_title, baseUrl + '/product/details?id=' + product_id + cid + '&TB_JSON=true&height=475&width=550', false);
}

function loadProductImage(product_id) {
    if ($('productImage')) {
        action('product', 'image', {
            'id': product_id
        }, function(response) {
            if ($('productImage')) {
                $('productImage').set('html', response.htmlContent);
            }
        }
        );
    }
}

function scrollImage( direction )
{
    var current_image_id, image_number;
    $$('img.product_image_list').each( function( element ) {
        if( element.getStyle('display') == "block" )
        {
            current_image_id = element.getAttribute('id');
            //console.log( current_image_id );
            image_number = parseInt( current_image_id.replace( "product_image_", "" ) ) + direction;
            //console.log( 'New image' + image_number );
        }
    });
    if( $('product_image_'+image_number) )
    {
        $(current_image_id).setStyle('display', 'none');
        $('product_image_'+image_number).setStyle('display','block');
    }
}
//*/

