// The following is a jQuery implementation for the javascript behaviour used with the site
$(function() {

	// re position the left nav
	var contentInnerOffset = $('.headerInner').offset().left; // runs it first time round when page loaded
	$('.content .submenuContainer').css({'left':contentInnerOffset + 'px', opacity: 0.8});
	$(window).resize(function(){
		var contentInnerOffset = $('.headerInner').offset().left;
		$('.content .submenuContainer').css({'left':contentInnerOffset + 'px', opacity: 0.8}); // run it each time after window is resized.
		if (document.documentElement) {
		    dimensionsWidth = document.documentElement.offsetWidth;
	    } else if (window.innerWidth && window.innerHeight) {
		    dimensionsWidth = window.innerWidth;
	    }
		if (dimensionsWidth && dimensionsWidth < 962) {
		    $(".content .contentInner").css({'margin-left': contentInnerOffset + 167 + 'px'});
		} else if (dimensionsWidth >= 962) {
		    DoProductListingScroll();
		    $('.content').css({'overflow':''});
		}
	});

	// turn loading panel off
    $(".ajaxLoader").fadeOut(1500, function() {

    });

	/* PRODUCT LISTING Startup Script */
	// get browser width
	// only call below if browser fall below 962px wide.
	var dimensionsWidth;
	if (document.documentElement) {
		dimensionsWidth = document.documentElement.offsetWidth;
	} else if (window.innerWidth && window.innerHeight) {
		dimensionsWidth = window.innerWidth;
	}
	if (dimensionsWidth > 962) {
		//Adding the scroll panel functionality to the appropriate divs
		// product Landing pages will be in /Themes/
		/* !!!REMEMBER!!! - for any ScrollPanel added, you have to add height:466px and overflow:hidden in the CSS - or you'll get an ugly brwoser scrollbar. */
		DoProductListingScroll();
	} else {
		// remove overflow:hidden on .content
		$('.content').css({'overflow':'visible'});
		$(".content .contentInner").css({'overflow':'auto'});
		$(".content .contentInner").css({'margin-left':'167px'}).css({'padding-left':'0'});
		// only for products landing - where we take the width of the seasonal image
		// and set the contentInner to be that width. This will force the horizontal scrollbar for lowres users.
		var imgWidth;
		$('.productsLanding .scrollPanel img').load(function(){
			imgWidth = $(this).width();
			$('.productsLanding .contentInner').css({'width': imgWidth+'px'});
        });
	}

    $(".content .contentInner").show();

    $('.productView').each(function(){
	    var productView = $(this);
	    var productCard = $(this).children('.productDetailsCard');
	    productView.hover(function(){
		    $('.productImage', this).css({'opacity':0.31});
		    $(this).mousemove(function(e){
			    productCard.show().css({top:(e.pageY - productView.offset().top + 10)+'px', left:(e.pageX - productView.offset().left + 13)+'px'});
		    });
	    },
	    function(){
		    $('.productImage', this).css({'opacity':1});
		    productCard.hide();
	    });
    });

	/* PRODUCT DETAILS Startup Script */
	if ($(".productDetails").length > 0) {
	    // product detail draggables
	    $('.productDetails .draggableImagePanel.productImageFront').load('img', function(){
		    if($('img', this).height() > 675){
			    $(".productDetails .draggableImagePanel.productImageFront").draggableImage($('img', this).height());
			    addProductTooltip($(this));
		    }
	    });
	    $('.productDetails .draggableImagePanel.productImageBack').load('img', function(){
		    if($('img', this).height() > 675){
			    $(".productDetails .draggableImagePanel.productImageBack").draggableImage($('img', this).height());
			    addProductTooltip($(this));
		    }
	    });
	    // flip to back/front functions
	    var productImageBack = $(".productImageBack");
	    $(".productDetails .flipToBack").click(function(e) {
		    e.preventDefault();
		    $(this).hide();
		    $(".flipToFront").show();
		    productImageBack.css({'opacity':0, 'z-index':30});
		    productImageBack.show();
		    productImageBack.stop(true, false);
		    productImageBack.animate({opacity: '1'}, "fast");
	    });
	    $(".productDetails .flipToFront").click(function(e) {
		    e.preventDefault();
		    $(this).hide();
		    $(".flipToBack").show();
		    productImageBack.stop(true, false);
		    productImageBack.animate({opacity: '0'}, "fast", null, function() {
			    productImageBack.hide();
		    });
	    });
	    //Add the tooltip to the product images on the product details page (prompting the user to drag)
	    $(".productDetails .productControls .colourSwatches li img").each(function(){
		    var altTag = $(this).attr("alt");
		    $(this).hover(function(){
			    $('body').append('<div id="swatchAlt">'+altTag+'</div>');
			    $(this).mousemove(function(e){
				    $('#swatchAlt').css({ display:'block',position:'absolute', top:(e.pageY + 10) + 'px', left:(e.pageX + 13) + 'px', opacity:0.9 });
			    });
		    }, function(){
			    $('body #swatchAlt').remove();
		    });
	    });
	}

	//Adding the default value (prompt) to the login fields
	$('.membersBar .loginField').defaultvalue('Email or Member No.');
	$('.membersBar .passwordField').defaultvalue('Password');

	//Adding the transparency hover state to the appropriate buttons
	$('.loginButton, .logoutButton, .membersBar a img, .keyLooks a img').hover(
		function() {
			$(this).css("opacity", 0.6);
		},
		function() {
			$(this).css("opacity", 1);
		}
	);

	//Add the hover state to the plus tips
	$(".plusTip").hover(
		function() {
			var $this = $(this).children("span");
			var plusImg = $this.children("img");
			plusImg.stop(true, false);
			plusImg.animate({opacity: "0"}, "fast");
			$this.stop(true, false);
			$this.animate({width: $this.children("strong").outerWidth() + "px"}, "fast");
		},
		function() {
			var $this = $(this).children("span");
			var plusImg = $this.children("img");
			plusImg.stop(true, false);
			plusImg.animate({opacity: "1"}, "fast");
			$this.stop(true, false);
			$this.animate({width: "13px"}, "fast");
		}
	);

	//Add the click behaviour to the colour swatches
	if ($(".colourSwatches img").length > 0) {
	    $(".colourSwatches img").click(function() {
		    $(this).siblings("input").click();
	    });
	}

	//Adding the transparency hover state to the wear it with images
	if ($('.wearItWith a img').length > 0) {
	    $('.wearItWith a img').hover(
		    function() {
			    $(this).css("opacity", 0.85);
		    },
		    function() {
			    $(this).css("opacity", 1);
		    }
	    );
	}

	//Header Login Bar: Fade out the success and error messages
	if ($(".header .alerts").length > 0) setTimeout("fadeinAlerts('.header .alerts')", 1000);

	// form validation for form pages
	if($('.formAlerts').length > 0){ //check if exists
		var formAlertHeight = $('.formAlerts').height(); // get height because it could be dynamic
		var formAreaHeadingHeight = $('.formArea h3').height();
		var marginBotSecondaryFormSection = $('.formArea .formSectionSecondary h3').css('margin-bottom');
		$('.formArea h3').css({'margin-bottom': formAlertHeight + 44 + 'px'});
		$('.formArea .formSectionSecondary').css({'zoom':1});
		$('.formArea .formSectionSecondary h3').css({'margin-bottom': marginBotSecondaryFormSection});
		$('.formAlerts').css({'top': formAreaHeadingHeight + 12 + 'px'});
	}
});

function DoProductListingScroll() {
    if ($(".content.productsBrowse .contentInner").length > 0) {
	    $(".content.productsBrowse .contentInner").scrollpanel($(".content"), $(".submenuContainer"), ".productView", 197, 197, false, true, "scrollPanel", false);
	} else if ($(".content.keyLooks .contentInner").length > 0) {
	    $(".content.keyLooks .contentInner").scrollpanel($(".content"), $(".submenuContainer"), ".productView", 197, 197, false, true, "scrollPanel", false);
	} else if ($(".content.faq .contentInner").length > 0) {
	    $(".content.faq .contentInner").scrollpanel($(".content"), $(".submenuContainer"), ".faqItem", 305, 305, false, true, "scrollPanel", false);
	}
}

function fadeoutAlerts(cssSelector) {
	$(cssSelector).stop(true, false);
	$(cssSelector).animate({opacity: '0'}, "slow", null, function() {
		$(cssSelector).remove();
	});
}
function fadeinAlerts(cssSelector) {
	$(cssSelector).stop(true, false);
	$(cssSelector).css({opacity: "0"});
	$(cssSelector).animate({opacity: '0.95'}, "slow");
	//setTimeout(fadeoutAlerts(cssSelector), 1000);
}

// Form validation error message functions
function AddErrorMessage(sender) {
    $('.required', $($(sender).parent())).addClass('errorRed');
    $(sender).addClass('error');
    $(sender).text(sender.errormessage);
}

function RemoveErrorMessage(sender) {
    $('.required', $($(sender).parent())).removeClass('errorRed');
    $(sender).removeClass('error');
    $(sender).text('').removeClass('error');
}

// Add to cart functions
// Colour swatches sizes availability check
function UpdateColorAvailability(productId, attrItemId, ddlSizeClientID) {
    StoreHelper.GetSizesAvailability(
        productId,
        attrItemId,
        ddlSizeClientID,
        UpdateColorAvailability_Callback);
}

function UpdateColorAvailability_Callback(response) {
    if (response.value) {
        var dtInventoryItems = response.value;
        var ddlSizeClientID = '';
        $.each(dtInventoryItems.Rows, function(outer,inventory) {
            if (ddlSizeClientID == '') {
                ddlSizeClientID = inventory.DdlSizeID;
            }
            $.each($('#'+ddlSizeClientID+' option'), function(inner,opt) {
                if ($(opt).attr('value') == inventory.AttributeItemId) {
                    if (inventory.Quantity == 0) {
                        if ($(opt).text().indexOf(' - Sold Out') < 0) {
                            $(opt).text($(opt).text() + ' - Sold Out');
                        }
                    } else {
                        $(opt).text($(opt).text().replace(' - Sold Out', ''));
                    }
                }
            });
        });
    }
}
function addProductTooltip(side){
	$(side).hover(function(){
		$('body').append('<div id="prodDetailTooltip">Click and drag to see more</div>');
		// moving behaviour
		$(this).mousemove(function(e){
			$('#prodDetailTooltip').css({ display:'block',position:'absolute', top:(e.pageY + 10) + 'px', left:(e.pageX + 13) + 'px', opacity:0.9 });
		});
		// remove it so it doesn't remain there and scrolls off page
		$(this).mousedown(function(){
			$('body #prodDetailTooltip').remove();
		});
		// put it back in.
		$(this).mouseup(function(){
			$('body').append('<div id="prodDetailTooltip">Click and drag to see more</div>');
		});
	}, function(){
		$('body #prodDetailTooltip').remove();
	});
}

function InternationalCustomerCountryInfoPopup(trigger) {
    var parent = $(trigger).parent();
    if ($(".alerts", $(parent)).length > 0) return;
    var msgHTML = "<strong>International Orders</strong>"
                + "For all other countries please call Jeanswest customer service on"
                + "<br />1800 809 889";
    $(parent).css("position", "relative");
    $(parent).append("<div class=\"alerts alertBox\"><div><p>" + msgHTML + "</p></div></div>");
    var alerts = $(".alerts", $(parent));
    alerts.stop(true, false);
    alerts.animate({opacity: '0.95'}, "fast", null, function(){
        alerts.animate({opacity: '0.95'}, 5000, null, function(){
            alerts.animate({opacity: 0}, 'slow', null, function(){
                alerts.remove(); // only remove after the 3 seconds are up
            });
        });
    });
}

function HideInternationalCustomerCountryInfoPopup(trigger) {
    var parent = $(trigger).parent();
    if ($(".alerts", $(parent)).length == 0) return;
    $(parent).css("position", "");
    $(".alerts", $(parent)).remove();
}

function ProductViewHover(productView) {
    var productView = $(this);
	var productCard = $(this).children('.productDetailsCard');
	productView.hover(function(){
		$('.productImage', this).css({'opacity':0.31});
		$(this).mousemove(function(e){
			productCard.show().css({top:(e.pageY - productView.offset().top + 10)+'px', left:(e.pageX - productView.offset().left + 13)+'px'});
		});
	},
	function(){
		$('.productImage', this).css({'opacity':1});
		productCard.hide();
	});
}