// We want to now when the user is scrolling the window
window.scrolling = false;
$(window).bind('scrollstart scrollstop', function(e) {
	
	if (e.type === 'scrollstart')
	{
		window.scrolling = true;
		$('div.grid-item.has-mouse').mouseout();
	}
	else
	{
		window.scrolling = false;
	}
});

// Check for ellipsis support?
window.ellipsis_support = true;
var s = document.documentElement.style;
if ( ! ('textOverflow' in s || 'OTextOverflow' in s)) {
    window.ellipsis_support = false;
}

function product_events()
{
    // When grid items come into view:
	$('div.grid-item.new:not([data-type=artist], [data-type=label])').one('inview', function (event, visible) {
	    if (visible == true) {
			var
				$this = $(this),
				toggle = $this
					.find('> div.front-container')
					.find(' > div.top-right-product-box, > div.quick-look-button, > a.img > img.bw');
			
			// Initially cache some vars for the grid-items
			$this.data('toggle', toggle);

            $this.removeClass('new');

			// No ellipsis support?
			if ( ! ellipsis_support) {
				$this.find('.info .ellipsis').each(function() {
					var $this = $(this);
					$this.attr('data-text-v1', $this.html());
					$this.ellipsis();
					$this.attr('data-text-v2', $this.html());
				});
			}
	    }
	});
    // Trigger scroll event
	$(window).scroll();
}

$(function() {
    
	// Compile templates
	window.tpl = {
		quick_look_container: _.template($('#quick-look-container').html())
	};
	
	// Effect speed
	var grid_hover_speed = $.browser.msie ? 'fast' : 'medium';
	var grid_icons_hover_speed = $.browser.msie ? 'fast' : 'medium';

	$('body')

    /*.delegate('.quick-look-container a', 'click', function() {
        $(this).closest('.grid-item').remove();
    })*/
	
	// Hover over grid-item
	.delegate('div.grid-item:not([data-type=artist], [data-type=label])', 'mouseenter mouseleave mousemove', function(e) {
		
		var	$this = $(this);
		
		if ( ! $this.data('toggle'))
		{
			return;
		}
		
		var
			toggle = $this.data('toggle'),
			opacity = toggle.css('opacity'),
			css = {display: 'block'};

		// Mouse enter
		if (e.type === 'mouseenter')
		{
			if ($this.data('timeout') || window.scrolling || $this.hasClass('has-mouse') || $this.hasClass('hovered') || $this.hasClass('has-been-cloned'))
			{
				return;
			}

			$this.addClass('has-mouse');
			
			$this.data('timeout', setTimeout(function() {
				if ($this.hasClass('has-mouse'))
				{
					$this.addClass('hovered');
					if (opacity == 1)
					{
						css['opacity'] = 0;
					}
					
					toggle.stop().css(css).fadeTo(grid_hover_speed, 1);
				}
				$this.removeData('timeout');
			}, 100));
		}
		
		// Mouse leave
		else if (e.type === 'mouseleave')
		{
			
			// The grid item has just been cloned and
			// the clone is positioned on top of it
			// so don't fire the mouseleave event
			if ($this.hasClass('has-been-cloned'))
			{
				return;
			}
			
			$this.removeClass('has-mouse');
			
			// The grid item does not need to fade out, because
			// it's not even visible, this may not be needed but just incase...
			if (toggle.css('display') == 'none')
			{
				return;
			}
			
			toggle.stop().fadeTo(grid_hover_speed, 0, function() {
				$this.removeClass('hovered');
				toggle.css('display', 'none').each(function(i, item) {
					// Remove opacity attributes from the element styles
					try
					{
						item.style.opacity = ''; // W3C
						item.style.filter = ''; // IE
					} catch(e) {}
				});
			});
		}
		
		// Mouse move
		else if (e.type === 'mousemove')
		{
			if ($this.hasClass('has-mouse') || window.scrolling)
			{
				return;
			}
			
			// After a scroll the mouse might happen to be on a
			// grid item, so if the mouse moves at least 1px it
			// will trigger the grid items' mouseenter
			$this.mouseover();
		}
	})
	
	// Hover over grid-item's info area
	.delegate('div.grid-item > div.info', 'mouseenter mouseleave mousemove', function(e) {

        var $this = $(this);

        if ($this.data('type') === 'artist' || $this.data('type') === 'label')
        {
            return;
        }

		var
			toggle = $this.find(' > div:last'),
			opacity = toggle.css('opacity'),
			css = {display: 'block'};
			
		// Mouse enter
		if (e.type === 'mouseenter')
		{
			if (($this.data('timeout') || window.scrolling || $this.hasClass('has-mouse')))
			{
				return;
			}
			
			$this.addClass('has-mouse');
			
			function do_animation(speed)
			{
				if (opacity == 1)
				{
					css['opacity'] = 0;
				}
                if ($this.closest('.grid-item').hasClass('banner'))
                {
                    $this.find('> div:first').stop().animate({opacity: 0}, speed);
                }
				toggle.stop().css(css).fadeTo(speed, 1);
			}
			
			/*if ($this.parent().hasClass('hovered'))
			{
				do_animation($.browser.msie ? 0 : 50);
			}
			else
			{*/
				$this.data('timeout', setTimeout(function() {
					if ($this.hasClass('has-mouse'))
					{
						do_animation(grid_icons_hover_speed);
					}
					$this.removeData('timeout');
				}, 100));
			/*}*/
		}
		
		// Mouse leave
		else if (e.type === 'mouseleave')
		{
			$this.removeClass('has-mouse');
			
			if (toggle.css('display') == 'none')
			{
				return;
			}
			
            if ($this.closest('.grid-item').hasClass('banner'))
            {
                $this.find('> div:first').animate({opacity: 1}, grid_icons_hover_speed);
            }
			toggle.stop().fadeTo(grid_icons_hover_speed, 0, function() {
				toggle.css('display', 'none').each(function(i, item) {
					// Remove opacity attributes from the element styles
					try
					{
						item.style.opacity = ''; // W3C
						item.style.filter = ''; // IE
					} catch(e) {}
				});
			});
		}
		
		// Mouse move
		else if (e.type === 'mousemove')
		{
			if ($this.hasClass('has-mouse') || window.scrolling)
			{
				return;
			}
			
			$this.mouseover();
		}
	})
	
	// Show quick-look
	.delegate('div.grid-item > .front-container > .quick-look-button', 'click', function(e) {
	
		var $this = $(this);
		if ($this.hasClass('clicked'))
		{
			return;
		}
		
		$this.addClass('clicked');
		setTimeout(function() {
			$this.removeClass('clicked');
		}, 250);
	
		// Do we need to close the previuosly expanded grid item?
		if (window.to_be_closed_grid_item)
		{
			window.to_be_closed_grid_item.find('.quick-look-container .quick-look-button').click();
			window.cloned_grid_item.removeClass('has-been-cloned');
			window.cloned_grid_item.mouseout();
		}
		
		var
			$this = $(this),
			
			// The original grid item, the one we clone from
			// Mark the original "has been cloned"
			original_grid_item = $this.parent().parent().addClass('has-been-cloned'),
			
			// Clone the grid item and put the clone on top of it
			clone = original_grid_item.find('.info > div').stop(true, true).end().clone(true)
				.css({
					position: 'absolute',
					top: original_grid_item.offset().top,
					left: original_grid_item.offset().left
				})
				.appendTo('#grid-item-cloned');

            var addthis = clone.find('.info .addthis_button').clone();
            addthis.removeClass('addthis_evented');
            clone.find('.info .addthis_button').replaceWith(addthis);
			
		clone.find('.info .line1').html(original_grid_item.find('.info .line1').attr('data-text-v1'));
		clone.find('.info .line2').html(original_grid_item.find('.info .line2').attr('data-text-v1'));
		clone.find('.info .line3').html(original_grid_item.find('.info .line3').attr('data-text-v1'));
		clone.find('.info .line4').html(original_grid_item.find('.info .line4').attr('data-text-v1'));
        
        if ($this.hasClass('page-release'))
        {
            var gi = $this.closest('.grid-item');
            if (gi.index() === 2)
            {
                clone.addClass('last-in-row');
            }
            else
            {
                clone.removeClass('last-in-row');
            }
        }

        // Left position of the clone
        var pos_left = clone.hasClass('last-in-row')
                ? original_grid_item.offset().left - 190
                : original_grid_item.offset().left,
			// Front container of the cloned grid item
			front_container = clone.find(' > .front-container'),
			
			// Template data
			data = $.parseJSON(decodeURIComponent($this.data('tracks-json')));

		// If another grid item is "opened/expanded"
		// We will need to close this one
		window.to_be_closed_grid_item = clone;
		
		window.cloned_grid_item = original_grid_item;
		
		// Insert the quick-look template into the cloned grid item
		$(tpl.quick_look_container(data)).insertAfter(front_container);
		
		var	quick_look_container = front_container.next();	
		
		// Fix IE flicker bug
		front_container.find('a.img > img:first').css('opacity', 1);
		
		front_container.css('z-index', 4);
		
		// Temporarily disable track backgrounds untill the animation ends
		quick_look_container.find('.found').addClass('no-bg');
		
		// Crossfade
		front_container.animate({opacity: 0}, 'fast');
		quick_look_container.animate({opacity: 1}, 'fast');
        front_container.parent().find('.info').animate({width: '360px'}, 'fast');
		front_container.parent().animate({width: '370px', left: pos_left + 'px'}, 'fast', function() {
		
			// Udjust z-indexes
			front_container.css('z-index', 2);
			quick_look_container.css('z-index', 4);
			
			quick_look_container.find('.found').removeClass('no-bg');
			
			// No ellipsis support?
			var s = document.documentElement.style;
			if ( ! window.ellipsis_support) {
				var els = quick_look_container.find('.ellipsis');
				els.ellipsis();
				els.each(function() {
					var $this = $(this);
					$this.attr('data-text-v1', $this.html());
				});
				
				clone.find('.info .ellipsis').each(function() {
					var $this = $(this);
					$this.ellipsis();
				});
			}
			
			// Remove opacity attributes
			try
			{
				front_container.find('a.img > img:first')[0].style.opacity = ''; // W3C
				front_container.find('a.img > img:first')[0].style.filter = ''; // IE
				quick_look_container[0].style.opacity = ''; // W3C
				quick_look_container[0].style.filter = ''; // IE
			} catch(e) {}
		});
	})
	
	// Go back from quick look
	.delegate('div.grid-item > .quick-look-container > .quick-look-button', 'click mouseleave', function(e) {
	
		if (e.type === 'mouseleave')
		{
			$(this).removeClass('hover');
			return;
		}
	
		var
			$this = $(this),
			quick_look_container = $this.parent(),
			front_container = quick_look_container.prev(),
			// The cloned grid item
			grid_item = front_container.parent(),
			grid_item_animate = grid_item.hasClass('last-in-row')
				? {width: '180px', left: grid_item.offset().left + 190}
				: {width: '180px'}
				
		quick_look_container.find('.found').addClass('no-bg');
		
		// Crossfade
		quick_look_container.animate({opacity: 0}, 'fast');
		front_container.animate({opacity: 1}, 'fast');
		
		grid_item.animate(grid_item_animate, 'fast', function() {
			
			// Udjust z-index
			front_container.css('z-index', 4);
			
			// Remove the quick_look_container
			quick_look_container.remove();
			
			// Fix IE flicker
			front_container.find('a.img > img:first').css('opacity', 1);
			
			grid_item.remove();
			
			window.cloned_grid_item.removeClass('has-been-cloned');
		});
	})
	
	// Quick look track activated
	.delegate('div.grid-item > .quick-look-container .track', 'click mouseenter mouseleave open close', function(e) {
		var $this = $(this);
		
		if (e.type === 'mouseenter')
		{
            if ( ! $this.parent().parent().hasClass('all-tracks-expanded'))
			{
                $this.addClass('has-mouse');
                setTimeout(function() {
                    if ($this.hasClass('has-mouse') && ! $this.hasClass('opening') && ! $this.hasClass('active'))
                    {
                        $this.click();
                    }
                }, 200);
            }
		}
		
		if (e.type === 'mouseleave')
		{
			$this.removeClass('has-mouse');
			
			if ( ! $this.parent().parent().hasClass('all-tracks-expanded'))
			{
				$this.data('timeout', setTimeout(function() {
					$this.trigger('close');
				}, 500));
			}
			else
			{
				// No ellipsis support?
				var s = document.documentElement.style;
				if ( ! window.ellipsis_support) {
					$this.find('.ellipsis').html($this.find('.ellipsis').attr('data-text-v1'));
				}
			}
		}
		
		else if (e.type === 'click' || e.type === 'close')
		{
			var speed = 'fast';
			
			if (e.type === 'close')
			{
				var prev_active = $this.parent().find('.track.active:not(.closing):not(.has-mouse)');
				
				if ( ! prev_active.size())
				{
					return;
				}
				
				prev_active.addClass('closing');
				
				prev_active.stop(true, true).animate({
					height: '18px',
					marginBottom: '0px'
				}, speed);
				
				prev_active.find('div.track-title').stop(true, true).animate({
					width: '330px',
					paddingTop: '0px'
				}, speed);
				
				prev_active.find('.right-side').stop(true, true).animate({
					right: '-250px'
				}, speed);
				
				prev_active.find('.track-icons').stop(true, true).animate({
					height: '0px'
				}, speed, function() {
					prev_active.removeClass('active').removeClass('closing');
					// No ellipsis support?
					var s = document.documentElement.style;
					if (!('textOverflow' in s || 'OTextOverflow' in s)) {
						prev_active.find('.ellipsis').html(prev_active.find('.ellipsis').attr('data-text-v1'));
					}
				});
				return;
			}

            if ($this.parent().parent().hasClass('all-tracks-expanded'))
            {
                return;
            }
			
			// Close previuosly opened track
			
			if ($this.siblings('.active, .opening').size())
			{
				var prev_active = $this.siblings('.active, .opening, .track:not(.closing)');
				
				prev_active.addClass('closing');
				
				if (prev_active.parent().parent().hasClass('all-tracks-expanded'))
				{
					prev_active.removeClass('active').removeClass('closing');
					// No ellipsis support?
					if ( ! window.ellipsis_support) {
						
						prev_active.find('.ellipsis').each(function() {
							$(this).html($(this).attr('data-text-v1'));
						});
					}
				}
				else
				{
					prev_active.animate({
						height: '18px',
						marginBottom: '0px'
					}, speed);

					prev_active.find('div.track-title').animate({
						paddingTop: '0px'
					}, speed);
					
					prev_active.find('div.track-title').css({
						width: '330px'
					});

					prev_active.find('.right-side').css({
						right: '-250px'
					});

					prev_active.find('.track-icons').animate({
						height: '0px'
					}, speed, function() {
						prev_active.removeClass('active').removeClass('closing');
						// No ellipsis support?
						if ( ! window.ellipsis_support) {
							prev_active.find('.ellipsis').each(function() {
								$(this).html($(this).attr('data-text-v1'));
							});
						}
					});
				}
			}
			
			// Expand track:
			
			if ($this.hasClass('closing') || $this.hasClass('active') || $this.hasClass('opening'))
			{
				return;
			}
			
			$this.addClass('opening');
			
			if ($this.parent().parent().hasClass('all-tracks-expanded'))
			{
				$this.addClass('active').removeClass('opening');
				// No ellipsis support?
				if ( ! window.ellipsis_support) {
					var el = $this.find('.ellipsis');
					if (el.attr('data-text-v2'))
					{
						el.html(el.attr('data-text-v2'));
					}
					else
					{
						el.ellipsis();
						el.attr('data-text-v2', el.html());
					}
				}
			}
			else
			{
				$this.find('div.track-title').css({
					width: '162px'
				});
			
				$this.find('.right-side').css({
					right: '0px'
				});
				
				$this.animate({
					height: '42px',
					marginBottom: '2px'
				}, speed);
			
				$this.find('div.track-title').animate({
					//width: '162px',
					paddingTop: '4px'
				}, speed);
				
				$this.find('.track-icons').animate({
					height: '20px'
				}, speed, function() {
					$this.addClass('active').removeClass('opening');
					// No ellipsis support?
					if ( ! window.ellipsis_support) {
						var el = $this.find('.ellipsis');
						if (el.attr('data-text-v2'))
						{
							el.html(el.attr('data-text-v2'));
						}
						else
						{
							el.ellipsis();
							el.attr('data-text-v2', el.html());
						}
					}
				});
			}
		}
	});

    // Tooltips
	$('.tip').tipsy({
		fade: true, gravity: 'nw',
		delayIn: 150,
		delayOut: 150,
		html: true,
		no_arrow: true,
		oldstyle: true,
		live: true
	});

    $('body').delegate('.grid-item-image', 'mouseenter mouseleave', function(e) {
        if (e.type == 'mouseenter')
        {
            $(this).attr('src', $(this).data('hover'));
        }
        if (e.type == 'mouseleave')
        {
            $(this).attr('src', $(this).data('src'));
        }
    });

    $('body').delegate('.with-grid-image', 'mouseenter mouseleave', function(e) {
        var id = $(this).data('release-id');
        var el = $('.grid-item-image[data-release_id=' + id + ']');
        if (e.type == 'mouseenter')
        {
            el.trigger('mouseover');
        }
        if (e.type == 'mouseleave')
        {
            el.trigger('mouseout');
        }
    });

    $('body').delegate('[data-hover-img]', 'mouseenter mouseleave', function(e) {
        if (e.type == 'mouseenter')
        {
            $(this).attr('src', $(this).attr('data-hover-img'));
        }
        if (e.type == 'mouseleave')
        {
            $(this).attr('src', $(this).attr('data-orig'));
        }
    });
});

