﻿$(function() {
    //detect if home page - if it is then lower menu bar and show background image
    if (window.location.pathname == "/") {
        $('#menu-container').css('margin-top', '20px');
        $('#menu-bar').css('margin-top', '190px');
        $('#background').fadeIn(1000);
        $('.dropdown-container').css('top', '233px');
    }

    //initialize Latest News Popup
    initLatestNewsPopup();

    //hide Live Chat text
    $('.lpPoweredByDiv').hide();
    $('.lpEmtStarRating').hide();

    //detect if on either Bikes or Goods category page, then highlight nav bar accordingly
    var pageType = $.trim($('#pageType').attr("value")); //'bikes' or 'goods'
    if (pageType == 'bike') {
        $('#bikes-link a').css('color', 'red');
        $('.page_item').not('#bikes-menu-item').removeClass('selected-page');
        $('#bikes-menu-item').addClass('selected-page');
    } else if (pageType == 'goods') {
        $('#goods-link a').css('color', 'red');
        $('.page_item').not('#goods-menu-item').removeClass('selected-page');
        $('#goods-menu-item').addClass('selected-page');
    }

    //event handlers for main menu dropdowns
    $('#bikes-menu-item').hover(
        function() {
            $('#bikes-menu-item span').css('background-color', '#FFFFFF');
            $('#bikes-link a').css('color', 'red');
            $('#bikes-menu-container').stop(true, true).slideDown('fast');
        },
        function() {
            $('#bikes-menu-item span').css('background-color', '#000000');
            $('#bikes-menu-container').stop(true, true).slideUp('fast');

            var selected = $(this).hasClass('selected-page');
            if (!selected) {
                $('#bikes-link a').css('color', '#FFFFFF');
            }
        }
    );

    $('#custom-menu-item').hover(
        function() {
            $('#custom-menu-item span').css('background-color', '#FFFFFF');
            $('#custom-link a').css('color', 'red');
            $('#custom-menu-container').stop(true, true).slideDown('fast');
        },
        function() {
            $('#custom-menu-item span').css('background-color', '#000000');
            $('#custom-menu-container').stop(true, true).slideUp('fast');

            var selected = $(this).hasClass('selected-page');
            if (!selected) {
                $('#custom-link a').css('color', '#FFFFFF');
            }
        }
    );

    $('#goods-menu-item').hover(
        function() {
            $('#goods-menu-item span').css('background-color', '#FFFFFF');
            $('#goods-link a').css('color', 'red');
            $('#goods-menu-container').stop(true, true).slideDown('fast');
        },
        function() {
            $('#goods-menu-item span').css('background-color', '#000000');
            $('#goods-menu-container').stop(true, true).slideUp('fast');

            var selected = $(this).hasClass('selected-page');
            if (!selected) {
                $('#goods-link a').css('color', '#FFFFFF');
            }
        }
    );

    $('#company-menu-item').hover(
        function() {
            $('#company-menu-item span').css('background-color', '#FFFFFF');
            $('#company-link a').css('color', 'red');
            $('#company-menu-container').stop(true, true).slideDown('fast');
        },
        function() {
            $('#company-menu-item span').css('background-color', '#000000');
            $('#company-menu-container').stop(true, true).slideUp('fast');

            var selected = $(this).hasClass('selected-page');
            if (!selected) {
                $('#company-link a').css('color', '#FFFFFF');
            }
        }
    );

    $('#buzz-menu-item').hover(
        function() {
            $('#buzz-menu-item span').css('background-color', '#FFFFFF');
            $('#buzz-link a').css('color', 'red');
            $('#buzz-menu-container').stop(true, true).slideDown('fast');
        },
        function() {
            $('#buzz-menu-item span').css('background-color', '#000000');
            $('#buzz-menu-container').stop(true, true).slideUp('fast');

            var selected = $(this).hasClass('selected-page');
            if (!selected) {
                $('#buzz-link a').css('color', '#FFFFFF');
            }
        }
    );

    $('#support-menu-item').hover(
        function() {
            $('#support-menu-item span').css('background-color', '#FFFFFF');
            $('#support-link a').css('color', 'red');
            $('#support-menu-container').stop(true, true).slideDown('fast');
        },
        function() {
            $('#support-menu-item span').css('background-color', '#000000');
            $('#support-menu-container').stop(true, true).slideUp('fast');

            var selected = $(this).hasClass('selected-page');
            if (!selected) {
                $('#support-link a').css('color', '#FFFFFF');
            }
        }
    );


    //initialize product menus
    $('.category-link').css('font-weight', 'bold');
    $('.btn-Mountain').addClass('expanded');
    $('.btn-Cyclocross').addClass('expanded');
    $('.btn-Urban').addClass('expanded');
    $('#shopp .btn-Mountain').show();
    $('.btn-Single').addClass('expanded');
    $('div.Braking ul.products').hide();
    $('div.Clothing ul.products').hide();
    var mountainProductListing = $('div.Mountain ul');
    var cyclocrossProductListing = $('div.Cyclocross ul');
    var urbanProductListing = $('div.Urban ul');
    var ssPartsProductListing = $('div.Single ul');
    var brakingPartsProductListing = $('div.Braking ul');
    var clothingProductListing = $('div.Clothing ul');
    $('.btn-product-desc').addClass('expanded');

    //event handlers for the left-hand nav product menus
    /*
    $('div.Mountain').bind('mouseover', function(event) {
    $('#shopp .btn-Mountain').show();
    });

    $('div.Mountain').bind('mouseout', function(event) {
    if (!$('#shopp .btn-Mountain').hasClass('expanded')) {
    $('#shopp .btn-Mountain').hide();
    }
    });
    */

    $('div.Mountain .category-link').bind('click', function(event) {
        $(mountainProductListing).slideToggle('slow');
        $('.btn-Mountain').toggleClass('expanded');
        $('#shopp .plus-minus-btn').show();
    });

    $('.btn-Mountain').bind('click', function(event) {
        $(mountainProductListing).slideToggle('slow');
        $(this).toggleClass('expanded');
        $('#shopp .plus-minus-btn').show();
    });

    /*
    $('div.Cyclocross').bind('mouseover', function(event) {
    $('.btn-Cyclocross').show();
    });

    $('div.Cyclocross').bind('mouseout', function(event) {
    if (!$('.btn-Cyclocross').hasClass('expanded')) {
    $('.btn-Cyclocross').hide();
    }
    });
    */


    $('div.Cyclocross .category-link').bind('click', function(event) {
        $(cyclocrossProductListing).slideToggle('slow');
        $('.btn-Cyclocross').toggleClass('expanded');
    });

    $('.btn-Cyclocross').bind('click', function(event) {
        $(cyclocrossProductListing).slideToggle('slow');
        $(this).toggleClass('expanded');
    });

    /*
    $('div.Urban').bind('mouseover', function(event) {
    $('.btn-Urban').show();
    });

    $('div.Urban').bind('mouseout', function(event) {
    if (!$('.btn-Urban').hasClass('expanded')) {
    $('.btn-Urban').hide();
    }
    });
    */

    $('div.Urban .category-link').bind('click', function(event) {
        $(urbanProductListing).slideToggle('slow');
        $('.btn-Urban').toggleClass('expanded');
    });

    $('.btn-Urban').bind('click', function(event) {
        $(urbanProductListing).slideToggle('slow');
        $(this).toggleClass('expanded');
    });

    /*
    $('div.Single').bind('mouseover', function(event) {
    $('#shopp .btn-Single').show();
    });

    $('div.Single').bind('mouseout', function(event) {
    if (!$('#shopp .btn-Single').hasClass('expanded')) {
    $('#shopp .btn-Single').hide();
    }
    });
    */

    $('div.Single .category-link').bind('click', function(event) {
        $(ssPartsProductListing).slideToggle('slow');
        $('.btn-Single').toggleClass('expanded');
    });

    $('.btn-Single').bind('click', function(event) {
        $(ssPartsProductListing).slideToggle('slow');
        $(this).toggleClass('expanded');
    });

    /*
    $('div.Braking').bind('mouseover', function(event) {
    $('.btn-Braking').show();
    });

    $('div.Braking').bind('mouseout', function(event) {
    if (!$('.btn-Braking').hasClass('expanded')) {
    $('.btn-Braking').hide();
    }
    });
    */

    $('div.Braking .category-link').bind('click', function(event) {
        $(brakingPartsProductListing).slideToggle('slow');
        $('.btn-Braking').toggleClass('expanded');
    });

    $('.btn-Braking').bind('click', function(event) {
        $(brakingPartsProductListing).slideToggle('slow');
        $(this).toggleClass('expanded');
    });

    /*
    $('div.Clothing').bind('mouseover', function(event) {
    $('.btn-Clothing').show();
    });

    $('div.Clothing').bind('mouseout', function(event) {
    if (!$('.btn-Clothing').hasClass('expanded')) {
    $('.btn-Clothing').hide();
    }
    });
    */

    $('div.Clothing .category-link').bind('click', function(event) {
        $(clothingProductListing).slideToggle('slow');
        $('.btn-Clothing').toggleClass('expanded');
    });

    $('.btn-Clothing').bind('click', function(event) {
        $(clothingProductListing).slideToggle('slow');
        $(this).toggleClass('expanded');
    });

    //event handlers for left-hand product listing links
    $('li.product a').bind('mouseover', function(event) {
        $('.default-product-image').hide();
        $('.product-image').hide();
        var pid = $(this).parent().parent().attr("id");
        $('.product-image').each(function(n) {
            if ($(this).attr('id') == pid) {
                $(this).show();
            }
        });
    });

    //event handlers for main nav
    $('#spot-logo img').bind('click', function(event) {
        window.location.href = '/';
    });

    //event handlers for the non-product left-hand nav menus
    /*
    $('.first-nav-item').bind('click', function(event) {
    $('.content-item').hide();
    $('.first-content-item').show();
    $('.nav-item').removeClass('selected');
    $('.first-nav-item').addClass('selected');
    });
    */

    $('li.product a').bind('mouseover', function(event) {
        var redDotContainer = $(this).parent().prev();
        $(redDotContainer).children().show();
    });

    $('li.product a').bind('mouseout', function(event) {
        var redDotContainer = $(this).parent().prev();
        $(redDotContainer).children().hide();
    });

    $('.first-nav-item a').bind('mouseover', function(event) {
        $('.first-red-dot').show();
    });

    $('.first-nav-item a').bind('mouseout', function(event) {
        $('.first-red-dot').hide();
    });

    /*
    $('.second-nav-item').bind('click', function(event) {
    $('.content-item').hide();
    $('.second-content-item').show();
    $('.nav-item').removeClass('selected');
    $('.second-nav-item').addClass('selected');
    });
    */

    $('.second-nav-item a').bind('mouseover', function(event) {
        $('.second-red-dot').show();
    });

    $('.second-nav-item a').bind('mouseout', function(event) {
        $('.second-red-dot').hide();
    });

    /*
    $('.third-nav-item').bind('click', function(event) {
    $('.content-item').hide();
    $('.third-content-item').show();
    $('.nav-item').removeClass('selected');
    $('.third-nav-item').addClass('selected');
    });
    */

    $('.third-nav-item a').bind('mouseover', function(event) {
        $('.third-red-dot').show();
    });

    $('.third-nav-item a').bind('mouseout', function(event) {
        $('.third-red-dot').hide();
    });

    /*
    $('.fourth-nav-item').bind('click', function(event) {
    $('.content-item').hide();
    $('.fourth-content-item').show();
    $('.nav-item').removeClass('selected');
    $('.fourth-nav-item').addClass('selected');
    });
    */

    $('.fourth-nav-item a').bind('mouseover', function(event) {
        $('.fourth-red-dot').show();
    });

    $('.fourth-nav-item a').bind('mouseout', function(event) {
        $('.fourth-red-dot').hide();
    });

    //initialize product page collapsable menus
    //$('div.product-desc-link a').bind('mouseover', function(event) {
    //$('#shopp .btn-product-desc').show();
    //});

    //$('div.product-desc-link a').bind('mouseout', function(event) {
    //if (!$('#shopp .btn-product-desc').hasClass('expanded')) {
    //$('#shopp .btn-product-desc').hide();
    //}
    //});

    $('div.product-desc-link a').bind('click', function(event) {
        $('.product-description').slideToggle('slow');
        $('.btn-product-desc').toggleClass('expanded');
        $('#shopp .plus-minus-btn').show();
    });

    $('div.product-features-link a').bind('mouseover', function(event) {
        $('#shopp .btn-product-features').show();
    });

    $('div.product-features-link a').bind('mouseout', function(event) {
        if (!$('#shopp .btn-product-features').hasClass('expanded')) {
            //$('#shopp .btn-product-features').hide();
        }
    });


    $('div.product-features-link a').bind('click', function(event) {
        $('.product-features').slideToggle('slow');
        $('.btn-product-features').toggleClass('expanded');
        $('#shopp .plus-minus-btn').show();
    });

    //$('div.product-geometry-link a, .btn-product-geometry').bind('mouseover', function(event) {
    //$('#shopp .btn-product-geometry').show();
    //});

    //$('div.product-geometry-link a, .btn-product-geometry').bind('mouseout', function(event) {
    //$('#shopp .btn-product-geometry').hide();
    //});


    //Safari CSS fix for Add to Cart label alignment
    if ($.browser.safari) {
        if (pageType == 'goods') {
            $('#add-to-cart-container').css('margin-top', '10px');
            $('#add-to-cart-container').css('margin-right', '-130px');
        }
    }

    //geometry and component specs lightbox
    var closeButtonMarkup = '<div id="close-btn" style="float: right;"><a class="close" href="#" onclick="javascript:closeModal();return false;"><img class="close_image" title="close" src="/wp-content/plugins/wp-facebox-gallery/images/x_close.png"/></a></div>';
    $('.wp-table-reloaded').before(closeButtonMarkup);
    $('.footer').remove();

    $('div.product-geometry-link a').bind('click', function(event) {
        showModalOverlay();
        $('#geometry-spec-table').fadeIn(300);
        $('#geometry-spec-table').addClass('open');
    });

    $('div.product-component-specs-link a').bind('click', function(event) {
        showModalOverlay();
        $('#component-spec-table').fadeIn(300);
        $('#component-spec-table').addClass('open');
    });

    /*
    $('#close-btn').bind('click', function(event) {
    //showModalOverlay();
    if ($('#geometry-spec-table').hasClass('open')) {
    alert("hi 1");
    $('#geometry-spec-table').fadeOut(300);
    $('#geometry-spec-table').removeClass('open');
    //} else if ($('#component-spec-table').hasClass('open')) {
    } else {
    alert("hi 2");
    $('#component-spec-table').fadeOut(300);
    $('#component-spec-table').removeClass('open');
    }
    //closeGeometryModal();
    $('.modalOverLay').animate({ opacity: '0.0' }, 500);
    $('.modalOverLay').remove();

    });
    */

    /*
    $('div.product-component-specs-link a').bind('click', function(event) {
    var modalTop = $('#facebox').css('top');
    pxIdx = modalTop.indexOf('px');
    modalTop = modalTop.substring(0, pxIdx);
    modalTop = modalTop - 100;
    $('#facebox').css('top', modalTop + 'px');
    showModalOverlay();
    });
    */



    //Reorder the list of products according to product id (oldest to newest)
    //this is a work-around for a sorting bug with shopp using the qsort jquery plug-in
    //qsort: http://niteshandbhavya.110mb.com/qsort/
    $('.Mountain li').qsort({ attr: "id", digits: true });
    $('.Cyclocross li').qsort({ attr: "id", digits: true });
    $('.Urban li').qsort({ attr: "id", digits: true });

    //initialize pages that have posts with inline images like Heritage and Latest News
    //It is necessary to make it easy for Latest News posts with no html required in the admin
    //this moves the img element into the right place in the template...
    $('.content-inline-photo-container:has(img)').each(function(n) {
        var imageElement = $(this).find('img');
        var imageTargetElement = $(this).next();
        $(imageElement).appendTo(imageTargetElement);
        $(this).css('float', 'left');
    });

    $('#image-gallery-image, #image-gallery-text').hover(
        function() {
            $('#image-gallery-text').css('font-weight', 'bold');
            $('#image-gallery-text').css('color', 'red');
            $('#image-gallery-image').css('background-position', '0px -20px');
        },
        function() {
            $('#image-gallery-text').css('font-weight', 'normal');
            $('#image-gallery-text').css('color', '#666666');
            $('#image-gallery-image').css('background-position', '0px 0px');
        }
    );

    //product page initialization
    var pageType = $.trim($('#pageType').attr("value")); //'bikes' or 'goods'

    if (pageType == 'bike') {
        //highlight BIKES nav item
        $('#bikes-link a').css('color', 'red');
        $('.page_item').not('#bikes-menu-item').removeClass('selected-page');
        $('#bikes-menu-item').addClass('selected-page');

        var firstSelectBox;
        var secondSelectBox;
        var thirdSelectBox;
        $('.product-variations select').each(function(n) {
            if (n == 0) {
                firstSelectBox = $(this); // colors
            } else if (n == 1) {
                secondSelectBox = $(this); // sizes
            } else if (n == 2) {
                thirdSelectBox = $(this); // complete bike /frame only
            }
        });

        //insert dropdown labels
        $('<div class="product-colors-heading align-right">COLORS</div>').insertBefore(firstSelectBox);
        $('<div class="product-sizes-heading align-right">SIZES</div>').insertBefore(secondSelectBox);
        $('<div class="product-frameonly-heading align-right">BIKE FORMAT</div>').insertBefore(thirdSelectBox);

        $(secondSelectBox).css('width', '66px');
        $(thirdSelectBox).css('width', '180px');

        //add onchange events to product drop-downs.
        //this is necessary for swapping out product photos based on product variation selection.
        //Currrently in Shopp you cannot associate a specific image to a specific product variation
        //so this is a work around. requires special naming scheme of the image alt (see wp admin) tag to work.
        $(firstSelectBox).bind('change', function(event) { loadProductImage(); });
        $(thirdSelectBox).bind('change', function(event) { loadProductImage(); });

        initNextPreviousProductNavigation();

        buildGallery();

    } else if (pageType == 'goods') {
        //highlight GOODS nav item
        //$('.page-item a').css('color', '#000000');
        //$('.page-item-12 a').css('color', '#FF1E21');

        $('#goods-link a').css('color', 'red');
        $('.page_item').not('#goods-menu-item').removeClass('selected-page');
        $('#goods-menu-item').addClass('selected-page');

        var firstSelectBox;
        var secondSelectBox;
        $('.product-variations select').each(function(n) {
            if (n == 0) {
                firstSelectBox = $(this); // sizes
            } else if (n == 1) {
                secondSelectBox = $(this); // ????
            }
        });

        initNextPreviousProductNavigation();

        //insert dropdown labels
        //$('<span class="product-colors-heading align-right">SIZE</span>').insertBefore(firstSelectBox);
        //$('<span class="product-sizes-heading align-right">????</span>').insertBefore(secondSelectBox);

        //$(firstSelectBox).css('width', '60px');
        //$(secondSelectBox).css('width', '170px');

        //$('#add-to-cart').css('clear', 'right').css('margin-left', '454px');
        //$('#add-to-cart').css('clear', 'right');

        //add onchange events to product drop-downs.
        //this is necessary for swapping out product photos based on product variation selection.
        //Currrently in Shopp you cannot associate a specific image to a specific product variation
        //so this is a work around. requires special naming scheme of the image alt (see wp admin) tag to work.
        $(firstSelectBox).bind('change', function(event) { loadProductImage(); });
        $(secondSelectBox).bind('change', function(event) { loadProductImage(); });
    }

    //load default product image
    loadProductImage();

    //Re-skin dropdowns on product page
    //$('select').select_skin();


    function loadProductImage() {
        var pageType = $.trim($('#pageType').attr("value")); //'bikes' or 'goods'

        if (pageType == 'bike') {
            var imageFound = false;
            //work-around for strange IE behavior and the complete bike dropdown
            //strip out excessive whitespace between text and price
            //split string in two, trim and reassemble
            if ($.browser.msie) {
                $(thirdSelectBox).each(function(n) {
                    var x = $(this).html();
                    var idx = x.indexOf("($");
                    var str1 = x.substring(0, idx);
                    str1 = jQuery.trim(str1);
                    var str2 = x.substr(idx);
                    str2 = jQuery.trim(str2);
                    var newString = str1 + " " + str2;
                    $(this).html(newString);
                    //$(this).css('color', '#000000');
                });
            }

            if ($('.product-name-heading').html() != null) {
                var productName = $('.product-name-heading').html().replace(/ /g, "_").toLowerCase();
            }
            var colorSelected = $(firstSelectBox).find(':selected').text().replace(/ /g, "_").toLowerCase();
            var completeBikeSelectedIndexValue = $(thirdSelectBox).attr("selectedIndex");
            var bikeFormat;
            if (completeBikeSelectedIndexValue == 0) {
                bikeFormat = "complete_bike";
            } else {
                bikeFormat = "frame_only";
            }

            productVariationName = productName + '-' + colorSelected + '-' + bikeFormat;

            //show the correct image based on productVariationName
            $('#product-photo-area img').each(function(n) {
                $(this).hide();
                $('#no-image').hide();
                if (this.alt == productVariationName) {
                    $(this).show();
                    $('#no-image').hide();
                    imageFound = true;
                }
            });

            //if no matches with productVariationName, show error message in the product image area
            if (!imageFound) {
                $('<div id="no-image"><div id="no-image-text">Currently no images available for this bike/color combination.</div></div>').insertAfter('#product-photo-area');
            }

        } else if (pageType == 'goods') {
            var imageFound = false;
            if ($('.product-name-heading').html() != null) {
                var productName = $('.product-name-heading').html().replace(/ /g, "_").toLowerCase();
            }

            // strip out $ price and replace spaces with underscores
            var partVariation = $(firstSelectBox).find(':selected').text();
            var dollarIdx = partVariation.indexOf('($');
            partVariation = partVariation.substring(0, dollarIdx);
            partVariation = jQuery.trim(partVariation);
            partVariation = partVariation.replace(/ /g, "_").toLowerCase();

            productVariationName = productName + '-' + partVariation;

            //show the correct image based on productVariationName
            $('#product-photo-area img').each(function(n) {
                $(this).hide();
                $('#no-image').hide();
                if (this.alt == productVariationName) {
                    $(this).show();
                    $('#no-image').hide();
                    imageFound = true;
                }
            });

        }
    }

    //event handelr for contact us slide down
    $('#contact-us-container a').bind('click', function(event) {
        $('#contact-subheading').slideToggle('fast');
    });

    $('#bike-link a').bind('mouseover', function(event) {
        $('.more-details-red-dot').addClass('hovered');
    });

    $('#bike-link a').bind('mouseout', function(event) {
        $('.more-details-red-dot').removeClass('hovered');
    });

    //populate dropdowns for Custom page using Related Selects plugin    
    /*
    $('#example-1').relatedSelects({
    onChangeLoad: 'datasupplier.php',
    defaultOptionText: 'Choose an Option',
    selects: {
    'stateID': { loadingMessage: 'Loading Counties...' },
    'countyID': { loadingMessage: 'Loading Towns...' },
    'townID': { loadingMessage: 'Loading Villages...' },
    'villageID': {}
    }
    });
    */

});

function positionLatestNewsPopup() {
    $("#latest-news-popup").css({
        position: "absolute", top: ($(window).scrollTop() + $(window).height() - $("#latest-news-popup").height()) + "px"
    });
    $('#latest-news-popup').css({
        left: ($(window).width() - $('#latest-news-popup').width()) / 2
    });
    $("#latest-news-popup").show();
}

function initLatestNewsPopup() {

    if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1)) {
        //temporary fix to hide the Latest News popup for iPad, iPhone and iPod devices due to javascript bug
        $('#latest-news-popup').hide();
    } else {
        //store site cookie to check if the user has already visited at least once
        //if not highlight the latest news otherwise don't
        //document.cookie = "spotbikes=visited"
        var latestNewsTitle = $('#latest-news-popup-heading').text();
        latestNewsTitle = jQuery.trim(latestNewsTitle)
        latestNewsTitle = latestNewsTitle.replace(/ /g, "_");

        if ((get_cookie('spotbikes') == '') || (get_cookie('spotbikes') != latestNewsTitle)) {
            //no cookie stored - or they have not seen the latest news
            var cookieString = "spotbikes=" + latestNewsTitle;
            var date = new Date();
            //first value below is number of days the cookie would expire - 100 in this case
            date.setTime(date.getTime() + (100 * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
            document.cookie = cookieString + expires + "; path=/";

            var newsImageElement = $('#latest-news-popup-copy img');
            var targetImageElement = $('#latest-news-popup-image')
            $(newsImageElement).appendTo(targetImageElement);

            var fullNewsText = $('#latest-news-popup-copy:first').text();
            var trimmedNewsText = jQuery.trim(fullNewsText);
            var truncatedNewsText = trimmedNewsText.substring(0, 140);
            $('#latest-news-popup-copy:first').text(truncatedNewsText + '...');

            if ($('#latest-news-popup-image img').size() != 0) {
                //image found
                $('#latest-news-popup-copy').css('width', '250px');
            } else {
                //no image with news item
                $('#latest-news-popup-copy').css('width', '390px');
            }
            
            //trigger latest news popup
            toggleLatestNews();
        } else {
            var fullNewsText = $('#latest-news-popup-copy:first').text();
            var trimmedNewsText = jQuery.trim(fullNewsText);
            var truncatedNewsText = trimmedNewsText.substring(0, 140);
            $('#latest-news-popup-copy:first').text(truncatedNewsText + '...');

            if ($('#latest-news-popup-image img').size() != 0) {
                //image found
                $('#latest-news-popup-copy').css('width', '250px');
            } else {
                //no image with news item
                $('#latest-news-popup-copy').css('width', '390px');
            }
        }

        $('#latest-news-uparrow, #latest-news-popup-close-button').bind('click', function(event) {
            toggleLatestNews();
        });

        positionLatestNewsPopup();
        $(window)
		        .scroll(positionLatestNewsPopup)
		        .resize(positionLatestNewsPopup)

    }

}

function toggleLatestNews() {
    if ($('#latest-news-popup-content').hasClass('open')) {
        //close latest news popup
        $("body").css("overflow", "auto");
        $('#latest-news-content-container').animate({ height: '44px' }, 500);
        $('#latest-news-popup-content').removeClass('open');
        $('.modalOverLay').animate({ opacity: '0.0' }, 500);
        $('.modalOverLay').remove();
    } else {
        //open latest news popup
        $("body").css("overflow", "hidden");
        $('#latest-news-content-container').animate({ height: '208px' }, 500);
        $('#latest-news-popup-content').addClass('open');

        //IE wants a percentage for height
        if ($.browser.msie) {
            documentHeight = '200%';
        } else {
            var documentHeight = $(document).height() + 130;
            documentHeight = documentHeight + 'px';
        }

        $(document.body).prepend('<div class="modalOverLay" style="opacity: 0.0; filter: alpha(opacity = 0); width: 100%; height:' + documentHeight + '; z-index:10; background-color: #000000; position: absolute; margin-top: -190px"></div>');
        $('.modalOverLay').animate({ opacity: '0.5' }, 500);
        $('.modalOverLay').bind('click', function(event) {
            toggleLatestNews();
        });
    }
}


//Get cookie
function get_cookie(Name) {
    var search = Name + "="
    var returnvalue = "";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search)
        // if cookie exists
        if (offset != -1) {
            offset += search.length
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) end = document.cookie.length;
            returnvalue = unescape(document.cookie.substring(offset, end))
        }
    }
    return returnvalue;
}

function showModalOverlay() {
    var documentHeight = $(document).height();
    //documentHeight = documentHeight + 90 + 'px';
    documentHeight = documentHeight + 60 + 'px';
    var strDiv1 = '<div class="modalOverLay" style="opacity: 0.0; filter: alpha(opacity = 0); width: 100%; height:';
    var strDiv2 = '; z-index:30; background-color: #000000; position: absolute; margin-top: -90px"></div>';
    $(document.body).prepend(strDiv1 + documentHeight + strDiv2);
    $('.modalOverLay').animate({ opacity: '0.5' }, 500);
}

function closeModal() {
    if ($('#geometry-spec-table').hasClass('open')) {
        $('#geometry-spec-table').fadeOut(300);
        $('#geometry-spec-table').removeClass('open');
    } else {
        $('#component-spec-table').fadeOut(300);
        $('#component-spec-table').removeClass('open');
    }
    $('.modalOverLay').animate({ opacity: '0.0' }, 500);
    $('.modalOverLay').remove();
}

function getPageSection() {
    var qs = window.location.search;
    var splitResult = qs.split("=");
    var pageSection = splitResult[1];

    if (pageSection) {
        return pageSection;
    } else {
        return 1;
    }
}

function initNextPreviousProductNavigation() {
    //Next-Previous navigation initialization
    var firstProduct = false;
    var lastProduct = false;
    var currentProductName = $('.product-name-heading').text().toLowerCase();
    var productCount = $('#product-nav a').size();
    $('#product-nav a').each(function(n) {
        var nProductName = $(this).html().toLowerCase();
        if (currentProductName == nProductName) {
            if (n == 0) {
                firstProduct = true;
            } else if (n == (productCount - 1)) {
                lastProduct = true;
            }
            $(this).parent().addClass('current-product');
            return false;
        }
    });

    if (firstProduct) {
        $('#product-nav a:last').parent().addClass('prev');
        $('#product-nav li.current-product').next().addClass('next');
    } else if (lastProduct) {
        $('#product-nav li.current-product').prev().addClass('prev');
        $('#product-nav a:first').parent().addClass('next');
    } else {
        $('#product-nav li.current-product').prev().addClass('prev');
        $('#product-nav li.current-product').next().addClass('next');
    }

    if ($('.prev a').html() != null) {
        var previousProductText = $('.prev a').html().toUpperCase();
        var nextProductText = $('.next a').html().toUpperCase();
        $('#prev-text').html(previousProductText);
        $('#next-text').html(nextProductText);
    }
    var prevUrl = $('.prev a').attr('href');
    var nextUrl = $('.next a').attr('href');

    $('#prev-container').bind('click', function(event) {
        window.location.href = prevUrl;
    });

    $('#next-container').bind('click', function(event) {
        window.location.href = nextUrl;
    });

    $('#prev-container').bind('mouseover', function(event) {
        $('#left-arrow').css({ 'background-position': '0px -8px' });
        $('#left-arrow-text').css({ 'color': 'red', 'font-weight': 'bold' });
        $('#prev-text').css({ 'color': 'red', 'font-weight': 'bold' });

    });

    $('#prev-container').bind('mouseout', function(event) {
        $('#left-arrow').css({ 'background-position': '0px 0px' });
        $('#left-arrow-text').css({ 'color': '#000000', 'font-weight': 'normal' });
        $('#prev-text').css({ 'color': '#666666', 'font-weight': 'normal' });
    });

    $('#next-container').bind('mouseover', function(event) {
        $('#right-arrow').css({ 'background-position': '0px 0px' });
        $('#right-arrow-text').css({ 'color': 'red', 'font-weight': 'bold' });
        $('#next-text').css({ 'color': 'red', 'font-weight': 'bold' });

    });

    $('#next-container').bind('mouseout', function(event) {
        $('#right-arrow').css({ 'background-position': '0px -8px' });
        $('#right-arrow-text').css({ 'color': '#000000', 'font-weight': 'normal' });
        $('#next-text').css({ 'color': '#666666', 'font-weight': 'normal' });
    });
}

function buildGallery() {
    if ($.browser.msie) {
        $('#product-photo-area img').each(function(n, domEle) {
            var altText = $(this).attr('alt');
            if (altText.indexOf('gallery_') != -1) {
                $(domEle).appendTo('#gallery-images');
            }
        });

        $('#gallery-images img').each(function(n, domEle) {
            $(this).wrap('<li></li>');
        });
    } else {
        $('#product-photo-area img').each(function(n, domEle) {
            var altText = $(this).attr('alt');
            if (altText.indexOf('gallery_') != -1) {
                var x = $(domEle).wrap('<div></div>');
                $(x).appendTo('#gallery');
            }
        });
    }

    $('#product-photo-area img, #image-gallery-image, #image-gallery-text').bind('click', function(event) {
        openGallery();
    });
}

function openGallery() {
    if ($.browser.msie) {
        // a separate gallery for IE browsers is necessary as Galleria was causing some conflicting
        // styling to the main nav. The gallery here for IE is not as nice but functional.  
        showModalOverlay();
        $('#gallery').fadeIn(500);
        if ($('.gallery-container').length == 0) {
            $('#gallery-images').bxGallery({
                maxwidth: 900,              // if set, the main image will be no wider than specified value (in pixels)
                maxheight: 600,             // if set, the main image will be no taller than specified value (in pixels)
                thumbwidth: 120,           // thumbnail width (in pixels)
                thumbcrop: false,          // if true, thumbnails will be a perfect square and some of the image will be cropped
                croppercent: .10,          // if thumbcrop: true, the thumbnail will be scaled to this
                // percentage, then cropped to a square
                thumbplacement: 'bottom',  // placement of thumbnails (top, bottom, left, right)
                thumbcontainer: 900,        // width of the thumbnail container div (in pixels)
                opacity: .7,               // opacity level of thumbnails
                load_text: '',             // if set, text will display while images are loading
                load_image: 'http://i302.photobucket.com/albums/nn92/wandoledzep/spinner.gif',
                // image to display while images are loading
                wrapperclass: 'gallery-container'      // classname for outer wrapping div
            });
        }
        
        //event handler for close button
        $('#ie-gallery-close-btn').bind('click', function(event) {
            $('#gallery').fadeOut(300);
            $('.modalOverLay').animate({ opacity: '0.0' }, 500);
            $('.modalOverLay').remove();
        });

    } else {
        //Galleria for all other browsers
        if ($('.galleria-container').length == 0) {
            $('#gallery').show(); //workaround to properly initialize gallery
            $('#gallery').galleria();
            $('.galleria-container').css('height', '620px');
            $('.galleria-info').remove();
            $('.galleria-counter').remove();
        }
        
        $('<div />').addClass('galleria-close').insertAfter('.galleria-images').show();
        $('<div />').addClass('overlay').appendTo('body');
        $('.overlay').css('filter', 'alpha(opacity=75)');
        $('.overlay').fadeIn(300);
        $('#gallery').fadeIn(500);

        //event handler for close button
        $('.galleria-close').bind('click', function(event) {
            $('.overlay').fadeOut(300);
            $('.overlay').remove();
            $('#gallery').fadeOut(300);
            
        });
    }
}