/*****************************
 * CATEGORY IMAGES & MENU
 *****************************/
jQuery(function($){
	var categoryMap = ['museum','hatch','membership','tickets', 'donate'],
		menu = $('#SideCategoryList');

	// identify & decorate root categories [musuem, hatch, memberships, tickets]
	$('div.BlockContent > ul > li > a', menu).each(function(i){
		$(this).append('<div />').wrap('<div class="root-category ' + categoryMap[i] + '" />');
	});

	// initialize menu
	$('ul ul ul',menu).hide();
	$('ul li a div', menu).hover(
		function(){$(this).addClass('hover')},
		function(){$(this).removeClass('hover')});
	$('li ul a', menu).click(function(){
		$('a.digome-active', menu).removeClass('digome-active');

		var subnav = $(this).addClass('digome-active').siblings('ul');
		if (subnav.length)
		{
			$('a div',$(this).parent()).addClass('selected');
			if(subnav.hasClass('expanded')){
				return true;
			}
			subnav.slideDown().addClass('expanded');
			return false;
		}
		return true;
	});

	// attempt to identify current category
	if(CMHOF.isCategory)
	{
		var cats = CMHOF.categories,
			root = false;

		$.each(cats,function(index,value){
			var match = unescape(value).replace(/\{.+\}/g,'').replace(/\W/g,'');

			if(index)
			{
				$('> ul > li > a',root).each(function(){
					if($(this).text().replace(/\W/g,'') == match)
					{
						$(this).click();
						root = $(this).addClass('digome-active').parent();
					}
				});
			}
			else
			{
				$('div.root-category',menu).each(function(){
					if($('> a',this).text().replace(/\W/g,'') == match)
					{
						root = $(this).parent();
					}
				});
			}
		});
	}
});

/******************
 * BREADCRUMBS
 ******************/
jQuery(function($){
	$('div.Breadcrumb > ul:last').show().find('li:not(:first)').addClass('smaller');

	// slim down "also in" product categories list
	var dupes = new Array();
	$('div.SubCategoryList ul ul').each(function(){
		// remove all but last category
		$('li:not(:last)',this).remove();

		var test =  $('li a',this).html();

		if($.inArray(test,dupes) > -1)
		{
			$(this).remove();
		}
		else
		{
			dupes.push(test);
		}
	});
});

/******************
 * RIGHT SIDEBAR
 ******************/
jQuery(function($){

	// randomize and limit top-sellers & new products to 3
	$('#LayoutColumn3 ul.ProductList').each(function(){
		var box = $(this);
		$('> li', box).each(function(){
			var e = $(this).remove();
			if(Math.ceil(Math.random()*2) == 2)
			{
				box.append(e);
			}
			else
			{
				box.prepend(e);
			}
		});
		$('li:gt(2)',box).remove();
	});

});

/******************************
 * RELATED AND RECENT PRODUCS
 ******************************/
jQuery(function($){

	$('#LayoutColumn2 #SideProductRelated ul.ProductList li:gt(2)').remove();
	$('#LayoutColumn2 #SideProductRecentlyViewed ul.ProductList li:gt(2)').remove();
});


/******************
 * ZERO price hiding on search results
 ******************/
$().ready(function(){
    $('.SearchPrice em').each(function(i){
        var p = $(this).text();
        if(p.indexOf('$') != -1){
            var n = parseInt(p.substring(1,3));
           if(n == 0 || isNaN(n) ){
               $(this).hide();
           }
        }
    })

})

/******************
 * FEATUREBOX
 ******************/

jQuery(function($){

	var apiMethod =[], m = 'GetHomepageFeatures';
	//api mappings - corresponds to url segment
	apiMethod["The-Museum-Store"] = "GetHomepageFeatures";
	apiMethod["Hatch-Show-Print"] = "GetHatchFeatures";
	apiMethod["Tickets"] = "GetTicketFeatures";
	apiMethod["Tickets-&-Packages"] = "GetTicketFeatures";
	apiMethod["Tickets-%26-Packages"] = "GetTicketFeatures";
	apiMethod["Memberships"] = "GetMemberFeatures";
	apiMethod["Membership"] = "GetMemberFeatures";
	apiMethod["Donate"] = "GetDonateFeatures";

	if(CMHOF.categories.length == 1){
		m = apiMethod[CMHOF.categories[0]];
	}
	if(CMHOF.categories.length <=1  && m){
		$.getJSON(config.ShopPath+'/addons/featurebox/ajax.php?method='+m,
			function(data){
				var $ = jQuery;
				var updateTime = 6100;
				var trannyTime = 450;
				var index = -1;
				if(data.data[1]){
					//create thumbnail holder
					$("#feature-box").html('<div id="feature-box-nav"></div><div id="feature-box-content"></div>');
					$.each(data.data, function(i,item){
						if(item!=null){
							var thumb = '<div class="feature-thumb-container" rel="'+(i-1)+'" ><img  src="'+ item.thumbnailurl+'" alt=""   /><div class="feature-image"><a href="'+item.link+'" title="'+item.title+'"><img  src="'+ item.imageurl+'" class="feature-image" alt=""  title="" /></a></div>';
							$("#feature-box-nav").append(thumb);
						}
					});

					// thumb events
					$('.feature-thumb-container').click(function(){
						var item = $(this);
						index = item.attr('rel');
						item.addClass("active").siblings().removeClass("active");
						$('#feature-box-content').fadeOut(trannyTime, function(){
							$(this).html($('.feature-image', item).html()).fadeIn(trannyTime);
						});
						return false;
					});

					$('.feature-thumb-container:first').click();
					startTimer();
					$('#feature-box').show().hover(stopTimer, startTimer);
					$(".SortBox").css({
						'top':'-300px'
					});
				}

				var intervalID;
				function featureBoxUpdate(){
					index ++;
					if(index >3) index= 0;
					$('.feature-thumb-container:eq('+index+')').click();
				}
				function startTimer(){
					intervalID = setInterval(featureBoxUpdate, updateTime);
				}
				function stopTimer(){
					intervalID = clearInterval(intervalID);
				}
			});
	}
});

/******************
 * ANNOUNCEMENTS
 ******************/
jQuery(function($){
	if($("#LayoutColumn3")[0]){
                
		var container;
		if($("#LayoutColumn3 #AnnouncementsContainer")[0]){
			 container = $('<div id="announcements" class="Block"></div>').insertAfter('#LayoutColumn3 #AnnouncementsContainer');
		}else if($("#LayoutColumn3 #SideAccountMenu")[0]){
                        container = $('<div id="announcements" class="Block"></div>').insertAfter('#SideAccountMenu');
                }else{
			 container = $('<div id="announcements" class="Block"></div>').insertBefore('#LayoutColumn3 div:first');
		}
               data = null;
		$.getJSON(config.ShopPath+'/addons/announce/ajax.php?method=getAnnouncements',
			function(data){
				if(data.data[0]){
					container.append('<h2>Live from The Museum Store</h2>');
					//create thumbnail holder
					$.each(data.data, function(i,item){
                                                var link = item.link ? item.link : config.ShopPath+'/pages/Museum-Store-Events.html';
						container.append(
							'<div class="announcement an-'+i+'">'+
							'<h5>'+item.title+'</h5>'+
							'<strong>'+item.subtitle+'</strong>'+
							'<img src="'+item.imageurl+'" alt="" />'+
							'<p>'+	item.description +'</p>'+
							'<span>'+item.time+'</span>'+
							'</div>'
							);
							var a = '<a href="'+link+'" />';
							$('.an-'+i+' img').wrap(a);
							$('.an-'+i+' h5').wrap(a);
					});
				}
			});
	}
});

/******************
 * Track Listings
 ******************/
jQuery().ready(function($){
    $("a[href$='.mp3']").each(function(i){

        var $el = $(this);
        $el.addClass('trackButton');

        $el.click(function(){
            if(!$(this).is('.trackButtonPlaying')){
                $(".trackButtonPlaying").each(function(i){
                    $(this).html('&nbsp;');
                    $(this).removeClass('trackButtonPlaying');
                });
            

                $(this).addClass('trackButtonPlaying');
                  
                $el.digomeMedia({
                    url: config.ShopPath+'/templates/cmhof/swf/mp3-button.swf',
                    width: 110,
                    height: 18,
                    params:{
                        bgcolor: '#ffffff',
                        wmode: 'transparent'
                    },
                    flashvars: {
                        mp3: $el.attr('href'),
                        autoStart:true
                    }
                });
            }
            return false;
        });
    });
});
/******************
 * General DOM manipulation
 ******************/
jQuery().ready(function($){
	/* sale tag */

	$(".ProductList .SalePrice").parent().parent().parent().append('<div class="sale-tag"></div>');
	$("#ProductDetails .SalePrice").parent().parent().parent().append('<div class="sale-tag"></div>');
	$('.sale-tag').click(function(){
		var p = $(this).parent();
		var productAddLink = $('div.ProductActionAdd a',p).attr('href');
		location = productAddLink;
	})

	//tower nav
	$('#section-nav').css({
			opacity:0
		}).show();
		$('#section-nav-container').hover(
			function(){
				$('#section-nav').stop().fadeTo('normal',1);
			},
			function(){
				$('#section-nav').stop().fadeTo('normal',0);
			}
		);

	//donation product
	$(".pid-373").find(".ProductPriceRating em").text("");
	// customer service
	$("#cs-em").html('<a href="mailto:customerservice@countrymusichalloffame.org">customerservice@countrymusichalloffame.org</a>');

//end -doc ready
});
///audio functions used by track listings
function stopAudio(id){
    for(var i = 0 ; i < mp3Buttons.length; i++){
        if(mp3Buttons[i] != id){
            getMovie(mp3Buttons[i]).stopMp3();
        }
    }
}
function getMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}