jQuery(document).ready(function()
    {
        if (jQuery('.jscriptThisIsTheShop').length == 0) {
            //alert('jsfuctions.js: This is not the shop')
            jQuery('form.cart').attr('target', 'prdpop');
            jQuery( 'form.cart').submit( function()
            {
                var loc = jQuery(this).attr('action').replace( '&Display=RB', '' );
                jQuery(this).attr('action', loc );
                
                var options = 'width=680,height=350,scrollbars=yes';
                
                var popupWindow = window.open( '', 'prdpop', options );
                popupWindow.focus();
                
                setTimeout(function() {
                    updateCartCount();
                }, 2000);
                
                return true;
            });
                
        //            jQuery( 'form.cart').submit( function()
        //            {
        //                jQuery(this).attr('action', jQuery(this).attr('action').replace( '&Display=RB', '' ) );
        //                jQuery.ajax( {
        //                   type: 'POST',
        //                   url: jQuery(this).attr('action'),
        //                   success: function(data) { displayCartOverlay( data ); }
        //                });
        //                return false;
        //            });
                
        } else {
        //alert('jsfuctions.js: This is the shop');
        }

        jQuery( 'a[rel=popupreturn]' ).click(function()
        {
            window.opener.document.location.href = jQuery(this).attr( 'href' );
            window.opener.focus();
            window.close();
            return false;
        });
        jQuery( 'a[rel~=popup],a[rel~=popupDada]' ).click(function()
        {
            var title = '_blank';
            var options = 'width=400,height=490';
            var href = jQuery(this).attr( 'href' );
            if( jQuery(this).is('a[rel~=cart]'))
            {
                href = href.replace( '&Display=RB', '' );
                title="prdpop";
                options = 'width=680,height=350,scrollbars=yes';
            }
            else if( jQuery(this).is('a[rel~=faq]'))
            {
                title='faq';
                options = '';
            }
            else if( jQuery(this).is('a[rel~=tac]'))
            {
                title='tac';
                options = '';
            }
            else if( jQuery(this).is('a[rel~=popupDada newsletter]'))
            {
                options = 'width=600,height=400,scrollbars=yes';
            }
            else if( jQuery(this).is('a[rel~=newsletter]'))
            {
                options = 'width=410,height=200,scrollbars=yes';
            }

            var popupWindow = window.open( href, title, options );
            popupWindow.focus();
            return false;
        });
        jQuery( 'a[rel=external]' ).click(function()
        {
            window.open( jQuery(this).attr( 'href' ), '_blank' );
            return false;
        });

        jQuery( 'form.popup' ).submit( function()
        {
            window.open( '', 'popupform', 'width=430,height=300' );
            return true;
        });
        jQuery( 'form.popupDada' ).submit( function()
        {
            window.open( '', 'popupform', 'width=600,height=680' );
            return true;
        });
        jQuery( 'form.popup, form.popupDada' ).attr('target', 'popupform' );

        //        jQuery( '.fieldhelp' ).hide();
        //
        //        jQuery( 'input').focus( function()
        //        {
        //            var fieldHelp = jQuery( 'label[for=' + jQuery(this).attr('id') + '].fieldhelp' );
        //            if( fieldHelp.is( 'label' ) )
        //            {
        //                fieldHelp.fadeIn( 'slow' );
        //            }
        //        }
        //        );
        //
        //        jQuery( 'input.required,select.required,fieldset.required' ).blur( function()
        //        {
        //            if( $(this).attr('value').length == 0 )
        //            {
        //                $( this).siblings('.requiredflag').hide();
        //                if( !$(this).siblings('.requiredmessage').is('.requiredmessage') )
        //                {
        //                    $(this).after('<span class="requiredmessage">Please enter a value</span>');
        //                    $(this).siblings('.requiredmessage').fadeIn( 'slow' );
        //                }
        //                else
        //                {
        //                    (this).siblings('.requiredmessage').show( 'slow' );
        //                }
        //            }
        //            else
        //            {
        //                $( this).siblings('.requiredmessage').remove();
        //                $( this).siblings('.requiredflag').show();
        //            }
        //        });

        jQuery( 'button.delete').click( function()
        {
            return confirm( 'Are you sure you want to delete ' + jQuery(this).attr('value') );
        });
        //
        //- - - If enter is pressed while in a text field
        //- - - this will click the button with id="defaultButton"
        jQuery('#defaultButton').closest('form').find(':input')
        .not('button').not('submit').keypress(function(e) {
            if (e.keyCode == 13) {
                jQuery(this).closest('form').find('#defaultButton').click();
                e.preventDefault();
            }
        });
        jQuery('#PaymentDetailsForm').submit(function(){
            jQuery('input#defaultButton', this).attr('disabled', 'disabled');
        });
        //
        //- - - Highlight first input field on Standard Forms.
        //- - - To disable it add class="jQueryDontFocus" to the field it would otherwise focus.
        //      eg. careers.jsp where form is at the bottom of a long page.
        //WARNING! returnToUrl logic means we re-position the page. It doesnt seem to
        //         interfere with this (yet!).
        jQuery('.StandardForm :input').not(':hidden').eq(0).not('.jQueryDontFocus').focus();
        
        if(jQuery('#header .loginSubmit').length > 0) {
    
            jQuery('#fieldEmailAddress').focus(function() {
                var x = jQuery(this);
                if (x.val() == 'Email >') x.val('');
            });
            jQuery('#fieldPassword').focus(function() {
                var x = jQuery(this);
                if (x.val() == 'password') x.val('');
            });
        }

        var menuFilter = jQuery(".menu-category .title");
        if(menuFilter.length > 0) {
            menuFilter.wrapInner('<a class="linky"></a>').children('a').click(function() {
                toggleFilter(this, "ul");
            });
        }
        
        var filters = jQuery(".filter-box h3");
        if(filters.length > 0) {
            filters.wrapInner('<a class="linky"></a>').children('a').click(function() {
                toggleFilter(this, ".wrap");
            });
        }

       addScrollBars();


    }); //End document.ready
    
    function addScrollBars() {
        var elem = jQuery('div.scroll:not(:has(.filtered))').filter(function() {
            return jQuery(this).children('ul').children('li').length > 6;
        });
        elem.wrapInner('<div class="viewport"><div class="overview"></div></div>') 
        elem.prepend('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
        elem.tinyscrollbar();
        
        jQuery(elem, '.scroll-target').each(function(){
            var scrollElem = jQuery(this).closest('div.scroll');
            var scrollOffset = scrollElem.height() / 2;
            var listElem = jQuery(this).closest('ul');
            var listItemElem = jQuery(this).closest('li');
            var selectedOffset = this.offsetTop;
            if((selectedOffset + scrollOffset) > listElem.height()) {
                scrollElem.tinyscrollbar_update('top');
            } else if((selectedOffset - scrollOffset) < (scrollOffset / 2) ) {
                scrollElem.tinyscrollbar_update();
            } else {
                scrollElem.tinyscrollbar_update(selectedOffset - scrollOffset + listItemElem.height() / 2);
            } 
        });
    }
function toggleFilter(elem, selector) {
    var e = jQuery(elem).parent().siblings(selector);
    if(e.length > 0) {
        var menuImg = jQuery(elem).children('a img.menustatus');
        if(menuImg.length > 0) {
            var imgSrc = menuImg.attr('src');
            if(e.is(":visible")) {
                e.hide();                    
                imgSrc = imgSrc.replace('minus', 'plus');
                menuImg.attr('src', imgSrc);
            } else {
                e.show();
                imgSrc = imgSrc.replace('plus', 'minus');
                menuImg.attr('src', imgSrc);
            }
        } else {
            e.toggle();
        }
    }
}


//function cartPopup( action, data )
function cartPopup( action )
{
    //    jQuery.ajax( {
    //       type: 'POST',
    //       url: action,
    //       data: data,
    //       success: function(respData) { displayCartOverlay( respData ); }
    //    });
    
    var options = 'width=680,height=350,scrollbars=yes';
    var popupWindow = window.open( action, 'prdpop', options );
    popupWindow.focus();
    setTimeout(function() {
        updateCartCount();
    }, 2000);
    return false;
}

function popup(mylink, windowname) 
{
    if (navigator.userAgent.indexOf("Opera") == -1)
    {
        cartwin = window.open('', windowname, 'width=400, height=225, scrollbars,location,resizable');
        cartwin.document.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\" />");
        cartwin.document.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        cartwin.document.write("<head>");
        cartwin.document.write("<title>Chemical Cart<\/title>");
        cartwin.document.write("</head>");
        cartwin.document.write("<body style=\"font-family: Arial, Helvetica, sans-serif;color:#fff;background-color:#f2f2f2;\">");
        cartwin.document.write("<iframe frameborder=\"0\" marginheight=\"0px\" marginwidth=\"0px\" id=\"mn\" src=\""+mylink+"\" width=\"99%\" height=\"1000px\" scrolling=\"no\"></iframe>");
        cartwin.document.write("</body>");
        cartwin.document.write("</html>");
        cartwin.document.close();
    }
    else
    {
        cartwin = window.open(mylink, windowname, 'width=400, height=225, scrollbars,location,resizable');
    }

    return false;
}

function updateCartCount() {
    jQuery.ajax( {
        type: 'POST',
        url: 'http://www.chemical-records.co.uk/sc/CartCount',
        success: function(data) { 
            try
            {
                var count = data * 1;
                jQuery('#itemcount').html( count );
            }
            catch(e){}
        }
    });
}

function closego(page) 
{
    window.parent.opener.document.location.href = page;
    window.parent.opener.focus();
    window.parent.close();
}

function loadParent(page) 
{
    pindex = page.indexOf("~");
		
    if (pindex >= 0)
    {
        page = page.substring(0,pindex);
        page = page + "&show=true"
    }

    pindex = page.indexOf("-");
		
    if (pindex >= 0)
    {
        page = page.substring(0,pindex);
    }

    if (navigator.userAgent.indexOf("Opera")==-1)
    {
        window.opener.document.location.href = page;
    }
    else
    {
        opener.document.location.href = page;
    }
}

function openFAQ( faqid )  
{
    // Opens the FAQ popup, passed "faqid" is used as an anchor reference on the new window
    var thewindow = window.open('http://www.chemical-records.co.uk/sc/information/faq#' + faqid, 'faq', config='height=400,width=490,toolbar=no,scrollbars=yes,resizable=yes,location=no,status=yes');
}

function openThawte(server)
{
    var thawtewin = window.open('https://sealinfo.thawte.com/thawtesplash?form_file=fdf/thawtesplash.fdf&dn=' + server + '&lang=en', 'anew',config='height=500,width=516,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=yes');
}

function openTAC()   
{
    // Opens the Terms & Conditions popup.
    var thewindow = window.open('http://www.chemical-records.co.uk/sc/information/terms', 'tac', config='height=400,width=490,toolbar=no,scrollbars=yes,resizable=yes,location=no,status=yes');
}

function openYSTAC() 
{
    // Opens the "You Sell" Terms & Conditions popup.
    var thewindow = window.open('http://www.chemical-records.co.uk/static_pages/yousell_tac.html', 'ystac', config='height=400,width=490,toolbar=no,scrollbars=yes,resizable=yes,location=no,status=yes');
}

function openImage( catid, productTitle, logo, numImages, thisImage, width, height )   
{
    if(width == undefined || width == null)
    {
        width = "840";
    }

    if(height == undefined || height == null)
    {
        height = "660";
    }

    if(thisImage == undefined || thisImage == null)
    {
        thisImage = 1;
    }

    // Opens the large image popup, passed "catid" is the item catalogue number from the image (example "vrs001_A")
    var url = 'http://www.chemical-records.co.uk/sc/servlet/imagepopup?' + 'cat=' + catid + '&p=' + thisImage + '&logo=' + logo;

    var config = "height="+height+",width="+width+",toolbar=no,scrollbars=yes,resizable=yes,location=no,status=yes";

    var thewindow = window.open(url,'imagepopup', config);

    if( window.event )
    {
        window.event.returnValue = false;
    }

    return false;
}

function getHTTPObject() 
{
    if (typeof XMLHttpRequest != 'undefined')
    {
        return new XMLHttpRequest();
    }

    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e) {}
    }

    return false;
}

function ClassChangeLI(thisform)
{

    category=thisform.categoryselect.value;

    maincat=category.substring(0,category.indexOf("_"));


    var showSelector;
    var hideSelector = null;
    if( category == 'All' )
    {
        showSelector = '#info span';
    }
    else
    {
        hideSelector = '#info span';
        showSelector = '#info span[class^=' + category + '],#info span[class^=' + category + ']';
    }
    if( hideSelector )
    {
        jQuery(hideSelector).hide();
    }
    jQuery(showSelector).show();
}

function displayOverlay( width, height )
{
    jQuery('body').append('<div id="mask" />');
    jQuery('body').append('<div id="overlay" />');
    jQuery('body').append('<a id="overlayclose"><img src="/site_images/footer/popup-cross.png" /></a>');
    jQuery('#overlay').css('width', width + "px");
    jQuery('#overlay').css('height', height + "px");
    var top = (jQuery(window).height() - jQuery('#overlay').height() ) / 2 +jQuery(window).scrollTop() + "px";
    var left = (jQuery(window).width() - jQuery('#overlay').width() ) / 2 +jQuery(window).scrollLeft()+ "px";

    jQuery('#overlay').css('top', top);
    jQuery('#overlay').css('left', left);
    var closetop = jQuery('#overlay').offset().top - 16 + "px";
    var closeleft = jQuery('#overlay').offset().left + jQuery('#overlay').outerWidth() - 16 + "px";
    jQuery('#overlayclose').css('top', closetop);
    jQuery('#overlayclose').css('left', closeleft);
    
    return false;
}

function displayCartOverlay( data )
{
    displayOverlay( 680, 350 );
    
    jQuery('#overlay').append(data);
    
    jQuery('#overlay').css('height', (jQuery('#cartsummary').height() + 80) + 'px');
    var top = (jQuery(window).height() - jQuery('#overlay').height() ) / 2 +jQuery(window).scrollTop() + "px";
    var left = (jQuery(window).width() - jQuery('#overlay').width() ) / 2 +jQuery(window).scrollLeft()+ "px";
    jQuery('#overlay').css('top', top);
    jQuery('#overlay').css('left', left);
    
    
    jQuery('#mask').click( function()
    {
        jQuery('#mask').remove();
        jQuery('#overlay').remove();
        jQuery('#overlayclose').remove();
    });
    
    jQuery('#overlayclose').click( function()
    {
        jQuery('#mask').remove();
        jQuery('#overlay').remove();
        jQuery('#overlayclose').remove();
    });
    
//    setTimeout( function() 
//    {
//        jQuery('#mask').fadeOut(1000, function() { jQuery('#mask').remove()} );
//        jQuery('#overlay').fadeOut(1000, function() { jQuery('#overlay').remove()} );
//    }, 3000);
}

function displaySocialNetworkContent(socialnetworkid, numitems) 
{   
    var cols = 3;
    var rows = Math.floor(numitems / 3);
    if( numitems % 3 > 0 )
    {
        if( rows == 0 )
        {
            cols = numitems % 3;
        }
        rows = rows + 1;
    }
    var width = (120 + cols * (jQuery('.sociallink img').width() + 40) );
    width = Math.max( width, 600 );
    var height = (170 + (rows * (jQuery('.sociallink img').height() + 40) ));
    displayOverlay( width, height );
    
    var c = jQuery('#' + socialnetworkid + "socialcontent").detach();
    c.addClass("overlaycontent");
    c.appendTo( jQuery('#overlay'));
    
    jQuery('#mask').click( function()
    {
        jQuery('#mask').remove();
        var d = jQuery('#overlay .socialcontent').detach();
        jQuery('#' + socialnetworkid).after(d);
        jQuery('#' + socialnetworkid + "socialcontent").removeClass("overlaycontent");
        jQuery('#overlay').remove();
        jQuery('#overlayclose').remove();
    });
    
    jQuery('#overlayclose').click( function()
    {
        jQuery('#mask').remove();
        var d = jQuery('#overlay .socialcontent').detach();
        jQuery('#' + socialnetworkid).after(d);
        jQuery('#' + socialnetworkid + "socialcontent").removeClass("overlaycontent");
        jQuery('#overlay').remove();
        jQuery('#overlayclose').remove();
    });
    
    
    return false;
}

var bannerChangeTimeout = 5000;
var bannerTimer;

function prepareBanners(banners) 
{
    jQuery('.BannerIcon').live( 'click', function() 
    {        
        if( bannerTimer )
        {
            clearTimeout(bannerTimer);
        }
        
        showBanner(this);
        
        bannerTimer = setTimeout(function() {nextBanner();}, 10000);
        
    });
    
    bannerTimer = setTimeout(function() {nextBanner();}, bannerChangeTimeout);
}



function nextBanner()
{
    if( bannerTimer )
    {
        clearTimeout(bannerTimer);
    }
    var icons = jQuery('.BannerIcon');
    var i = 0;
    for( i = 0; i < icons.length; i++ )
    {
        if( jQuery(icons[i]).hasClass('selected') )
        {
            
            if( i == icons.length - 1 )
            {
                showBanner( icons[0] );
//                jQuery(icons[0]).click();
            }
            else
            {
                showBanner( icons[i+1] );
//                jQuery(icons[i+1]).click();
            }
            bannerTimer = setTimeout(function() {nextBanner();}, bannerChangeTimeout);
        }
    }
    
    return false;
}

function showBanner( ic )
{
    
        var icon = jQuery(ic);
        
        jQuery( '#Banner').css( 'background-image', 'url(' + icon.attr('data-src') +')' );
        var image = jQuery('#Banner img');
        
        image.attr('data-src', icon.attr('data-src'));
        image.attr('data-title', icon.attr('data-title'));
        image.attr('data-url', icon.attr('data-url'));
        image.attr('data-id', icon.attr('id'));
        
        
        image.fadeOut( '500', function() {

            var image = jQuery('#Banner img');
            image.attr('src', image.attr('data-src'));
            image.attr('alt', image.attr('data-title'));
            var banner = jQuery('#Banner');
            banner.attr('href', image.attr('data-url'));
            if( image.attr('data-url') && image.attr('data-url').length > 0 && image.attr('data-url') != '#' )
            {
                banner.click( function() {
                    return true;
                });
                banner.removeClass( 'nolink' );
            }
            else
            {
                banner.click( function() {
                    return false;
                });
                banner.addClass( 'nolink' );
            }
            jQuery('.BannerIcon.selected .BannerStatus').attr('src', '/site_images/dot-off.png');
            jQuery('.BannerIcon.selected').removeClass('selected');
            jQuery('#' + image.attr('data-id') + " .BannerStatus").attr('src', '/site_images/dot-on.png');
            jQuery('#' + image.attr('data-id')).addClass('selected');
            
            image.fadeIn();
        } );
}
