/* Calling sv plugins */
jQuery(function() {
	$('#primary-nav').dropdownNav()

	$('div.Jewellery ul, div.Contemporary ul, div.Designer ul, div.Fine ul').supersleight();

	$('.link-button').linkButton();
	
	$('#content.login').manageLoginFocus();	

	$('.sv-cleartextfield').clearTextfield();

	$('.basketqty').numericUpDown();

	$(document).closeOverlays();
	
	//check there is more than one image before activating slideshow 
	if ($('.slideshowContainer div').length > 1){
		
		$('.slideshowContainer').slideshow({ 
		showPagination: true, 
		fadeSpeed: 1000, 
		slideDelay: 5000, 
		paginationAttributes: { 'class': 'sv-slideshow-pagination', 'id': ''} 
	});
	
	}
	
	jQuery(function() {
		($('.add-to-basket').length) ? $('.add-to-basket .variants select').trigger("change") : null;

	})
	
	if ($('#newsletter-overlay').length && $('#content.homepage').length){
			$('#newsletter-overlay').addClass('enabled');
			$('#newsletter-overlay-lightbox').css('display', 'block');
			$('#newsletter-overlay-lightbox').click(function () {
				if (!$.browser.msie) {
					$('div.overlay').fadeOut('fast');
				}
				if ($.browser.msie) {
					$('div.overlay').css('display', 'none');
				}
				
				$("#newsletter-overlay-lightbox").css('display', 'none');
			 });
	
		}		
	
	
	
});

Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(showAjaxLoader);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(hideAjaxLoader);



function showAjaxLoader() {
    $("#ajax-loader").css('display', 'block');
}

function showAjaxError() {
	$('.overlay').hide();
    $("#ajax-error").css('display', 'block');
	$('html, body').animate({scrollTop:0}, 'fast');
}

function hideAjaxLoader(sender, args) {
   $("#ajax-loader").css('display', 'none');
 
   if (args.get_error() != undefined) {
       showAjaxError();
   }
}



	
	// Carousel
jQuery('#content.homepage .content-carousel-wrapper').each(function() { // setup homepage carousel
    var btnPrev = jQuery('<a />').addClass('sv-carousel-prev')
              .attr('href', '#').text('Back')
              .appendTo(this);

    var btnNext = jQuery('<a />').addClass('sv-carousel-next')
              .attr('href', '#').text('Next')
              .appendTo(this);

    jQuery('.sv-carousel', this).jCarouselLite({
      visible: 1,
      btnNext: btnNext,
      btnPrev: btnPrev,
	  speed: 200,
	  easing: "swing",
	  items: 'ul'
    });	
});
	



jQuery(function() {
	$.ajaxSetup({ // Deftault AJAX setup
		type: "POST",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		error: function(request, textStatus, errorThrown) {
			//alert(request);
			//console.log(errorThrown);
		}
	});

	Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
	
	//Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler)
	
	Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(initializeRequestHandler);
	
	// UPDATE PANELS start here
	function initializeRequestHandler(sender, args) {
		$('.add-to-basket .variants').each(function() {
			var firstTimeVal = sender._getPageLoadedEventArgs(args).get_panelsUpdated() == 0;
			OutOfStockCheck(firstTimeVal);
		});
	}
	
	//function pageLoadingHandler(sender, args) {
	// this can be used to bind events to when a ajaj request is currently happening
	//}
	
	function pageLoadedHandler(sender, args) {
	// this function is called on page load as well as an AJAX partial post ( i.e Always!)
		/*$('.add-to-basket .variants').each(function() {
			OutOfStockCheck();
		});*/
			
		if (args.get_panelsUpdated() == 0) { // anything placed after this condition will only run if the pageLoadedHandler function is called *and* an AJAX postback has occured
			return;
		}

		cbb.init();	


		$('div.overlay:not(".sv-overlay, #email-when-in-stock.overlay")').each(function() {
			if ($.fn.bgiframe){
				$(this).bgiframe();
			}

			var scrollY = document.body.scrollTop || document.documentElement.scrollTop, // get the vertical scroll position of browser document
			  windowHeight = window.innerHeight || document.documentElement.clientHeight,
			  overlayHeight = $(this).height();
			  
		  	$(this).css({ // adjust vertical postion in case user has scrolled down
                		top:  function() {
                    				var verticalDistance = ( windowHeight - overlayHeight ) / 2  + scrollY;
                    				return  (verticalDistance > scrollY) ? verticalDistance : scrollY;
                			    }
  			  }).fadeIn('fast');
		});

		$('.link-button').linkButton();
		$('.sv-cleartextfield').clearTextfield();
		$('.basketqty').numericUpDown();
		$('.variants select').customDropdown();
		

		closeOverlay();
		creditCardDetails();
		giftwrapImage();
		$('input.specify-other').each(function() {
			showOrHideOtherTextfield(this);
		});
		securityOverlays();
		passwordLabels();

	} // end update panels
	

	// Gift Wrap image overlay
	function giftwrapImage() {
		$('.giftwrap a').click(function() {
			if ($('.giftwrap-image').length > 0) {
				$('.giftwrap-image').fadeIn('fast');
				if (jQuery.fn.bgiframe) {
                    $('.giftwrap-image').bgiframe();
				};
				return false;
			}
		});
	}

	// Close overlay
	function closeOverlay() {
		$('a.close').click(function() {
			if (!$.browser.msie) {
				$('div.overlay').fadeOut('fast');
			}
			if ($.browser.msie) {
				$('div.overlay').css('display', 'none');
			}
			
			$("#newsletter-overlay-lightbox").css('display', 'none');
			
			return false;
		});
	}

	// Show or hide Extra Card details based on payment card type
	function creditCardDetails() {
		$('#additional-card-detail').each(function() {
			var creditCardType = $('select.credit-card-type').eq(0);
			var showForCardTypes = ['Maestro', 'Solo'];
			var additionalCardDetails = this;


			function showOrHideAdditionalDetails() {
				if ($.inArray($('option:selected', creditCardType).text(), showForCardTypes) >= 0) {
					$(additionalCardDetails).slideDown();
				} else {
					$(additionalCardDetails).slideUp();
				};
			}

			$(creditCardType).change(showOrHideAdditionalDetails);

			showOrHideAdditionalDetails(); // set intiial state for page

		});
	}

	// Show or hide the textfield for the 'Other' option in  dropdown menus
	function showOrHideOtherTextfield(textfield) {
		var dropdown = $('select', $(textfield).parent()).get(0);

		if (!dropdown) { // exit if can't find a sibling dropdown to trigger the textfield
			return false;
		};

		function showOrHideTextfield() {
			if ($('option:selected', dropdown).val() == 'Other...') {
				$(textfield).show().focus();
			} else {
				$(textfield).hide();
			}
		}

		$(dropdown).change(showOrHideTextfield);

		showOrHideTextfield(); // set correctly for initial page load
	}


	closeOverlay();
	creditCardDetails();
	giftwrapImage();


	$('input.specify-other').each(function() {
		showOrHideOtherTextfield(this);
	});

	//Image swap on product page
	$('.images ul img').each(function() {
		$(this).click(function() {
			$('#mainimage').attr({ 'src': this.src.replace(/_st.jpg/i, '_p.jpg'),
				'alt': this.alt
			});
		});
	});
	
	// View on a model overlay
	$('a.viewmodel').click(function() {
		if ( $('#model-image').length > 0) {
			$('#model-image').fadeIn('fast');
		return false;
		}
	});

	/* Email when back in stock overlay
	$('li.outofstock').click(function() {
		if ($('#email-when-in-stock').length > 0) {
			$('#email-when-in-stock').fadeIn('fast');
			return false;
		}
	});
*/
	// Print link
	$('a.sv-print').click(function() {
		print();
		return false;
	});
	
	// Security and Issue number help overlay
	function securityOverlays() {
		$('.securitynumber a.helplink').click(function() {
			if ($(this).parent().next().length > 0) {
				$(this).parent().next().fadeIn('fast');
				return false;
			}
		});
	}
	securityOverlays();

	// Ghost User Signup: Hide password labels on input field focus 
	function passwordLabels() {
		$('#signup .form input.textfield').focus(function() {
			$(this).prev().hide();
		});
		$('#signup .form input.textfield').blur(function() {
			if ($(this).val() == '') {		//put the default value back if nothing has been entered
				$(this).prev().show();
			}
		});
	}
	passwordLabels();

	// Product list hover effect
	function productListHovers(container) {
		container.children('li').hoverIntent(function() {
			if ($.browser.msie) {		// need to just switch opacities as fading text looks unsightly in IE
				$('.detail .description', this).show();
				$('.detail p.product-name a, .price', this).addClass('faded');
			} else {
				$('.detail .description', this).fadeIn('slow');
				$('.detail p.product-name, .price', this).fadeTo('slow', 0.35);
			}
		}, function() {
			if ($.browser.msie) {
				$('.detail .description', this).hide();
				$('.detail p.product-name a, .price', this).removeClass('faded');
			} else {
				$('.detail .description', this).fadeOut('slow');
				$('.detail p.product-name, .price', this).fadeTo('slow', 1);
			}
		});
	}
	productListHovers($('.two-col .product-list'));

	// Set up showcase carousel
	function showcaseCarousel(list) {

		var visibleItems = 3; 	// how many items visible in carousel

		// Set up carousel structure
		list
			.wrap('<div class="scrollable"></div>')
			.fadeIn("slow");

		var carousel = $('.scrollable');

		// Set up navigation
		var carouselNav = $('<ul class="carousel-nav"></ul> ');

		for (i = 1; i <= list.children('li').length; i++) {		// for every visibleItems (3), create a new nav list item
			if (i % visibleItems == 0) {
				carouselNav.append('<li>' + (i - visibleItems + 1) + ' - ' + i + '</li>');
			} else {		// for when there's left over items
				if (i == list.children('li').length) {		// on the last item do the following
					// create a link for the last items: leftover items up to i 
					if ((list.children('li').length - (i % visibleItems) +1) == i) {
						carouselNav.append('<li>' + i + '</li>');
					} else {
						carouselNav.append('<li>' + (list.children('li').length - (i % visibleItems) +1) + ' - ' + i + '</li>');
					}
				}
			}
		}
				
		if (list.children('li').length == 24) {
			var navViewAll = $('<li class="view-all">View more</li>');
		} else {
			var navViewAll = $('<li class="view-all">View all</li>');
		}
				
		carouselNav.append(navViewAll);

		carousel.after(carouselNav);

		// Initialize scrollable  
		carousel.scrollable({
			items: '.product-list',
			speed: 800,
			navi: 'ul.carousel-nav',
			size: visibleItems
		});
		
        productListHovers( carousel.find('ul.product-list') ); 

		// Set up view all button - unbind click (from scrollable) and add style switching behaviour
		$('.view-all', '.carousel-nav')
			.unbind('click')
			.click(function() {
				$('.showcase')
					.fadeOut("fast", function() {
						$(this)
							.removeClass('showcase')
							.addClass('two-col switched')
							.fadeIn();
                            productListHovers($('.two-col .product-list'));
					});

				$('ul.carousel-nav').hide();
				$('a.prev').hide();
				$('a.next').hide();
			});

	}
	showcaseCarousel($('.showcase #product-list'));

	// Slide down Mini Basket, using hoverIntent
	$('.mybag').hoverIntent(function() {
		$(this).addClass('hover');
		$('#minibasket').slideDown('normal');
	}, function() {
		$(this).removeClass('hover');
		$('#minibasket').slideUp('normal');
	});

	// Slide Down Wishlist Search, using hoverIntent
	$('.account-menu .wishlist').hoverIntent(function() {
		$(this).addClass('hover');
		$('#wishlistminisearch').slideDown('normal');
	}, function() {
		$(this).removeClass('hover');
		$('#wishlistminisearch').slideUp('normal');
	});


	// Product Zoom
	$('.product-detail').each(function() {
		var url = $('form#aspnetForm').attr('action').split('?')[0]
		var productID = url.split('-')[2];

		$.ajax({
			data: JSON.stringify({ productID: productID }),
			url: '/Views/Core/CatalogueProduct.aspx/GetProductImagePaths',
			success: function(data) {
				data = data.d || data; // .NET wraps the data in a d key

				if (data.Value.Zoom.length) {

					if ($(".jqzoom").length > 0) {

						$(".jqzoom").jqueryzoom({
							xzoom: 440, //zooming div default width (default width value is 200)
							yzoom: 570, //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: 450,
							hideElement: ".info"
						});
					}

				};

			}
		});
	});


       

	//Tooltips
	$("#sidebar .breadcrumbs li.crumb").tooltip({
		tip: '.crumbtooltip',
		position: 'center right',
		lazy: true,
		relative: true,
		effect: 'fade',
		fadeOutSpeed: 400,
		fadeInSpeed: 400,
		offset: [12, -3]
	});
	
	$("#sidebar .breadcrumbs .clear-h3").tooltip({
		tip: '.cleartooltip',
		position: 'center right',
		lazy: true,
		relative: true,
		effect: 'fade',
		fadeOutSpeed: 400,
		fadeInSpeed: 400,
		offset: [0, -3]
	}); 
	
		$("#sidebar .breadcrumbs .clear").tooltip({
		tip: '.cleartooltip',
		position: 'center right',
		lazy: true,
		relative: true,
		effect: 'fade',
		fadeOutSpeed: 400,
		fadeInSpeed: 400,
		offset: [0, -3]
	}); 
	

});

// overlay iframe fix for IE (tackles overlay issue for dropdowns and form elements)
$(document).ready(function(){ 
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ){
		$.getScript("/assets/astleyclarke/scripts/jquery.bgiframe.min.js");
	}
});


function LimitTextAreaLength(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}



//Continue shopping button will take you back to the product detail or list page that you were browsing.
//When the url format changes, "/Store" will need to be changed to "/S" -AH
	if (document.referrer.indexOf("/Store") >-1) { 
	$(".con-shopping a").live("click", function(){
    history.go(-1);
    return false;
	});
	}
//document.referrer currently not supported in chrome - so this will temporarily fix until they support it
if ($.browser.safari) {
	$(".con-shopping a").live("click", function(){
    history.back(1);
    return false;
	});
 }

	
function OutOfStockCheck(firstTime) {	
var variantId = $('option:selected', '.add-to-basket .variants select').val();

var data = {
				'productId': productId,
				'variantId': variantId
			};
			
if (!firstTime) {			
	$('.add-to-basket input.addtobag').css('display', 'none');
	$('.add-to-basket .outofstock a').css('display', 'none');
}

$.ajax({
			data: JSON.stringify(data),
			url: '/Views/Core/CatalogueProduct.aspx/GetVariantStockInformation',
			success: function(data) {

				var IsOutOfStock = (data.d.Value.OutOfStock);
				if (IsOutOfStock == true) {
					$('.add-to-basket input.addtobag').css('display', 'none');
					$('.add-to-basket .outofstock a').css('display', 'block');
					
				}
				
				else {
					$('.add-to-basket input.addtobag').css('display', 'block');
					$('.add-to-basket .outofstock a').css('display', 'none');
				}
			
			}
		});
}


 
// AJAX
//$(document).ready(function() {

//    $('div.sv-ajax').each(function() {
//        var ajaxPanel = $(this);
//        var ajaxUrl = $(ajaxPanel).attr('id').match(/[a-zA-Z0-9]+$/);
//        var validationSummary = $('.alert', ajaxPanel);

//        $('.action input', ajaxPanel).click(function() { // might need to be more specific
//            var requestData = [];

//            $(':input:not(:radio), :radio:checked', ajaxPanel).each(function() { // TODO: use jQuery.serializeArray() instead
//                var datum = "'" + this.name + "':'" + $(this).val() + "'";
//                requestData.push(datum);
//            });

//            $.ajax({
//                'url': '/Views/Core/Basket.aspx/DoUserLoginCheckout',
//                'data': "{" + requestData.join(',') + "}",
//                success: function(responseData, textStatus) {

//                    if (responseData.d.Value === true) {
//                        window.location = '/checkout'; // this url should come from the JSON resposne
//                    }

//                    if (responseData.d.Errors && responseData.d.Errors.length > 0) {
//                        displayErrors(ajaxPanel, responseData.d.Errors);
//                    }
//                }
//            });

//            return false;
//        });

//    });
//    
//    $()

//});

//function displayErrors(context, errors)
//{
//    // TODO: cope with finding the right validation summary based on the error group? Don't know if we can do that in JS!
//    var validationSummary = $('.alert', context).empty();
//    
//    $('<h3 />').text('There was a problem').appendTo(validationSummary);
//    var errorList = $('<ul />').appendTo(validationSummary);

//    $(errors).each(function() {
//        $('<li />').text(this.ShortDescription).appendTo(errorList);
//    });
//    
//    if ( $(validationSummary).is(':visible') == false ) {
//      validationSummary.css('marginTop', '-10px')
//                       .fadeIn()
//                       .animate({marginTop: "+10px"}, {queue: false });
//    } 
//    

//}

		






