$(function () {
    var itemAmount = $('.itemAmount').text();
    var itemAmountInteger = parseInt(itemAmount);
    if (itemAmountInteger >= 20) { $('.itemAmount').css('left', '82px'); }

    $(".homeProducts .stubbiesProduct:eq(3), .homeProducts .stubbiesProduct:eq(7), .listingProducts .stubbiesProduct:nth-child(5n), .mightLike .stubbiesProduct:eq(1), .mightLike .stubbiesProduct:eq(3), .recentlyViewed .stubbiesProduct:eq(1), .recentlyViewed .stubbiesProduct:eq(3)").css("margin", "0 0 19px 0");
    $(".stockists li:nth-child(3n)").css("margin", "19px 0 0 0");

    if ($.browser.msie) { $(".stubbiesProductOverlay, .productOverlay").css("height", "163px").hide() }
    else { $(".stubbiesProductOverlay, .productOverlay").hide().fadeTo("0", "0").css("height", "163px").show(); }

    $(".checkoutProgress:eq(2)").css("background", "none");
    //$("#standardContent .contentRight").append("<div class=\"stubbieKids\"></div>");

    $('.testimonials li:odd').find('img.quoteLeft').attr('src', '/images/testimonials/greenQuoteLeft.png');
    $('.testimonials li:odd').find('img.quoteRight').attr('src', '/images/testimonials/greenQuoteRight.png');
    $('.testimonials li:odd').find('.speechLeft').attr({ 'class': 'speechRight', 'src': '/images/testimonials/speechRight.png' });

    var rightColumnHeight = $(".listingProducts").height();
    $(".listingRight").css("height", rightColumnHeight + 108);

    $(".contentBanner").find("img").parent().append("<div class=\"imageOverlay\"></div>");

    $(".stubbiesProduct, .listingProducts .stubbiesProduct a").hover(function () {
        if ($.browser.msie) { $(this).children(".stubbiesProductOverlay, .productOverlay").show(); }
        else { $(this).children(".stubbiesProductOverlay, .productOverlay").stop().animate({ opacity: "1" }, 300); }
    }, function () {
        if ($.browser.msie) { $(this).children(".stubbiesProductOverlay, .productOverlay").hide(); }
        else { $(this).children(".stubbiesProductOverlay, .productOverlay").stop().animate({ opacity: "0" }, 600); }
    });

    $(".overlayNewsletter > a").click(function () {
        $("div.overlayNewsletter").fadeOut(500);
        $("fieldset.joinForm").fadeIn(500);
        return false;
    });

    $(".colourFilter li a").hover(function () {
        if ($(".allColours").is(":checked")) { return false; }
        else {
            $(this).css({
				"z-index" : "5",
				"margin" : "-4px 0 0 -4px"
			}).stop().animate({ 
				'border': '4px solid #fff' 
			}, 150);
        }
    }, function () {
        $(this).css({
				"z-index" : "0",
				"margin" : "0"
			}).stop().animate({ 
				'border': '0' 
			}, 0);
    });

    $(".allColours").click(function () {
        if ($(this).is(":checked")) {
            $(".colourFilter a").animate({ opacity: "0.2" }, 250);
            $(".enabled").removeClass("enabled");
            $(".colourFilter").find("a.selected").removeClass("selected");

            $("#" + selectedColour).html("");
            $("#" + hdColourId).val("");
            $("#" + hdColourTitle).val("");
        }
        else {
            $(".colourFilter a").animate({ opacity: "1" }, 250);
            $(".colourFilter").addClass("enabled");
        }
    });
    $(".colourFilter li a").click(function () {
        if ($(".allColours").is(":checked")) { return false; }
        else {
            $(".colourFilter").find("a.selected").removeClass("selected");
            $(this).addClass("selected");

            var url = $(this).attr('href');
            var query = url.split('?');
            var dim = query[1].split('&');

            var chosenColourId = dim[0].split('=')[1];
            var chosenColourCode = dim[1].split('=')[1];
            var chosenColourTitle = $(this).html();

            $("#" + selectedColour).html(chosenColourTitle);
            $("#" + hdColourId).val(chosenColourId);
            $("#" + hdColourTitle).val(chosenColourCode);

            return false;
        }
    });

    // Product Reviews
    var rated = false;
    $('.yourRating .ratings_stars').hover(
        function () {
            if (!rated) {
                $(this).prevAll().andSelf().addClass('ratings_over');
                $(this).nextAll().removeClass('ratings_vote');
            }
        },
       	function () {
       	    if (!rated) {
       	        $(this).prevAll().andSelf().removeClass('ratings_over');
       	        //set_votes($(this).parent());
       	    }
       	}
    );

    $('.yourRating .ratings_stars').click(function (event) {
        var accountId = $('#' + productReviewIds.hfAccountId).val();
        if (accountId == '0') {
            $('#ratingLogin').fadeIn('2000');
            return;
        }
        var productId = $("#hdProductId").val();
        var rating = $(this).attr('class').split(' ')[0].split('_')[1];
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/Services/CartService.asmx/AddRating',
            dataType: 'json',
            data: '{"ProductId": "' + productId + '", "AccountId": "' + accountId + '", "Rating": "' + rating + '"}',
            complete: function () {
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr + ' (' + thrownError + ')');
            },
            success: function (result) {
                if (result == -1) {
                    $('#alreadyVoted').fadeIn('slow', function () { $(this).fadeOut(5000); });
                } else {
                    // Product Rank
                    $('span', '.overallRating').removeClass('ratings_over');
                    if (result >= 1)
                        $('#' + productReviewIds.lblRankStar1, '.overallRating').addClass('ratings_over');
                    if (result >= 2)
                        $('#' + productReviewIds.lblRankStar2, '.overallRating').addClass('ratings_over');
                    if (result >= 3)
                        $('#' + productReviewIds.lblRankStar3, '.overallRating').addClass('ratings_over');
                    if (result >= 4)
                        $('#' + productReviewIds.lblRankStar4, '.overallRating').addClass('ratings_over');
                    if (result >= 5)
                        $('#' + productReviewIds.lblRankStar5, '.overallRating').addClass('ratings_over');
                }
                // User Rank
                if (rating >= 1)
                    $('#' + productReviewIds.lblRateStar1, '.yourRating').addClass('ratings_over');
                if (rating >= 2)
                    $('#' + productReviewIds.lblRateStar2, '.yourRating').addClass('ratings_over');
                if (rating >= 3)
                    $('#' + productReviewIds.lblRateStar3, '.yourRating').addClass('ratings_over');
                if (rating >= 4)
                    $('#' + productReviewIds.lblRateStar4, '.yourRating').addClass('ratings_over');
                if (rating >= 5)
                    $('#' + productReviewIds.lblRateStar5, '.yourRating').addClass('ratings_over');
                $('#' + productReviewIds.pnlUserRating).removeClass('yourRating').addClass('finalRating');
                rated = true;
            }
        });
    });

    $('.finalRating').click(function () {
        $('#alreadyVoted').fadeIn('slow', function () { $(this).fadeOut(5000); });
    });

    $(".productTechnology h3").after("<span class=\"techArrow\"><img src=\"/images/productDetail/techArrow.png\" width=\"12\" height=\"8\"></span>");
    $(".productTechnology ul li").hover(function () {
        var itemHovered = $(this).index();
        var tooltipArrow = $(".productTechnology .techArrow").stop();

        $(this).children(".techTooltip").show();
        $(".productTechnology .techArrow").show();

        if (itemHovered > 4) { $(".productTechnology .techArrow").css("top", "126px"); $(".productTechnology .techTooltip").css("top", "139px") }
        else { $(".productTechnology .techArrow").css("top", "67px"); $(".productTechnology .techTooltip").css("top", "80px") }

        if (itemHovered == 0) { tooltipArrow.animate({ left: '17px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 1) { tooltipArrow.animate({ left: '72px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 2) { tooltipArrow.animate({ left: '127px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 3) { tooltipArrow.animate({ left: '182px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 4) { tooltipArrow.animate({ left: '237px' }, { duration: 500, easing: "easeOutBack" }); }

        if (itemHovered == 5) { tooltipArrow.animate({ left: '17px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 6) { tooltipArrow.animate({ left: '72px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 7) { tooltipArrow.animate({ left: '127px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 8) { tooltipArrow.animate({ left: '182px' }, { duration: 500, easing: "easeOutBack" }); }
        if (itemHovered == 9) { tooltipArrow.animate({ left: '237px' }, { duration: 500, easing: "easeOutBack" }); }

    }, function () {
        $(this).children(".techTooltip").hide();
        $(".productTechnology .techArrow").hide();
    });

    $(".deliveryHover").hover(function () { $(".deliveryTooltip").show(); }, function () { $(".deliveryTooltip").hide(); });
    $(".gstHover, .countryHover, .whatisThis").hover(function () { $(".gstTooltip").show(); }, function () { $(".gstTooltip").hide(); });
    //When you click on a link with class of poplight and the href starts with a # 
    $('a.sizingChart[href^=#], a.homeSizingChart[href^=#]').click(function () {
        var popID = $(this).attr('rel'); //Get Popup Name
        var popURL = $(this).attr('href'); //Get Popup href to define size

        //Pull Query & Variables from href URL
        var query = popURL.split('?');
        var dim = query[1].split('&');
        var popWidth = dim[0].split('=')[1]; //Gets the first query string value

        //Fade in the Popup and add close button
        $('#' + popID).fadeIn().css({ 'width': Number(popWidth) }).prepend('<a href="#" class="close"><img src="/images/productDetail/closeThis.png" class="btn_close" title="Close Window" alt="Close" /></a>');

        //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
        var popMargTop = ($('#' + popID).height() + 80) / 2;
        var popMargLeft = ($('#' + popID).width() + 80) / 2;

        //Apply Margin to Popup
        $('#' + popID).css({
            'margin-top': -popMargTop,
            'margin-left': -popMargLeft
        });

        //Fade in Background
        $('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
        $('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 

        return false;
    });

    //Close Popups and Fade Layer
    $('a.close, #fade').live('click', function () { //When clicking on the close or fade layer...
        $('#fade , .sizeBox').fadeOut(function () {
            $('#fade, a.close').remove();  //fade them both out
        });
        return false;
    });

    $('a.skipToAdults').click(function () {
        var boxHeight = $("div.children").height();
        $(".sizeChartsInner").animate({ scrollTop: boxHeight - 3 }, 1500);
    });
    $('a.backToTop').click(function () { $(".sizeChartsInner").animate({ scrollTop: 0 }, 1500); });

    $('.faqContainer').hide(); //Hide/close all containers
    $('.contentRight').find('.active').removeClass('active');
    $('.faqTrigger:first').addClass('active').next().show(); //Add "active" class to first trigger, then show/open the immediate next container

    //On Click
    $('.faqTrigger').click(function () {
        $('.faqTrigger').find('.active').removeClass('active');
        $(this).toggleClass('active').next().slideToggle();
        return false; //Prevent the browser jump to the link anchor
    });

    $(".paymentType input:radio").change(function () {
        if ($("input:radio:checked").val() == 'pp') {
            $(".ccDetails, .orderSubmit").hide();
            $(".paypal").show();
        }
        else {
            $(".ccDetails, .orderSubmit").show();
            $(".paypal").hide();
        }
    });

    var $payType = $('.paymentType input:radio');
    if ($payType.is(':checked') === false) {
        $payType.filter('[value=cc]').attr('checked', true);
    }

    $('a.testLink').click(function () {
        $('div.testBox').slideToggle('slow');
        $(this).toggleClass('open');
    });
});


function showMasterModal(heading, contentDivReference) {
	var popID = "masterModal";
	var popWidth = 751;

	// add content
	$("#" + popID + " h5").html(heading);
	$("#" + popID + " .children").html($(contentDivReference).html());
	Cufon.refresh();

	//Fade in the Popup and add close button
	$('#' + popID).fadeIn().css({ 'width': Number(popWidth) }).prepend('<a href="#" class="close"><img src="/images/productDetail/closeThis.png" class="btn_close" title="Close Window" alt="Close" /></a>');

	//Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
	var popMargTop = ($('#' + popID).height() + 80) / 2;
	var popMargLeft = ($('#' + popID).width() + 80) / 2;

	//Apply Margin to Popup
	$('#' + popID).css({
		'margin-top': -popMargTop,
		'margin-left': -popMargLeft
	});

	//Fade in Background
	$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
	$('#fade').css({ 'filter': 'alpha(opacity=80)' }).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
}
