﻿
//Quantity Selector Functions
function minusone(id) {
    var minQty = $("#minQty" + id).val();
    var Qty = $("#Qty" + id).val();

    if (Qty == "") { Qty = 0 }
    Qty = parseInt(Qty) - 1;
    $("#Qty" + id).val(Qty);
    return true;
}
function addone(id) {
    var maxQty = $("#maxQty" + id).val();
    var Qty = $("#Qty" + id).val();

    if (Qty == "") { Qty = 0 }
    Qty = parseInt(Qty) + 1;
    if (parseInt(Qty) > parseInt(maxQty)) {
        Qty = maxQty
        alert("Sorry, that is all we have in stock");
        return false;
    }
    else {
        $("#Qty" + id).val(Qty);
        return true;
    }
}

$(document).ready(function() {

    $('[name="Qty"]').click(function() {
        this.focus();
        this.select();
    });

    $("a[rel='lightbox-collection']").colorbox({ rel: "lightbox-collection", maxWidth: "95%", maxHeight: "95%", scalePhotos: true, current: "image {current} of {total}" });
    $("a#SizeGiudeLink").colorbox({ maxWidth: "95%", maxHeight: "95%", scalePhotos: true });
    $("#openNotify").colorbox({ width: "30%", inline: true, href: "#notifyPopup" });

    $("#openNotify").click(function() {
        var colorDD;
        var sizeDD;

        $("#emailLabel").show();
        $("#_notifyEmail").show();
        $("#stockNotifySubmit").show();
        $('.btnsubmit').show();
        $("#StockNotifyFeedback").hide();

        //## clone the dropdowns from the main page - use these values when requesting
        //## stock notification.
        if ($('#Matrix1').length) {
            if ($('#notifyColor').length == 0) {
                colorDD = $('#Matrix1').clone();
                $(colorDD).attr("id", "notifyColor");
                $(colorDD).attr("name", "notifyColor");
                colorDD.appendTo('#notifyColorContainer');

                //## setup the onchange function
                $('#notifyColor').change(function() {
                    //## set the orginal matrix drop down to the new value to repopulate the sizes
                    $('#Matrix1').val($('#notifyColor').val());

                    //## replace the sizes drop down with the new one.
                    if ($('#notifySize').length) {
                        $('#notifySize').remove();
                    }
                    if (window.selectionsChanged) {
                        selectionsChanged();
                    }

                    $("#emailLabel").show();
                    $("#_notifyEmail").show();
                    $("#stockNotifySubmit").show();
                    $('.btnsubmit').show();
                    $("#StockNotifyFeedback").hide();

                    addSizeDD();

                    //## update the size drop down to ensure it reflects the chosen size - this may
                    //## have changed as the previously selected size might be available to buy and
                    //## therefore not selectable

                    //## check the option value is valid
                    if (!$("#notifySize option:selected").length) {
                        if ($("#notifySize option")[0]) {
                            $("#notifySize option")[0]['selected'] = true
                        }
                    } else {
                        $('#Matrix2').val($('#notifySize').val());
                    }

                    //## Ensure Notify link is showing still and add button is removed.
                    document.getElementById("StockNotifyLink").style.display = "inline";
                    document.getElementById('buynowContainer').style.display = "none";

                });
            }
            //## update the value to match the one currently chosen
            $('#notifyColor').val($('#Matrix1').val());

            //## replace the sizes drop down with the new one.
            if ($('#notifySize').length) {
                $('#notifySize').remove();
            }
            if (window.selectionsChanged) {
                selectionsChanged();
            }
            addSizeDD();
        }

    });

    $('#productStamp a').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        showBody: " - ",
        fade: 250,
        top: -112,
        left: -95,
        //fixPNG: true,
        bodyHandler: function() {
            return $($(this).parent().siblings(".footnote").html());
        }
    });

    //## use supersleight jQuery plugin to enable transparency on the given image
    //## when the image isn't a link
    //$('.ieApplyTrans').supersleight();

    //## set up the slider functionality
    $("#productslider").easySlider({
        auto: true,
        continuous: true,
        nextText: '',
        prevText: '',
        pause: 5000,
        speed: 800,
        hideItems: true,
        containerWidth: 600
    });

    //----------------------------------------------------------------------------//

    $("#oimg").mouseleave(function() {
        $("#oimg").hide().unbind('click');
    });

    function hovers(img_x, img_y, img_w, img_h, id, nav_url) {
        $("#si_box").removeClass().addClass(id + "_img");
        $("#si_box > img").hide();
        $("#img_" + id).show();
        $("#si_box").removeClass().addClass(id + "_img");
        $("#" + id).show();
        $("#oimg")
                .css({ 'top': img_x + 'px', 'left': img_y + 'px', 'width': img_w + 'px', 'height': img_h + 'px' })
                .click(function() {
                    window.location = nav_url;
                })
                .show();
    }

    $("#oimg").hide().unbind('click');

    $("#logoLink").click(function() {
        window.location = "/";
    });


    /*
    $("#Matrix2")
    .blur(hideSizeGuide)
    .click(showSizeGuide);

    $("#Matrix2 option")
    .click(hideSizeGuide);

    $("#SizeGiudeLink")
    .mouseenter(showSizeGuide)
    .mouseleave(hideSizeGuide);
        
    function showSizeGuide() {

        $("#sizeGuide" + $("#sizeGuideId").val()).show();
    $("#ProductContent").hide();
    }

    function hideSizeGuide() {

        $("#ProductContent").show();
    $("#sizeGuide1").hide();
    $("#sizeGuide2").hide();

    }
    */

    // requires jquery.onfontresize.js
    $(document).bind("fontresize", function() {
        $sects.equalizeCols().find(".b, .bl, .br").each(function(i) {
            var thisHeight = $(this).parents(".section").height();
            $(this).height(thisHeight);
        });
    });

    var $askQ = $("#askQ")
		   .dialog({
		       bgiframe: true,
		       title: 'Ask a Question',
		       buttons: {
		           "Close": function() {
		               $(this).dialog("close");
		           }
		       },
		       width: 600,
		       autoOpen: false,
		       modal: true
		   });

    var $eFnd = $("#eFnd")
		   .dialog({
		       bgiframe: true,
		       title: 'Send an Email to a Friend',
		       buttons: {
		           "Close": function() {
		               $(this).css('position', 'absolute').dialog("close");
		           }
		       },
		       width: 600,
		       autoOpen: false,
		       modal: true
		   });

    $("#sendfriendLink").click(function() {
        $eFnd.css('position', 'relative').dialog('open');
        return false;
    });
    $("#askquestionlink").click(function() {
        $askQ.css('position', 'relative').dialog('open');
        return false;
    });

    /*
    $(function() {
    var zoomoptions = {
    zoomWidth: 265,
    zoomHeight: 300,
    xOffset: 44,
    yOffset: 0,
    position: "right",
    title: false,
    showEffect: 'show',
    hideEffect: 'fadeout',
    fadeoutSpeed: 'slow'
    };
    $(".jqzoom").jqzoom(zoomoptions);
    });
    */

    $("#friendSend").click(function() {
        if (ValidateCustomForm('TellFriendForm', 'TellFriendValidationResult')) {
            $(".errortable").hide();
            var hasError = false;
            var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

            var emailToVal = $("#FriendEmail").val();
            if (!emailReg.test(emailToVal)) {
                $("#FriendEmail").after('<span class="errortable">&nbsp;Invalid email</span>');
                hasError = true;
            }
            var emailFromVal = $("#Text1").val();
            if (!emailReg.test(emailFromVal)) {
                $("#Text1").after('<span class="errortable">&nbsp;Invalid email</span>');
                hasError = true;
            }

            if (hasError == false) {
                $("#friendSend").hide();
                $("#friendSend").after('<img src="/media/images/loading-bar-black.gif" alt="Loading" class="loading" />');

                var url = $("#formaction").val();
                var _YourName = $("#YourName").val();
                var _FriendName = $("#Text2").val();
                var Message = $("#Message").val();
                var ProductID = $("#ProductID").val();
                var MatrixColour = $("#MatrixColour").val();
                var MatrixPrice = $("#MatrixPrice").val();

                pausecomp(1000);

                $.post(url,
                  { _FriendEmail: emailToVal, _YourEmail: emailFromVal, Message: Message, MatrixPrice: MatrixPrice, MatrixColour: MatrixColour, ProductID: ProductID, _YourName: _YourName, _FriendName: _FriendName },
   	                    function(data) {
   	                        $("#friendSend").hide();
   	                        $(".loading").hide();
   	                        $("#submitFriendCell").append('<span class="errortable">&nbsp;Thanks, your email has been sent</span>');
   	                    }
                );

            }

        }
    });


    $("#questionSend").click(function() {
        if (ValidateCustomForm('AskQuestionForm', 'SendQuestionValidationResult')) {
            $(".errortable").hide();
            var hasError = false;
            var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

            var questionEmail = $("#questionEmail").val();
            if (!emailReg.test(questionEmail)) {
                $("#questionEmail").after('<span class="errortable">&nbsp;Invalid email</span>');
                hasError = true;
            }

            if (hasError == false) {
                $("#questionSend").hide();
                $("#questionSend").after('<img src="/media/images/loading-bar-black.gif" alt="Loading" class="loading" />');

                var url = $("#questionformaction").val();
                var questionName = $("#questionName").val();
                var questionTel = $("#questionTel").val();
                var questionComments = $("#questionComments").val();
                var Subject = $("#questionSubject").val();
                var ProductID = $("#questionProductID").val();
                var StockCode = $("#questionStockCode").val();
                var Validate = "false";
                var EmailTemplateName = $("#QuestionEmailTemplateName").val();
                var Recipients = $("#questionRecipients").val();

                pausecomp(1000);

                $.post(url,
                  { _name: questionName,
                      _email: questionEmail,
                      _comments: questionComments,
                      telephone: questionTel,
                      ProductID: ProductID,
                      StockCode: StockCode,
                      Subject: Subject,
                      Validate: Validate,
                      EmailTemplateName: EmailTemplateName,
                      Recipients: Recipients

                  },
   	                    function(data) {
   	                        // alert(data);
   	                        $("#questionSend").hide();
   	                        $(".loading").hide();
   	                        $("#submitQuestionCell").append('<span class="errortable">&nbsp;Success, your email has been sent</span>');
   	                    }
                );

            }

        }
    });

    $("#stockNotifySubmit").click(function() {
        if (document.getElementById("_notifyEmail").value != "") {
            $(".errortable").hide();
            var hasError = false;
            var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

            var emailToVal = $("#_notifyEmail").val();
            if (!emailReg.test(emailToVal)) {
                //$("#_notifyEmail").after('<span class="errortable">&nbsp;Invalid email</span>');
                document.getElementById("_notifyEmail").style.backgroundColor = "#ef9999";
                document.getElementById("_notifyEmail").value = "Invalid email"
                hasError = true;
            }

            if (hasError == false) {
                $("#_notifyEmail").hide();
                $("#stockNotifySubmit").hide();
                $("#_notifyEmail").after('<img src="/media/images/elements/ajax-loader.gif" alt="Loading" class="loading" />');

                var url = $("#notifyURL").val();
                var ProductID = $("#ProductID").val();
                if ($("#MatrixID")) {
                    var MatrixID = $("#MatrixID").val();
                    var MatrixColour = $("#notifyColor").val();
                    if ($("#notifySize")) {
                        var MatrixSize = $("#notifySize").val();
                    } else {
                        var MatrixSize = "";
                    }
                } else {
                    var MatrixID = "";
                    var MatrixColour = "";
                    var MatrixSize = "";
                }

                pausecomp(1000);

                $.post(url,
                  { notifyEmail: emailToVal, MatrixID: MatrixID, MatrixColour: MatrixColour, MatrixSize: MatrixSize, ProductID: ProductID },
   	                    function(data) {
   	                        $("#stockNotifySubmit").hide();
   	                        $(".loading").hide();
   	                        $("#emailLabel").hide();
   	                        $("#StockNotifyFeedback").css("background-color", "#A9F2D6");
   	                        $("#StockNotifyFeedback").css("margin-top", "4px");
   	                        $("#StockNotifyFeedback").html('<span>Success, you will be notified when we have more stock available.</span>');
   	                        $("#StockNotifyFeedback").show();
   	                    }
                );

            }

        } else {
            document.getElementById("_notifyEmail").style.backgroundColor = "#ef9999";
            document.getElementById("_notifyEmail").value = "Please enter your email"
        }
    });

    $("#_notifyEmail").click(function() {
        if ($(this).val() == "Please enter your email" || $(this).val() == "Invalid email") {
            document.getElementById("_notifyEmail").style.backgroundColor = "#FFF";
            document.getElementById("_notifyEmail").value = ""
        }
    });

});
function pausecomp(millis) {
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while (curDate - date < millis);
}

function addSizeDD() {
    //## add the new size dropdown
    if ($('#Matrix2').length && $('#notifySize').length == 0) {
        sizeDD = $('#Matrix2').clone();
        $(sizeDD).attr("id", "notifySize");
        sizeDD.appendTo('#notifySizeContainer');
        var sizeDDLen;
        var sizeObj;
        var optionTxt;
        sizeObj = document.getElementById("notifySize");

        sizeDDLen = sizeObj.options.length;
        for (i = sizeDDLen - 1; i >= 0; i--) {
            optionTxt = sizeObj.options[i].text;
            if (optionTxt.indexOf("Out of Stock") > 0) {
                // the item is out of stock, leave in place and remove the out of stock message
                sizeObj.options[i].text = optionTxt.replace(' (Out of Stock)', '');
            } else {
                sizeObj.remove(i);
            }
        }
        //## if the select length becomes 0, all items are in stock
        if (sizeObj.options.length == 0) {
            $('.btnsubmit').hide();
            $("#StockNotifyFeedback").css("background-color", "#EF9999");
            $("#StockNotifyFeedback").html('<span>All sizes are in stock.</span>');
            $("#StockNotifyFeedback").show();
        } else {
            $('.btnsubmit').show();
            $("#StockNotifyFeedback").hide();

            //## setup the onchange function
            $('#notifySize').change(function() {
                if (window.selectionsChanged) {
                    $('#Matrix2').val($('#notifySize').val());
                    selectionsChanged();
                }
            });
        }

        //## update the value to match the one currently chosen
        $('#notifySize').val($('#Matrix2').val());
    } else {
        if (window.selectionsChanged) {
            selectionsChanged();
        }
    }
}

