﻿var menuTimer;

$(document).ready(function() {

    ShowFirstIconOnProductPage();

    ShowFirstSimilarProdArrowOnProductPage();

    //Close all Filter options
    $(".filter_option_e").hide();

    //Toggle selected option open and closed
    $(".filter_vis").click(function(evt) {
        var ef_target = $(evt.target).parent().next(".filter_option_e");

        $(".filter_option_e").each(function(i, tgt) {

            var colour = 'Orange';
            if ($(".filter_data").children("a:first").attr('class').indexOf('Blue') > 0) {
                colour = 'Blue'
            }

            if ($(tgt).html() == ef_target.html()) {
                $(tgt).animate({ opacity: "show", height: "show" }, "slow");
                $(tgt).prev(".filter_data").children("a").removeClass(("closed" + colour));
                $(tgt).prev(".filter_data").children("a").addClass(("open" + colour));
            }
            else {
                $(tgt).animate({ opacity: "hide", height: "hide" }, "slow");
                $(tgt).prev(".filter_data").children("a").removeClass(("open" + colour));
                $(tgt).prev(".filter_data").children("a").addClass(("closed" + colour));
            }
        });
    });

    //Open first filter option
    $(".filter_vis").eq(0).click();

    // Show Icon Text on product page
    $(".Icon").mouseover(function(evt) {
        // Switch all icons back to default state
        $('.Icon').each(function(i, tgt) {
            $(tgt).removeClass('IconOn');
        });

        // Highlight the one the use is over
        $("#aIconText").html($(evt.target).attr('rel'));
        $(evt.target).addClass('IconOn');
    });

    // Open Help and Advice Menu
    $('#aHelpAndAdvice').mouseover(function(evt) {
        clearTimeout(menuTimer);
        $('#HelpAndAdviceMenu').attr('style', 'width:176px;display:block;background-color:#000d33;position:absolute;border-left:solid 1px #ffffff;border-right:solid 1px #ffffff;border-bottom:solid 1px #ffffff;');
    });

    // Moved off Help and Advice menu opener so start close timer
    $('#aHelpAndAdvice').mouseout(function(evt) {
        menuTimer = setTimeout('CloseMenu()', 1000);
    });

    // User has moved into help and advice menu so stop close timer
    $('.HADOption').mouseover(function(evt) {
        clearTimeout(menuTimer);
    });

    // User has moved out of help and advice menu so start timer
    $('.HADOption').mouseout(function(evt) {
        menuTimer = setTimeout('CloseMenu()', 1000);
    });

    // Change Similar Product Link
    $(".SimilarImageThumb").mouseover(function(evt) {
        // First grab the link that is holding all the similar product info
        var link = $(evt.target).parent().parent().find('a:first');

        // Now set the links text and href
        $('.SimilarProductLink').html($(link).attr('rel'));
        $('.SimilarProductLink').attr('href', $(link).attr('href'));

        // Hide all arrows underneath all boxes
        $('.SimilarArrow').each(function(i, tgt) {
            $(tgt).addClass('Hidden');
        });

        // Finally, show the arrow underneath the box
        //alert($(link).parent().html());
        $(link).parent().find('.SimilarArrow').removeClass('Hidden');
    });


    // User hovers over thumb image on product page
    $(".ImageThumb").mouseover(function(evt) {
        $('.main_image').attr('src', $(evt.target).attr('rel'));
    });

    // User has tabbed out of the quantity field on product page
    $(".VarQuantity").blur(function(evt) {
        var reqdQty = $(evt.target).val();
        if (reqdQty > 0) {
            var orderMult = $(evt.target).parent().parent().find("input[id$='hidOrderMultiple']").val();
            var multiplier = Math.ceil(reqdQty / orderMult);
            var roundedQty = RoundNumber(multiplier * orderMult, 2);
            var price = $(evt.target).parent().parent().find("input[id$='hidPrice']").val();
            var lineTotal = RoundNumber(roundedQty * price, 2);

            $(evt.target).val(roundedQty);
            $(evt.target).parent().parent().find('.LineValue').html(lineTotal.toFixed(2));
        }
        else {
            $(evt.target).val('');
        }

        RecalculateGrandTotal();
    });

    // User has clicked to request a stock reminder
    $(".EmailReminder").click(function(evt) {
        var reminderDiv = $(evt.target).parent().parent().find('.EmailStockReminder');
        $(reminderDiv).animate({ opacity: "show", height: "show" }, "fast", function() {
            // Reset and show email bubble
            $(reminderDiv).removeClass('Hidden');
            var emailField = $(reminderDiv).find('.EmailTxt');
            $(emailField).val('please enter your email address');
            $(emailField).removeClass('InvalidField');
            $(reminderDiv).find('.EmailQtyTxt').val('quantity reqd');
            $(reminderDiv).find('.ErrorMessage').html('');
        });
        return false;
    });

    // User has clicked to close a stock reminder
    $(".ReminderCloser").click(function(evt) {
        $(evt.target).parent().animate({ opacity: "hide", height: "hide" }, "fast");
        return false;
    });

    // Clear Text box on focus
    $(".ClearTxt").focus(function(evt) {
        $(evt.target).val('');
    });

    // User has reque
    $('.SendEmail').click(function(evt) {
        // Grab DOM elements
        var emailField = $(evt.target).parent().find('.EmailTxt');
        var errorMessage = $(evt.target).parent().find('.ErrorMessage');

        // Get the email address entered for validation
        var emailAddress = $(emailField).val();

        if (emailAddress == '' || !ValidateEmail(emailAddress)) {
            $(emailField).addClass('InvalidField');
            if (emailAddress == '') {
                $(errorMessage).html('* Email address required');
            }
            else {
                $(errorMessage).html('* Email address invalid');
            }
            return false;
        }
        else {
            $(emailField).removeClass('InvalidField');
            $(errorMessage).html('');
            return true;
        }
    });

    // User has clicked to visit a Retailer website
    $('.RetailerLink').click(function(evt) {
        RetailerLink_Click($(evt.target).attr('title'));
        return true;
    });
});

// Recalculate grand total of goods
function RecalculateGrandTotal() {
    var basketTotal = 0;
    $('.VarQuantity').each(function(i, tgt) {
        var quantity = $(tgt).val();
        
        if (quantity == '') {
            quantity = 0;
        }
        
        var price = $(tgt).parent().parent().find("input[id$='hidPrice']").val();
        basketTotal += RoundNumber(quantity * price, 2);
    });

    $('#GrandTotal').html(basketTotal.toFixed(2));
}

// Round a number
function RoundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
    return Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength)
}

// Validate Email Address
function ValidateEmail(address) {
    var reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;

    if (address.match(reg)) {
        return true;
    }
    else {
        return false;
    }
}

// Show text for first icon on product page
function ShowFirstIconOnProductPage() {
    var firstIcon = $('#IconSection').find('.Icon:first');
    $("#aIconText").html(firstIcon.attr('rel'));
    firstIcon.addClass('IconOn');
}

// Show only the first arrow product page
function ShowFirstSimilarProdArrowOnProductPage() {
    var firstArrow = $('.SimilarArrow:first');

    if (firstArrow != null) {
        $(firstArrow).removeClass('Hidden');
    }
}

// Closes the menu after an elapsed time period
function CloseMenu() {
    $('#HelpAndAdviceMenu').attr('style', 'display:none;');
}

// Called to break out of iframe
function Breakout() {
    try {
        if (self.parent.frames.length != 0) {
            self.parent.location = document.location;
        }
    }
    catch (Exception) { }
}

// Add to basket Button clicked
function Add_Click() {
    //If the selected variant is a sample, check that the sample limit has not been breached
    var desc = ($('.Variant:first').find('.VariantDesc').text()).match('Sample');

    if (desc == 'Sample' || desc == 'sample') {
        // First input box is a sample, see if there is anything in qty box
        var sampleQty = $('.Variant:first').find('.VarQuantity').val();
        sampleQty = sampleQty.replace(' ', '');

        if (sampleQty != '') {
            // Someone has entered something in the sample box so check before postback
            var basketSamps = $("input[id$='hidBasketSampleQty']").val();
            var sampsLimit = $("input[id$='hidSampleLimit']").val();

            if (basketSamps >= sampsLimit) {
                // Stop postback
                alert('Sorry, no more than ' + sampsLimit + ' free samples are available.\r\nIf you require more than ' + sampsLimit + ' samples a delivery charge may apply.\r\nPlease contact our Customer services team for more details.');
                return false;
            }            
        }
    }
    return true;
}

/* BGI Hack for ie6 */
(function($) {

    /**
    * The bgiframe is chainable and applies the iframe hack to get 
    * around zIndex issues in IE6. It will only apply itself in IE6 
    * and adds a class to the iframe called 'bgiframe'. The iframe
    * is appeneded as the first child of the matched element(s) 
    * with a tabIndex and zIndex of -1.
    * 
    */

    $.fn.bgIframe = $.fn.bgiframe = function(s) {
        // This is only for IE6
        if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
            s = $.extend({
                top: 'auto', // auto == .currentStyle.borderTopWidth
                left: 'auto', // auto == .currentStyle.borderLeftWidth
                width: 'auto', // auto == offsetWidth
                height: 'auto', // auto == offsetHeight
                opacity: true,
                src: 'javascript:false;'
            }, s || {});
            var prop = function(n) { return n && n.constructor == Number ? n + 'px' : n; },
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="' + s.src + '"' +
		               'style="display:block;position:absolute;z-index:-1;' +
			               (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') +
					       'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' +
					       'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' +
					       'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' +
					       'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' +
					'"/>';
            return this.each(function() {
                if ($('> iframe.bgiframe', this).length == 0)
                    this.insertBefore(document.createElement(html), this.firstChild);
            });
        }
        return this;
    };

})(jQuery);

// Postback link clicked for Retailer website
function RetailerLink_Click(retailerLink) {  
    // Do Ajax post
    $.ajax({
        url: retailerLink,
        async: false,
        dataType: 'text',
        success: function() {
            // Well done old bean
        }
    });              
}