jQuery.noConflict(); // Run jQuery in noConflict mode so it doesn't clash with prototype

// Put all javascript in the document.ready funcition
jQuery(document).ready(function($j){
	// to prevent horizontal scroll bar when resizing window due to extra wide afeature image
	function windowSize(element){
	    viewWidth = $j(window).width();
	    if (viewWidth < 1400){
			newMargin = - (1400 - viewWidth)/2;
			newMargin = Math.max(newMargin,-240);
	        $j(element).css('margin-left', newMargin);
			$j(element).css('width', (viewWidth - newMargin));
	    }else{
			$j(element).css('margin-left', 'auto');
			$j(element).css('width', 1400);
	    }
	}

	function lookbookBackground(element){
	    viewWidth = $j(window).width();
		newMargin = - (1400 - viewWidth)/2;
		newMargin = Math.max(newMargin,-240);
        $j(element).css('background-position', newMargin+'px 0');
	}

	//run above function on load
	windowSize('.afeature');
	lookbookBackground('.lookbook .wrapper');
	lookbookBackground('.cms-about-us .wrapper');
	// to prevent horizontal scroll bar when resizing window due to extra wide afeature image
	$j(window).resize(function() {
	    windowSize('.afeature');
	    lookbookBackground('.lookbook .wrapper');
		lookbookBackground('.cms-about-us .wrapper');
	});


	// home page afeature images
	$j('#slide ul')
	.cycle({
	    fx:      'fade',
	    speed:    500,
	    timeout:  5000,
	    pause:  0,
	    manualTrump: true,
		pager: '#slide-button ul',
		    pagerAnchorBuilder: function(idx, slide) {
        // return selector string for existing anchor
			return '#slide-button ul li:eq(' + idx + ') a';
		}
	});

	var lis = $j('#slide-button ul li');

	lis.mouseover(function(){
	    $j('#slide ul').cycle(lis.index(this));
		//$j('#slide-button ul li a').eq(lis.index(this)).addClass('active');
	});

	lis.click(function(){
		return false;
	});

	$j('#slide ul li').click(function(){
		window.location = $j(this).find('a').attr('href');
	});
	// end home page afeature images


	//customer services rollover on top nav
	$j('.customer-btn').hover(function(){
		$j(this).addClass('extra-background');
		$j(this).find('ul').addClass('reveal');
	}, function(){
		$j(this).removeClass('extra-background');
		$j(this).find('ul').removeClass('reveal');
	});
	

	//home page bfeatures
	$j('.bfeatures .feature').hover(function() {
		$j(this).css( 'cursor', 'pointer' );
        var feature = $j(this);
		feature.find('.bfeature-title').stop(true, true).fadeOut('200');
        feature.find('.bfeature-reveal').stop(true, true).fadeIn('200');
	}, function(){
        var feature = $j(this);
		feature.find('.bfeature-reveal').stop(true, true).fadeOut('200');
		feature.find('.bfeature-title').stop(true, true).fadeIn('200');
	}).click(function (){
		window.location = $j(this).find('a').attr('href');
    });


	$j(".tab-description").click(function () {
		$j(this).toggleClass("over");
		$j(".delivery-and-returns").fadeOut(200);	
		$j(".garment-care").fadeOut(200);
		$j('#product-options-wrapper').fadeIn(200);
		$j('.product-options-bottom').fadeIn(200);
		$j(".tab-garment-care").removeClass("over");
		$j(".tab-delivery").removeClass("over");
		$j(".tab-description").addClass("selected");
    });

	$j(".tab-delivery").click(function () {
		$j(this).toggleClass("over");
		$j(".delivery-and-returns").slideDown('slow');
		$j(".garment-care").fadeOut(200);
		$j('#product-options-wrapper').fadeOut(200);
		$j('.product-options-bottom').fadeOut(200);
		$j(".tab-description").removeClass("selected");
		$j(".tab-description").removeClass("over");
		$j(".tab-garment-care").removeClass("over");
    	return false;
    });
	
	
	$j(".tab-garment-care").click(function () {
		$j(this).toggleClass("over");
		$j(".garment-care").slideDown('slow');
		$j(".delivery-and-returns").fadeOut(200);
		$j('#product-options-wrapper').fadeOut(200);
		$j('.product-options-bottom').fadeOut(200);
		$j(".tab-description").removeClass("selected");
		$j(".tab-description").removeClass("over");
		$j(".tab-delivery").removeClass("over");
    	return false;
    });
	
	
	// Transparent box on product grid, which contains the product name and price
	$j(".products-grid .item").mouseenter(function() {
		$j(".show-hide",this).stop(true, true).fadeIn(200);
	}).mouseleave(function(){
		$j(".show-hide",this).stop(true, true).fadeOut(200);
    });
	
	$j('.products-grid .item:has(a[href])').click(function()
		{
		var location = $j('a[href]', this).eq(0).attr('href');
			
		if (location !== undefined)
		{
			window.location = location;
			window.status = location;
		}
			
		}).bind('mouseenter mouseleave', function()
		{	
			var title = $j('a[href]', this).eq(0).attr('title');
			$j(this).attr('title', title);
	});
	
	
	
	$j(".thumbnails .item .feature").hover(function() {
		$j(".rollover",this).stop(true, true).fadeIn(200);
	},function(){
		$j(".rollover",this).stop(true, true).fadeOut(200);
    }).find('.rollover').click(function(){
        window.location = $j(this).find('a').attr('href');
    });
	
	$j(".essentials-categories .category-thumbnail").hover(function() {
		$j(".rollover",this).stop(true, true).fadeIn(200);
	},function(){
		$j(".rollover",this).stop(true, true).fadeOut(200);
    }).find('.rollover').click(function(){
        window.location = $j(this).find('a').attr('href');
    });
	
	
	$j(".reveal-extra-categories").click(function () {
		$j(".extra-categories").slideToggle('slow');		
    	return false;
    });
	
	$j(".reveal-list").click(function () {
    	$j(this).parents('h5').nextAll('.list-reveal').slideToggle('slow');
    	return false;
    });
	
	
	$j(".comment-and-share .share-box").mouseenter(function() {
		$j(this).parent().find('.share-box-rollover').stop(true, true).fadeIn(200);
	}).mouseleave(function(){
    	$j(this).parent().find('.share-box-rollover').stop(true, true).fadeOut(200);
    });	
	

	$j(".block-reveal h4").click(function () {
		$j(this).nextAll('.reveal').slideToggle('slow');
    	return false;
    });

	$j(".block-reveal h4").click(function () {
		$j(this).toggleClass("grey");
    });

    // garment care section rollovers
    $j(".symbol-block .symbol").mouseenter(function() {
		$j(this).addClass("over");
    }).mouseleave(function(){
    	$j(this).removeClass("over");
    });

  
    $j(".symbol").hover(function() {
        var index = $j(".symbol").index(this);
        $j(this).parent().next().find('.symbol-description:eq('+index+')').stop(true, true).fadeIn(200);
    }, function(){
        var index = $j(".symbol").index(this);
        $j(this).parent().next().find('.symbol-description:eq('+index+')').stop(true, true).fadeOut(200);
    });
    //end garment care


    // handling search box
	var signup = 'Sign up for our mailing list';

	$j('#newsletter-validate-detail .input-box input[type="text"]').focus(function(){
		if ( $j(this).val() === signup) {
			$j(this).val('');
		}
	}).blur(function(){
		if ($j(this).val() === '') {
			$j(this).val(signup);
		}
	}).val(signup);

	
	/**
	 * Hide/Show search box
	 */
	var searchContainer = $j('#search_mini_form .form-search'),
		searchInput     = $j('input', searchContainer),
		searchButton    = $j('button', searchContainer),
		invisibleClass  = 'invisible',
		closedObj       = {width:2, paddingLeft:0, paddingRight:0},
		openObj         = {width:200, paddingLeft:2, paddingRight:2},
		animation       = {easing: "easeOutSine", duration:200},
		extend           = function(one,two){ return $j.extend({}, one, two);},
		messageTop      = $j('#message-top');
	
	// Hide the input box
	searchInput.addClass(invisibleClass).css(closedObj);
	
	// Listen for intended mouse over and animate
	searchContainer.hoverIntent({
		over: function(){			
			messageTop.fadeOut();
			searchInput.stop(true).removeClass(invisibleClass).animate(extend(animation, openObj));
		},
		out: function(){
			messageTop.fadeIn();
			searchInput.stop(true).animate(extend(animation, closedObj), function(){
				$j(this).blur().addClass(invisibleClass);			
			});
		},
		timeout: 1200
	});
	
	
	
	
	/** Grid items animation Helper */
	var gridAnimationHelper = function(nodes, index) {
		var img;
		var node = nodes.get(index) || null;
		
		if ( ! node) return;		

		$j(node).addClass('grid-item-loading');

		var _animate = function(node) {
			$j('div:first', node).fadeIn(200, function() {
				$j(node).removeClass('grid-item-loading');
				gridAnimationHelper(nodes, ++index);
			});
		}
		
		if ($j('img:first', node).length) {
			img = $j('img', node);
			var preload = new Image();
			preload.onload = function() { _animate(node); }
			preload.src = img.attr('src');
		} else {
			_animate(node);
		}		
	}	

	gridAnimationHelper($j('.grid-thumbnails .item'), 0);

	/** essentials */
	$j('#essentials-slide .items')
	.cycle({
	    fx:      'fade',
	    speed:    300,
	    timeout:  4000,
	    pause:  1,
	    manualTrump: true,
		pager: '#essentials-slide .essentials-navigation',
		pagerEvent: 'mouseover.cycle',
		prevNextEvent:'mouseover.cycle',		
		pagerAnchorBuilder: function (i, el) {
			return '<li><a href="#">'+(i+1)+'</a></li>';
		}
	});

	$j('.essentials-navigation li a').click(function(){
		return false;
	});

	$j('#essentials-slide .items .item .double-cp').hover(function(){
		$j(this).css({'cursor':'pointer', 'backgroundPosition':'0px -181px'});

	}, function(){
		$j(this).css({'backgroundPosition':'0px 0px'});
	}).click(function(){
		window.location = $j(this).find('p a').attr('href');
	});

	/*$j('.double-cp').hover(function(){
		$j(this).css('cursor', 'pointer');
	}).click(function(){
		window.location = $j(this).find('p a').attr('href');
	});*/
	
	$j('.featured-product').hover(function(){
		$j(this).css('cursor', 'pointer');
	}).click(function(){
		window.location = $j(this).find('p a').attr('href');
	});

	// collection home page images
	$j('.essentials-header')
	.cycle({
	    fx:      'fade',
	    speed:    300,
	    timeout:  14000,
	    pause:  1
	});

PAGE_LOADED = true;
});
var PAGE_LOADED = false;
var Tracking = {
    init : function() {
        var self = this;
        document.observe("tracking:opc", this.trackCheckoutStage.bind(this));
        document.observe("tracking:successful_order", this.trackOrder.bind(this));
        document.observe("tracking:page", this.trackPage.bind(this));
    },

    trackOrder : function(event) {
        var qty = event.memo.qty,
            cost = event.memo.cost,
            orderId = event.memo.orderId;

        document.write('<iframe src="https://fls.doubleclick.net/activityi;src=3527484;type=sales006;cat=sales156;qty='+qty+';cost='+cost+';ord='+orderId+'?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
    },

    trackCheckoutStage : function(event) {
        var trackedUrls = new Hash();

        trackedUrls.set('billing','sales303');                // billing
        trackedUrls.set('shipping','sales589');               // shipping
        trackedUrls.set('shipping_method','sales216');        // shipping_method
        trackedUrls.set('payment','sales426');                // payment
        trackedUrls.set('review','sales811');                 // review
        trackedUrls.set('no_clue_how_to_do_this','sales446'); // card details

        var section = trackedUrls.get(event.memo.stage);

        if (undefined != section) {
            this.outputTrackingFrame(section);
        }
    },

    trackPage : function(event) {
        var trackedUrls = new Hash(),
            path = window.location.pathname;

        path = path.replace(/^\/peterwerth\/ecom/, '');
        path = path.replace(/\/$/, '') + '/';

        trackedUrls.set('/','homep412');
        trackedUrls.set('/lookbook/','lookb075');
        trackedUrls.set('/collection/','colle697');
        trackedUrls.set('/blog/','blogu260');
        trackedUrls.set('/about-us/','about281');
        trackedUrls.set('/competitions/peter-werth-experience/','peter688');
        trackedUrls.set('/competitions/peter-werth-experience/confirmation-page/','peter159');
        trackedUrls.set('/customer/account/create/','signu948');
        trackedUrls.set('/customer/account/index/','signu979');
        trackedUrls.set('/collection/coats-and-jackets/','coats705');
        trackedUrls.set('/collection/tailoring/','tailo546');
        trackedUrls.set('/collection/knitwear/','knitw995');
        trackedUrls.set('/collection/trousers-and-jeans/','trous551');
        trackedUrls.set('/collection/shoe-shop/','shoes625');
        trackedUrls.set('/collection/blazers/','blaze063');
        trackedUrls.set('/collection/shirts/','shirt606');
        trackedUrls.set('/collection/tees-and-polos/','teesp896');
        trackedUrls.set('/collection/elements-collection/','eleme270');
        trackedUrls.set('/collection/accessories/','acces090');
        trackedUrls.set('/collection/accessories/scarves-and-hats/','scarv378');
        trackedUrls.set('/checkout/cart/','mybag991');
        trackedUrls.set('/checkout/onepage/','check719');

        var cat = trackedUrls.get(path);

        if (undefined != cat) {
            this.outputTrackingFrame(cat);
        }
    },

    outputTrackingFrame : function(cat) {
        var axel = Math.random() + "";
        var a = axel * 10000000000000;
        var protocol = window.location.protocol + '//';
        var srcPath = protocol+'fls.doubleclick.net/activityi;src=3527484;type=websi956;cat='+cat+';ord=1;num=' + a + '?';
        var node = '<iframe src="'+srcPath+'" width="1" height="1" frameborder="0" style="display:none"></iframe>';

        if (PAGE_LOADED != true) {
            document.write(node);
        } else {
            jQuery('body').append(jQuery(node));
        }
    }
}
Tracking.init();

var gridAnimationHideItemsHelper = function() {
	jQuery('.grid-thumbnails .item').each(function(){
		jQuery('div:first', this).hide();
	});
}
