/* --------------------------------------- */
/*  Argyle Distributors - In Page JS Code  */
/*  Ver          : 2.6                     */
/*  Created      : 2 Aug 2011              */
/*  Last Updated : 9 Feb 2012              */
/* --------------------------------------- */

/*------------------*/
/* Table of Content */
/*------------------*/

/*
1. Functions
1.1. Simple Image Rotator
1.2. Content Rotator Type I
1.3. Content Rotator Type II
1.4. Function Adjust Featured Products Arrow Position
1.5. Content Carousel
1.6. Text Box Functions
1.7. Point Wheel Functions

2. Document Ready Functions
2.1.  Activate JS Elements
2.2.  Display Carousel Slider
2.3.  Argyle 360 Images Rotating Heading
2.4.  Featured Products Nav Selected state
2.5.  My Argyle Point Wheel
2.6.  Setup any uncheck all buttons
2.7.  Accordion Area
2.8.  New Shopping List Code
2.9.  Add To Favourites Code
2.10. Product category heading on Place an Order Page

3. Window Load Functions
3.1. Set up the password box
3.2. Home Slider Trigger and Set up
3.3. Carousel Triggers
3.4. Jqzoom Trigger
3.5. Alternative Product Image Trigger
*/

/*--------------*/
/* 1. Functions */
/*--------------*/

// 1.1. Simple Image Rotator

function slideShow(slideContainer, slideTiming) {
    var $slider = $(slideContainer),
        $activeSlide = "",
        $nextToActive = "",
        slideTiming = slideTiming;

    setInterval(
        function () {
            $activeSlide = $slider.find(".active-slide");

            if ($activeSlide.hasClass("last")) {
                $nextToActive = $slider.find(".first");
            } else {
                $nextToActive = $activeSlide.next();
            }

            $activeSlide.fadeOut(2000, function () {
                $(this).removeClass("active-slide");
            });

            $nextToActive.fadeIn(2000).addClass("active-slide");
        }
        , slideTiming);
}

// 1.2. Content Rotator Type I

function contentRotatorType1(contentContainer, navContainer) {
    var $contentContainer = $(contentContainer),
        $navContainer = $(navContainer),
        $navItem = $(navContainer + " a"),
        currIndex = 0,
        modIndex = 0;

    // Display current active item
    $contentContainer.find("li.active").show();

    // Setting the panel index
    $(contentContainer + '>li').each(function (index) {
        modIndex = index + 1;
        $(this).addClass("panel-item panel-" + modIndex);
    });

    // If a nav item is clicked
    $navItem.live("click", function () {

        // Get the index of clicked item
        currIndex = $navItem.index(this) + 1;

        // Remove selected class from current selected item
        $navContainer.find("li.selected").removeClass("selected");

        // Add selected class to the clicked item
        $(this).parent().addClass("selected");

        // Fade out current active item
        $contentContainer.find("li.active").removeClass("active").fadeOut(400, function () {
            $(this).parent().find("li.panel-" + currIndex).fadeIn(400, function () {
                $(this).addClass("active");
            });
        });

        // Custom Functions
        if ($("div.home-featured-products").length) {
            adjustSelectedState();
        }

        // Preventing default behaviour
        return false;
    });
}

// 1.3. Content Rotator Type II

function contentRotatorType2(slideContainer, slideTiming, sliderNavPosRef, sliderNavContainerName) {
    var i = 0,
        defIndex = 1,
        $slider = $(slideContainer),
        sliderNav = "",
        selectedIndex = "",
        numOfSlide = $slider.children().size(),
        slideTiming = slideTiming,
        sliderNavContainerName = sliderNavContainerName;

    // Setting up the slider navigation
    for (i = 1; i <= numOfSlide; i++) {
        if (i > 1) {
            sliderNav = sliderNav + "<a href='#' class='sliderIndexNav'>" + i + "</a>";
        } else {
            sliderNav = sliderNav + "<a href='#' class='sliderIndexNav selected'>1</a>";
        }
    };

    sliderNav = "<div class='" + sliderNavContainerName + " sliderNavContainer'><div class='slider-nav-wrapper'><span class='sliderNav'>" + sliderNav + "</span></div></div>";

    $(sliderNav).insertAfter(sliderNavPosRef);

    // hide content of slider 2 above
    $(slideContainer + " li:gt(0)").hide();

    // set automatic sliding
    var timer = setInterval(function () { autoSliding(slideContainer, numOfSlide, sliderNavContainerName); }, slideTiming);

    // if navigation being clicked
    $("div." + sliderNavContainerName + " span.sliderNav a.sliderIndexNav").live("click", function () {
        var $thisElement = $(this);

        if ($thisElement.hasClass("selected")) {
            return false;
        } else {
            // update the class in navigation
            $thisElement.parent().find(".selected").removeClass("selected");
            $thisElement.addClass("selected");

            // get the index from the navigation
            selectedIndex = $thisElement.html();

            // update the active status on the slider
            $slider.find(".active").fadeOut(2000).removeClass("active");

            // display the coressponding slide
            $slider.children("'li:eq(" + (parseInt(selectedIndex) - 1).toString() + ")'").addClass("active").fadeIn(2000);

            // reset the interval
            clearInterval(timer);
            timer = setInterval(function () { autoSliding(slideContainer, numOfSlide, sliderNavContainerName); }, slideTiming);
        }

        return false;
    });
}

function autoSliding(slideContainer, numOfSlide, sliderNavContainerName) {
    var $slider = $(slideContainer),
        numOfSlide = numOfSlide,
        sliderNavContainerName = sliderNavContainerName;

    // Get the current slider index
    var $selectedSliderNav = $("div." + sliderNavContainerName + " span.sliderNav").find(".selected");

    selectedIndex = $selectedSliderNav.html();
    selectedIndex = parseInt(selectedIndex) + 1;

    // Update the selected status on the navigation
    if (selectedIndex > numOfSlide) {
        selectedIndex = 1;
        $selectedSliderNav.removeClass("selected");
        $("div." + sliderNavContainerName + " span.sliderNav").children("'a:eq(" + (parseInt(selectedIndex) - 1).toString() + ")'").addClass("selected");
    } else {
        $selectedSliderNav
            .removeClass("selected")
            .next()
            .addClass("selected");
    }

    // Update the active status on the slider
    $slider.find(".active").fadeOut(2000).removeClass("active");

    // Display the coressponding slide
    $slider.children("'li:eq(" + (parseInt(selectedIndex) - 1).toString() + ")'").addClass("active").fadeIn(2000);
};

// 1.4. Function Adjust Featured Products Arrow Position

function adjustSelectedState() {
    var $navLinkSelContainer = $("ul.featured-products-nav li.selected"),
        navLinkWidth = $navLinkSelContainer.width(),
        navLinkArrowLeftPos = Math.round((parseInt(navLinkWidth) - 20) / 2);

    $navLinkSelContainer.find("span.arrow").css("left", navLinkArrowLeftPos + "px");
}

// 1.5. Content Carousel

function contentCarousel(carouselContainer, visibleDisplayItem, animationSpeed) {
    var $carouselContainer = $(carouselContainer),
        $carouselSlider = $carouselContainer.find("ul.carousel-slider"),
        $carouselSliderLi = $(carouselContainer + " ul.carousel-slider>li"),
        carouselVisibleItem = parseInt(visibleDisplayItem),
        carouselItemAmount = $carouselSliderLi.size(),
        carouselSliderLiWidth = $carouselSliderLi.outerWidth(true),
        carouselSliderWidth = carouselItemAmount * carouselSliderLiWidth,
        carouselDisplayAreaWidth = carouselSliderLiWidth * carouselVisibleItem,
        carouselNavMarkUp = "<a class='carousel-btn carousel-btn-left'>&laquo;</a><a class='carousel-btn carousel-btn-right'>&raquo;</a>",
        carouselCurrPos = 0,
        carouselNewPos = 0,
        animationSpeed = animationSpeed,
        isAnimated = false;

    // Set up the navigation
    $carouselContainer.append(carouselNavMarkUp);

    var $carouselBtn = $carouselContainer.find("a.carousel-btn"),
        $carouselLeftBtn = $carouselContainer.find("a.carousel-btn-left"),
        $carouselRightBtn = $carouselContainer.find("a.carousel-btn-right");

    // Set the width and initial position of the carousel slider
    $carouselSlider.
        css("width", carouselSliderWidth).
        css("left", "0px");

    // Set the state of scroll buttons
    carouselCurrPos = parseInt($carouselSlider.css("left"));

    if (carouselCurrPos == 0) {
        $carouselLeftBtn.
            css("opacity", "0.5").
            css("cursor", "default");
    }

    if ((carouselSliderWidth + carouselCurrPos) <= (carouselVisibleItem * carouselSliderLiWidth)) {
        $carouselRightBtn.
            css("opacity", "0.5").
            css("cursor", "default");
    }

    // When a navigation button is clicked
    $carouselBtn.live("click", function () {

        if (isAnimated == false) {
            // Set animation status to true to avoid the effect of mulitple clicking
            isAnimated = true;

            // Calculate the slider transition
            if ($(this).hasClass("carousel-btn-left")) {
                // Left Button
                if (carouselCurrPos == 0) {
                    carouselNewPos = 0;
                } else {
                    carouselNewPos = carouselCurrPos + carouselDisplayAreaWidth;
                }
            }
            else {
                // Right  Button
                if ((carouselSliderWidth + carouselCurrPos) <= (carouselVisibleItem * carouselSliderLiWidth)) {
                    carouselNewPos = carouselCurrPos;
                } else {
                    carouselNewPos = carouselCurrPos - carouselDisplayAreaWidth;
                }
            }

            // Animate the slider transitition
            $carouselSlider.animate({
                left: carouselNewPos + "px"
            }, animationSpeed, function () {

                // set the animated status
                isAnimated = false;

                // set the state of scroll buttons
                carouselCurrPos = parseInt($carouselSlider.css("left"));

                if (carouselCurrPos == 0) {
                    $carouselLeftBtn.
                        css("opacity", "0.5").
                        css("cursor", "default");
                } else {
                    $carouselLeftBtn.
                        css("opacity", "1").
                        css("cursor", "pointer");
                }

                if ((carouselSliderWidth + carouselCurrPos) <= (carouselVisibleItem * carouselSliderLiWidth)) {
                    $carouselRightBtn.
                        css("opacity", "0.5").
                        css("cursor", "default");
                } else {
                    $carouselRightBtn.
                        css("opacity", "1").
                        css("cursor", "pointer");
                }
            });
        }

        return false;
    });
}

// 1.6. Text Box Functions
function blurTextBox(input, text) {
    if (input.value == "") {
        input.value = text;
    }
}

function focusTextBox(input, text) {
    if (input.value == text) {
        input.value = "";
    } else {
        input.select();
    }
}

// 1.7. Point Wheel Functions

function activatePointWheelNA(wheelType) {
    
    /* Init */
    var wType         = wheelType,
        deficit       = 0,
        digitPosition = 7,
        blankImg      = "",
        extension     = "";

    switch (wType) {
        case "small":
            var $wheelContainer = $("div.wheel-small div.wheel-container"),
                $wheelDigit = $("div.wheel-small div.wheel-container span.digit"),				
                pointToDisplay = $("div.wheel-small>span.point").html(),
                blankImg = "img/empty-sm.gif",
                extension = "-sm.gif";;
            break;

        default:
            var $wheelContainer = $("div.wheel div.wheel-container"),
                $wheelDigit = $("div.wheel div.wheel-container span.digit"),                
                pointToDisplay = $("div.wheel>span.point").html(),
                blankImg = "img/empty.gif",
                extension = ".gif";
    }
    
    /* Standardize the format of the point */

    // Check if the number of character is 8
    if ((pointToDisplay.length) != 8) {
        // Check the deficit
        deficit = 8 - (pointToDisplay.length);

        // Adding extra character to make it 8 characters
        for (i = 1; i <= deficit; i++) {
            pointToDisplay = "_" + pointToDisplay;
        }
    }		
    
    // Replacing each Digit 	
    for (i = 7; i >= 0; i--) {
    
        switch (pointToDisplay.charAt(i)) {
            case '_':
                $wheelContainer.find('span.digit-' + i.toString()).
                    find('img').
                    attr('src', blankImg).
                    attr('alt', " ");						
                break;
            default:
                $wheelContainer.find('span.digit-' + i.toString()).
                    find('img').
                    attr('src', 'img/' + pointToDisplay.charAt(i) + extension).
                    attr('alt', pointToDisplay.charAt(i));				
        }						
    }			    
}

function activatePointWheel(wheelType) {
    
    /* Init */
    var wType = wheelType,
        deficit = 0,
        digitPosition = 7;

    switch (wType) {
        case "small":
            var $wheelContainer = $("div.wheel-small div.wheel-container"),
                $wheelDigit = $("div.wheel-small div.wheel-container span.digit"),
                wCounterImg = "img/wheel-counter-sm.gif",
                pointToDisplay = $("div.wheel-small>span.point").html();
            break;

        default:
            var $wheelContainer = $("div.wheel div.wheel-container"),
                $wheelDigit = $("div.wheel div.wheel-container span.digit"),
                wCounterImg = "img/wheel-counter.gif",
                pointToDisplay = $("div.wheel>span.point").html();
    }

    /* Activate Wheel */

    $wheelDigit.each(function () {
        $(this).find("img").
            attr("src", wCounterImg).
            attr("alt", "counting");
    });

    /* Standardize the format of the point */

    // Check if the number of character is 8
    if ((pointToDisplay.length) != 8) {
        // Check the deficit
        deficit = 8 - (pointToDisplay.length);

        // Adding extra character to make it 8 characters
        for (i = 1; i <= deficit; i++) {
            pointToDisplay = "_" + pointToDisplay;
        }
    }

    // Replacing each digit on the pointToDisplay String
    setTimeout("replaceDigit(" + digitPosition + ",'" + pointToDisplay + "','" + wType + "')", 1000);		
}

function replaceDigit(digitPosition, pointToDisplay, wheelType) {

    var wType = wheelType,
        delay = 1000;        

    switch (wType) {
        case "small":
            var $wheelContainer = $("div.wheel-small div.wheel-container"),
                blankImg = "img/empty-sm.gif",
                extension = "-sm.gif";
            break;
        default:
            var $wheelContainer = $("div.wheel div.wheel-container"),
                blankImg = "img/empty.gif",
                extension = ".gif";
    }

    switch (pointToDisplay.charAt(digitPosition)) {
        case '_':
            $wheelContainer.find('span.digit-' + digitPosition.toString()).
                find('img').
                attr('src', blankImg).
                attr('alt', " ");
            digitPosition--;
            delay = 0;
            break;
        default:
            $wheelContainer.find('span.digit-' + digitPosition.toString()).
                find('img').
                attr('src', 'img/' + pointToDisplay.charAt(digitPosition) + extension).
                attr('alt', pointToDisplay.charAt(digitPosition));
            digitPosition--;
            delay = 1000;
    }

    if (digitPosition < 0) return // exit condition
    setTimeout("replaceDigit(" + digitPosition + ",'" + pointToDisplay + "','" + wType + "')", delay);
}

/*-----------------------------*/
/* 2. Document Ready Functions */
/*-----------------------------*/

$(document).ready(function () {
    
    // Temp code for development purpose
    
    /*
    $("div.my-argyle").attr("class", "grand-wrapper my-argyle royal");
    $("a.logo").find("img").attr("src", "/argyle/img/logo-mar.png");
    $("div.header-bg").find("img").attr("src", "/argyle/img/bg-mar-header-2.jpg");
    */
    
    // 2.1. Activate JS Elements
    $("body").addClass("js");

    // 2.2. Display Carousel Slider
    $("ul.carousel-slider").show();

    // 2.3. Argyle 360 Images Rotating Heading
    if ($("h1.argyle-360").length) {

        var $heading = $("h1.argyle-360"),
            slideShowMarkUp = "<img src='img/heading-argyle-360-01.jpg' alt='Argyle 360' class='first active-slide'/>" +
                              "<img src='img/heading-argyle-360-02.jpg' alt='Argyle 360' />" +
                              "<img src='img/heading-argyle-360-03.jpg' alt='Argyle 360' />" +
                              "<img src='img/heading-argyle-360-04.jpg' alt='Argyle 360' class='last'/>";

        // Preparing the DOM
        $heading.wrap("<div class='visual-container' />")
                .after(slideShowMarkUp)
                .hide();

        // Running the slideshow
        slideShow("div.visual-container", 4000);
    }

    // 2.4. Featured Products Nav Selected state
    adjustSelectedState();

    // 2.5. My Argyle Point Wheel
        
    if ($("div.small-wheel-area").length) {
        
        // Get the Cookie for small wheel
        var bSmallWheelPlayed = $.cookie('smallWheelPlayed');
        
        if (bSmallWheelPlayed == "1") {
            // Trigger Wheel With No Animation
            activatePointWheelNA("small");			
        }
        else {
            // Trigger Wheel
            activatePointWheel("small");
        }
        
        // create cookie for small wheel played status
        $.cookie('smallWheelPlayed', '1', { path: '/' });
    }

    if ($("div.home-point-wheel").length) {
        
        // Get the Cookie for home page wheel
        var HomePgWheelPlayed = $.cookie('HomePgWheelPlayed');
        
        if (HomePgWheelPlayed == "1") {
            // Trigger Wheel With No Animation
            activatePointWheelNA();			
        }
        else {
            // Trigger Wheel
            activatePointWheel();
        }
        
        // create cookie for home page wheel played status
        $.cookie('HomePgWheelPlayed', '1', { path: '/' });
    }
    
    if ($("div.point-pg-point-wheel").length) {
        
        // Get the Cookie for point page wheel
        var PointPgWheelPlayed = $.cookie('PointPgWheelPlayed');
        
        if (PointPgWheelPlayed == "1") {
            // Trigger Wheel With No Animation
            activatePointWheelNA();			
        }
        else {
            // Trigger Wheel
            activatePointWheel();
        }
        
        // create cookie for point page wheel played status
        $.cookie('PointPgWheelPlayed', '1', { path: '/' });
    }
    
    // 2.6. Setup any uncheck all buttons
    
    $('#uncheck-all').click(function () {
        $('input:checkbox').removeAttr('checked');
    })

    // 2.7. Accordion Area
    if ($("div.accordion-area").length) {

        // Change the arrow in Tab heading to right arrow
        $("div.tab-heading img.arrow")
            .removeClass("arrow-down")
            .addClass("arrow-right")
            .attr("src", "img/arrow-right.png")
            .attr("alt", "Arrow Right");

        // Open the first Accordion and update the arrow state
        $("div.accordion-area:first div.accordion-tab:first-child")
            .find("div.tab-content")
            .css("display", "block")
            .prev()
            .find("img.arrow")
            .removeClass("arrow-right")
            .addClass("arrow-down")
            .attr("src", "img/arrow-down.png")
            .attr("alt", "Arrow Down");

        // Accordion Toggle Control
        var $accordionTabHeading = $("div.accordion-tab div.tab-heading");

        $accordionTabHeading.live("click", function () {

            var $e = $(this),
                $imgArrow = $e.find("img.arrow");

            // Update the arrow state
            if ($imgArrow.hasClass("arrow-down")) {
                $imgArrow.removeClass("arrow-down")
                .addClass("arrow-right")
                .attr("src", "img/arrow-right.png")
                .attr("alt", "Arrow Right");
            } else {
                $imgArrow.removeClass("arrow-right")
                .addClass("arrow-down")
                .attr("src", "img/arrow-down.png")
                .attr("alt", "Arrow Down");
            }

            // Toggle the accordion part
            $e.next().slideToggle();
        });
    }

    // 2.8. New Shopping List Code

    $("#SaveShoppingListButton").click(function () {
        $("div[ID$='SaveShoppingListPanel']").show();
        $("#SaveShoppingListButtonPanel").hide();
    });

    // 2.9. Add To Favourites Code

    $(".add-to-fave-btn").click(function () {
        $(this).hide();
        $(this).next().next().show();
    });
	
	// 2.10. Product category heading on Place an Order Page
	$("h2.prod-category-hd a").live("click", function() {
		var $e = $(this);
			isAnimated = false;
		
		if (isAnimated == false) {
			
			isAnimated = true;
			
			if ($e.hasClass("expanded")) {
				$e.removeClass("expanded").parent().next().children().slideUp("fast", function(){
					isAnimated = false;
				});
			}
			else {
				$e.addClass("expanded").parent().next().children().slideDown("fast", function() {
					isAnimated = false;
				});
			}
		}
	});
});

/*--------------------------*/
/* 3. Window Load Functions */
/*--------------------------*/

$(window).load(function () {
    // 3.1. Set up the password box
    var passwordField = $("div.login-area input[ID$='Password']");

    if (passwordField.length) {
        if (passwordField.val().length > 0) {
            passwordField.css('background-image', 'none');
        } else {
            passwordField.css('background-image', 'url(\'img/password_bg.gif\')');
        }
        passwordField.blur(function () {
            if ($(this).val().length > 0) {
                $(this).css('background-image', 'none');
            } else {
                $(this).css('background-image', 'url(\'img/password_bg.gif\')');
            }
        });
        passwordField.focus(function () {
            $(this).css('background-image', 'none');
        });
    }

    // 3.2. Home Slider Trigger and Set up
    if ($("div.home-slider-area").length) {
        contentRotatorType2("ul.slider", 10000, "div.home-slider-area", "homeSliderNavCont");

        // Get nav-container computed width and center aligned it
        $(".homeSliderNavCont span.sliderNav")
            .css("width", $("div.homeSliderNavCont span.sliderNav").width())
            .css("margin", "0px auto")
            .css("display", "block");

        // Remove the padding of Featured Products area
        $("div.featured-products").css("padding-top", "0");
    }

    // 3.3. Carousel Triggers
    if ($("div.home-featured-products").length) {

        // Carousel Category Nav Trigger
        contentRotatorType1("ul.featured-products-display", "ul.featured-products-nav");

        // Carousel Triggers ....
        contentCarousel("div.overalls-carousel-container", 5, 200);
        contentCarousel("div.footwear-carousel-container", 5, 200);
        contentCarousel("div.food-industry-carousel-container", 5, 200);
        contentCarousel("div.hi-visibility-carousel-container", 5, 200);
        contentCarousel("div.apparel-carousel-container", 5, 200);
        contentCarousel("div.rainwear-carousel-container", 5, 200);
        contentCarousel("div.accessories-carousel-container", 5, 200);
    }

    // 3.4. Jqzoom Trigger

    if ($("a.product-img").length) {
        $('a.product-img').jqzoom({
            zoomType: 'innerzoom',
            lens: true,
            preloadImages: true,
            alwaysOn: false,
            zoomWidth: 300,
            zoomHeight: 250,
            xOffset: 90,
            yOffset: 30,
            position: 'left'
        });
    }

    // 3.5. Alternative Product Image Trigger
    if ($("div.alternative-product-img").length) {

        // style set up
        $("ul.product-img-list li").
            css("position", "absolute").
            css("top", "0").
            css("left", "0").
            css("display", "none");

        // Trigger Content Rotator Type 1
        contentRotatorType1("ul.product-img-list", "ul.alt-prod-nav");
    }

});
