/*
Edited: SC 29th April removing code now superceeded
Edited:14 May 2009 (Last edited by:LD 17:00)
Website: http://www.tmlewin.co.uk
Created: 01 September 2008
Author: Laura Zucchetti.  Based on Henry's already done coolness.

NOTE: These scripts are based on jQuery 1.2.3
*/

/*
Set input field behaviours
==========================================================================================================================================
*/
$(document).ready(function(){

	function setTextFields(elementToSet, changeElement) {
		if ($(elementToSet)) {
			var fieldText = $(elementToSet).val();
			$(elementToSet).focus(function(){ 
				if ($(elementToSet).val()==fieldText) $(elementToSet).val('');
				if ($(changeElement)) { $(changeElement).addClass('over'); }
			});
			$(elementToSet).blur(function(){
				if (!$(elementToSet).val()) $(elementToSet).val(fieldText);
				if ($(changeElement)) { $(changeElement).removeClass('over'); }
			});
			$(elementToSet).next().click(function(){
				if (($(elementToSet).val() == fieldText) || ($(elementToSet).val() == "")) return false;
			});
		}
	}

	setTextFields('#newsletter_newslettersignup');	// 1st value is a CSS selector for the input field, 2nd is an element to toggle an "over" class on
	setTextFields('.search-field');	// 1st value is a CSS selector for the input field, 2nd is an element to toggle an "over" class on
});

/*
Collapsible lists in category navigation
==========================================================================================================================================
*/
$(document).ready(function(){
 
	if ($("#category-nav li.hide").length > 0 ) {
		$("#category-nav li.active").show();
		$("#category-nav li.hide").parent().eq(0).each(function(){
			$(this).append("<li><a class='show-hide' title='Expand/collapse this menu' href='#'>More...</a></li>");
		});
		$(".show-hide").click(function() {
			if ($(this).text() == "More...") { 
				$(this).parent().siblings(".hide").show();
				$(this).text("Less..."); 
			} else { 
				$(this).parent().siblings(".hide:not(.active)").hide();
				$(this).text("More...") ;
			}
			return false;
		});
	}

});

/*
Nick wrote this to split the list that sits below a hero-product so that the 6 products can sit aligned to the 
hero and the list carrys on underneath and wraps the hero product. It also wraps the hero product div and 
product list in a div.
==========================================================================================================================================
*/
$(document).ready(function() {     

	$(".landing .product-info").wrap("<div class='new clearfix'></div>");        
	
	$(".new").append("<ul class='product-list-four'></ul>");
	
	$(".landing:has('.product-info')>ul>li").each(function(index) {
		if((index) < 4) {
			$(this).appendTo(".new>ul");
		}
	});

});


// turn a UL grid into a series of self-clearing ULs that behave like table rows
/*

MSS + HT: 13 October 2008 - various performance improvements

Requires:
- ul.row style defined in CSS if borders are required
- "clearfix"
- you may need to add some styles for ".gridRow", "ul.gridRow" and "ul.gridRow li"

Just put in a selector and the number of columns in the "makeGridList" call at the end.
*/
$(document).ready(function(){

function makeGridList(element, numCols) {
	var gridRowHolder = $("<div class='gridRowHolder'></div>").insertAfter(element);			// a container for the new ULs
	$(element).children("li").each(function(i) {
			  $(this).css("min-height", "0");			// get rid of min-height
			  if (i % numCols == 0) {
							$("<ul class='clearfix products gridRow'></ul>").appendTo(gridRowHolder);
			  }
			$(this).clone().appendTo($(this).parent().eq(0).siblings("div.gridRowHolder").children("ul:last")[0]);
	});
	$(element).eq(0).remove();	  // remove the original UL
	
	$("ul.gridRow li:last-child").css("margin-right","0");		// gets rid of any right margin on the last item of each row
}

	makeGridList(".items-list ul.gridList", 4);	// 1st argument is a selector for the original UL, the 2nd is the number of columns in the grid
	makeGridList(".landing ul.product-list", 4); 
	makeGridList(".sub-cta-one ul.gridList", 3); 
	makeGridList(".sub-cta-two ul.gridList", 3);
	makeGridList(".highlights ul.gridList", 4); 

});

// split a UL with class="cols" into multiple 
/*
Requires:
- "clearfix"
- "col" style defined in CSS with width, float, etc

Just put in a selector and the number of columns in the "multiColList" call at the end.
Each separate list needs its own function call with a unique selector
==========================================================================================================================================
*/
$(document).ready(function(){

	function multiColList(element, numCols) {

		var colItems = Math.ceil($(element).find("li").length / numCols);

		$("<ul class='col'></ul>").insertAfter(element);		// new UL

		$(element).find("li").each(function(i) {

			$(this).clone().appendTo($(element).parent().find("ul.col:last"));
			if (i == colItems - 1) {
				$("<ul class='col'></ul>").insertAfter($(element).parent().find("ul.col:last"));
			}
		});
		$(element).remove();	// remove the original UL
	}

	multiColList("#shop-footer ul.cols", 2);	// 1st argument is a selector for the original UL, the 2nd is the number of columns
	multiColList("#browse-products ul.cols", 2);

});



/*
Options show hide Maestro/Switch on payment page
==========================================================================================================================================
*/

$(document).ready(function(){
    showHidePaymentExtras();
	
	$("#paymentdetails select.type").change(function(){
		showHidePaymentExtras();
	});
});

function showHidePaymentExtras() {
	if (($("#paymentdetails select.type option:selected").text() == "Maestro") || ($("#paymentdetails select.type option:selected").text() == "Switch")) {
		$("#paymentdetails #card-options").slideDown("slow");
	} else {
		$("#paymentdetails #card-options").slideUp("slow");
	}
}

/*
Add	.first and .last to list items - 
LZ:	This is last so that is applies to all list items 
	that may have been split in the grid clearing script above.
==========================================================================================================================================
*/
$(document).ready(function(){
 
	$("li:first-child").addClass("first");
	$("li:last-child").addClass("last");
	$("ul.product-list-four li:nth-child(2)").addClass("last");
});


/*
Dynamically load jqzoom and set up simple image zooming
HT:	On all product pages.
==========================================================================================================================================
*/

$(document).ready(function(){

    if ($(".jqzoom").length > 0) {

		$(".product-pane").css("opacity",.9999); // fix for IE opacity issues
		$(".jqzoom").jqueryzoom({
			xzoom: 458, //zooming div default width (default width value is 200)
			yzoom: 367, //zooming div default height (default height value is 200)
			offset: 0, //zooming div default offset(default offset value is 10)
			position: "right", //zooming div position(default position value is "right")
			preload: 0, // by default preload of big images is 1
			lens: 1, // by default the lens is 1
			positionTop: 0,
			positionLeft: 310,
			hideElement: ".product-pane"
		  });

       }
});

/* 
Home page banner rotator functions
HT:	just drop in divs with class "slide" and this will rotate them automagically
==========================================================================================================================================
*/

function slideFadeIn(slideContainer, slideElements) { 

		var slides = $(slideContainer).children(slideElements);
		$(slides).eq(frame).fadeIn("slow").siblings().fadeOut(); 
		if (frame == slides.length-1) { frame = 0; } else { frame++; }
}

function simpleRotation(slideContainer, slideElements) {

	delay = 6000;
	var slides = $(slideContainer).children(slideElements);
	slides.eq(0).show();

	frame = 1;
	cycle = self.setInterval(function(){slideFadeIn(slideContainer, slideElements)}, delay);
}

// initialise home page banner rotator 
$(document).ready(function(){

	if ($(".main-banners .main").length > 0) {
		simpleRotation(".main-banners .main",".slide");
	}
	
	if ($("#slideshow #slide-1 .slide").length > 0) {
		simpleRotation("#slideshow #slide-1",".slide");
	}
});

/* 
Slideshow tabs
HT:	Sets up fading tabs for various landing pages
==========================================================================================================================================
*/

function slideshow() {

	var hoverOverOpacity = 1;
	var hoverOutOpacity = .65;

	// set up tab appearance and behaviour
	$("#slideshow .navigation").addClass("tabs");
	$('#slideshow .navigation a').click(function(){$(this).blur(); });
	$("#slideshow .tabs li")
		.hover( function() { 
			if ($(this).hasClass("selected")) { return }
			$(this).fadeTo("normal", hoverOverOpacity) 
		}, function() { 
			if ($(this).hasClass("selected")) { return }
			$(this).fadeTo("normal", hoverOutOpacity )
		})
		.not(".selected").css("opacity", hoverOutOpacity);

	// set up idTabs
	if ($("#slideshow").length > 0) {
		$("#slideshow").idTabs(function(id,list,set){ 
			$("[@href='"+id+"']",set).parent().eq(0).addClass('selected')
				.siblings().removeClass('selected')
				.css("opacity", hoverOutOpacity);

			for(i in list) 
				$(list[i]).hide(); 
			$(id).fadeIn(); 
			return false; 
		}); 
	}

}

$(document).ready(slideshow);
/* 
Faded add to basket
AK:	Sets up fading button that doesn't return anything
==========================================================================================================================================
*/
/*$(document).ready(function(){
	if ($('input.out-of-stock')) {
		$('input.out-of-stock').fadeTo('fast', 0.5);
		$('input.out-of-stock').click( function() { return false;});
	}
});*/

//disable 'no stock/not offered' links in the g
$(function(){
	$('img[id*=imgNotOffered]').next().addClass('notoffered').removeAttr("href");
	$('img[id*=imgNoStock]').next().addClass('nostock').removeAttr("href");
});

/*
Buy the look on shirt pages
============================
*/
$(function(){
	$('#buythelook ul:has(li)').parent().show();	//only display this when the list is populated
});

//Size selection - updating cookie process
function updateCookieFormal(collar, sleeve)
{
	var expDate=new Date();
	expDate.setDate(expDate.getDate()+720);
	document.cookie="formal_selection="+collar+":"+sleeve+";expires="+expDate.toGMTString()+";path=/";
}

function updateCookieCasual(size)
{
	var expDate=new Date();
	expDate.setDate(expDate.getDate()+720);
	document.cookie="casual_selection="+size+";expires="+expDate.toGMTString()+";path=/";
}

$(document).ready(function() {$("#aAllSizesF").click(clearCookieFormal);$("#aAllSizesC").click(clearCookieCasual);});

function clearCookieFormal()
{
	var expDate=new Date();
	expDate.setDate(expDate.getDate()-720);
	document.cookie="formal_selection=;expires="+expDate.toGMTString()+";path=/";
}

function clearCookieCasual()
{
	var expDate=new Date();
	expDate.setDate(expDate.getDate()-720);
	document.cookie="casual_selection=;expires="+expDate.toGMTString()+";path=/";
}

//Alterations
$(document).ready(function(){
	$(".community").show()
	$("#aError").hide();
	$("select[id*=ddlAlterations]").change(recalculate);
});

function recalculate()
{
	var unitPrice=Number($("input[id*=hidPrice]").val());
	var alterationPrice=Number($("input[id*=hidAlteration]").val());
	var quantity=Number($("input[id*=txtQuantity]").val());
	var newPrice;
	
	if($("select[id*=ddlAlterations]").val()=="none")
		newPrice=(unitPrice * quantity).toFixed(2);
	else
		newPrice=((unitPrice + alterationPrice) * quantity).toFixed(2);
	$(".total .price").text(newPrice);
}

/*
apply "ifixpng" PNG transparency fix for IE6
==========================================================================================================================================
*/
$(document).ready(function(){

	$.ifixpng('/images/pixel.gif'); 
	$('#header h1, #shopping-basket, #map-overlay, #sv-header .custom-currency').ifixpng();

});

/*
Autoclick on buttons
*/

$(document).ready(function()
{
	$(".mediacodefield").keypress(function (e) {if(e.keyCode==13) $(this).siblings(".mediacodebutton").click();});
	$(".newsletterfield").keypress(function (e) {if(e.keyCode==13) $(".newsletterbutton").click();});
	$(".signinpassword").focus(function() {$("#password_yes").attr("checked", "true");});
});


/* Alterations custom dropdown
   Custom UI which triggers a standard dropdown 
*/

jQuery(function($) {

    $(".alterationSelection").each(function() {
        var alterationSelection = this,
            container = $(this).parent(),
            flyout = container.find('.flyout').eq(0),
            realSelect = container.find('select').eq(0),
            labelText = function() {
                return container.find('label').eq(0).text() || "";
            },
            selectionText = function() {
                return realSelect.find('option:selected').text() || "";  // text of the selected option 
            },
            updateLabel = function() {  
                var html = $('<span/>');
                
                if (realSelect.find('option').length > 1) { 
                    html.text(labelText());
                    html.append( $('<span/>').text(selectionText()));
                } else { 
                    html.text(selectionText()); // the dropdown is not enabled, so only the the text from the first item
                }

                $(alterationSelection).find('div').eq(0).css('width', '235px').html(html); // IE6 loses the width, so set it explicitly
            };


        if ( realSelect.is(':disabled') ) {
          $(alterationSelection).addClass('disabled'); // dropdown is disabled if user hasn't selected a shirt size
        };
        
        realSelect.find('option').each(function() { // populate the list with options from the real select control
            $('<li>').text( $(this).text() ).appendTo( flyout.find('ul').eq(0) );
        });
        
        flyout.find('.close-flyout').click(function() { // allow the user to dismiss the flyout
           flyout.fadeOut('fast');
        });
        
        flyout.find('li').click(function() { // update the hidden select when a choice is clicked
            var index = flyout.find('li').index(this);
            realSelect.find('option').eq(index).attr('selected', 'selected');
            updateLabel();
            flyout.fadeOut('fast');
        });

        
        if (!$(this).is('.disabled')) { // show the flyout if the state is enabled
            $(this).find('div').eq(0).click(function() {
                flyout.show();
				$('.flyout .close-flyout').iunfixpng();
                return false;
            });
        };
        
        updateLabel(); // setup the dropdown for the initial page load
    });
});
   
   
