﻿$(document).ready(function () {
    // load the large image on the product page
    largeImageModalPopup(false);

    /* Home Page How Popup : START */

    $('.popupContainer').hide();

    $('.popupHow .how').hover(
        function () {
            $('.popupContainer').show();
        },
        function () {
            $('.popupContainer').hide();
        }
    );

    /* Home Page How Popup : END */

    /* Main Nav : START */
    $('.sub-nav-item').removeClass('active');

    $('.sub-nav-item').hover(
        function () {
            $(this).addClass('active');
            $(this).find('.sub').show();
        },
        function () {
            $(this).removeClass('active');
            $(this).find('.sub').hide();
        }
    );
    /* Main Nav: END */

    /* popup subcat links : START */
    $('.browseLink').hover(
        function () {
            $('.popupContainerBrowse').show();
        },
        function () {
            $('.popupContainerBrowse').hide();
        }
    );
    $('.copyNotice').hover(
        function () {
            $('.popupContainerCopy').show();
        },
        function () {
            $('.popupContainerCopy').hide();
        }
    );
    $('.aboutLink').hover(
        function () {
            $('.popupContainerAbout').show();
        },
        function () {
            $('.popupContainerAbout').hide();
        }
    );
    $('.highlightLink').hover(
        function () {
            $('.popupContainerHighlight').show();
        },
        function () {
            $('.popupContainerHighlight').hide();
        }
    );
    /* popup subcat links : END */

    /* highlight on click event : START */

    // to tick the checkbox if the highlight text is clicked
    $('.highlightText').click(function () {
        var result = $(this).closest('.subcatResult');
        var cb = $(result).find('.scpChk');

        var pID = $(result).find('.pID').val();

        if ($(cb).attr('checked')) {
            $(cb).removeAttr('checked');
            $(result).removeClass('selected');
            updateHighlightCookie(false, pID);
        } else {
            $(cb).attr('checked', 'checked');
            $(result).addClass('selected');
            updateHighlightCookie(true, pID);
        }
    });

    // to tick the checkbox when the checkbox itself is clicked
    $('.scpChk').change(function () {
        var result = $(this).closest('.subcatResult');

        var pID = $(result).find('.pID').val();

        //alert(pID);

        if ($(this).attr('checked')) {
            $(result).addClass('selected');
            updateHighlightCookie(true, pID);

            return;
        }

        $(result).removeClass('selected');
        updateHighlightCookie(false, pID);
    });
    /* highlight on click event : END */

    /* ajax add to cart product page : START */
    $('.ProductAddToCartButton').click(function (e) {
        e.preventDefault();

        var resultImgAddedText = $('.pMessage');
        var qtyInput = $('.ProductQuantity');

        var pid = $('#pID').val();
        var vid = $('#vID').val();
        var catID = $('#cID').val();
        var catName = $('#cName').val();

        var q = $(qtyInput).val();

        if (q == null || q == NaN || q == undefined || q < 1 || isNaN(q)) {
            alert('Please select a valid quantity.');
            return;
        }

        $.ajax({
            type: "POST",
            url: "ajaxaddtocart.aspx",
            data: "productid=" + pid + "&variantid=" + vid + "&quantity=" + q + "&categoryid=" + catID + "&categoryname=" + catName,
            async: true,
            dataType: ($.browser.msie) ? "text" : "xml",
            cache: false,
            success: function (data) {
                var xml;
                if (typeof data == "string") {
                    xml = new ActiveXObject("Microsoft.XMLDOM");
                    xml.async = true;
                    xml.loadXML(data);
                } else {
                    xml = data;
                }

                var succeeded = $(xml).find('success').text() == 'true';
                var msg = $(xml).find('message').text();

                if (succeeded) {
                    $(qtyInput).val('');
					//IF ISSUES ARRISE WITH IE8, comment out lines 154, 155 and uncomment 152, 153
					//There is an issue with the way IE8 handles the $().attr('style', ''); and $().fadeOut(5500);
					$(resultImgAddedText).show();
					$(resultImgAddedText).fadeOut(5500);
                    //$(resultImgAddedText).attr('style', '');
                    //$(resultImgAddedText).fadeOut(5500);

                    $('.cartItemsAndTotal').html(msg);
                } else {
                    alert(msg);
                }
            }
        });
    });
    /* ajax add to cart product page : END */

    /* ajax add to cart : START */
    $('.EntityAddToCartButton').click(function (e) {
        e.preventDefault();

        //        var resultImgAddedText = $(this).parent().siblings('.subcatResultImg').find('.itemAdded');
        //        var qtyInput = $(this).parent().siblings('.scpLeft').find('.Quantity');

        var resultImgAddedText = $(this).parents('.subcatTable').siblings('.subcatResultImg').find('.addedSuccess');
        var resultImgAddedTextFailed = $(this).parents('.subcatTable').siblings('.subcatResultImg').find('.addedFail');
        var qtyInput = $(this).parents('.subcatTable').find('.Quantity');

        var hdnIDs = $(this).parents('.subcatTable').siblings('.scpRight');

        //        var pid = $(this).parent().find('.pID').val();
        //        var vid = $(this).parent().find('.vID').val();
        var pid = $(hdnIDs).find('.pID').val();
        var vid = $(hdnIDs).find('.vID').val();
        var catID = $('#hdnCategoryID').val();
        var catName = $('#hdnCategoryName').val();

        var q = $(qtyInput).val();

        if (q == null || q == NaN || q == undefined || q < 1 || isNaN(q)) {
            //alert('Please select a valid quantity.');
            $(qtyInput).val('');
            $(resultImgAddedTextFailed).attr('style', '');
            $(resultImgAddedTextFailed).fadeOut(5500);

            return;
        }

        $.ajax({
            type: "POST",
            url: "ajaxaddtocart.aspx",
            data: "productid=" + pid + "&variantid=" + vid + "&quantity=" + q + "&categoryid=" + catID + "&categoryname=" + catName,
            async: true,
            dataType: ($.browser.msie) ? "text" : "xml",
            cache: false,
            success: function (data) {
                var xml;
                if (typeof data == "string") {
                    xml = new ActiveXObject("Microsoft.XMLDOM");
                    xml.async = true;
                    xml.loadXML(data);
                } else {
                    xml = data;
                }

                var succeeded = $(xml).find('success').text() == 'true';
                var msg = $(xml).find('message').text();

                if (succeeded) {
					//alert('215')
					
				$(resultImgAddedText).show();
				$(resultImgAddedText).fadeOut(5500);
                    

                    $('.cartItemsAndTotal').html(msg);
                } else {
                    alert(msg);
                }
            }
        });
    });
    /* ajax add to cart : END */

    /* view larger product image : START */
    $('.largerImagePopupContainer').click(function (e) {
        e.preventDefault();
        $(this).hide();
    });

    $('.largerImagePopupContainer span.close').click(function (e) {
        $('.largerImagePopupContainer').hide();
    });

    $('.productPic').click(function (e) {
        e.preventDefault();

        largeImageModalPopup(true);
    });

    $('.viewLargerLink').click(function (e) {
        e.preventDefault();

        largeImageModalPopup(true);
    });

    //    $(window).scroll(function(e) {
    //        if ($('.largerImagePopupContainer').length > 0) {
    //            if ($('.largerImagePopupContainer').css('display') != 'none') {
    //                var h = $('.largerImagePopupContainer').height();

    //                var t = ($(window).scrollTop() + ($(window).height() / 2)) - (h / 2);

    //                $('.largerImagePopupContainer').offset({ top: t });
    //            }
    //        }
    //    });
    /* view larger product image : END */

    /* load image rollover images asap in the order they appear on the page instead of on hover : START */
    $('.subcatResultImg a img').each(function () {
        var imgpopup = $(this).parents('.subcatResultImg').find('.imgPopup');

        if (!$(imgpopup).find('.largeImage').attr('src')) {
            var pID = $(this).parents('.subcatResultImg').find('.hdnProductID').val();

            $.ajax({
                type: "POST",
                //url: "ajaxLargePopup.aspx",
                url: "ajaxMedPopup.aspx",
                data: "ProductID=" + pID,
                async: true,
                dataType: ($.browser.msie) ? "text" : "xml",
                cache: false,
                success: function (data) {
                    var xml;
                    if (typeof data == "string") {
                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        xml.async = true;
                        xml.loadXML(data);
                    } else {
                        xml = data;
                    }

                    $(imgpopup).find('.largeImage').attr('src', $(xml).find('imageurl').text());
                }
            });
        }
    });
    /* load image rollover images asap in the order they appear on the page instead of on hover  : ENED */

    /* image rollover : START */
    var tmpTop = 0;

    //$(this).find('.pHorizInside').height(150);
    //$(this).find('.pHorizFront').height(150);

    $('.subcatResultImg a img').hover(
        function () {

            $('.imgPopup').hide();

            //$(this).parents('.subcatResult').css('z-index', '2050');
            $(this).parents('.subcatResult').addClass('scrActive');
            var imgpopup = $(this).parents('.subcatResultImg').find('.imgPopup');


            if (!$(imgpopup).find('.largeImage').attr('src')) {
                var pID = $(this).parents('.subcatResultImg').find('.hdnProductID').val();
                $.ajax({
                    type: "POST",
                    //url: "ajaxLargePopup.aspx",
                    url: "ajaxMedPopup.aspx",
                    data: "ProductID=" + pID,
                    async: true,
                    dataType: ($.browser.msie) ? "text" : "xml",
                    cache: false,
                    success: function (data) {
                        var xml;
                        if (typeof data == "string") {
                            xml = new ActiveXObject("Microsoft.XMLDOM");
                            xml.async = true;
                            xml.loadXML(data);
                        } else {
                            xml = data;
                        }

                        $(imgpopup).find('.largeImage').attr('src', $(xml).find('imageurl').text());
                    }
                });
            }

            $(imgpopup).show();

            var offset = $(imgpopup).offset();

            tmpTop = offset.top;

            if (offset.top < 190) {
                $(imgpopup).offset({ top: 190 });
            } else {
                var movepixels = 0;

                if (offset.top < $(window).scrollTop()) { // image is off the top
                    //alert('image is off the top of the page by ' + ($(window).scrollTop() - offset.top) + ' pixels...');
                    movepixels = $(window).scrollTop() + 15;
                    //$(imgpopup).offset({ top: movepixels });
                } else if ((offset.top + $(imgpopup).height()) > (($(window).scrollTop() - 24) + $(window).height())) { // image is off the bottom
                    //alert('image is off the bottom of the page by ' + ((offset.top + $(imgpopup).height()) - (($(window).scrollTop() - 24) + $(window).height())) + ' pixels...');
                    movepixels = (($(window).scrollTop() - 24) + $(window).height()) - $(imgpopup).height() - 15;
                    //$(imgpopup).offset({ top: movepixels });
                } else {
                    movepixels = $(this).offset().top + 10;
                    //$(imgpopup).offset({ top: t });
                }

                if (movepixels < 190) { movepixels = 190; }

                $(imgpopup).offset({ top: movepixels });
            }

            if ($(imgpopup).hasClass('popupVert')) {
                var w = $(imgpopup).find('.largeImage').width() / 2;
                $(imgpopup).find('.pVertFront').width(w);
            } else {
                var h = $(imgpopup).find('.largeImage').height() / 2;
                $(imgpopup).find('.pHorizFront').height(h);
                $(imgpopup).find('.pHorizInside').height(h);
            }
        },
        function () {
            //$(this).parents('.subcatResult').css('z-index', '2000');
            $(this).parents('.subcatResult').removeClass('scrActive');

            var imgpopup = $(this).parents('.subcatResultImg').find('.imgPopup');
            $(imgpopup).offset({ top: tmpTop });
            tmpTop = 0;
            $(imgpopup).hide();
        }
    );
    /* image rollover : END */

    /* tell a friend popup : START */
    $('.share').click(function () {
        $('.tellAFriendPopupContainer').show();
        $('#hideOnSuccess').show();
        $('#showOnSuccess').hide();
    });

    $('.close').click(function (e) {
        e.preventDefault();
        $('.tellAFriendPopupContainer').hide();
    });

    $('.btnSubmit').click(function (e) {
        e.preventDefault();

        var email = $('#txtEmail').val();
        var friendsemail = $('#txtFriendsEmail').val();
        var message = $('#txtMessage').val();
        var copy = false;

        if ($('#cbCopy:checked').val() != undefined) {
            copy = true;
        }

        var code = $('#SecurityCode').val();

        $.ajax({
            type: "POST",
            url: "sendtellfriendemail.aspx",
            data: "txtEmail=" + email + "&txtFriendsEmail=" + friendsemail + "&txtMessage=" + message + "&cbCopy=" + copy + "&SecurityCode=" + code,
            async: true,
            dataType: ($.browser.msie) ? "text" : "xml",
            cache: false,
            success: function (data) {
                var xml;
                if (typeof data == "string") {
                    xml = new ActiveXObject("Microsoft.XMLDOM");
                    xml.async = true;
                    xml.loadXML(data);
                } else {
                    xml = data;
                }

                var succeeded = $(xml).find('success').text() == 'true';
                var msg = $(xml).find('message').text();
                var rand = Math.floor(Math.random() * 1000001)
                if (succeeded) {
                    $('#txtEmail').val('');
                    $('#txtFriendsEmail').val('');
                    $('#cbCopy:checked').val(undefined);
                    $('#SecurityCode').val('');
                    $('.imgSecurityImage').attr('src', 'Captcha.ashx?id=1&rand=' + rand);

                    $('.lblErrorMsg').text('Email(s) sent.');

                    $('#hideOnSuccess').hide();
                    $('.sentConfirmation').html(msg);
                    $('#showOnSuccess').show();

                } else {
                    $('.lblErrorMsg').text(msg);
                    $('.imgSecurityImage').attr('src', 'Captcha.ashx?id=1&rand=' + rand);
                    $('#SecurityCode').val('');
                }
            }
        });
    });
    /* tell a friend popup : END */

    // load highlights saved in the cookie
    LoadAllHighlights();
});

/* large image modal popup : START */
function largeImageModalPopup(show) {
    var largeimg = $('#popupImageURL').val();

    if (!$('.largerImage').attr('src')) {
        $('.largerImage').attr('src', largeimg);
    }

    if (show) {
        $('.largerImagePopupContainer').show();

        var w = $('.largerImage').width();
        
        $('.largerImagePopupContainer').css('width', w);

        var t = 22;  //$('.pImage').offset().top + $(window).scrollTop() - 40;

        $('.largerImagePopupContainer').offset({ top: t });
    }
}
/* large image modal popup : END */

/* highlight cookie : START */
function updateHighlightCookie(addToCookie, pID) {
    var highlightarr = new highlights("pcshighlights", pID);

    if (addToCookie) {
        highlightarr.add(pID);
    } else {
        highlightarr.remove(pID);
    }
}

var highlights = function (cookieName, pID) {

    var catID = $('#hdnCategoryID').val();
    var ck = $.cookie(cookieName);
    var items = ck.length > 0 ? ck.split(/,/) : new Array();

    return {
        "add": function (val) {
            var found = false;

            $.each(items, function () {
                if ($(this)[0] == (catID + '|' + val)) {
                    found = true;
                }
            });

            if (!found) {
                items.push(catID + '|' + pID);
                $.cookie(cookieName, items);
            }
        },
        "clear": function () {
            $.cookie(cookieName, null);
        },
        "items": function () {
            return items;
        },
        "remove": function (val) {
            var tmpItems = new Array();

            $.each(items, function () {

                var t = $(this)[0].split('|');

                if (t[0] == catID && t[1] == val) {
                    // nothing...this is the one we want removed
                } else {
                    tmpItems.push(t[0] + '|' + t[1]);
                }
            });

            items = tmpItems;
            $.cookie(cookieName, items);
        }
    }
}

/* highlight cookie : END */

/* highlight on page load : START */
function LoadAllHighlights() {
    var ck = $.cookie('pcshighlights');
    var items = ck.length > 0 ? ck.split(/,/) : new Array();

    var catID = $('#hdnCategoryID').val();

    $.each(items, function () {
        var t = $(this)[0].split('|');

        if (t[0] == catID) {
            var result = $('.subcatResult_' + t[1]);
            $(result).addClass('selected');
            $(result).find('.scpChk').attr('checked', 'checked');
        }
    });
}
/* highlight on page load : END */



