$(document).ready(function() {
	
	if($('#sizes')) $('#sizes').bgiframe();
	
	//Set custom configurations
	var config = {
	     sensitivity: 20, // number = sensitivity threshold (must be 1 or higher)
	     interval: 100, // number = milliseconds for onMouseOver polling interval
	     over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
	     timeout: 100, // number = milliseconds delay before onMouseOut
	     out: megaHoverOut // function = onMouseOut callback (REQUIRED)
	};

	$("#tabs > ul > li > a").click( function(){
		var loc = window.location;
		var regex = /^.*\/\/[^\/]*\/([^\/]*)\//gi;
		var match = regex.exec( loc );
		if( match )
		{
			loc = match[1];
		}
		else
		{
			loc = 'home';
		}
		_gaq.push(['_trackEvent', 'navigation_tabs', $(this).text().replace( ' ', '_' ), loc ]);
	});
	$("td.mini_basket_summary_checkout > a.checkout_button").click( function() {
		_gaq.push(['_trackEvent', 'navigation_buttons', 'basket_dropdown', 'proceed_to_checkout' ]);
		_gaq.push(['_link', $(this).attr('href'), true ]);
		return false;
	});
	$("a.mini_basket_edit_country_button").click( function(){
		_gaq.push(['_trackEvent', 'navigation_buttons', 'basket_dropdown', 'edit_basket' ]);
		_gaq.push(['_link', $(this).attr('href'), true ]);
		return false;
	});
	$("a.cross_site").click( function(){
		_gaq.push(['_link', $(this).attr('href'), true ]);
		return false;
	});
	$("a.currency_change").click( function(){
		_gaq.push(['_trackEvent', 'currency', 'select', $(this).text() ]);
		_gaq.push(['_link', $(this).attr('href'), true ]);
		return false;
	});
	$("ul#topnav > li > a").click(function(){
		_gaq.push(['_trackEvent', 'navigation_menu', $(this).text() ]);
		_gaq.push(['_link', $(this).attr('href'), true ]);
		return false;
	});
	$("ul#topnav li .sub li a").click(function(){
		var action = $(this).parent().parent().parent().prev().text();
		_gaq.push(['_trackEvent', 'navigation_menu', action, $(this).text() ]);
		_gaq.push(['_link', $(this).attr('href'), true ]);
		return false;
	});
	$("ul#topnav li .sub").css({'opacity':'0'}); //Fade sub nav to 0 opacity on default
	$("ul#topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations	
	
	$('.menu_dropdown_link').hover(
		function(){
			$(this).css('background', '#333333');
			$(this).css('color', '#FFFFFF');
		},
		function(){
			$(this).css('background', 'none');
			$(this).css('color', '#333333');
		}
	);
	
	$('.sub').hover(
		function(){
			$(this).prev('.menu_dropdown_link').css('background', '#333333');
			$(this).prev('.menu_dropdown_link').css('color', '#FFFFFF');
		},
		function(){
			$(this).prev('.menu_dropdown_link').css('background', 'none');
			$(this).prev('.menu_dropdown_link').css('color', '#333333');
		}
	);
	
	$('.more a').click(function(){
		if ($(this).text() == 'show all +') {
			$(this).text('show less -');
			$(this).parent().parent().find('.hid').show(100);
		}
		else {
			$(this).text('show all +');
			$(this).prev('ul').find('.hid').hide();
			$(this).parent().parent().find('.hid').hide(100);
		}
		return false;
	});
	
	$('#add_to_basket').live('click', function(){
		
		product_variant_id = $('#sizes').val();
		_gaq.push(['_trackPageview', '/basket/add/' + product_variant_id]);
		
		if($("#sizes-message").text() != ''){
			$("#sizes-message").text('');
			$("#sizes").css('border','none');
		}
		
		quantity = 1;
		if (product_variant_id > 0 && quantity > 0) {
			addToBasket(product_variant_id, quantity);
		} else {
			$("#sizes").css('border', '3px solid gold');
			$("#sizes-message").text('Please select a size').css('color','red');
		}
		
		return false;
		
	});
	
	$('.add_voucher_to_basket').live('click', function(){
		$("#vouchers").find("select").each(function(){
			name = $(this).attr("name");
			quantity = $(this).val();
			
			product_variant_id = name.replace(/voucher\[(\d+)\]/, '$1');
			
			if (product_variant_id && quantity > 0) {
				addToBasket(product_variant_id, quantity);
			}
		});
		
		return false;
	});
	
	$('.remove_basket_item').live('click', function(){
		
		product_variant_id = $(this).attr('data-ProductVariantId');
		
		if (product_variant_id) {
			removeItemFromBasket(product_variant_id);
			if( $(this).hasClass('basketAddedRemove') )
			{
				$(this).parent().prev().find("span.basketAddedQuantity").text( 0 );
				$('#basket_added_container').stop( true, true ).fadeOut(1200);
			}
		}
		
		return false;
		
	});
	
	$('.mini_basket_increase_quantity').live('click', function() {
		qty = parseInt($(this).attr('data-quantity'), 10) + 1;
		$(this).attr( 'data-quantity', qty );
		updateBasketQuantity($(this).attr('data-basket-item-id'), qty, $(this).attr('data-ProductVariantId'));
		if( $(this).hasClass( 'basketAddedIncrease' ) )
		{
			$('.basketAddedDecrease').attr( 'data-quantity', qty );
			$('#basket_added_container').stop( true,true ).show().delay(3000).fadeOut(1200);
			$(this).prev("span.basketAddedQuantity").text( qty );
		}
		return false;
	});
	
	$('.mini_basket_decrease_quantity').live('click', function() {
		qty = parseInt($(this).attr('data-quantity'), 10) - 1;
		if( qty < 0 )
		{
			return false;
		}
		$(this).attr( 'data-quantity', qty );
		updateBasketQuantity($(this).attr('data-basket-item-id'), qty, $(this).attr('data-ProductVariantId'));
		if( $(this).hasClass( 'basketAddedDecrease' ) )
		{
			if( qty == 0 )
			{
				$('#basket_added_container').stop( true, true ).fadeOut(200);
			}
			$('.basketAddedIncrease').attr( 'data-quantity', qty );
			$('#basket_added_container').stop( true,true ).show().delay(3000).fadeOut(1200);
			$(this).prevAll("span.basketAddedQuantity").text( qty );
		}
		return false;
	});
	
	function updateBasketQuantity(basket_item_id, quantity, product_variant_id) {
		
		if (quantity <= 0) {
			removeItemFromBasket(product_variant_id)
		} else {
		
			$.ajax({
				type: "POST",
				dataType: "xml",
				url: "/ajax/basket/updateBasketQuantity.php",
				data: "basket_item_id=" + basket_item_id + "&quantity=" + quantity,
				success: function(data, textStatus){
	
					success = $(data).find("response").attr('success');
	
					if(success == 'true') {
						getBasketLight();
						getBasketTotal();
					} else {
						alert('Error removing item from basket');
					}
					
				},
				error: function (jqXHR, textStatus, errorThrown){
					log("updateBasketQuantity(): " + textStatus);
				}
			});
		
		}
		
	}
	
	function removeItemFromBasket(product_variant_id){

		$.ajax({
			type: "POST",
			dataType: "xml",
			url: "/ajax/basket/removeItemFromBasket.php",
			data: "product_variant_id=" + product_variant_id,
			success: function(data, textStatus){

				success = $(data).find("response").attr('success');

				if(success == 'true') {
					$('.pv' + product_variant_id).fadeOut(1000, 'linear', function(){
						getBasketLight();
						getBasketTotal();
					});					
				}
				else {
					alert('Error removing item from basket');
				}
				
			},
			error: function (jqXHR, textStatus, errorThrown){
				log("removeItemFromBasket(): " + textStatus);
			}
		});
	}
	
	$('#select_quantity').click(function(){
		$(this).select();
	});
	
	$('.product_size').live('click', function(){
		if ($(this).hasClass('selected_size')) {
			$(this).removeClass('selected_size');
		}
		else {
			$('.product_size').removeClass('selected_size');
			$(this).addClass('selected_size');
		}
		return false;
	});
	
	var $showBasketButton = $('.show_basket_button');
	var $miniBasketContainer = $('#mini_basket_container');
	
	/*
	$(document).keyup(function(e) {
		if (e.keyCode == 27 && $miniBasketContainer.css('height') == '410px') {
			$showBasketButton.removeClass('closebasket').addClass('openbasket');
			$miniBasketContainer.fadeOut(500, 'linear', function(){
				$miniBasketContainer.css('height', '0px');
			});
			return false;
		}
	});
	 */
	
	function getBasketLight(){
		$.ajax({
			type: "POST",
			dataType: "xml",
			url: "/ajax/basket/getBasket.php",
			success: function(data, textStatus){

				success = $(data).find("response").attr('success');

				if(success == 'true') {
					$('#mini_basket').hide().html(ajaxResponseText(data, 'html')).show();
				}
			},
			error: function (jqXHR, textStatus, errorThrown){
				log("getBasketLight(): " + textStatus);
			}
		});

	}

	function getBasketTotal(){
	
		$.ajax({
			type: "POST",
			dataType: "xml",
			url: "/ajax/basket/getBasketTotal.php",
			success: function(data, textStatus){
	
				success = $(data).find("response").attr('success');
	
				if(success == 'true') {
					$('#basket_summary').html('Items: ' + ajaxResponseText(data, 'basket_quantity') + ' | Total: ' + ajaxResponseText(data, 'currency_total'));
					$('.mini_basket_summary_totals_items span').html(ajaxResponseText(data, 'basket_quantity'));
					$('.mini_basket_summary_totals_total span').html(ajaxResponseText(data, 'currency_total'));
					$('.mini_basket_shipping_estimate_price').html(ajaxResponseText(data, 'shipping'));
					$('.mini_basket_shipping_estimate_country').html(ajaxResponseText(data, 'country'));
					$('.mini_basket_shipping_estimate_days').html(ajaxResponseText(data, 'del_est'));
				}
				
			},
			error: function (jqXHR, textStatus, errorThrown){
				log("getBasketTotal(): " + textStatus);
			}
		});
	
	}
	
	function addToBasket(product_variant_id, quantity){

		$.ajax({
			type: "POST",
			dataType: "xml",
			url: "/ajax/basket/addItemToBasket.php",
			data: "product_variant_id=" + product_variant_id + "&quantity=" + quantity,
			success: function(data, textStatus){

				success = $(data).find("response").attr('success');

				if(success == 'true') {
					
					$('#product_quick_look').dialog('close');
					
					getBasketLight();
					getBasketTotal();
					
					$('.basketAddedImage').html(ajaxResponseText(data, 'basketAddedImage'));
					$('.basketAddedName').html(ajaxResponseText(data, 'basketAddedName'));
					$('.basketAddedPrice').html(ajaxResponseText(data, 'basketAddedPrice'));
					$('.basketAddedVariant').html(ajaxResponseText(data, 'basketAddedVariant'));
					$('.basketAddedQuantity').html(ajaxResponseText(data, 'basketAddedQuantity'));					
					$('.basketAddedRemove').attr('data-ProductVariantId', product_variant_id);					
					$('.basketAddedIncrease').attr({
						'data-quantity': ajaxResponseText(data, 'basketAddedQuantity'),
						'data-basket-item-id': ajaxResponseText(data, 'basketItemId'),
						'data-ProductVariantId': product_variant_id
					});
					$('.basketAddedDecrease').attr({
						'data-quantity': ajaxResponseText(data, 'basketAddedQuantity'),
						'data-basket-item-id': ajaxResponseText(data, 'basketItemId'),
						'data-ProductVariantId': product_variant_id
					});
					
					/*
					if (window.pageYOffset > 29) {
						$('#basket_added_container').css('top', window.pageYOffset + 'px');
					}
					else {
						$('#basket_added_container').css('top', '29px');
					}
					*/
					$('#basket_added_container').fadeIn(400, 'linear', function() { $(this).delay(3000).fadeOut(1200) });
					
				}
				
			},
			error: function (jqXHR, textStatus, errorThrown){
				log("addToBasket(): " + textStatus);
			}
		});
	}
	
	function ajaxResponseText( data, key ){
		val = $( "response value[key=" + key + "]", data ).text();
		val = val.replace( /%26/g, "&" );
		val = val.replace( /%3C/g, "<" );
		val = val.replace( /%3E/g, ">" );
		return val;
	}
	
	$('.minimise_basket_button').click(function(){
		closeBasket();
		return false;
	});
	
	$('.view_full_basket_button').click(function(){
		_gaq.push(['_trackPageview', '/basket/view/']);
		//_gaq.push(['_trackEvent', 'navigation_buttons', 'header', 'view_basket' ]);
		openBasket();
		return false;
	});
	
	$showBasketButton.click(function(){
		if ($showBasketButton.hasClass('openbasket')) {
			openBasket();
		} else {
			closeBasket();
		}
		return false;
	});
	
	$('.mini_basket_nav_up_button').live('click', function(){
		basketUp();
		return false;
	});
	
	$('.mini_basket_nav_down_button').live('click', function(){
		basketDown();
		return false;
	});
	
	$('#basketItemsSurround').live('mousewheel', function(event, delta) {		
		if (delta > 0) {
			basketUp();
		} else {
			basketDown();
		}
        return false;
    });
	
	$('#basket_modal').live('click', function(){
		closeBasket();
	});
	
	function closeBasket() {
		$showBasketButton.removeClass('closebasket').addClass('openbasket');
		$miniBasketContainer.fadeOut(500, 'linear', function(){
			$miniBasketContainer.css('height', '0px');
		});
		$('#basketItems').css('top', '0px');
		$('#basket_modal').hide();
	}
	
	function openBasket() {
		getBasketLight();
		getBasketTotal();
		$showBasketButton.removeClass('openbasket').addClass('closebasket');
		$miniBasketContainer.show().animate({ height : "410px" }, 300);
		$('#basket_modal').css({
								'background':'0',
								'height':'100%',
								'width':'100%',
								'position':'fixed',
								'top':'0',
								'left':'0',
								'z-index':'60'
								}).show();
		return false;
	}
	
	var scrolling = false;
	
	function basketUp() {
		if( scrolling )	{
			return false;
		}
		
		var $basketItems = $('#basketItems');
		scrolleditems = parseInt($basketItems.css('top').replace('px', ''), 10) / 60;
		
		//if (parseInt($basketItems.css('top').replace('px', ''), 10) + 60 < 0) 
		scrolling = true;
		if( scrolleditems < 0 ) {
			$basketItems.animate({ top : "+=30px" }, 30, function() { scrolling = false; } );
		} else {
			$basketItems.animate({ top : '0px'}, 30, function() { scrolling = false; } );
		}
		return false;
	}
	
	function basketDown() {
		if( scrolling ) {
			return false;
		}

		var $basketItems = $('#basketItems');
		scrolleditems = parseInt($basketItems.css('top').replace('px', ''), 10) / 60;
		totalitems = Math.floor(parseInt($basketItems.height(), 10) / 60);
		
		//if ((parseInt($basketItems.height(), 10) + parseInt($basketItems.css('top').replace('px', ''), 10)) > 203) 
		if (scrolleditems + totalitems > 3 ) {
			scrolling = true;
			$basketItems.animate({ top : "-=30px" }, 30, function() { scrolling = false; } );
		}
		return false;
	}
	
	if(typeof Globalize != 'undefined') {
		// Globalize allows us to display currencies properly for their native locale
		// i.e. if the currency is set to Euro, the euro symbol comes after the total
		// You must set the culture using "Globalize.culture" before using Globalize.*
		// @link https://github.com/jquery/globalize
		switch(parseInt($('body').data('website-currency-id'), 10)) {
			case 1: Globalize.culture('en-GB'); break; // GBP
			case 2: Globalize.culture('fr-FR'); break; // EUR
			case 3: Globalize.culture('en-US'); break; // USD
			case 4: Globalize.culture('en-AU'); break; // AUD
		}
	}
	
	// Get conversion rate for current currency
	var rate = $('#rate').data('rate');
	var sliderRange = $("#slider-range");
	if( sliderRange.length > 0 )
	{
	var minSlider = parseInt($('#slider_start_value').val(), 10);
	if( minSlider < 10 ) {
		minSlider = 0;
	} else {
		minSlider -= 10;
	}
	var maxSlider = parseInt($('#slider_end_value').val(), 10);
	if( maxSlider < 500 ) {
		if( maxSlider % 100 == 0 ) {
			maxSlider += 100;
		} else {
			maxSlider = maxSlider + 100;
			maxSlider -= maxSlider % 100;
		}
	}

	sliderRange.slider({
		range: true,
		min: minSlider,
		max: maxSlider,
		step: 1,
		values: [parseInt($('#slider_start_value').val(), 10), parseInt($('#slider_end_value').val(), 10)],
		change: function(event, ui) {
			
			$('#page_refreshing').show();
			$('#products_listing').hide();
			
			listing = false;
			var nloc = '';
			
			if (window.location.href.match(/products/)) {
				listing = true;
			}
			
			if (window.location.href.match(/price-\d+(,\d+)?-to-\d+(,\d+)?/)) {
				if (listing) {
					nloc = window.location.href.replace(/price-\d+(,\d+)?-to-\d+(,\d+)?/, 'price-' + ui.values[0] + '-to-' + ui.values[1]).replace(/#.*$/,'');
				} else {
					nloc = window.location.host + '/products' + window.location.pathname.replace(/price-\d+(,\d+)?-to-\d+(,\d+)?/, 'price-' + ui.values[0] + '-to-' + ui.values[1]);
				}
			} else {
				if (listing) {
					nloc = window.location.href + 'price-' + ui.values[0] + '-to-' + ui.values[1] + '/';
				} else {
					nloc = 'http://' + window.location.host + '/products' + window.location.pathname + 'price-' + ui.values[0] + '-to-' + ui.values[1] + '/';
				}
			}
			_gaq.push(['_trackEvent', 'Price', 'slider' ]);
			_gaq.push(['_link', nloc, true ]);
		}, 
		slide: function(event, ui) {
			if(typeof Globalize != 'undefined') $("#amount").html(Globalize.format( ui.values[0] * rate , "c" ) + " to " + Globalize.format( ui.values[1] * rate , "c" ));
		}
	});
	}

	if(typeof Globalize != 'undefined') $("#amount").html(Globalize.format( sliderRange.slider("values", 0) * rate, "c") + " to " + Globalize.format( sliderRange.slider("values", 1) * rate, "c"));
	
	$("#largerImage").live("click",function(ev){
		ev.preventDefault();
		var href = this.href;
		
		$.fancybox({
			href: href,
			'autoScale': true
		})
		 
	});
	
	var top_link_config = {
	     sensitivity: 20, // number = sensitivity threshold (must be 1 or higher)
	     interval: 250, // number = milliseconds for onMouseOver polling interval
	     over: topLinkOver, // function = onMouseOver callback (REQUIRED)
	     timeout: 100, // number = milliseconds delay before onMouseOut
	     out: topLinkOut // function = onMouseOut callback (REQUIRED)
	};
	
	$('.top_link').hoverIntent(top_link_config);
	
	/*$("#countrySelect").click(function(){
		alert('What country?');
		return false;
	});*/
	
	$(".buttonset").buttonset();
	
	if ($("#mini_basket_container").html()) {
		$("#mini_basket_container").bgiframe();
	}
	
	$('.gift_voucher_item_total').show();
	
	$('.voucher-dropdown').change(function(){
		items = 0;
		total = 0;		
		$('.voucher-dropdown').each(function(){			
			items += parseInt($(this).val(), 10);
			total += parseInt($(this).attr('data-voucher-value'), 10) * parseInt($(this).val(), 10);			
		});		
		$('.gift_voucher_items').html(items);
	if(typeof Globalize != 'undefined') {
	var rate = $('#rate').data('rate');
		$('.gift_voucher_total').html(Globalize.format( total * rate, "c"));		
		}
	});
	
	if( jQuery.fn.carousel != undefined )
	{
		if( $('#brand_ticker').length > 0 )
		{
			$('#brand_ticker').carousel('#brand_ticker_prev', '#brand_ticker_next');
			window.setInterval(brand_ticker_slide, 2000);
		}
	}
	
	function brand_ticker_slide(){
	  $('#brand_ticker_next').click();
	}
	
	$('#show_product_video_tab').click(function(){
		$('.ui-state-default a[href$="video"]').click();
	});
	
	// Accounts section
	
	// Only show state select if user selects USA as their country
	$('#addressCountry').toggleStates();
	$('#addressCountry').click(function() {
		$(this).toggleStates();
	}).keyup(function() {
		$(this).toggleStates();
	});
});

/**
 * Toggle the display of US States
 * @usage $('select#states').toggleStates();
 */
(function($) {
	$.fn.toggleStates = function() {
		return this.each(function () {
			var $state = $('label[for=addressState]').parent();
			var $county = $('label[for=addressCounty]').parent();
			var $country = $('#addressCountry > option:selected').val();
			
			if ( ($country != "US") && ($state.not(':hidden')) ) {
				// Hide state select
				$state.hide();
				// Show county input field
				$county.find('input').removeAttr('disabled');
				$county.show();
			} else if ( ($country == "US") && ($state.is(':hidden')) ) {
				// Replace county field with state select
				$county.hide();
				$county.find('input').attr('disabled', 'disabled');
				// Hide the span which says "US orders only" (that's only for non-js users)
				$state.show().find('label span').remove();
				// Remove the option "N/A" (also only for non-js users)
				$state.find('option:contains("N/A")').remove();
			} else if ( ($country == "US") && ($state.not(':hidden')) ) {
				$county.hide();
				$county.find('input').attr('disabled', 'disabled');
			}
		});
	}
})(jQuery);

// Function to calculate total width of all ul's
jQuery.fn.calcSubWidth = function() {
	// Set basic width = padding of the sub
    var rowWidth = 2;
    //Calculate row
    $(this).find("ul").each(function() { //for each ul...
        rowWidth += $(this).width(); //Add each ul's width together
    });
	return rowWidth;
};

function megaHoverOver(){
    $(this).find(".sub").stop().fadeTo('fast', 1).show(); //Find sub and fade it in

    if ( $(this).find(".row").length > 0 ) { //If row exists...

        var biggestRow = 0;	

        $(this).find(".row").each(function() {	//for each row...
            rw = $(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if(rw > biggestRow) {
                biggestRow = rw;
            }
        });

        $(this).find(".sub").css({'width' :biggestRow}); //Set width
        $(this).find(".row:last").css({'margin':'0'});  //Kill last row's margin

    } else { //If row does not exist...

        rw = $(this).calcSubWidth();  //Call function to calculate width of all ul's
        $(this).find(".sub").css({'width' : rw}); //Set Width

    }
}

// On Hover Out
function megaHoverOut(){
	$(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
		$(this).hide();  //after fading, hide it
	});
}

function validateForm(value, type, id) {
	//log('validateForm(value, type, id)', value, type, id);
	$.ajax({
		type: "POST",
		dataType: "xml",
		url: "/ajax/misc/validateForm.php",
		data: "value=" + value + "&type=" + type,
		success: function(data, textStatus){

			success = $(data).find("response").attr('success');
			
			var $selector = $('#'+id);
			if(success == 'true') {
				// Remove pre-existing validation (tick/cross) icons
				if ( ($selector.parent().next().attr('class') == "invalid") || ($selector.parent().next().attr('class') == "valid") ) {
					$selector.parent().next().remove();
				}
				// Display the tick icon to the right of the input
				$selector.css({'background-color':'#e4f4d3'}).parent().after('<div class="valid"></div>');
			}
			else {
				// Remove pre-existing validation (tick/cross) icons
				if ( ($selector.parent().next().attr('class') == "invalid") || ($selector.parent().next().attr('class') == "valid") ) {
					$selector.parent().next().remove();
				}
				// Display the cross icon to the right of the input
				$selector.css({'background-color':'#fbaca5'}).parent().after('<div class="invalid"></div>');
			}
			
		},
		error: function (jqXHR, textStatus, errorThrown){
			log("validateForm(): " + textStatus);
		}
	});
	
}

function topLinkOver(){
	$(this).find('.top_link_hover').slideDown(100);
}

function topLinkOut(){
	$(this).find('.top_link_hover').slideUp(100);
}

// this code prevents google translate to translate dropdown boxes
// without this code FF is buggy and hides the content of options
// rendering dropdown empty

$(document).ready(function() {
    $("select").addClass("notranslate");
});

