$(function(){

	// nav roundies
	$('.top-nav > li:not(.top-nav ul li)').append('<span></span>');

	// fix shop breadcrumbs
	if ($('.shop-breadcrumbs').html()) {
		$('.shop-breadcrumbs a:first-child').remove();
		$('.shop-breadcrumbs a:first-child').remove();
		$('.shop-breadcrumbs').html( $('.shop-breadcrumbs').html().substring(12) );
	}

	// fix cart :(
//	$('span.cart-qty').append('&nbsp;x');

	// fix factory code
	$('input[type="submit"]', '#main #content.wide #checkout-member-account').addClass('continue-button');

	// remove fax option, reword things
	try {
		$('#payment_type_phone').parent().html( $('#payment_type_phone').parent().html().substr(0, $('#payment_type_phone').parent().html().length - 4) );
		$('#payment_type_fax').parent().append(' / Money Order');
	} catch (e) {}

	// remove store credit
	$('#checkout-codes label:nth-child(3)').remove();
	$('#credit_code').remove();

	// print this page
	$('#general-print').click(function(){
		print();
		return false;
	});

	if ($.browser.msie) {
		// add child selectors to IE
		$('.top-nav li ul li:last-child').addClass('last-child');
		$('.top-nav li ul li:first-child').addClass('first-child');
		$('#footer #trisect li:last-child').addClass('last-child');
		$('#left-panel ul li:first-child').addClass('first-child');
		$('#left-panel ul li:first-child').addClass('first-child');
		$('table#cart-list td:first-child').addClass('first-child');
		$('.home #content #news ul li:first-child').addClass('first-child');

		// add :hover interactions to ie6
		if ($.browser.version < 7) {
			$('.top-nav li').hover(function() {
				$(this).addClass('over');
			}, function() {
				$(this).removeClass('over');
			});

			DD_roundies.addRule('#left-panel ul li.first-child a', '7px 7px 0 0', true);
			DD_roundies.addRule('#left-panel ul li.first-child ul li a', '0', true);

			DD_roundies.addRule('#header h2 a');
			DD_roundies.addRule('#header .top-nav', '6px 6px 0 0', true);
		}
	}


	// open cart
	$('#toggle-cart a').click(function() {
		$(this).toggleClass('on');
		$('#cart').slideToggle(400);
	});
	$('.item-count').click(function() {
		$('#toggle-cart a').toggleClass('on');
		$('#cart').slideToggle(400);
	});

	// Clear the default Text #firstname #lastname #email
	function defaultText(field) {
		if ($('#'+field).val() == 'Enter your '+field) { $('#'+field).css('color', '#aaa'); }
		$('#'+field).focus(function() { $(this).css('background-color','#ffc'); if ($(this).val() == 'Enter your '+field) { $(this).val(''); $(this).css('color', '#000'); } });
		$('#'+field).blur(function() { $(this).css('background-color','#fff'); if ($(this).val() =='') { $(this).val('Enter your '+field); $(this).css('color', '#bbb'); } });
	}

	// Add external interface
	jQuery.extend({
    initForm: function(label) {
		switch (label) {
			case 'contact': var fields = Array('name', 'email', 'subject', 'enquiry'); break;
			default: break;
		}
		for (var i=0; i<fields.length; i++)
			defaultText(fields[i]);
	}
	});

	// Replace default text prior to validation
	$("#contactform").submit(function() {
    	$("#contactform input").each(function() {
			if ($(this).val().substring(0,10) == 'Enter your') {
	           	$(this).val('');
			}
		});
    	$("#contactform textarea").each(function() {
			if ($(this).val().substring(0,10) == 'Enter your') {
        	    	$(this).val('');
			}
		});
	});

	// default text on search box
	$('#searchterm').focus(function() { $(this).css('background-color','#ffc'); if ($(this).val() == 'SEARCH') { $(this).val(''); } });
	$('#searchterm').blur(function() { $(this).css('background-color','#fff'); if ($(this).val() =='') { $(this).val('SEARCH'); } });

	// left product nav interaction: toggle if subcategories
	$('#menu-products li a:not(#menu-products li li a)').click(function() {
		var context = this;
		if ($('ul', $(context).parent()).size()) {
			if ($(this).parent().attr('class')!='selected') {
				if ($('ul', $(context).parent().parent().parent()).css('display')=='block') {
					$('ul', $(context).parent().parent()).slideUp(400);
				}
				$('li', $(context).parent().parent()).removeClass('selected');
				$(context).parent().addClass('selected');
				$('ul', $(context).parent()).slideDown(400);
			}
			return false;
		}
	});

	// list style for customer services
	$('#menu-customer li a').prepend('&gt;&nbsp;');

	// add border-radius for Gecko/Trident/Webkit
	DD_roundies.addRule('#carousel', '7px', true);
	DD_roundies.addRule('#header #search', '7px', true);
	DD_roundies.addRule('#header #searchterm', '7px 0 0 7px', true);
	DD_roundies.addRule('#header fieldset .item-count div', '7px', true);

	DD_roundies.addRule('#main #content', '7px 7px 0 0', true);
	DD_roundies.addRule('#standard-inner #featured', '7px 7px 0 0', true);
	DD_roundies.addRule('#featured #featured-search', '7px 7px 0 0', true);
	DD_roundies.addRule('#content #featured #featured-nav li.selected a', '7px 7px 0 0', true);
	DD_roundies.addRule('#product-inner #featured', '7px 7px 0 0', true);
	DD_roundies.addRule('#checkout-member-account h3', '7px 7px 0 0', true);
	DD_roundies.addRule('#header fieldset', '0px 0px 7px 7px', true);

	// roundies on hover state crashes ie6
	if (!($.browser.msie && $.browser.version < 7)) {
		DD_roundies.addRule('#menu-products li:first-child>a', '7px 7px 0 0', true);
		DD_roundies.addRule('#menu-products li li:first-child>a', '0', true);
		DD_roundies.addRule('#content #featured #featured-nav li a:hover', '7px 7px 0 0', true);
	}

	DD_roundies.addRule('#content h2', '7px 7px 0 0', true);
	DD_roundies.addRule('.cart-step-heading', '7px 7px 0 0', true);
	DD_roundies.addRule('#cart-list', '7px 7px 0 0', true);
	DD_roundies.addRule('.error', '7px 7px 0 0', true);
	DD_roundies.addRule('#error', '7px 7px 0 0', true);
	DD_roundies.addRule('.errors', '7px 7px 0 0', true);
	DD_roundies.addRule('#add-product-popup', '7px 7px 7px 7px', true);
	DD_roundies.addRule('.home #content #news .newsitem-img img', '0 7px 7px 0', true);
//	DD_roundies.addRule('#content .news-single img', '0 7px 7px 0', true);
	DD_roundies.addRule('.newsitem-img img', '0 7px 7px 0', true);
	DD_roundies.addRule('.news-single img', '0 7px 7px 0', true);

	$('#nav-menu-customer > li:first-child > a').addClass('round-me');
	DD_roundies.addRule('.round-me', '7px 7px 0 0', true);
	DD_roundies.addRule('#general-share-panel', '7px 7px 7px 7px', true);
	DD_roundies.addRule('#header .top-nav', '6px 6px 0 0', true);

	// image zoomer
	containerHeight = $('#image-zoomer').height();
	containerWidth =$('#image-zoomer').width();
	$('#image-zoomer').append('<span class="marker">+ click to enlarge</span>');
	$('#image-zoomer img').hide();
	$('#image-zoomer img').load(function() {
		$('#image-zoomer img').css('height', 'auto');
		$('#image-zoomer img').css('width', 'auto');
		imageHeight = $('#image-zoomer img').height();
		imageWidth = $('#image-zoomer img').width();
		if (imageHeight >= imageWidth) {
			thumbHeight = containerHeight;
			thumbWidth = Math.round(containerWidth * (imageWidth/imageHeight));
		} else {
			thumbHeight = Math.round(containerHeight * (imageHeight/imageWidth));
			thumbWidth = containerWidth;
		}
		
		$('#image-zoomer img').css('height', thumbHeight+'px').fadeIn(250);
		$('#image-zoomer img').css('width', thumbWidth+'px').fadeIn(250);
		$('#image-zoomer img').css('top', ((containerHeight/2)-(thumbHeight/2))+'px');
		$('#image-zoomer img').css('left', ((containerWidth/2)-(thumbWidth/2))+'px');
	});
	$('#image-zoomer img').click(function(e) {
		if ($('#image-zoomer img').css('height') == imageHeight+'px') {
			$('#image-zoomer img').animate({height: thumbHeight+'px', width: thumbWidth+'px', top: (containerHeight-thumbHeight)/2, left: (containerWidth-thumbWidth)/2}, 150);
			$('#image-zoomer .marker').html('+ click to enlarge');
		} else if ($('#image-zoomer img').css('height') == thumbHeight+'px') {
			offset = $('#image-zoomer').offset();
			mouseX = (e.pageX - offset.left);
			mouseY = (e.pageY - offset.top);
			if (imageHeight >= containerHeight) {
				imageTop = (imageHeight - containerHeight) / 100 * (100 / containerHeight * mouseY) * -1;
			} else {
				imageTop = (containerHeight/2)-(imageHeight/2);
			}
			if (imageWidth >= containerWidth) {
				imageLeft = (imageWidth - containerWidth) / 100 * (100 / containerWidth * mouseX) * -1;
			} else {
				imageLeft = (containerWidth / 2) - (imageWidth / 2);
			}
			$('#image-zoomer img').animate({
				height: imageHeight+'px', 
				width: imageWidth+'px', 
				top: imageTop + 'px',
				left: imageLeft + 'px'
			}, 150);
			$('#image-zoomer .marker').html('- click to zoom out');
		}
	});
	$('#image-zoomer img').mousemove(function(e) {
		offset = $('#image-zoomer').offset();
		mouseX = (e.pageX - offset.left);
		mouseY = (e.pageY - offset.top);
		if (imageHeight >= containerHeight) {
			imageTop = (imageHeight - containerHeight) / 100 * (100 / containerHeight * mouseY) * -1;
		} else {
			imageTop = (containerHeight/2)-(imageHeight/2);
		}
		if (imageWidth >= containerWidth) {
			imageLeft = (imageWidth - containerWidth) / 100 * (100 / containerWidth * mouseX) * -1;
		} else {
			imageLeft = (containerWidth / 2) - (imageWidth / 2);
		}
		if ($('#image-zoomer img').css('height') == imageHeight+'px') {
			$('#image-zoomer img').css('top', (imageTop) + 'px');
			$('#image-zoomer img').css('left', (imageLeft) + 'px');
		}
	});

	$('#product-thumbnails a').click(function() {
		$('#image-zoomer img').css('height', thumbHeight+'px').hide(); 
		$('#image-zoomer img').attr('src', $(this).attr('href'));
		return false;
	});

	// Product Page - Variant Selection
	var productOptions = false;
	var productIdSelect = false;
	var selectedIndex=false;
	$('#productselect').each(function(){
		productSelectClone = this.cloneNode(true);
		productOptions = productSelectClone.getElementsByTagName("option");
		productIdSelect = this;
	});

	$(".selector li a").click(function(){
		// update the selected color
		$("li.selected", $(this).parent().parent()).removeClass("selected");
		$(this).parent().addClass("selected");
		return false;
	});
	$(".size li a").click(function(){
		$('#productId').val($('.size li.selected a').attr('class'));
		var li = $(this).parent();
		selectedIndex = $('.size li').index(li);

		return false;
	});
	$("#productselect").change(function(){
		$('#productId').val($('#productselect').val());
		return false;
	});

	$(".colour li a").click(function(){
		// remove all options from the select, then append any that match class names
		while (productIdSelect.options.length) {
			productIdSelect.remove(0);
			$('.size li').remove(0);
		}
		var pattern2 = new RegExp("( |^)(" + $(this).attr('class') + ")( |$)");
		for (var i = 0; i < productOptions.length; i++) {
			if (productOptions[i].className.match(pattern2)) {
				productIdSelect.appendChild(productOptions[i].cloneNode(true));
				$('.size').append('<li><a href="#" class="'+productOptions[i].value+'">'+productOptions[i].innerHTML+'</a></li>');
			}
		}
		
		//highlight the selected size
		var index = selectedIndex +1;
		$(".size :nth-child("+index+")").addClass("selected");
		$("#productselect :nth-child("+index+")").attr("selected","selected");
		$('#productId').val($('#productselect').val());
		
		
		$(".selector li a").click(function(){
			// update the selected color
			$("li.selected", $(this).parent().parent()).removeClass("selected");
			$(this).parent().addClass("selected");
			updateStatus();
			return false;
		});
		$(".size li a").click(function(){
			var valueID = parseInt($('.size li.selected a').attr('class'));
			$('#productId').val(valueID);
			var li = $(this).parent();
			selectedIndex = $('.size li').index(li);
			updateStatus();
			return false;
		});
		productIdSelect.selectedIndex = 0;
		updateStatus();
		return false;
	});

	$(".colour li.selected a:first-child").click(function(){}, function(){
		$(".size li.selected a:first-child").click();
	});

	// product slider
	$(".product-scroller").accessNews();

	// homepage filter
	$('#featured-nav li a').click(function() {

		// change selected nav tab
		$("li.selected", $(this).parent().parent()).removeClass("selected");
		$(this).parent().addClass("selected");
		
		// filter out items to name of selected nav tab
		var sel = '.'+$(this).attr('name');
		$('li', '.products').hide();
		$('.products').css('width', $('li:first', '.products').outerWidth() * $('.products').children(sel).length).css('left', 0);
		$(sel, '.products').show();

		return false;
	});
	
	$('#general-friend').click(function() {
		window.open(this.href,'Send to a friend','resizable=0,menubar=0,status=0,location=0,scrollbars=0,toolbar=0,width=600,height=460');
		return false;
	}); 
	
	$('#general-share-panel').css('opacity', 0);
	$('#general-share').hover(function() {
		if ($('#general-share-panel').css('opacity')=='0') {
			$('#general-share-panel').animate({opacity:1, right:"160px"});
		} else {
			$('#general-share-panel').animate({opacity:0, right:"180px"});
		}
	}).click(function() {
		return false;
	});
	$('#general-share-panel').mouseleave(function() {
		$(this).animate({opacity:0, right:"180px"});
	});
	
	//Handle stock option in the product page
	$(".size li a").click(function(){
		updateStatus();
	});
	
	function updateStatus(){
		
		var productId =  $("#productId").val();
		var productStock = $('#product-id-'+productId).text();
		if(productStock !== ''){
			if (productStock == 0){
				$(".product-buttons-container").hide();
				$(".product-message").text("This product is currently out of stock");
			} else  if(productStock == 1){
				$(".product-buttons-container").show();
				$(".product-message").text("");
			} else  if(productStock == 3){
				$(".product-buttons-container").hide();
				$(".product-message").text("This product requires the presentation of a Letter of Introduction. For product enquiries or to place your order, please contact Mailorder on Freecall Australia 1800 811 312");
			} else  if(productStock == 4){
				$(".product-buttons-container").hide();
				$(".product-message").text("New Season - not yet in stock");
			}  else  if(productStock == 5){
				$(".product-buttons-container").show();
				$(".product-message").text("This product is ordered directly from the supplier upon purchase and therefore order turnaround is approx. 1-2 weeks. Any queries, please contact Mailorder on Freecall Australia 1800 811 312.");
			} else  if(productStock == 6){
				$(".product-buttons-container").hide();
				$(".product-message").text("Available In Store Only.");
			} else  if(productStock == 7){
				$(".product-buttons-container").show();
				$(".product-message").text("Available online only. Not to be used in conjunction with any other offer.");
			} 
		}
	}
	
	$(".colour :first-child a").trigger("click");
});

// TODO jQuery
function populateAddress(addressType, selectBox, form) {
	selectedId = selectBox.options[selectBox.selectedIndex].value;
	if (selectedId) {
		if (customerAddresses.length) {
			for(x=0; x < customerAddresses.length; x++) {
				if (customerAddresses[x].address_id == selectedId) {
					form.elements[addressType+'_address_firstname'].value = customerAddresses[x].address_firstname;
					form.elements[addressType+'_address_lastname'].value = customerAddresses[x].address_lastname;
					form.elements[addressType+'_address_line_one'].value = customerAddresses[x].address_line_one;
					form.elements[addressType+'_address_line_two'].value = customerAddresses[x].address_line_two;
					form.elements[addressType+'_address_state'].value = customerAddresses[x].address_state;
					if (addressType != 'delivery') {
						form.elements[addressType+'_address_postcode'].value = customerAddresses[x].address_postcode;
						for(y=0; y<form.elements[addressType+'_address_country'].options.length; y++) {
							if (form.elements[addressType+'_address_country'].options[y].value == customerAddresses[x].address_country){
								form.elements[addressType+'_address_country'].selectedIndex = y;			
								break;
							}
						}
					}
					form.elements[addressType+'_address_phone'].value = customerAddresses[x].address_phone;
					break;
				}
			}
		} else if (customerAddresses[0].address_id == selectedId) {
			form.elements[addressType+'_address_firstname'].value = customerAddresses[0].address_firstname;
			form.elements[addressType+'_address_lastname'].value = customerAddresses[0].address_lastname;
			form.elements[addressType+'_address_line_one'].value = customerAddresses[0].address_line_one;
			form.elements[addressType+'_address_line_two'].value = customerAddresses[0].address_line_two;
			form.elements[addressType+'_address_state'].value = customerAddresses[0].address_state;
			if (addressType != 'delivery') {
				form.elements[addressType+'_address_postcode'].value = customerAddresses[0].address_postcode;
				for(y=0; y<form.elements[addressType+'_address_country'].options.length; y++) {
					if (form.elements[addressType+'_address_country'].options[y].value == customerAddresses[0].address_country){
						form.elements[addressType+'_address_country'].selectedIndex = y;			
						break;
					}
				}
			}
			form.elements[addressType+'_address_phone'].value = customerAddresses[0].address_phone;
		}
	}
}

function resetAddressSelect(addressType, form) {
	form.elements[addressType+'_address_id'].selectedIndex = 0;
}

