/******************************************************

Concord Main JavaScript -- Digital Download Version

Created: 11 September 2008
Depedencies: jQuery 1.2.6, SWFObject 2.1

******************************************************/

/**
 * The following runs as soon as the DOM is ready to receive input.
 */
$(function() {

	// Initialize tabs
	Tabs.init();

	// If an initial tab should be shown, we can do it here
	if(typeof albumFormat != 'undefined') {
		if(albumFormat == 'MP3') {
			Tabs.show('mp3');
		} else if (albumFormat == 'SACD') {
			Tabs.show('sacd');
		} else if (albumFormat == 'LP') {
			Tabs.show('lp');
		}
	}

	// Activate MP3 buy buttons
	$('a.buyMP3').click(Cart.addMP3);

	// Embed preview SWF
	swfobject.embedSWF('/swf_ddl/preview-masked.swf', 'audioPreviewer', '100', '20', '9.0.0', '/swf_ddl/expressInstall.swf', {}, {}, {id: 'PreviewPlayer', name: 'PreviewPlayer'});

	// Setup audio preview buttons
	$('a.preview').click(playPreview);

	// Old-Skool tour jump menu
	$('.tourModule select').bind('change', function() {
		if(this.value.toLowerCase() != 'select') window.location = this.value;
	});

	// Adjust Media Page Tabs' class names so IE can handle them
	$('#mediaHeader li').each(function() {
		if($(this).hasClass('first') && $(this).hasClass('active')) {
			$(this).removeClass('first').removeClass('active').addClass('activeFirst');
		} else if($(this).hasClass('last') && $(this).hasClass('active')) {
			$(this).removeClass('last').removeClass('active').addClass('activeLast');
		}
	});
	
	// Make sure first option is selected on page load
	$('.featuredMerch select option:first').attr('selected', 'selected');
	
	// Listen for merch format options being selected from a drop-down (size, for example)
	$('.featuredMerch select').bind('change', function() {
		
		if($(this).attr('value') == 'NULL') { // first item
			$('.featuredMerch .outOfStock').hide();
			$('.featuredMerch input.image').hide();
		} else if($(this).attr('value') == '') { // out of stock
			$('.featuredMerch .outOfStock').show();
			$('.featuredMerch input.image').hide();
		} else { // item is available
			$('.featuredMerch .outOfStock').hide();
			$('.featuredMerch input.image').show();
		}
	});

	// Fix merch items in IE. It's the only way.
	if($.browser.msie && $.browser.version < 8) { // IE7 and lower
		$('.featuredMerch select').css({
			position: 'relative',
			top: '-2px'
		});
		$('.featuredMerch .outOfStock').css({
			position: 'relative',
			top: '-4px'
		});
		$('.featuredMerch input.image').css({
			position: 'relative',
			top: '-5px'
		});
	}
	
});


/**
 * Play Track Preview (via Flash/ExternalInterface)
 */
function playPreview() {

    var swf = ($.browser.msie ? window : document)['PreviewPlayer'];

    if(!$(this).data('playing')) {

        $('a.preview').each(function() {
            $(this).data('playing', false).css({
                backgroundPosition: '0 0',
                color: '#4E9D44'
            });
        });

        $(this).data('playing', true).css({
            backgroundPosition: '0 -20px',
            color: '#E01F26'
        });

        try {
            var hash = this.href.match(/\/?(\w+)$/)[1]; // make sure we're JUST getting the hash, not a full URL that the browser might generate from the HREF attribute
            swf.sendTrack(hash); // play audio via Flash/ExternalInterface
        } catch(e) {
            if(console && console.log) console.log(e.message);
        }

    } else {

        $(this).data('playing', false).css({
            backgroundPosition: '0 0',
            color: '#4E9D44'
        });
        swf.stopTrack(); // stop audio via Flash/ExternalInterface
    }

    return false;
}

/**
 * Stop Track Preview (called from Flash via Flash/ExternalInterface)
 */
function stopPreview() {
    $('a.preview').data('playing', false).css({
        backgroundPosition: '0 0',
        color: '#4E9D44'
    });
}

/**
 * Spawn Pop-Up Windows
 */
Popup = {

	open: function(url, width, height, name, toolbar, scroll, x, y) {
		if(name == null) {
			var name = new Date();
			name = name.getTime();
			name = name.toString();
		}

		toolbar				  = toolbar ? 'yes' : 'no';
		scroll				  = scroll ? 'yes' : 'no';
		var features		  = 'toolbar='+toolbar+',menubar='+toolbar+',location='+toolbar+',status='+toolbar+',scrollbars='+scroll+',resizable='+scroll;
		if (width) features	 += ',width='+width;
		if (height) features += ',height='+height;
		if (x) features		 += ',screenX='+x+',left='+x;
		if (y) features		 += ',screenY='+y+',top='+y;
		this.reference		  = window.open(url, name, features);

		if(this.reference != null && ! this.reference.closed) {
			this.reference.focus();
		}
	},

	openCenter: function(url, width, height, name, toolbar, scroll) {
		var x = (width && window.screen.availWidth) ? Math.round((window.screen.availWidth - parseInt(width)) / 2) : 0;
		var y = (height && window.screen.availHeight) ? Math.round((window.screen.availHeight - parseInt(height)) / 2) : 0;
		this.open(url, width, height, name, toolbar, scroll, x, y);
	}
}


/**
 * Spawn Webradio
 */
function openWebRadio(url) {
	Popup.openCenter(url, 510, 240, 'webradio', false, false);
	return false;
}


/**
 * Tab Functionality
 * Requires jQuery
 * Note that this is quite a bit more complicated than it should be because of IE
 */
Tabs = {

	init: function() {

		var tabCount = $('.tabs').children().size(); // added by andrew

		if(tabCount < 2) {
		    $('.tabs>li').addClass('solo');
		} else {
		    $('.tabs>li:first').addClass('activeFirst');
			$('.tabs>li:last').addClass('last');
		}

		if(tabCount > 1) $('.tabs>li>a').click(Tabs.tabClicked);

		// Show the contents of the first tab only
		$('.tabContent>li').hide();
		$('.tabContent>li:first').show();

		// Some fine-tuning for Gecko
		if($.browser.mozilla) {
			$('.tabs>li>a').css('line-height', '25px');
		}

		// Setup additional buttons that should show the MP3 tab
		$('a.mp3DownloadButton').click(function() {
			Tabs.show(1);
	        return false;
		});

	},

	tabClicked: function() {
		var index = $('.tabs>li>a').index(this);

		Tabs.show(index);

		return false;
	},

	show: function(index) {

		var clicked = null;

		// Either show tab based on passed index (as a number) or passed
		// "code" (as a string)
		if(typeof index == 'number') {

			var clicked = $('.tabs>li').eq(index);
		} else {

			var i = 0;

			$('.tabs>li').each(function() {

				if($(this).attr('id').indexOf(index) !== -1) {
					clicked = $('.tabs>li').eq(i);
					index = i;
				}

				i++;
			});
		}

		// Abort the operation if the tab we're looking for is already active (or if there's only 1 tab total)
		if(clicked.attr('class').match(/(?:active|solo)/i)) {
			return false;
		}

		$('.tabs>li').each(function() {
			$(this).removeClass('active');
			$(this).removeClass('first');
			$(this).removeClass('last');
			$(this).removeClass('activeFirst');
			$(this).removeClass('activeLast');
		});

		$('.tabs>li:first').addClass('first');
		$('.tabs>li:last').addClass('last');

		// Juggle around class names. Thanks, IE.
		if(clicked.hasClass('first')) {
			clicked.removeClass('first');
			clicked.addClass('activeFirst');
		} else if(clicked.hasClass('last')) {
			clicked.removeClass('last');
			clicked.addClass('activeLast');
		} else {
			clicked.addClass('active');
		}

		$('.tabContent>li').hide();

		// Show tab contents corresponding to the tab that was clicked
		$('.tabContent>li').eq(index).hide().fadeIn();

		return false;
	}
}

jQuery.fn.fadeIn = function(speed, callback) { 
    return this.animate({opacity: 'show'}, speed, function() { 
        if (jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
};

/**
 * Cart Count Manipulation
 */
Cart = {

	addMP3: function() {
		// Abort if MP3 has aleady been added to cart
		if($(this).data('added')) return false;

		// Send id of item added to server
		$.get($(this).attr('href'), {id: $(this).attr('id')});

		// Update UI
		$(this).data('added', true).css({
			backgroundPosition: '0 -20px',
			color: '#FCE502',
			cursor: 'default'
		});

		Cart.increment();

		return false;
	},

	increment: function() {
		var cartCount = Cart.getCount();
		if(cartCount < 1) {
			$('.itemsInYourCart').addClass("itemInYourCart");
			$('.itemsInYourCart').removeClass("itemsInYourCart");
		} else {
			$('.itemInYourCart').addClass("itemsInYourCart");
			$('.itemInYourCart').removeClass("itemInYourCart");
		}
		Cart.setCount(cartCount + 1);
		
	},

	decrement: function() {
		Cart.setCount(Cart.getCount() - 1);
	},

	setCount: function(n) {
		$('#cartCount').text(Cart.pad(n));
		$('.bonusCartCount').text(Cart.pad(n));
	},

	getCount: function() {
		// Very important! We need to explicitly state that the count be
		// parsed as base 10 or parseInt() assumes something else once we
		// reach 8 items and things start to get funky.
		if($('#cartCount').text() == 'NO' || $('#cartCount').text() == 'no' || $('#cartCount').text() == 'No' || $('#cartCount').text() == 'nO') {
			return parseInt(0, 10);
		} else {
			return parseInt($('#cartCount').text(), 10);
		}
	},

	pad: function(n) {
		//if(parseInt(n) < 10) return '0' + n;
		if(parseInt(n) < 10) return n;
		else return n;
	}
}

