$(document).ready(function() {
	

	// Keep In Touch control for news listing page
	$('#keepInTouchContent').hide();
	$('#keepInTouchControl').bind('click',function(){
		$(this).next().slideToggle('fast');
		$(this).parent().toggleClass('open');
	});

	if ( $.cookie('emailform') != '1' ) {
		$('a.thickbox').trigger('click');
		$.cookie('emailform', '1', {expires:999} );
	}
	
	// top-left search box focus/blur events
	var searchText = 'Search Rhino...';
	$("#finder-form input.form-autocomplete").val(searchText);

	$("#finder-form input.form-autocomplete").focus(function() {
	   if ( $(this).val() == searchText ) {
	     $(this).val('');
	   }
	});

	$("#finder-form input.form-autocomplete").blur(function() {
	   if ( $(this).val() == '' ) {
	      $("#finder-form input.form-autocomplete").val(searchText);
	   }
	});
	
	
	// article list newsletter submission
	$("#newsletter-submit").bind('click', function() {
		$.ajax({
			type: "POST",
			url: "/silverpop.php",
			data: "name=" + $("#newsletter-name").val() + "location=" + $("#newsletter-email").val(),
			success: function(msg){		
				$("#newsletter-email").val( 'Thank you!' );
				$("#newsletter-name").val('Thank you!' );
			}
		}); 
		return false;
	});
	
	
	// Tabs (jquery UI)
	$('.homepage #rhinoNews').tabs();
	$('.homepage #releases').tabs();
	$('.homepage #listen').tabs();
	$('.artist #pfa').tabs();
	
	$('.rhinotab a').bind('click', function() {
		var tabupc = $(this).parent().attr('upc');

		$(".player").hide();
		$(".commerce-player-" + tabupc).show();
	});
	
	// Tabs for product details page
	$('.productDetail #productInfo').tabs(); 
	
	// Trigger the appropriate tab (format)
	var hash = window.location.hash;
	if ( hash != '' ) {
	    hash = hash.replace('productInfo-', '') + ' a.productTab';
	    $(hash).trigger('click');
	}
	
	$(".genre .revolverWrapper .loneLine").ticker('eeebe3');
	$(".article .loneLine").ticker();
	$(".artist .revolverWrapper .loneLine").ticker('dfd9c6');
	
	$(".artist .view-artist-releases .loneLine").ticker('eeebe3');
	
	
	$(".artist .view-the-search .release-teaser .loneLine").ticker('ebe6d9');
	$(".view-artist-page .release-teaser .loneLine").ticker();
	$(".styleTemplate .view-the-search p.loneLine").ticker('f9f5ee');
	
	$('#cartContainer .alt p.trunc').ticker('efebe2');
	$('#cartContainer .alt2 p.trunc').ticker('ffffff');
	
	$(".RhinoHandmadePage .loneLine").ticker();
	$(".productDetail .loneLine").ticker('e7e4df');
	

	// full size image popup for product pages
	$('.btn-viewFullSize').bind('click', function(){
		$('#'+$(this).attr('rel')).dialog({
			width:804,
			modal: true,
			minHeight: 0,
			bgiframe: true,
			open: function(event, ui) {
				$(this).parent().append('<div class="ui-dialog-footer"></div>');
				$(this).parent().addClass('fullSizeProductImage');
			},
			close: function() {
				$(this).dialog('destroy');
			}
		});
	});
	
	// change the review links on product pages to include "/shop/product"
	// should this be done in PHP instead?? (for SEO purposes?)
	/*
	$(".productDetail .pager a").each(function() {
	   var href = $(this).attr('href');
	   href = '/shop/product' + href;
	   $(this).attr('href', href);
	});
	*/
	
	
	// read more / read less control on product pages
	
	$(".readMore, .readLess").bind("click", function() {
	    var olddesc = $(this).closest('.productDescription');
	    olddesc.hide();
	    var newdesc = olddesc.siblings('.productDescription');
	    newdesc.show();
	});
		
	// gws integration for product page "add to cart" buttons
	
	
	$(".btn-addToCart").live("click", function() {
	
		if ( $(this).hasClass('cartBtn-digital') ) {
			// determine which digital formats are checked
			var skuvallist = '';
			$("#digitalFormats input").each(function() {
				if ( $(this).is(":checked") ) {
					skuvallist += $(this).val() + ',';
				}
			});
			
			if ( skuvallist == '' ) {
				// if none are checked, throw an error and abort
				alert( 'Please choose at least one digital format.' );
				return;
			}
			
			$(this).attr('skuvallist', skuvallist);
		}
	
		var sku = $(this).attr('skuvallist');
		var format = $(this).attr('rel');
		var qty = $("#quantity-" + sku).val();
		
		if ( qty == undefined ) {
			qty = 1;
		}
		
		// immediately change the button state
		$(this).addClass('btn-addToCart-clicked');
		
		var promocode = getParameterByName('promocode');
	
		if ( promocode != null && promocode != '' && promocode != undefined) {
		
			$.ajax({
			   type: "POST",
			   url: "/sites/all/themes/rhino_zen/gws-update-cart.php",
			   data: "skus=" + sku + ':' + qty + '&promocode=' + promocode,
			   success: function(result){		   
				displayMiniCart(result);
			   }
			 });
		}
		else {
			$.ajax({
			   type: "POST",
			   url: "/sites/all/themes/rhino_zen/gws-update-cart.php",
			   data: "skus=" + sku + ':' + qty + '&promocode=' + promocode,
			   success: function(result){		   
				displayMiniCart(result);
			   }
			 });
		}

	});
	
	deluxeTip();
	
	// Simple tooltips for icons
	$('.simpleTip').deluxeTip({
		x: -5,
		y: -10,
		tooltipClass: 'smallBtnTooltip'
	});
	
	// Deluxe Tooltips for checkout page
	/*
	$('.deluxeTip').deluxeTip({
		x: 10,
		mode: 'deluxe',
		defaultSide: 'left'
	});
	*/
	
	// Deluxe Tooltips for checkout page
	$('.deluxeTip').deluxeTip({
		x: 10,
		mode: 'deluxe',
		defaultSide: 'right'
	});
	
	// Artist page tooltip
	$('#linksIcon').deluxeTip({
		x: 7,
		y: 33,
		mode: 'deluxe',
		defaultSide: 'left',
		tooltipClass: 'artistLinks'
	});
	
	// bug: for some reason the artist lists have to be activated
	// once before they will appear to use clicks
	//$(".artist #artistLinks").trigger('click');


	// simpleTips were not disappearing in some cases, so this forces them to close on mouseout
	
	$(".simpleTip").bind('mouseleave', function() {
	    $(".simpleTipWrap").hide();
	}); 

	updateNavBar();
	activateCarousels();
	imageReplace();
	flashVideo();
	flashAudio();
	fillInProductImages();
	textReplacement();
	forceNumeric();
	myRhino();
	myAddressBook();//part of myRhino
	secondaryMenu();
	gallery();
	centerStage();
});

var centerStage = function() {

	$("#artistCenterStage").unbind('click');
	$("#artistCenterStage .seeLess").unbind('click');
	$("#artistCenterStage .seeMore").unbind('click');
	$("#artistCenterStage .drawerControl").unbind('click');
	
	// check to ensure that there are > 3 items (if not, we can hide the drawer control)
	
	if ( $("#artistCenterStage .article").length <= 3 ) {
		$("#artistCenterStage .seeMoreTop").hide();
		$("#artistCenterStage .seeMore").hide();
	}
	else {
		$("#artistCenterStage .drawerControl").bind('click', function() {
			if ( $(".article-4").is(":hidden") ) {
				$("#artistCenterStage .article").fadeIn('fast');
				$("#artistCenterStage .drawerControl span").html("Less");	
			}
			else {
				$("#artistCenterStage .article-4").fadeOut('fast');
				$("#artistCenterStage .article-5").fadeOut('fast');
				$("#artistCenterStage .article-6").fadeOut('fast');
				$("#artistCenterStage .article-7").fadeOut('fast');
				$("#artistCenterStage .article-8").fadeOut('fast');
				$("#artistCenterStage .article-9").fadeOut('fast');
				$("#artistCenterStage .article-10").fadeOut('fast');
				$("#artistCenterStage .article-11").fadeOut('fast');
				$("#artistCenterStage .article-12").fadeOut('fast');

				$("#artistCenterStage .drawerControl span").html('All');
			}
		});
	}
} 

var omnitureCartEvents = function(skuvallist) {
	// omniture cart events
	var events = 'scAdd';
	var eventsDesc = 'Add to Cart';

	if ( $("#mycartQty").attr('qty') == '0') {
		events = 'scAdd,scOpen';
		eventsDesc = 'Cart Started';
	}

	//var s=s_gi('WMG,WMGRHI,WMGrhinobrand,WMGrhino.com');

	var s=s_gi('WMG,WMGRHI,WMGrhinobrand,WMGrhino.com,wmgrhinodev,wmgtestrhino');
	s.linkTrackEvents=events;
	s.linkTrackVars='events,products';
	s.products=';' + skuvallist;
	s.events=events;
	s.tl(this,'o',eventsDesc);
}

/** shows the mini cart after gws-update-cart.php is displayed **/
var displayMiniCart = function( result ) {
	$('#miniCartContainer').hide();
	$('#miniCartContainer').html(result);
	$('#miniCartContainer').fadeIn('fast');
	
	// get a list of all skus added to the cart
	var skuvallist = $("#miniCart #allskus").html();
	
	// fire the scAdd and scOpen omniture events
	omnitureCartEvents(skuvallist);

	$("#miniCartContainer .product").each(function() {

		var sku = $(this).attr('sku');
		var prodtype = $(this).attr('prodtype');
		


		// maybe load the small thumbnail for each product onto the product page instead?

		var imgsrc, prodtitle, prodartist, prodformat;

		if ( prodtype == 'physical' ) {
			imgsrc = $(".productImage-" + sku + " img").attr('src');
			prodtitle = $("#hiddenProductTitle-" + sku).html();
			prodartist = $("#hiddenProductArtist-" + sku).html();
			prodformat = $("#hiddenProductFormat-" + sku).html();
			
			if ( !prodformat || prodformat == undefined || prodformat == null ) {
				prodformat = $(".hiddenProductFormat").html();
				prodartist = $(".hiddenProductArtist").html();
			}
			
			// if this is a merch item with multiple options, try to get
			// image/title/artist/format info using classes rather than IDs
			// since the UPC might be different (due to size/color combos)
			
			if ( !imgsrc || imgsrc == undefined || imgsrc == null ) {
				imgsrc = $("#productInfo .productImage img").attr('src');
			}
			if ( !prodtitle || prodtitle == undefined || prodtitle == null ) {
				prodtitle = $("#productInfo .hiddenProductTitle").html();
			}
			if ( !prodartist || prodartist == undefined || prodartist == null ) {
				prodartist = $("#productInfo .hiddenProductArtist").html();
			}
			if ( !prodformat || prodformat == undefined || prodformat == null ) {
				prodformat = $("#productInfo .hiddenProductFormat").html();
			}
		} 
		else {
			imgsrc = $(".productImage-digital img").attr('src');
			prodtitle = $("#hiddenProductTitle-digital").html();
			prodartist = $("#hiddenProductArtist-digital").html();
			prodformat = $("#hiddenProductFormat-digital").html();
		}
		
		if ( prodformat == 'organic' || prodformat == 'other' ) {
			prodformat = 'merch';
		}
		
		var httploc = window.location.pathname;
		
		if ( httploc == undefined || httploc == null ) {
			// unsupported browsers default to homepage
			httploc = '/';
		}
		
		localStorage.setItem('item_url_' + sku, httploc);
		localStorage.setItem('item_thumb_' + sku, imgsrc);
		localStorage.setItem('artist_name_' + sku, prodartist); 

		// set some cookies that we'll use in the shopping cart display
		//$.cookie('item_url_' + sku, );
		//$.cookie('artist_url_' + sku, );

		//$.cookie('item_thumb_' + sku, imgsrc, { path: '/', expires: 999 });
		//$.cookie('artist_name_' + sku, prodartist, { path: '/', expires: 999 });

		var prodprice = $("#productInfo .itemPrice-" + sku).html();
		
		//var prodqty = $("#quantity-" + prodformat).val();
		
		var skubase = sku.replace('_mp3', '');
		skubase = skubase.replace('_aac', '');
		skubase = skubase.replace('_alac', '');
		skubase = skubase.replace('_wma', '');
		skubase = skubase.replace('_flac', '');
		
		var prodqty = $("#quantity-" + skubase).val();
		

		
		
		if ( prodprice == null || !prodprice || prodprice == 'null' || prodprice == undefined ) {
			// try to get the price from the track button label(?)

			// does this code work?
			if ( prodformat == 'digital' ) {
				sku = sku.replace( 'aac', 'alac' );
				prodprice = $("#commerce-player div." + sku).attr('saleprice');
			}
			else if ( prodformat == 'merch' || prodformat == 'MERCH' ) {
				prodprice = $("#productInfo .itemPrice").html();
			}
			
			if ( !prodprice ) {
				// try to get it using another method
				
				// use index "1" instead of index "0" here because in the tophits
				// "0" is the "add all" button!
				
				if ( sku.indexOf( '_mp3' ) != -1 ) {
					// assume tophits skin, and get mp3 price from the popup label itself?
					prodprice = $("#commerce-player .goldmp3price").html();
				}
				else {
					prodprice = $("#commerce-player .hidef:eq(1)").attr('label');
				}
				
				if ( prodprice != null && prodprice != undefined && prodprice != false ) {
					prodprice = prodprice.replace('+ ', '');
				}
				else {
					prodprice = '';
				}
				prodqty = 1;
			}
			if ( !prodtitle ) {
				// try to get the title from the commerce player row (class=song_$sku)
				prodtitle = $("#commerce-player .song_" + skubase).html();
			}
			
			
			if ( !prodartist ) {
				// try to get the artist from the commerce player row (class=artist_$sku)
				prodartist = $("#commerce-player .artist_" + skubase).html();
			}
		}

 
		$(this).find(".icon").addClass('icon-' + prodformat);
		$(this).find(".productTitle").html(prodtitle);
		$(this).find(".productArtist").html(prodartist);

		if ( prodtype == 'physical' ) {
		
			if ( prodformat == 'merch' || prodformat == 'MERCH' ) {
				// special tags just for merch!
				
				var currentSize = '';
				
				$("select.sizeSelect :selected").each(function() {
					if ( $(this).is(":visible") ) {
					    currentSize = $(this).text();
					}
				});
				
				if ( currentSize != '' ) {
					$(this).find(".merchSize").html('Size: ' + currentSize);
				}
				
				var currentColor = $("#currentColor").html();
				
				if ( currentColor != undefined && currentColor != null && currentColor != '' ) {
					$(this).find(".merchColor").html('Color: ' + currentColor);
				}
			}
		
			$(this).find(".productArt img").attr('src', imgsrc);
			$(this).find(".productMeta").html(prodformat);
			$(this).find(".productQuantity").html('Quantity <span>' + prodqty + ' x ' + prodprice + '</span>');
		}
		else {
			// digital quantity
			if ( prodprice ) {
			
				if ( prodqty == undefined ) 
					prodqty = 1;
					
				$(this).find(".digitalQuantity span").html('Quantity ' + prodqty + ' x ' + prodprice);
			}
			else {
				// for some reason could not get the digital track price...
				$(this).find(".digitalQuantity span").html('Quantity ' + prodqty);
			}

		}
	});


	// update the mini-cart display
	var itemsString = 'Items';

	var totalQty = $('#miniCartContainer .cartQuantity').attr('qty');

	if ( totalQty == '1' || totalQty == 1 )
		itemsString = 'Item';

	$("#mycartQty").html( '(' + totalQty + ' ' + itemsString + ')' );
	$("#mycartQty").attr('qty', totalQty);
	


	//force the popup window to scrollfollow the main page
	$('#miniCart').scrollFollow({
		container: 'wrapper'
	});

	// align popup window with right edge of document
	var viewport = $(document).width();
	var mainwidth = $('#main').width();
	var miniCartWidth = $('#miniCart').width();
	var offset = viewport / 2 + mainwidth / 2 - miniCartWidth + 'px';

	$('#miniCart').css({
		'left' : offset
	});

	$("#miniCart .close").bind('click', function() {
	    $("#miniCart").fadeOut('fast');
	});

	//force the popup window to remain aligned with the right edge of the document
	$(window).bind('resize', function() {
		var viewport = $(document).width();
		var mainwidth = $('#main').width();
		var miniCartWidth = $('#miniCart').width();
		var offset = viewport / 2 + mainwidth / 2 - miniCartWidth + 'px';

		$('#miniCart').css({
			'left' : offset  
		});
	});
	
	// remove any existing gradient classes from the minicart popup
	$("#miniCart .ticker").removeClass("fade_eeebe3");
	$("#miniCart .ticker").removeClass("fade_f9f5ee");
	$("#miniCart p.loneLine > div.ticker").removeClass('ticker');
	
	// long line gradients
	
	$("#miniCart .odd .loneLine").ticker('cdc9c3');
	$("#miniCart .even .loneLine").ticker('edeae4');
	
	/*
	
	$("#miniCart .row1 .loneLine").ticker('e7e4df');	
	$("#miniCart .row3 .loneLine").ticker('e3e0d9');
	
	$("#miniCart .row5 .loneLine").ticker('e1dac3');
	$("#miniCart .row7 .loneLine").ticker('e1dac3');
	
	
	$("#miniCart .row7 .loneLine").ticker('cdc9c6');
	$("#miniCart .row9 .loneLine").ticker('cdc9c6');
	$("#miniCart .row11 .loneLine").ticker('cdc9c6');
	*/
}



/** initialize myRhino events **/
var myRhino = function() {

	//  Choose Genre Add/Remove
	$('.genreSelection').live('mouseover', function() {
		$(this).addClass('delete');
	});
	$('.genreSelection').live('mouseout', function() {
		$(this).removeClass('delete');
	});
	$('.genreSelection').live('click', function() {
		var text = $(this).text();
		$('#genreSet input:checked').each(function() {
			if($(this).parent().text().indexOf(text) != -1) {
				$(this).attr('checked', false);
			}
		});
		$(this).remove();
	});

	$('#genreSet').bind('click', function() {
		var selectedGenres = '';
		$('#genreSet input:checked').each(function() {
			var text = $(this).parent().text();
			var newGenre = '<p class="genreSelection">' + text + '</p>';
			selectedGenres += newGenre;
		});
		$('#genreSelections').html(selectedGenres);
	});
	
	
	// Choose Artist Accordion
	$('.titleItem ul').hide();
	$('.browseTitle > span').bind('click', function() {
		$(this).parent('.browseTitle').toggleClass('closed');
		$(this).next('ul:eq(0)').slideToggle('fast');
	});
	$('.titleItem > span').bind('click', function() {
		$(this).parent('.titleItem').toggleClass('open');
		$(this).next('ul').slideToggle('fast');
	});

	// Choose Artist Add/Remove
	$('.artistSelection').live('mouseover', function() {
		$(this).addClass('delete');
	});
	$('.artistSelection').live('mouseout', function() {
		$(this).removeClass('delete'); 
	});
	$('.artistSelection').live('click', function() {
		var text = $(this).text();
		$('.artistSet input:checked').each(function() {
			if($(this).parent().text().indexOf(text) != -1) {
				$(this).attr('checked', '');
			}
		});
		$(this).remove();
	});

	$('.artistSet').bind('click', function(e) {		
		if(e.target.nodeName == 'INPUT') {
			$(e.target).attr('checked',true);
			var labelText = $(e.target).parent().text();
			var checked = $(e.target).attr('checked');


			$('.artistSet label').each(function() {
				if($(this).text() == labelText) {
					$('input', this).attr('checked', checked);
				}
			});
			var selectedArtists = '';
			$('#artistByAlpha input:checked').each(function() {
				var text = $(this).parent().text();
				var newArtist = '<p class="artistSelection">' + text + '</p>';
				selectedArtists += newArtist;
				text = null;
				newArtist = null;
			});
			$('#artistSelections').html(selectedArtists);
			selectedArtists = null;
			labelText = null;
			checked = null;
		}
	});


}


/** attempts to "fill in" missing product images with images from other formats, if possible **/
var fillInProductImages = function() {
	var sharedimg = '';

	$(".productImage img").each(function() {
	    var src = $(this).attr('src');
	    if ( src != '' ) {
	       sharedimg = src;
	    }
	});

	$(".productImage img").each(function() {
	    var src = $(this).attr('src');
	    if ( src == '' && sharedimg != '' ) {
	       $(this).attr('src', sharedimg);
	    }
	});
}

var setRocketFuelCookie = function(conversionID) {
	params = 'campaignId=' + conversionID + '&AffiliateId=RocketFuel';
	$.cookie('promoParameters', params, {expires: 1, path: '/'});
}

var activateCarousels = function() {
	// remove unpublished nodes from all carousels
	/*
	$("div.node-unpublished").closest('.field-item').remove();
	$("#artistInfo-listen .no-thumbnail-image").closest('.field-item').remove();
	*/
	
	// "listen" carousel on artist page
	/*
	$("#artistInfo-listen .views-field-field-productlist-products-nid .field-content").cycle({
		fx: 'fade',
		next: '.btn-carouselNext',
		prev: '.btn-carouselPrev',
		timeout: 0
	});
	*/
	
	
	// START OF ARTIST PAGE 'LISTEN LIST' CAROUSEL
	
	$(".view-artist-page-listen-list .views-row .field-content .field-item").hide();

	var curslide = 1;
	var numslides = 0;

	$(".view-artist-page-listen-list .views-row .field-content .field-item").each(function() {
		if ( ++numslides == 1 ) {
			$(this).show();
		}
		$(this).addClass("next-" + numslides);
	});

	$("#artistInfo-listen .btn-carouselNext").live('click', function() {
		$(".view-artist-page-listen-list .views-row .field-content .next-" + curslide).hide();

		curslide = curslide + 1;

		if ( curslide > numslides ) 
			curslide = 1;

		$(".view-artist-page-listen-list .views-row .field-content .next-" + curslide).fadeIn('fast');
	});
	$("#artistInfo-listen .btn-carouselPrev").live('click', function() {
		$(".view-artist-page-listen-list .views-row .field-content .next-" + curslide).hide();

		curslide = curslide - 1;

		if ( curslide < 1 )
			curslide = numslides;

		$(".view-artist-page-listen-list .views-row .field-content .next-" + curslide).fadeIn('fast');

	});

	
	// END OF ARTIST PAGE 'LISTEN LIST' CAROUSEL
	
	//$("#artistInfo-listen .views-field-field-productlist-products-nid .field-item").css({"background-color", "transparent"});

	// add ul/li before the view contents for jCarouselLite

	if ( $("#albums .views-field-field-productlist-products-nid .field-content div.field-item").length > 0 ) {
		$("#albums .views-field-field-productlist-products-nid .field-content div.field-item").wrapAll('<ul />');
		$("#albums .views-field-field-productlist-products-nid .field-content ul div.field-item").wrap('<li />');

		// top albums carousel for artist page
		$("#albums .views-field-field-productlist-products-nid div.field-content").jCarouselLite({
			btnNext: ".btn-carouselNext2",
			btnPrev: ".btn-carouselPrev2",
			visible: 2,
			scroll:2, 
			circular: false
		});
	}

	// add ul/li before the view contents for jCarouselLite
 
	if ( $("#rhinoRecommends .views-field-field-productlist-products-nid .field-content div.field-item").length > 0 ) {
		$("#rhinoRecommends .views-field-field-productlist-products-nid .field-content div.field-item").wrapAll('<ul />');
		$("#rhinoRecommends .views-field-field-productlist-products-nid .field-content ul div.field-item").wrap('<li />');
 
		// top albums carousel for artist page
		$("#rhinoRecommends .views-field-field-productlist-products-nid div.field-content").jCarouselLite({
			btnNext: ".btn-carouselNext",
			btnPrev: ".btn-carouselPrev",
			visible: 2,
			scroll:2, 
			circular: false
		});
	}

	// add ul/li before the view contents for jCarouselLite

	if ( $("#fansDig .views-field-field-productlist-products-nid .field-content div.field-item").length > 0 ) {
		$("#fansDig .views-field-field-productlist-products-nid .field-content div.field-item").wrapAll('<ul />');
		$("#fansDig .views-field-field-productlist-products-nid .field-content ul div.field-item").wrap('<li />');

		// top albums carousel for artist page
		$("#fansDig .views-field-field-productlist-products-nid div.field-content").jCarouselLite({
			btnNext: ".btn-carouselNext2",
			btnPrev: ".btn-carouselPrev2",
			visible: 2,
			scroll:2, 
			circular: false
		});
	}

	// add ul/li before the view contents for jCarouselLite

	if ( $(".genre .views-field-field-productlist-products-nid .field-content div.field-item").length > 0 ) {
		$(".genre .views-field-field-productlist-products-nid .field-content div.field-item").wrapAll('<ul />');
		$(".genre .views-field-field-productlist-products-nid .field-content ul div.field-item").wrap('<li />');

		// top albums carousel for artist page
		$(".genre .views-field-field-productlist-products-nid div.field-content").jCarouselLite({
			btnNext: ".btn-carouselNext2",
			btnPrev: ".btn-carouselPrev2",
			visible: 2,
			scroll:2, 
			circular: false
		});
	}
}

var updateNavBar = function() {
	$.ajax({
	   type: "POST",
	   data: "page_url=" + window.location,
	   url: "/gws-nav-bar.php",
	   success: function(result){
	   	$("#utilityNav").html(result);
	   }
	});	     
}

var imageReplace = function() {
	$('a.videoPlayer, #mainPromo a, #rhinoRecommends .item a').each(function() {
		var placeholder = $(this).html();
		placeholder = placeholder.replace('src="/images','src="http://www.rhino.com/images');
		placeholder = placeholder.replace('src="/dimages','src="http://www.rhino.com/dimages');
		
		$(this).html(placeholder);
	});
}

/** fetch contents of a view and set selectorDest contents to the result **/
var loadViewDisplay = function(viewname, selectorDest, selectorSrc, viewArgs) {
	
	var displayName = $(selectorSrc).val();
	 
	$.ajax({
	   type: "POST",
	   url: "/sites/all/themes/rhino_zen/fetchViewContents.php",
	   data: "view="+viewname+"&display="+displayName+"&arg="+viewArgs,
	   success: function(result){	
	   
	   
	   
	   	$(selectorDest).html(result);
	   }
	 });
}

var textReplacement = function() {
	$('input.replace').each(function() {
		var self = $(this);
		if(self.val() != '') {				
			var originalvalue = self.val();
			self.focus(function(){
				if( $.trim(self.val()) == originalvalue ){ self.val(''); }
			});
			self.blur(function(){
				if( $.trim(self.val()) == '' ){ self.val(originalvalue); }
			});
		}
	});
}
	
// Only allow numeric values in an input
var forceNumeric = function(input) {
	$(input).bind('keydown',function(){
		if(!$(this).val().match(/^\d+$/ )) {
			$(this).val($(this).val().replace(/[^0-9]/gi, ''));
		}
	});
	$(input).blur(function(){
		$(this).val($(this).val().replace(/[^0-9]/gi, ''));
	});
}

var flashAudio = function(){
	var playAll = false;
	$('a.playAllClips').bind('click',function(){
		playAll = true;
		$('a.playClip:first').trigger('playAll');
		return false;
	});
	$('a.playClip').bind('click playAll',function(e){
		var self = $(this);
		var clipSrc = $(this).attr('rel');


		// Check which event was fired
		if(e.type == "click") {
			playAll = false;
		}
		if(playAll || $('#audioPlayer').length == 0) {
			$('body').append('<a href="' + clipSrc + '" id="audioPlayer"></a>');
			flowplayer('audioPlayer','/swf/flowplayer.commercial-3.1.4.swf',{
				plugins: { 
				controls: { 
				    fullscreen: false, 
				    height: 30 
				}
			    },
				key: '@3f1e8c654710a530394'
			});
		}
		// If Playing
		if($(this).hasClass('audioPlaying')){
			// Pause	
			$f('audioPlayer').pause();
			if(!playAll) $(this).removeClass('audioPlaying').addClass('audioPaused');

		// If Paused
		} else {
			// If current song is same as what was clicked, resume play
			if($(this).hasClass('audioPlayerActive')) {
				$f('audioPlayer').play();	
				$(this).removeClass('audioPaused').addClass('audioPlaying');


			// Otherwise start new clip
			} else {
				$f('audioPlayer').play(clipSrc);

				$('.audioPlayerActive').removeClass('audioPlayerActive audioPlaying audioPaused')
				$(this).addClass('audioPlayerActive audioPlaying');
			}
		}
		$f('audioPlayer').onFinish(function(){

			$(self).removeClass('audioPlayerActive audioPlaying audioPaused');
			$('#audioPlayer').remove()
			if(playAll) $(self).next('.playClip').trigger('playAll');
		});

		return false;
	});
}


var flashVideo = function(){ 
	$('a.videoPlayer').each(function() {
	
		// replace center stage video images if a static image exists...
		var imgblock = $(this).closest('.views-field-field-article-videourl-value').siblings('.views-field-field-article-teaserimage-fid');
		var imgblockLink = imgblock.find('a').html(); 

		if ( imgblockLink != null && imgblockLink.indexOf('<img') != -1 ) {
		   imgblock.hide();
		   $(this).html(imgblockLink);
		   $(this).css({'height':'auto'});
		}
	
	
		// replace inner img src with path to rhino.com (replace this later)

		var videoSrc = $(this).attr('href');
		var overlayLogo = "video-overlay-none.png";
		
		if($(this).hasClass('smallVideo')) {
			overlayLogo = "video-overlay-small.png";
			var controlsObj = {
				all: false,
				fullscreen: true,
				play: true,
				autoHide: 'always',
				hideDelay: 2000
		   }
		} else {
			if($(this).hasClass('fullVideo')) overlayLogo = "video-overlay-full.png";
			if($(this).hasClass('largeVideo')) overlayLogo = "video-overlay-large.png";
			if($(this).hasClass('mediumVideo')) overlayLogo = "video-overlay-medium.png";
			var controlsObj = {
				autoHide: 'always',
				hideDelay: 2000
		   }
		}
		if(typeof flowplayer == 'function') {
			flowplayer(this,'/swf/flowplayer.commercial-3.1.4.swf',{
				clip: {
					autoBuffering: true
				},
				plugins: {
					controls: controlsObj
				},
				playlist: [
					{
						url: 'http://rhino.edgeboss.net/download/rhino/videos/preroll_640x480.flv'
					},
					{
						url: videoSrc,
						onBegin: function() { 
							this.getPlugin("logo").fadeTo(0.5,10); 
						}
					}
				],	
				logo: { 
				url: '/images/global/'+overlayLogo, 
					top: 0,
					right: 0,
				fullscreenOnly: false, 
				opacity: 0 
			    },
				key: '@3f1e8c654710a530394' 
			});
		}
	});
	
}


// Expand/contract for secondary menu
function secondaryMenu() {
	var expandedHeight = $('#lockup').height();
	var collapsedHeight = expandedHeight - $('#secondaryNavItems').height()-12;
	var moreStyles = $('#secondaryNav #moreStyles')
	var divsToHide = $('#secondaryNav .eras,#secondaryNav .artists');
	moreStyles.hide();
	$('#secondaryNav #control').toggle(
		function(){
			//divsToHide.hide()
			moreStyles.show();
			$(this).html('- Less');
		},
		function(){
			moreStyles.hide()
			//divsToHide.show();
			$(this).html('+ More');
		}
	);
	//Expand/Contract 
	$('.btn-expandArrow').toggle(
		function(){
			$('#secondaryNavItems').slideToggle(1000,function(){	
			$('.btn-expandArrow').addClass("collapsed");
				// $('#secondaryNav .separatorLine').css("border","none");
			});

		},
		function(){
			$('#secondaryNavItems').slideToggle(1000,function(){
				$('.btn-expandArrow').removeClass("collapsed");		
			});
			// $('#secondaryNav .separatorLine').css({"border-bottom":"1px solid #424039","border-top":"1px solid #000000"});
		}
	);
}

function gallery() {
	$.fn.extend({
		gallery: function(options) {
			return this.each(function() {
				new $.Gallery(this, options);
			});
		}
	});

	$.Gallery = function(element, options) {

		var defaults = {
			nextBtn : $(element).find("#controls .btn-galleryNext"),
			prevBtn : $(element).find("#controls .btn-galleryPrev")
		};
		this.options = $.extend({}, defaults, options || {});

		this.element	= $(element);
		this.setup();
	};

	$.extend($.Gallery.prototype, {

		setup: function() {
			var imageHolder		= this.element.find("#imageContainer");
			var self = this;
			this.disableBtn(this.options.prevBtn);
			this.element.find('#thumbnails a').bind('click',function(){
				var oldImageSource 	= imageHolder.find('img').attr('src');
				var newImageSource 	= $(this).attr('href');
				var nextThumb = $(this).parent().next().find('a');
				var prevThumb = $(this).parent().prev().find('a');
				if(oldImageSource!=newImageSource){
					self.swapImage(imageHolder,newImageSource);
					self.selectedThumb($(this));

					if(!nextThumb.length) {
						self.disableBtn(self.options.nextBtn);
					} else {
						self.enableBtn(self.options.nextBtn);
					}
					if(!prevThumb.length) {
						self.disableBtn(self.options.prevBtn);
					} else {
						self.enableBtn(self.options.prevBtn);
					}

				};
				return false;
			});
			this.options.nextBtn.bind('click',function(){
				self.nextImage();
			});
			this.options.prevBtn.bind('click',function(){
				self.prevImage();
			})
		},

		nextImage: function(){
			var myNextThumb = this.element.find('#selected').parent().next().find('a');
			if(myNextThumb.length) {
				this.swapImage(this.element.find("#imageContainer"),$(myNextThumb).attr('href'));
				this.selectedThumb(myNextThumb);
				this.enableBtn(this.options.prevBtn);
				if(!myNextThumb.parent().next().length) {
					this.disableBtn(this.options.nextBtn);
				} else {
					this.enableBtn(this.options.nextBtn);
				}
			};

		},

		prevImage: function(){
			var myPrevThumb = this.element.find('#selected').parent().prev().find('a');
			if(myPrevThumb.length) {
				this.swapImage(this.element.find("#imageContainer"),$(myPrevThumb).attr('href'));
				this.selectedThumb(myPrevThumb);
				this.enableBtn(this.options.nextBtn);
				if(!myPrevThumb.parent().prev().length) {
					this.disableBtn(this.options.prevBtn);
				} else {
					this.enableBtn(this.options.prevBtn);
				}
			};

		},

		swapImage: function(imageHolder,newImageSource){
			var img = $(new Image()).attr('src',newImageSource);
			$(imageHolder).find('img').fadeOut(300, function(){
				$(imageHolder).empty().append(img);
				$(img).css('display','none').fadeIn(300);
			});
		},

		selectedThumb: function(e){
			// Set selected
			this.element.find('#selected').prependTo($(e).parent());
		},

		disableBtn: function(e){
			$(e).addClass('disabled');
		},

		enableBtn: function(e){
			$(e).removeClass('disabled');
		}

	});
	
	var galleryInited = '';

	$('.btn-lookInside').bind('click', function() {
	
		
		
		// copy the "addToCartButton" contents to the gallery "buyButton" div
		//var addToCartButtonHTML = $(this).find('#addToCartButton').html();
	
		var galleryID = $(this).attr('rel');
		
		var addToCartButtonID = galleryID.replace('gallery', 'addToCartButton');
		var addToCartButtonHTML = $('#'+addToCartButtonID).html();
		
		var title = '';
		
		if(galleryInited.search(galleryID)==-1){
		
			$('#'+galleryID + ' .buyButton').html(addToCartButtonHTML);
		
			$('#'+galleryID).dialog({
				title: title,
				width: 804,
				modal: true,
				minHeight: 0,
				bgiframe: true,
				open: function(event, ui) {
					if($(this).parent().find('.ui-dialog-footer').length==0) {
						$(this).parent().append('<div class="ui-dialog-footer"></div>');
					}
					$(this).parent().addClass('dialog-gallery');
				}
			});
			//Cufon.replace('.ui-dialog-title h2', {fontFamily: 'Archer Semibold'});
			//Cufon.replace('.ui-dialog-title h3', {fontFamily: 'Archer Medium'}); 
			$('#'+galleryID).gallery();
			
			
		} else {
			$('#'+galleryID).dialog('open');
		}
		
		
		if (navigator.appName != 'Microsoft Internet Explorer') {		
			winW=document.body.clientWidth || window.innerWidth;
			$('#'+galleryID).parent().css({left:"auto",position:"fixed",top:"40px"});
			$('#'+galleryID).parent().wrap('<div style="width:804px;margin:0 auto;position:relative" />');
		}
		
		galleryInited += ','+galleryID;
		return false;
	});
}

// My Rhino Address Book
var myAddressBook = function() {
	$(".myRhino .addAddress").bind('click', function() {		
		$(".myRhino .addressBook #secondary .infoSection").fadeIn();
	});
	$(".myRhino #newAddressForm .btn-cancel").bind('click', function() {
		$(".myRhino .addressBook #secondary .infoSection").fadeOut();
	});
	$(".myRhino .deleteAddress").bind('click', function() {
		$(this).closest('.infoSection').fadeOut();
		
		$.ajax({
		   type: "POST",
		   url: "/sites/all/themes/rhino_zen/myrhino_remove_address.php",
		   data: "emailAddress=" + $("#emailAddress").val() + "&profileId=" + $("#profileId").val() + "&username=" + $("#username").val(),
		   success: function(msg){
		     //alert( "Data Saved: " + msg );
		   }
		 });
	});
	
	var savedContent = new Object();

	$('.myRhino .editAddress').live('click', function() {
		var element = $(this).closest('.infoSection');

		savedContent[element.attr('addressId')] = element.html();

		element.removeClass('displayMode');
		element.addClass('editMode');

		var output = '';

		$('.control', element).each(function() {
			var label		= $('.label', this).text();
			var value		= $('.value', this).text();
			var id	 		= $('.label', this).attr('rel');
			var type 		= ($(this).hasClass('hidden')) ? 'hidden' : 'text';
			var disabled	= (label == 'Country:' || label == 'State:' || label == 'Province:' ) ? ' disabled="disabled"' : '' ;
			var defaultAdd	= id.indexOf('addressdefault');
			var selected	= (value == 'true') ? ' selected="selected"' : '' ;

			if(defaultAdd == 0) {

				$(this).removeClass('hidden');

				output += '<label for="' + id + '">Default</label>';
				output += '<select id="' + id + '" name="' + id + '">\
							<option value="no">No</option>\
							<option value="yes"' + selected + '>Yes</option>\
						   </select>';

			} else {

				output += '<label for="' + id + '">' + label + '</label>';
				output += '<input id="' + id + '" name="' + id + '" type="' + type + '" class="' + type + '" value="' + value + '"' + disabled + '/>';

			}

			$(this).html(output);
			output = '';
		});
	});

	$('.myRhino .btn-cancel').live('click', function() {
		var element = $(this).closest('.infoSection');

		element.removeClass('editMode');
		element.addClass('displayMode');

		element.html(savedContent[element.attr('addressId')]);
	});
}


// this fixes a minor bug in the global store page:
// http://dev.rhinopop.com/global/store

if ( typeof checkCookie != 'function' ) {
	function checkCookie() { }
}


function fadeInToolTip() {
	$('.differenceToolTip').fadeIn('fast');
}
function fadeOutToolTip() {
	$('.differenceToolTip').fadeOut('fast');
}
function fadeInSizeTip() {
	$('.sizeTipWrap').fadeIn('fast');
}
function fadeOutSizeTip() {
	$('.sizeTipWrap').fadeOut('fast');
}
function fadeInLinks() {
	$('.artistTipWrap').fadeIn('fast');
}
function fadeOutLinks() {
	$('.artistTipWrap').fadeOut('fast');
}

function getParameterByName(name) {

    var match = RegExp('[?&]' + name + '=([^&]*)')
                    .exec(window.location.search);

    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));

}
