j(document).ready(function() {
					   
	var j = jQuery.noConflict();
	//j("a.anchorLink").anchorAnimate();
			   
	 //Trigger any lightbox content
	j("a#inline-lightbox").fancybox({
		'hideOnContentClick': true,
		'autoDimensions': false
	});
	
	if (j('.slideshow').length != 0) {
		initHomepageSlideshow();
	}
	
	if (j('.homepagePromoOuter').length != 0) {
		initHomepagePromos();
	}
	
	if (j('.categoryPromo').length != 0) {
		initCategoryPromos();
	}
	
	if (j('.categoryIbanner').length != 0) {
		initCategorySlideshow();
	}
	
	if (j('.products-grid').length != 0 || j('.block-related').length != 0) {
		initProductGrid();
	}
	
	if (j('.product-view').length != 0) {
		initProductDetail();
	}
	
	if (j('#promoCodeForm').length != 0) {
		initPromoCode();
	}

	if (j('.find-us-postcode-form').length != 0) {
		initDirections();
	}

    if(j('.hoverbox').length != 0) {
        initHoverBox();
    }
	
});


// http://www.position-absolute.com/articles/better-html-anchor-a-jquery-script-to-slide-the-scrollbar/
jQuery.fn.anchorAnimate = function(settings) {

 	var j = jQuery.noConflict();
	
	settings = jQuery.extend({
		speed : 900
	}, settings);	

	return this.each(function(){
		var caller = this
		j(caller).click(function (event) {	
			event.preventDefault()
			var locationHref = window.location.href
			var elementClick = j(caller).attr("href")

			var destination = j(elementClick).offset().top;
			j("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
				//window.location.hash = elementClick
			});
		  	return false;
		})
	})
}

function initHomepageSlideshow()
{
	var j = jQuery.noConflict();
	
	j('.slideshow').cycle({
		fx: 'fade',
		speed:  1200,
		timeout:  6000,
		pager:  '.rotatorThumbs ul', 
		pagerAnchorBuilder: function(idx, slide) { 
			// return selector string for existing anchor 
			return '.rotatorThumbs li:eq(' + idx + ') a'; 
			
		} 
	});
	
	
	//fire off GA event tracking
	//_gaq.push(['_trackEvent', 'test', 'load', 'Go!']);
}

function initHomepagePromos()
{
	var j = jQuery.noConflict();
	
	j('.homepagePromo .overlay').css('background','#0054a5');
	j('.homepagePromo .overlay').hide();
	
	j('.homepagePromo a').hover(function() {
		j(this).parent().parent().find('.overlay').show();
  	}).mouseleave(function() {
    	j(this).parent().parent().find('.overlay').hide();
 	});
	

}

function initCategoryPromos()
{
	var j = jQuery.noConflict();
	
	j('.categoryPromo .overlay').css('background','#0054a5');
	j('.categoryPromo .overlay').hide();
	
	j('.categoryPromo a').hover(function() {
		j(this).parent().parent().find('.overlay').show();
  	}).mouseleave(function() {
    	j(this).parent().parent().find('.overlay').hide();
 	});
}

function initCategorySlideshow()
{
	var j = jQuery.noConflict();
	
	j('.slideshow').cycle({
		fx: 'fade',
		speed:  1200,
		timeout:  6000,
		pager:  '.categorySlideshowNav ul', 
		pagerAnchorBuilder: function(idx, slide) { 
			// return selector string for existing anchor 
			return '.categorySlideshowNav li:eq(' + idx + ') a'; 
		}
	});
	
	j('#pauseButton').click(function(e) { 
		e.preventDefault();
        var catName = j('#pauseButton').attr( "class" ).replace( "pause-button-", "" );
		_gaq.push(['_trackEvent', 'Category page - '+catName, 'Click', 'Slideshow nav pause']);
		j('.slideshow').cycle('pause');
		j('#pauseButton').hide(); 
		j('#resumeButton').show();
		
	});
	
	j('#resumeButton').click(function(e) { 
		e.preventDefault();
        var catName = j('#resumeButton').attr( "class" ).replace( "resume-button-", "" );
		_gaq.push(['_trackEvent', 'Category page - '+catName, 'Click', 'Slideshow nav play']);
		j('.slideshow').cycle('resume');
		j('#pauseButton').show(); 
		j('#resumeButton').hide();
	});
}

function initProductGrid()
{
	var j = jQuery.noConflict();
	
	j('.item h2 a').hover(function() {
		//alert(j(this).parent().find('.product-image'));
		j(this).parent().parent().find('.product-image').addClass('active');
  	}).mouseleave(function() {
    	j(this).parent().parent().find('.product-image').removeClass('active');
 	});
	
	j('.item .price-box').hover(function() {
		//alert(j(this).parent().find('.product-image'));
		j(this).parent().find('.product-image').addClass('active');
  	}).mouseleave(function() {
    	j(this).parent().find('.product-image').removeClass('active');
 	});
	
	j('.item .price-box').click(function(e) {
		e.preventDefault(); 
		var productLink = j(this).parent().find('.product-image').attr("href");
		window.location = productLink;
	});

}

function initProductDetail()
{
	var j = jQuery.noConflict();
	prodName = j('.product-name h1').text();
	initProductDetailTabs();
	
	//set up "see large view" link
	var imgLink = j('.more-views:first a').attr("href");
	j('#largeView').attr("href",imgLink);
	
	j('.more-views a').click(function(e) {
		e.preventDefault();
		//set up "see large view" link
		var imgLink = j(this).attr("href");
		j('#largeView').attr("href",imgLink);
		
		//set active nav state
		j(this).parent().parent().find('li').removeClass('selected');
		j(this).parent().addClass('selected');

	});
	
	j('#inline-lightbox').click(function(e) {
		e.preventDefault();						   
		var view = j(this).attr("href");	
		view = parseInt(view.substr(11, 1)) + 1;
		_gaq.push(['_trackEvent', 'Product detail - ' + prodName, 'Click', 'See large view', view]);
	});

	
	j('#quantityPlusBtn').click(function(e) {

		e.preventDefault();
		var value = parseInt(j('#qty').val());
		j('#qty').val(value + 1);
		var newValue = parseInt(j('#qty').val());
		_gaq.push(['_trackEvent', 'Product detail - ' + prodName, 'Click', 'Quantity plus', newValue]);
	});
	
	j('#quantityMinusBtn').click(function(e) {	
		e.preventDefault();
		var value = parseInt(j('#qty').val());
		if(value > 0)
		{
			j('#qty').val(value - 1);
		}
		var newValue = parseInt(j('#qty').val());
		_gaq.push(['_trackEvent', 'Product detail - ' + prodName, 'Click', 'Quantity minus', newValue]);
	});

}


function initProductDetailTabs()
{
	var j = jQuery.noConflict();
	prodName = j('.product-name h1').text();
	
	j('#deliveryDetails').hide();
											   
	j('#productDetailsTab').click(function(e) {	
		e.preventDefault();
		j('#deliveryDetailsTab').removeClass('active');
		j(this).addClass('active');
		j('#deliveryDetails').hide();
		j('#productDetails').show();
		_gaq.push(['_trackEvent', 'Product detail - ' + prodName, 'Click', 'Product details tab']);
	});
	
	j('#deliveryDetailsTab').click(function(e) {	
		e.preventDefault();
		j('#productDetailsTab').removeClass('active');
		j(this).addClass('active');
		j('#productDetails').hide();
		j('#deliveryDetails').show();
		_gaq.push(['_trackEvent', 'Product detail - ' + prodName, 'Click', 'Delivery and Returns tab']);
	});
	
	
}






function initDirections()
{
	
	var j = jQuery.noConflict();
	var directionsDisplay;
	var directionsService = new google.maps.DirectionsService();
	var map;

	function initialize() {
		directionsDisplay = new google.maps.DirectionsRenderer();
		var latlng = new google.maps.LatLng(51.383219, -2.357407);
        var image = '/skin/frontend/bathrugby/default/images/bathrugby/google_map_icon.png';
		var myOptions = {
		  zoom: 16,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
		directionsDisplay.setMap(map);
	
		var marker = new google.maps.Marker({ position: latlng, map: map, icon: image,/*shadow: shadow, shape: shape, */ title: "Bath Rugby Shop", zIndex: 2 });
	}
	
	
	function calcRoute() {
		var start = document.getElementById("postcode").value;
		var end = "BA2 4BA";
		var request = {
			origin:start,
			destination:end,
			travelMode: google.maps.TravelMode.DRIVING
		};
		directionsService.route(request, function(result, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(result);
			}
		});
	}
	

	j('#directionsBtn').click(function(e) {	
		e.preventDefault();
		calcRoute();
	});

	initialize();
	initPostcodeForm();
}





function initPostcodeForm()
{
	
	
	var j = jQuery.noConflict();

	var message = j("#postcode").val();
	

	j('#postcode').focus(function() {
		if(j("#postcode").val() == message){							   
			j("#postcode").val("");
		}
	});

	j('#postcode').blur(function() {
	  if(j("#postcode").val() == ""){
		j("#postcode").val(message);
	  }
	});
}



function initPromoCode()
{
	
	var j = jQuery.noConflict();
	j('#promoCodeForm').hide();
	j('#promoCodeLink').show();

	j('#promoCodeLink').click(function(e) {	
		e.preventDefault();
		j(this).hide();
		j('#promoCodeForm').fadeIn();
	});
	
}


function initHoverBox()
{
    var j = jQuery.noConflict();
	
    if (j(".hoverbox").length != 0){

        j(".hoverbox").each(function(){

            // remove alt attr
            //j(this).removeAttr("alt");
            var tt = j(this).attr("id");

            j(this).click(function(event){
                            event.preventDefault();
            });

            j(this).mouseover(function(){
                            j("." + tt).css({opacity:1,display:"none"}).fadeIn(200);
            }).mousemove(function(kmouse){
                            var left_pos;
                            var top_pos;
                            left_pos = kmouse.pageX + 25;
                            top_pos = kmouse.pageY - 25;
                            j("." + tt).css({left:left_pos, top:top_pos});
            }).mouseout(function(){
                            j("." + tt).hide();
            });
        });
    }
}


function updateQty( id, increment )
{
    var j = jQuery.noConflict();
    if( j("#"+id).length > 0 && j("#"+id).attr( "disabled" ) != "disabled" )
    {
        var value = parseInt( j("#"+id).val() );
        j("#"+id).val( value + increment );
    }
}


function validateNumber( elementid )
{
    var j = jQuery.noConflict();
    var strValidChars = "0123456789";
    var valid = true;
    for (var i = 0; i < j("#"+elementid).val().length && valid == true; i++)
    {
        var strChar = j("#"+elementid).val().charAt(i);
        if (strValidChars.indexOf(strChar) == -1)
            valid = false;
    }

    if( valid )
    {
        var value = parseInt( j("#"+elementid).val() );
        if( value > 22 )
            valid = false;
    }

    if( !valid )
    {
        if( !j("#"+elementid).hasClass('validation-failed') && j("#advice-required-number").length == 0 )
        {
            j("#"+elementid).addClass('validation-failed');
            j("#"+elementid).after( '<div id="advice-required-number" class="validation-advice">You must enter a valid number between 1 and 22</div>' );
        }
    }
    else
    {
        j("#"+elementid).removeClass('validation-failed');
        j("#advice-required-number").remove();
    }

    return valid;
}
