/* Catalogue Script for Peter Alexander AUS */ 


$(function(){
	

	/* Collect all product data (from non JavaScript table)
	************************************************************/
	var products = new Array();
	$("#non-script-colour-size table tbody tr").each(function (i) {
		products[i] = {
			colour : jQuery.trim( $(this).find(".colour").text() ),
			colourID : $(this).find(".colour input").val(),
			size : jQuery.trim( $(this).find(".size").text() ),
			sizeID : $(this).find(".size input").val(),
			sizeSequence : $(this).find(".size input").attr("tabindex"),
			colourSequence : $(this).find(".colour input").attr("tabindex"),
			m : $(this).attr("m"),
			l : $(this).attr("l"),
			h : $(this).attr("h"),
			soldOut : $(this).find(".soldout").length > 0
		};
	});
	// DEBUG - show all product data
	/*$("body").prepend("<div id='DEBUG' style='background:yellow; padding:1em; color:red; margin-top:2em;'></div>");
	for( i in products ) {
		$("#DEBUG").append("("+i+") - colour["+products[i].colour+"]["+products[i].colourID+"] colourSequence["+products[i].colourSequence+"] size["+products[i].size+"]["+products[i].sizeID+"] sizeSequence["+products[i].sizeSequence+"] m["+products[i].m+"] l["+products[i].l+"] h["+products[i].h+"]  soldOut["+products[i].soldOut+"]<br/>");
	}
	$("#DEBUG").append("Alternate Product names:["+ALTERNATE_NAMES+"]");*/
	
	
	
	/* Generate swatches
	************************************************************/
	for( i in products ) {
		
		// Generate colour swatches (only for unique colours, in sequence order)
		var unique = true;
		var swatchBefore = null;
		$(".colour.swatch-list .swatch").each(function () {
			if( products[i].colour == products[$(this).attr('id')].colour ) unique = false;
			if( Number(products[$(this).attr('id')].colourSequence) <= Number(products[i].colourSequence) ) swatchBefore = $(this);
		});
		if( unique ) {
			var imageName = String(products[i].colour).replace(/\W/g, "");
			if( $(".colour.swatch-list .swatch").length <= 0 ) {
				//alert( "add first: ("+products[i].colour+","+products[i].colourSequence+")" );
				$(".colour.swatch-list").append("<div class='swatch' id='"+i+"'><div class='frame'></div><img src='/images/Catalog/ColourSwatches/"+ imageName +".jpg' title='' alt='"+products[i].colour+"'/></div>");
			} else if( swatchBefore == null ) {
				//alert( "add to start: ("+products[i].colour+","+products[i].colourSequence+")" );
				$(".colour.swatch-list .swatch:first").before("<div class='swatch' id='"+i+"'><div class='frame'></div><img src='/images/Catalog/ColourSwatches/"+ imageName +".jpg' title='' alt='"+products[i].colour+"'/></div>");
			} else {
				//alert( "add ("+products[i].colour+","+products[i].colourSequence+") after ("+products[swatchBefore.attr('id')].colour+","+products[swatchBefore.attr('id')].colourSequence+")" );
				swatchBefore.after("<div class='swatch' id='"+i+"'><div class='frame'></div><img src='/images/Catalog/ColourSwatches/"+ imageName +".jpg' title='' alt='"+products[i].colour+"'/></div>");
			}
		}
		
		// Generate size swatches (only for unique sizes, in sequence order)
		unique = true;
		swatchBefore = null;
		$(".size.swatch-list .swatch").each(function () {
			if( products[i].size == products[$(this).attr('id')].size ) unique = false;
			if( Number(products[$(this).attr('id')].sizeSequence) <= Number(products[i].sizeSequence) ) swatchBefore = $(this);
		});
		if( unique ) {
			var imageName = String(products[i].size).replace(/\W/g, "");
			if( $(".size.swatch-list .swatch").length <= 0 ) {
				//alert( "add first: ("+products[i].size+","+products[i].sizeSequence+")" );
				$(".size.swatch-list").append("<div class='swatch' id='"+i+"'><div class='frame'></div><img src='/images/Catalog/SizeSwatches/"+ imageName +".gif' title='' alt='"+products[i].size+"'/></div>");
			} else if( swatchBefore == null ) {
				//alert( "add to start: ("+products[i].size+","+products[i].sizeSequence+")" );
				$(".size.swatch-list .swatch:first").before("<div class='swatch' id='"+i+"'><div class='frame'></div><img src='/images/Catalog/SizeSwatches/"+ imageName +".gif' title='' alt='"+products[i].size+"'/></div>");
			} else {
				//alert( "add ("+products[i].size+","+products[i].sizeSequence+") after ("+products[swatchBefore.attr('id')].size+","+products[swatchBefore.attr('id')].sizeSequence+")" );
				swatchBefore.after("<div class='swatch' id='"+i+"'><div class='frame'></div><img src='/images/Catalog/SizeSwatches/"+ imageName +".gif' title='' alt='"+products[i].size+"'/></div>");
			}
		}
		
	}
	
	
	
	/* Colour swatch rollover
	************************************************************/
	$(".colour .swatch").hover(
      function () {
		$(this).addClass("hover");
		$(".product-image img").attr( "src", IMAGE_PATH + "/" + products[$(this).attr('id')].m );
		$(this).updateColourText();
		disableSizes( products[$(this).attr('id')].colour );
      }, 
      function () {
        $(this).removeClass("hover");
		var activeID = $(".colour.swatch-list .swatch.active").attr("id");
		if( activeID != undefined ) {
			$(".colour.name").text( products[activeID].colour );
			 $(".product-image img").attr( "src", IMAGE_PATH + "/" + products[activeID].m );
		} else {
			$(".colour.name").text("");
		}
		disableSizes( products[activeID].colour );
      }
    );
	/* Colour swatch click
	************************************************************/
	$(".colour .swatch").click(function () {
		if( !$(this).hasClass("disabled") ) {
			$(".colour .swatch").removeClass("active");
			$(this).addClass("active");
			$(".product-image img").attr( "src", IMAGE_PATH + "/" + products[$(this).attr('id')].m );
			$(".product-image").attr("href", ZOOM_LINK + "&Colour=" + products[$(this).attr('id')].colour + "&l=" + products[$(this).attr('id')].l + "&h=" + products[$(this).attr('id')].h   );
			$("#ColourId").val( products[$(this).attr('id')].colourID );
			$(this).updateColourText();
			
			// Update size swatches
			disableSizes( products[$(this).attr('id')].colour );
			
			// Leave active size swatch as is unless it is unavaiable/disabled, if so select first valid one
			/*$(".size.swatch-list .swatch.active.unavailable, .size.swatch-list .swatch.active.disabled").removeClass("active");
			if( $(".size.swatch-list .swatch.active").length <= 0 ) {
				$(".size.swatch-list .swatch:not(.disabled):not(.unavailable):first").click();
			}
			$(".quantity, #js-colour-size input:submit").show();*/ //show 'Add to Bag' just incase it isn't visible yet
		}
    });
	
	// Disable sold out and unavailable size swatches for given colour
	function disableSizes( colour ) {
		$(".size .swatch").removeClass("active").fadeTo(0.1, 1);
		//$("#js-colour-size input:submit").addClass("disabled").fadeTo(0.1, 0.5);
		disableAddToBag(true)
		$(".size.name").html("<em style='color:#666'>Please select a size</em>");
		$(".size.swatch-list .swatch").addClass("unavailable").removeClass("disabled");
		$(".size.swatch-list .swatch").each(function () {
			for( i in products ) {
				if( products[i].colour == colour && products[i].size == products[$(this).attr("id")].size ) {
					if( products[i].soldOut ) { 
						$(this).addClass("disabled").fadeTo(0.1, 0.5);
					}
					$(this).removeClass("unavailable");
					break;
				}
			}
		});
	}
	
	
	
	/* Size swatch rollover
	************************************************************/
	$(".size .swatch").hover(
      function () {
        if( !$(this).hasClass("disabled") && !$(this).hasClass("unavailable") )  $(this).addClass("hover");
		$(this).updateSizeText();
      },
      function () {
        if( !$(this).hasClass("disabled") && !$(this).hasClass("unavailable") )  $(this).removeClass("hover");
		var activeID = $(".size.swatch-list .swatch.active").attr("id");
		if( activeID != undefined ) {
			$(".size.name").text( products[activeID].size );
		} else {
			$(".size.name").html("<em style='color:#666'>Please select a size</em>");
		}
      }
    );
	/* Size swatch click
	************************************************************/
	$(".size .swatch").click(function () {
		if( !$(this).hasClass("disabled") && !$(this).hasClass("unavailable") ) {
			$(".size .swatch").removeClass("active");
			$(this).addClass("active");
			$("#SizeId").val( products[$(this).attr('id')].sizeID );
			$(this).updateSizeText();
			//$("#js-colour-size input:submit").removeClass("disabled").fadeTo(0.1, 1);
			disableAddToBag(false)
		}
    });
	
	
	// Update product text
	jQuery.fn.extend({
		updateColourText: function() {
			if( $(this).hasClass("disabled") ) {
				$(".colour.name").html( products[$(this).attr('id')].colour + " - <span class='special' style='font-weight:bold;'>Sold Out</span>" );
			} else {
				$(".colour.name").text( products[$(this).attr('id')].colour );
			}
		},
		updateSizeText: function() {
			if( $(this).hasClass("disabled") ) {
				$(".size.name").html( products[$(this).attr('id')].size + " - <span class='special' style='font-weight:bold;'>Sold Out</span>");
			} else if( $(this).hasClass("unavailable") ) {
				$(".size.name").html( products[$(this).attr('id')].size + " - <span class='special' style='font-weight:bold;'>Not available in this colour</span>");
			} else {
				$(".size.name").text( products[$(this).attr('id')].size );
			}
		}
	});
	
	
	// Disable/Enable Add to Bag button 
	function disableAddToBag(disable) {
		if(disable) {
			$("#js-colour-size input:submit").addClass("disabled").fadeTo(0, 0.5);
			$("#addtowishlist").addClass("disabled").attr("disabled","disabled").fadeTo(0, 0.5);
		} else {
			$("#js-colour-size input:submit").removeClass("disabled").fadeTo(0, 1);
			$("#addtowishlist").removeClass("disabled").attr("disabled","").fadeTo(0, 1);
		}
	}
	
	

	
	/* Initial setup of colour/size swatches
	************************************************************/
	
	$("#js-colour-size").show();
	$("#js-colour-size input#ColourId").val("");
	$("#js-colour-size input#SizeId").val("");
	$(".size.name").html("<em style='color:#666'>Please select a size</em>");
	//disableAddToBag(true)
	
	
	// disable form submition when size not selected
	$("#js-colour-size").submit(function() {
		if( $(".size .swatch.active").length <= 0 ) {
			$(".size.name").html("<em style='color:red;'>Please select a size</em>");
			return false;
		} else {
			return true
		}
    });
	
	
	// Disable sold out colours
	$(".colour.swatch-list .swatch").each(function () {
		var soldOutColour = true;
		for( i in products ) {
			if( products[$(this).attr('id')].colour == products[i].colour && !products[i].soldOut ) {
				soldOutColour = false;
				break;
			}
		}
		if( soldOutColour ) {
			$(this).addClass("disabled");
		}
	});
	
	// If URL colour is set activate it otherwise activate the first colour swatch that is not disabled
	if( START_COLOUR != null ) {
		$(".colour.swatch-list .swatch").each(function () {
			if( products[$(this).attr('id')].colour == START_COLOUR ) $(this).click();
		});
	} else {
		$(".colour.swatch-list .swatch:not(.disabled):first").click();
	}
	
	// If no product avaiable at all, disable all size swatches and ability to add to bag
	if( $(".colour.swatch-list .swatch.active").length <= 0 ) {
		$(".size.swatch-list .swatch").addClass("disabled").fadeTo(0.1, 0.5);
	}
	
	

	/* Generate alternate image view links
	************************************************************/
	if( ALTERNATE_NAMES[0] != "" ) {
		var altString = "<strong>Alternate View:</strong> ";
		for( i in ALTERNATE_NAMES ) {
			altString += " <a onclick='popup(this.href,600,670); return false;' target='_blank' href='"+ZOOM_LINK+"&Colour="+ALTERNATE_NAMES[i]+"&l="+LINE+"_"+ALTERNATE_NAMES[i]+"_l.jpg&h="+LINE+"_"+ALTERNATE_NAMES[i]+"_h.jpg'>"+ALTERNATE_NAMES[i]+"</a>"
			if( ALTERNATE_NAMES.length > Number(i+1) ) altString += ",";
		}
		$(".alternate-view").append( altString );
	}
	
	

});