﻿// jQuery DOM modification
jQuery(document).ready(function() {
    // Settings
    jQuery.jGrowl.defaults.closer = false;

    // Drop down menus
    jQuery("ul.sf-menu").supersubs({
        minWidth: 12,
        maxWidth: 27,
        extraWidth: 1
    }).superfish({
        delay: 1000,
        dropShadows: false,
        autoArrows: false,
        animation: { height: 'show' }
    });

    // Add to basket link
    jQuery('a.add-to-basket').click(function() {
        jQuery.jGrowl('Updating your basket.', { theme: 'jGrowlBasket' });
        var href = jQuery(this).attr('href');
        if (href.indexOf('/addtobasket.aspx') === 0) {
            var query = jQuery.query.load(href);
            var quantity = query.get('q');
            var productId = query.get('p');
            var uom = query.get('u');
            var dutyStatus = query.get('d');
            var offerCode = query.get('o') === true ? '' : query.get('o');
            var enprimeur = query.get('e');
            var bypass = query.get('b');
            var data = { productId: productId, quantity: quantity, uom: uom, dutyStatus: dutyStatus, offerCode: offerCode, enprimeur: enprimeur, bypass: bypass };
            jQuery.ajax({
                type: 'POST',
                url: '/WebServices/Basket.asmx/AddToBasket',
                data: jQuery.toJSON(data),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(msg) {
                    jQuery('#values').html('Items: ' + msg.d[1] + ' &nbsp;' + msg.d[0]);
                    var itemsText = 'item';
                    if (msg.d[1] > 1)
                        itemsText = 'items';
                    jQuery.jGrowl('<a href="/home/wineshop/basket.aspx">Your basket</a> contains ' + msg.d[1] + ' ' + itemsText + ' worth ' + msg.d[0] + '.', { theme: 'jGrowlBasket' });
                },
                error: function(request, textStatus, errorThrown) {
                    displayAjaxError();
                }
            });
        }
        return false;
    });

    // Add to basket form
    jQuery('form.add-to-basket').submit(function() {
        var form = jQuery(this);
        var quantity = form.children('input[name="quantity"]').val();
        if (/[1-9]{1}[0-9]{0,2}/.test(quantity)) {
            form.children('input[name="quantity"]').removeClass('error');
            jQuery.jGrowl('Updating your basket.', { theme: 'jGrowlBasket' });
            var productId = form.children('input[name="product-id"]').val();
            var uom = form.children('input[name="uom"]').val();
            var dutyStatus = form.children('input[name="duty-type"]').val();
            var offerCode = form.children('input[name="short-code"]').val();
            var enprimeur = form.children('input[name="en-primeur"]').val();
            var bypass = form.children('input[name="broking"]').val();
            var data = { productId: productId, quantity: quantity, uom: uom, dutyStatus: dutyStatus, offerCode: offerCode, enprimeur: enprimeur, bypass: bypass };
            jQuery.ajax({
                type: 'POST',
                url: '/WebServices/Basket.asmx/AddToBasket',
                data: jQuery.toJSON(data),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(msg) {
                    jQuery('#values').html('Items: ' + msg.d[1] + ' &nbsp;' + msg.d[0]);
                    var itemsText = 'item';
                    if (msg.d[1] > 1)
                        itemsText = 'items';
                    jQuery.jGrowl('<a href="/home/wineshop/basket.aspx">Your basket</a> contains ' + msg.d[1] + ' ' + itemsText + ' worth ' + msg.d[0] + '.', { theme: 'jGrowlBasket' });
                },
                error: function(request, textStatus, errorThrown) {
                    displayAjaxError();
                }
            });
        }
        else {
            form.children('input[name="quantity"]').addClass('error');
        }
        return false;
    });

    jQuery('form.add-to-basket > input[name="quantity"]').keyup(function() {
        var quantity = jQuery(this).val();
        if (/[1-9]{1}[0-9]{0,2}/.test(quantity)) {
            jQuery(this).removeClass('error');
        }
        else {
            jQuery(this).addClass('error');
        }
    });

    // Product POP-UP background
    jQuery('<div id="qtip-blanket">')
        .css({
            position: 'absolute',
            top: 0,
            left: 0,
            height: jQuery(document).height(),
            width: '100%',
            opacity: 0.7,
            backgroundColor: 'black',
            zIndex: 5000
        })
        .appendTo(document.body)
        .hide();

    // Product POP-UP
    jQuery('a.product-popup').click(function() {
        var href = jQuery(this).attr('href');
        if (href.match(/\/home\/wineshop\/product\.aspx\?prodid\=([A-Za-z0-9]+)/i)) {
            // Create qTip
            jQuery(this).qtip({
                content: {
                    title: {
                        text: 'Wine details',
                        button: 'Close'
                    },
                    text: '<div style="text-align:center"><br /><br /><br /><p><img src="/img/loading.gif" /></p><br /><br /><br /></div>'
                },
                position: {
                    target: jQuery(window),
                    corner: 'center'
                },
                show: {
                    when: false,
                    solo: true
                },
                hide: false,
                style: {
                    width: 600,
                    border: {
                        width: 9,
                        radius: 9,
                        color: '#333333'
                    },
                    title: {
                        color: '#ffffff',
                        background: '#595536'
                    },
                    name: 'light'
                },
                api: {
                    beforeShow: function() {
                        jQuery('#qtip-blanket').fadeIn(this.options.show.effect.length);
                    },
                    beforeHide: function() {
                        jQuery('#qtip-blanket').fadeOut(this.options.hide.effect.length);
                    }
                }
            });

            qtip = jQuery(this).qtip('api');
            qtip.show();

            // Get Ajax Content
            var productId = href.split('=')[1];
            jQuery.ajax({
                type: 'POST',
                url: '/WebServices/Product.asmx/GetProductPopupHtml',
                data: '{"productId": "' + productId + '"}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(msg) {
                    var html = msg.d;
                    qtip.updateContent(html, true);
                }
            });
        }
        return false;
    });

    // Maturity help
    setupPopUp({
        id: '.maturityHelp',
        title: 'Wine Development &amp; Maturity',
        content: '\
<img src="/img/maturityHelp.png" style="margin: 0 0 0.5em;" alt="Wine maturity chart" />\
<p style="margin: 0 0 0.5em;"><strong>Drink dates are not an exact science. The dates we provide are meant to offer guidance rather than be prescriptive. It is not necessarily the case that a wine simply gets better and better with age, rather, it evolves and changes in style.</strong></p>\
<p><strong>How a red wine typically matures of time</strong></p>\
<p style="margin: 0 0 0.5em;">A young fine quality red wine will typically have an overt fruit expression and be tannic, before developing secondary flavours with time whilst also retaining a clear fruit character and some tannic grip. With further ageing, savoury and earthy flavours develop and the tannin softens.</p>\
<p><strong>When should a wine be drunk?</strong></p>\
<p style="margin: 0 0 0.5em;">It really depends on how mature you enjoy your wine. For many, one of the key (and fun) aspects of purchasing wine by the case is following a wine’s progress as one drinks through the case, monitoring its development with time. Often better to have a case a touch too early than too late, especially when there are six or twelve bottles to enjoy.</p>\
<p style="margin: 0 0 0.5em;">Remember, our knowledgeable and experienced wine advisors are always available for more detailed advice.</p>\
<a href="/wineknowledge/wine-tips/cellaring-wine/maturity-advice.aspx"><img src="/UserFiles/Image/Homepage/Buttons2011/btViewMore.jpg" /></a>\
',
        close: 'Close'
    });


    // Register hint qtip
    jQuery('.registerhint-lhs,.glossary-lhs').qtip({
        content: {
            text: false
        },
        position: {
            corner: {
                target: 'topRight',
                tooltip: 'bottomLeft'
            }
        },
        style: {
            width: 200,
            padding: 5,
            background: '#666666',
            color: '#ffffff',
            border: {
                width: 1,
                radius: 5,
                color: '#666666'
            },
            tip: 'bottomLeft',
            name: 'red'
        }
    });

    jQuery('.registerhint-rhs,.glossary-rhs').qtip({
        content: {
            text: false
        },
        position: {
            corner: {
                target: 'topLeft',
                tooltip: 'bottomRight'
            }
        },
        style: {
            width: 200,
            padding: 5,
            background: '#666666',
            color: '#ffffff',
            border: {
                width: 1,
                radius: 5,
                color: '#666666'
            },
            tip: 'bottomRight',
            name: 'red'
        }
    });

    // Duty status qtip
    $('.dutystatus-qtip').qtip({
        position: {
            corner: {
                target: 'topRight',
                tooltip: 'bottomLeft'
            }
        },
        style: {
            width: 200,
            padding: 5,
            background: '#666666',
            color: '#ffffff',
            border: {
                width: 1,
                radius: 5,
                color: '#666666'
            },
            tip: 'bottomLeft',
            name: 'red'
        }
    });

    // Image popup
    jQuery('a.zoom').fancybox();

    // End jQuery(document).ready()
});


// Helper functions
helpToggle = function(id) {
    jQuery(id).slideToggle('normal');
    return false;
}

displayAjaxError = function() {
    jQuery.jGrowl('Sorry, an error occurred. Please try reloading the page and repeating your action or call us on 01473 313 300', { sticky: true });
}

setupPopUp = function(settings) {
    var d = {}
    var defaults = { title: 'Lay & Wheeler', close: 'Close' };
    jQuery.extend(true, d, defaults, settings);
    jQuery(d.id).click(function() {
        jQuery(this).qtip({
            content: {
                title: {
                    text: d.title,
                    button: d.close
                },
                text: d.content
            },
            position: {
                target: jQuery(window),
                corner: 'center'
            },
            show: {
                when: false,
                solo: true
            },
            hide: false,
            style: {
                width: 600,
                border: {
                    width: 9,
                    radius: 9,
                    color: '#333333'
                },
                title: {
                    color: '#ffffff',
                    background: '#595536'
                },
                name: 'light'
            },
            api: {
                beforeShow: function() {
                    jQuery('#qtip-blanket').height(jQuery(document).height());
                    jQuery('#qtip-blanket').fadeIn(this.options.show.effect.length);
                },
                beforeHide: function() {
                    jQuery('#qtip-blanket').fadeOut(this.options.hide.effect.length);
                }
            }
        });

        qtip = jQuery(this).qtip('api');
        qtip.show();

        return false;
    });


}
