$(document).ready(function () {

  /* top navigation */
    $("ul.sf-menu").superfish({ delay: 100, animation: { opacity: 'show', height: 'show' }, speed: 'fast', autoArrows: false, dropShadows: false }).find('ul').bgIframe();
    $("ul.sf-menu li a.nav-item").each(function () {
        if ($(this).text().length > 12)
            $(this).addClass('double-lines');
    });

    /* onfocus clear input value */
    $('.focus-clear').focus(function () {
        ($(this).val() == $(this).attr('title')) ? $(this).val('') : null;
    }).blur(function () {
        ($(this).val() == '') ? $(this).val($(this).attr('title')) : null;
    });

    $("#header .focus-clear, #footer .focus-clear, #getEstimateCart .focus-clear").focus(function () {
        $(this).css('color', '#000');
    }).blur(function () {
        $(this).css('color', '#878787');
    });

    /* department side navigation */
    $("ul.side-nav li h3").click(function () {
        $(this).next("ul").slideToggle("slow");
        $(this).parent("li").toggleClass("on");
    });

  /* product qty +/- */
    $(".quantity .subtract").click(function () {
    	var qtyInput = $(this).nextAll('a');
        var qtytxt = $(qtyInput).prev('input');
        var qty = qtytxt.val();
        
        if (qty > 1)
            qtytxt.val(qty - 1);

        qtytxt.focus();
        return false;
    });

    $(".quantity .add").click(function () {
        var qtyInput = $(this).prev('input');
        var qty = parseInt(qtyInput.val());
        if (qty >= 0 && (qty + 1 <= 999))
            qtyInput.val(qty + 1);

        qtyInput.focus();
        return false;
    });

    $(".quantity input.text").focus(function () {
        if ($(this).val() == 0)
            $(this).val(1);
    }).blur(function () {
        if ($(this).val() == 0)
            $(this).val(1);
    }).numeric();

    /* pop-ups */
    $("a.popup").fancybox().click(function () {
        $("#quicklinks").hide();
    });

    /* product delivery tab */
    $('.deliveries .delivery-estimate input.text').numeric();

    /* product image vertically centre */
    $('#product-detail table.images-container').css('height', $('#product-detail .col-right').height());

    /* tooltips */
    //$(".tooltip").tooltip({ showURL: false, fade: 250, left: 15 });

    $(".tooltip").mouseover(function () {
        var title = $(this).attr('alt');
        if (title != '') {
            var ttHtml = '<div class="pop-tooltip"><h3>' + title + '</h3><div class="body"></div><div class="url"></div></div>';
            $(this).append(ttHtml);
            $(this).find('.pop-tooltip').show("slide", { direction: "left" }, 500);
        }
    }).mouseout(function () {
        $(this).find('.pop-tooltip').remove();
    });

    $('.pop-tooltip').click(function () {
        $(this).remove();
    });

    /* hompeage products container */
    var tallest = 0;
    $('#featured-products .feat-product').each(function () {
        if ($(this).height() > tallest)
            tallest = $(this).height();
    });
    if (tallest > 0)
        $('#featured-products .feat-product').css({ 'min-height': tallest + 'px', 'height': 'auto !important', 'height': tallest + 'px' });

    /* hompeage products title */
    tallest = 0;
    $('#featured-products .title').each(function () {
        if ($(this).height() > tallest)
            tallest = $(this).height();
    });
    if (tallest > 0)
        $('#featured-products .feat-product .title').css('height', tallest);

    /* gallery products container */
    tallest = 0;
    $('.results-gallery').each(function () {
        if ($(this).height() > tallest)
            tallest = $(this).height();
    });
    if (tallest > 0)
        $('.results-gallery').css({ 'min-height': tallest + 'px', 'height': 'auto !important', 'height': tallest + 'px' });

    //$('#product-extras .results-gallery').css({ 'min-height': (tallest + 14) + 'px', 'height': 'auto !important', 'height': tallest + 'px' }); // Special for tabbed results gallery

    $('.results-gallery .results-gallery-buttons').css({'bottom': '12px' });

    /* Category landing varieties */
    tallest = 0;
    $('#featured-varieties .variety h3').each(function () {
        if ($(this).height() > tallest)
            tallest = $(this).height();
    });
    if (tallest > 0)
        $('#featured-varieties .variety h3').css({ 'min-height': tallest + 'px', 'height': 'auto !important', 'height': tallest + 'px' });
    $('#category-landing #featured-varieties .varieties .variety .summary a.bt-more').css({ 'bottom': '-20px' });

    /* Results list product container */
    $("#search-results-listing .results-list").each(function () {
        var resultHeight = $(this).height();
        $(this).find(".thumb").height(resultHeight - 12); 	// Make container same height as box to align quick info button
        $(this).find(".thumb img").css({					// Align image vertical centre as per client request
            "padding-top": (resultHeight - 172) / 2
        });

        $(this).find(".pricing").height(resultHeight);

    });

    $("#search-results-listing .results-list .online-offer").each(function () {
        var container = $(this).parent().parent();
        var myHeight = $(this).parent().parent().height();
        container.height(myHeight + 30); // Adjust height for 2 for offer
        container.find(".thumb").height(myHeight); // Make container same height as box to align quick info button
    });

    /* Fix summary if badge present / not present */
    if ($("div.summary img.badge-icon").length) {
        $("div.summary div.product-info").css({
            "min-height": "93px",
            "height": "auto !important",
            "height": "93px"
        });
    } else {
        $("div.summary div.product-info").css({
            "height": "auto",
            "min-height": "0"
        });
    }

    /* Count # of chars in .store p and apply padding if required - p4.5 */
    $(".stock .store p").each(function () {
        var chars = $(this).text();
        if (chars.length <= 25)		// Max character count
        {
            $(this).css("padding-top", "5px");
        }
    });

    /* Count # of chars in .store p and apply padding if required - p3.1D */
    $("#search-results-listing .stock .store p").each(function () {
        var chars = $(this).text();
        if (chars.length <= 34)		// Max character count
        {
            $(this).css("padding-top", "5px");
        }
    });

    $("#store-locator .locator-form h3").each(function () {
        var chars = $(this).text();
        if (chars.length <= 56) {
            $("#store-locator .locator-form .help-box").css("padding-bottom", "35px");
        }

    });

    /* Inline popup dynamic height function */
    $(".inline-popup").each(function () {
        var boxHeight = $(this).height(); // Computed height
        $(this).css("height", boxHeight); // Apply css height for fancy box script to pick up
    });

    /* Checkout delivery selection state */
    $("td.product-delivery li input[type=radio]").each(function () {
        $(this).is(":checked") ? $(this).parent().parent().addClass("selected") : $(this).parent().parent().removeClass("selected");
    }).click(function () {
        $(this).parent().parent().parent().parent().find("li input[type=radio]").each(function () {
            $(this).is(":checked") ? $(this).parent().parent().addClass("selected") : $(this).parent().parent().removeClass("selected");
        });
    });

    $("td.product-delivery").click(function () {
        $(this).find("input[type=radio]").attr("checked", "checked");
        $(this).parent().parent().find("li input[type=radio]").each(function () {
            $(this).is(":checked") ? $(this).parent().parent().addClass("selected") : $(this).parent().parent().removeClass("selected");
        });
    });

    /* Checkout add border to product table since IE doesn't support styling of the tbody tag */
   /* $("#checkout table.checkout-delivery-table tr").each(function () {
        $(this).find("td:first").css("border-left", "1px solid #D5D5D5");
    }); */

    /* Character count for textarea */

    $(".count-chars").each(function () {
        var maxChars = $(this).attr("title");
        $(".count-chars").keypress(function (e) {
            var chars = $(this).val().length;
            var charsLeft = maxChars - chars;
            if (charsLeft <= 0) {
                if (e.keyCode != 8) {
                    $("span.chars-left").html("<strong class='mandatory'>Only " + maxChars + " Characters allowed</strong>");
                    return false;
                }
            } else {
                $("span.chars-left").text(charsLeft + " Characters remaining");
            }
        });

    });

    $(".product-wishlist").each(function (index, value) {

        var pPos = $(this).parent().offset();
        var theHtml = "<ul class='prod-wish' id='prod-wish" + index + "'><li class='product-wishlist'>This product will be moved to your Wish List</li></ul>";
        $(theHtml).appendTo("body");
        $("ul#prod-wish" + index + "").css({
            "position": "absolute",
            "top": pPos.top + 52,
            "left": pPos.left
        });

        $(this).remove();

    });

    /* Validate Newsletter Subscription Form */
    $("#newsletter-form").validate({
        rules: {
            newsletter: {
                required: true,
                email: true
            }
        },
        messages: {
            newsletter: {
                required: "Please enter an email address",
                email: "Please enter a valid email address"
            }
        },
        errorPlacement: function (error, element) {
            if (element.is(":radio"))
                error.appendTo(element.parent().next().next());
            else if (element.is(":checkbox"))
                error.appendTo(element.next().next());
            else
                error.appendTo(element.parent().find(".status"));
        },
        submitHandler: function () {
            this.submit();
        },
        success: function (label) {
            label.html("&nbsp;").addClass("checked");
        }

    });

    $("#storefinder-form").submit(function () {

        var val = $(this).find("input[name=storefinder]").val();
        if (val == "Enter postcode or suburb") {
            $(this).find("span.status").text("Please enter a postcode or suburb");
            return false;
        }

    });

    /* Popups with validation */
    $(".popup-p8s1").fancybox({

        callbackOnShow: function () {

    	$("#fancy_div #checkBalance").validate({

                rules: {
                    "GIFT_CARD<>accountNumber": "required",
                    "GIFT_CARD<>pin": "required"
                },
                messages: {
                    "GIFT_CARD<>accountNumber": "Please enter a card number",
                    "GIFT_CARD<>pin": "Please enter a pin number"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 32);
                }

            });

            $("input[name=GIFT_CARD<>accountNumber]").numeric();

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s1a").fancybox({

        callbackOnShow: function () {
    		
            $("#fancy_div #checkBalance").validate({

                rules: {
                    "GIFT_CARD<>accountNumber": "required",
                    "GIFT_CARD<>pin": "required"
                },
                messages: {
                    "GIFT_CARD<>accountNumber": "Please enter a card number",
                    "GIFT_CARD<>pin": "Please enter a pin number"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 32);
                }

            });

            $("input[name=GIFT_CARD<>accountNumber]").numeric();

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s2").fancybox({

        callbackOnShow: function () {

            $("#fancy_div #useGiftCard").validate({

                rules: {
                    "GIFT_CARD<>amount": "required"
                },
                messages: {
                    "GIFT_CARD<>amount": "Please enter an amount"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 16);
                }

            });

          

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s4").fancybox({

        callbackOnShow: function () {

            $("#fancy_div #checkBalance").validate({

                rules: {
                    "GIFT_CARD<>accountNumber": "required",
                    "GIFT_CARD<>pin": "required"
                },
                messages: {
                    "GIFT_CARD<>accountNumber": "Please enter a card number",
                    "GIFT_CARD<>pin": "Please enter a pin number"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 32);
                }

            });

            $("input[name=giftcard], input[name=GIFT_CARD<>accountNumber]").numeric();

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s5").fancybox({

        callbackOnShow: function () {

            $("#fancy_div #useGiftCard").validate({

                rules: {
                    "GIFT_CARD<>accountNumber": "required",
                    "GIFT_CARD<>pin": "required",
                    "GIFT_CARD<>amount": "required"
                },
                messages: {
                    "GIFT_CARD<>accountNumber": "Please enter a card number",
                    "GIFT_CARD<>pin": "Please enter a pin number",
                    "GIFT_CARD<>amount": "Please enter an amount"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 48);
                }

            });

            $("input[name=giftcard], input[name=GIFT_CARD<>accountNumber]").numeric();

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s7").fancybox({

        callbackOnShow: function () {

            $("#fancy_div #p8s7-form").validate({

                rules: {
            	promotionCode: "required"
                },
                messages: {
                	promotionCode: "Please enter a voucher code"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 18);
                }

            });

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s8").fancybox({

        callbackOnShow: function () {

            $("#fancy_div #p8s8-form").validate({

                rules: {
            	promotionCode: "required"
                },
                messages: {
                	promotionCode: "Please enter a voucher code"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 18);
                }

            });

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });

    $(".popup-p8s9").fancybox({

        callbackOnShow: function () {

            $("#fancy_div #p8s9-form").validate({

                rules: {
            	promotionCode: "required"
                },
                messages: {
                	promotionCode: "Please enter a voucher code"
                },
                errorPlacement: function (error, element) {
                    if (element.is(":radio"))
                        error.appendTo(element.parent().next().next());
                    else if (element.is(":checkbox"))
                        error.appendTo(element.next().next());
                    else
                        error.appendTo(element.parent().find(".status"));
                },
                submitHandler: function () {
                    this.submit();
                },
                success: function (label) {
                    label.html("&nbsp;").addClass("checked");
                },
                invalidHandler: function (form, validator) {
                    var fbHeight = $("#fancy_outer").height();
                    $("#fancy_outer").height(fbHeight + 18);
                }

            });

            // Hack for webkit
            var fbNewHeight = $("#fancy_div").height();
            $("#fancy_outer").height(fbNewHeight + 10);

        }
    });
    
    /* Checkout confirmation suggest products add */
    $('.suggested-products .results-gallery .results-gallery-buttons .bt-add-cart').click(function () {
           $(this).addClass('bt-added');
    });

});

    $(".count-chars").each(function () {
        var maxChars = $(this).attr("title");
        $(".count-chars").keypress(function (e) {
            var chars = $(this).val().length;
            var charsLeft = maxChars - chars;
            if (charsLeft <= 0) {
                if (e.keyCode != 8) {
                    $("span.chars-left").html("<strong class='mandatory'>Only " + maxChars + " Characters allowed</strong>");
                    return false;
                }
            } else {
                $("span.chars-left").text(charsLeft + " Characters remaining");
            }
        });

    });

/* Keep fancy box always on screen */
function fancyPosition() {

    var winTop = $(this).scrollTop();
    var winWidth = $(this).width();
    var winHeight = $(this).height();
    var fWidth = $("#fancy_inner").width();
    var fHeight = $("#fancy_inner").height();

    $("#fancy_outer").css({ 
        "top": (winHeight - fHeight) / 2 + winTop -35, 
        "left": ((winWidth - fWidth) / 2) - 18 
   }); 

}

$(window).resize(function () {

    fancyPosition();

}).scroll(function () {

    fancyPosition();

});


function trimTextArea(field,maxlimit)
{
	var remain = field + "_remain";
	var field = document.getElementById(field);
	
	if(field.value.length > maxlimit){
		field.value = field.value.substring(0, maxlimit);
	}	
	
	//Update remaining characters
	document.getElementById(remain).innerHTML = (maxlimit - field.value.length);
}

$(window).load(function () {

    /* 
        This is on Window load because on document ready
        Chrome runs it too quickly...
    */

    /* gallery products container */
    tallest = 0;
    $('.results-gallery').each(function () {
        if ($(this).height() > tallest)
            tallest = $(this).height();
    });
    if (tallest > 0)
        $('.results-gallery').css({ 'min-height': tallest + 'px', 'height': 'auto !important', 'height': tallest + 'px' });

    $('.results-gallery .results-gallery-buttons').css({ 'position': 'absolute', 'bottom': '12px' });

});

