// HTML Truncator for jQuery
// by Henrik Nyh <http://henrik.nyh.se> 2008-02-28.
// Free to modify and redistribute with credit.

(function($) {

  var trailing_whitespace = true;

  $.fn.truncate = function(options) {

    var opts = $.extend({}, $.fn.truncate.defaults, options);
    
    $(this).each(function() {

      var content_length = $.trim(squeeze($(this).text())).length;
      if (content_length <= opts.max_length)
        return;  // bail early if not overlong

      var actual_max_length = opts.max_length - opts.more.length - 3;  // 3 for " ()"
      var truncated_node = recursivelyTruncate(this, actual_max_length);
      var full_node = $(this).hide();

      truncated_node.insertAfter(full_node);
      
      findNodeForMore(truncated_node).append(' (<a href="#show more content">'+opts.more+'</a>)');
      findNodeForLess(full_node).append(' (<a href="#show less content">'+opts.less+'</a>)');
      
      truncated_node.find('a:last').click(function() {
        truncated_node.hide(); full_node.show(); return false;
      });
      full_node.find('a:last').click(function() {
        truncated_node.show(); full_node.hide(); return false;
      });

    });
  }

  // Note that the " (…more)" bit counts towards the max length – so a max
  // length of 10 would truncate "1234567890" to "12 (…more)".
  $.fn.truncate.defaults = {
    max_length: 100,
    more: '',
    less: ''
  };

  function recursivelyTruncate(node, max_length) {
    return (node.nodeType == 3) ? truncateText(node, max_length) : truncateNode(node, max_length);
  }

  function truncateNode(node, max_length) {
    var node = $(node);
    var new_node = node.clone().empty();
    var truncatedChild;
    node.contents().each(function() {
      var remaining_length = max_length - new_node.text().length;
      if (remaining_length == 0) return;  // breaks the loop
      truncatedChild = recursivelyTruncate(this, remaining_length);
      if (truncatedChild) new_node.append(truncatedChild);
    });
    return new_node;
  }

  function truncateText(node, max_length) {
    var text = squeeze(node.data);
    if (trailing_whitespace)  // remove initial whitespace if last text
      text = text.replace(/^ /, '');  // node had trailing whitespace.
    trailing_whitespace = !!text.match(/ $/);
    var text = text.slice(0, max_length);
    // Ensure HTML entities are encoded
    // http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
    text = $('<div/>').text(text).html();
    return text;
  }

  // Collapses a sequence of whitespace into a single space.
  function squeeze(string) {
    return string.replace(/\s+/g, ' ');
  }
  
  // Finds the last, innermost block-level element
  function findNodeForMore(node) {
    var $node = $(node);
    var last_child = $node.children(":last");
    if (!last_child) return node;
    var display = last_child.css('display');
    if (!display || display=='inline') return $node;
    return findNodeForMore(last_child);
  };

  // Finds the last child if it's a p; otherwise the parent
  function findNodeForLess(node) {
    var $node = $(node);
    var last_child = $node.children(":last");
    if (last_child && last_child.is('p')) return last_child;
    return node;
  };

})(jQuery);




















var newwindow;
function jamRadio(url) {
	newwindow=window.open(url,'lastFM','height=225,width=525');
	if (window.focus) {newwindow.focus()}
}



jQuery(document).ready(function(){
	
	//CART
	var cart = jQuery('ul.cart li.cart_item').size();
	var shipCosts = cart * .30;
	
	$('.cart_items_wrapper').html('<li>You have ' + cart + ' items in your basket.</li>');
	
	var items_in = jQuery('ul.cart_items_wrapper li').html();
	if (items_in == 'You have 0 items in your basket.') {
		$('h2#cart_box').hide();
		jQuery('#Cartbox').animate({top: "-60px"}, 500);
	} else {
		$('h2#cart_box').show();
		jQuery('#Cartbox').animate({top: "0px"}), 500;
	}
	
	//FORMAT
	
	var itemFormat = jQuery('.vinyl_option').html();
	if (itemFormat == 'Vinyl') {
		jQuery('span.vinyl_option').parent('td.format').html('Vinyl');
	};
	
	var confirm_itemFormat = jQuery('.confirm_vinyl_option').html();
	if (confirm_itemFormat == 'Vinyl') {
		jQuery('.confirm_vinyl_option').prev('.jam_confirm_format').hide();
	};
	
	jQuery('.invoice_vinyl_option').css('visibility','hidden');
	var invoice_itemFormat = jQuery('.invoice_vinyl_option').html();
	if (invoice_itemFormat == 'Vinyl') {
		jQuery('.invoice_vinyl_option').parent().next('.invoice_model').html('Vinyl');
	};
	
	//PNG FIX FOR IE
	if($.browser.msie && $jq.browser.version=="6.0") {
		jQuery('body').pngFix( );
	}
	
	//HIDE CART IF EMPTY
	var inBasket = jQuery('ul.cart li').html();
	var basket = jQuery.trim(inBasket);
	
	if (basket == '0 items') {
		jQuery('ul.cart').parent().hide();
	} else {
		jQuery('ul.cart').parent().show();
	}
	
	//AUTO FILL EMAIL HELP
	var logEmail = jQuery('#jam_email').val();
	if (logEmail == '') {
		jQuery('#jam_email').val("Your email address...");	
	}
	//AUOFILL PASSWORD HELP
	var logPass = jQuery('#jam_password').val();
	if (logPass == '') {
		jQuery('#jam_password').val("password");	
	}

	//SEARCH TEXT REMOVED 
	jQuery('#jam_search_go').attr('value','')
    
	//PLUG IN THE STEREO
	jQuery('#stereo_off').attr('title','Turn it on!').css('cursor','pointer');
	
	jQuery('#stereo_off').click( function() {
		var jamListen = jQuery('h2#search_me span').text().replace('the ','');
		var strip = jamListen.indexOf("-");
		var lastFM = jamListen.substr(0, strip);
		
		var titled = jQuery(this).attr('title');
		if (titled == 'Turn it on!') {
			jQuery('#stereo').show();
			jQuery('#stereo_off').hide();
			jamRadio('http://www.last.fm/listen/artist/' + lastFM);
			jQuery(this).attr('title','Turn it off!');
		} else {
			jQuery('#stereo').hide();
			jQuery('#stereo_off').show();
			newwindow.close();
			jQuery('#stereo_off').attr('title','Turn it on!');
		}
	});
	
	//CLEAR THE LOGIN FIELDS ON FOCUS	
	$('#jam_email').focus(function() {
        if( $(this).val() == "We'll be needing your email address...")
        	$(this).val('');
    }).blur(function() {
        if( $(this).val() == '')
        	$(this).val("We'll be needing your email address...");
    });
    
    $('#jam_password').focus(function() {
        if( $(this).val() == "password")
        	$(this).val('');
    }).blur(function() {
        if( $(this).val() == '')
        	$(this).val('password');
    });

	//FORMAT
	jQuery('#format_2').hide();
	jQuery('#vinyl_option').parent().next('li.format').html('Vinyl LP');
	var formatCart = jQuery('#purchase li.format').html();
	if (formatCart == 'Compact Disk') {
		jQuery('#purchase li.format').html('CD');
	}
	
	//REVIEWS

	jQuery('h3.category_rating').children('span.total_ratings').each(function(i) {
		var rate = jQuery(this).html();
		if(rate == '(0)') {
			jQuery(this).parent().hide();
		}
	});
	
	var rating = jQuery('span.total_ratings').html();
	if (rating == '(0)') {
		jQuery('h2.rating_title').css('display','none');
	};
	
	
	jQuery('#not_logged_in').show();
	jQuery('#logged_in').hide();	
	
	var writeReview = jQuery('#logged_in_set').val();
	if (writeReview == '1') {
		jQuery('#not_logged_in').hide();
		jQuery('#logged_in').show();	
	};
	
	//AUDIO
	var audioClips = jQuery('.listen').html();
	if (audioClips == '') {
		jQuery('#audio_player').hide();	
	};
	
	jQuery('a.home_audio_clip').each(function(i) {
		var href = jQuery(this).attr('href');
		if(href == 'audio/') {
			jQuery(this).hide();
		}
	});
	
	//PAYMENT TITLES
	var payment = jQuery('.payment_title').html();
	if (payment == 'WorldPay') {
		jQuery('.payment_title:first').html('Pay securely using your Credit, Debit Card or via Paypal');
	}
	jQuery('#worldpay').attr("checked", "checked"); 
	
	//HIDE RADIO BUTTON
	jQuery('#item_item').css('display','none');
	jQuery('#item_item').attr("checked", "checked"); 
	
	//HIDE TEXTAREA
	jQuery('#postage_comments').hide();
	jQuery('#add_commnets').click(function() {
		var textarea = jQuery('#postage_comments');
		if(textarea.is(':visible')) {
			textarea.slideUp();
		} else {
			textarea.slideDown();
		}
		return false;
	});
	
	//DELIVERY TIME
	var delivery = jQuery('#jam_quantity').attr('value');
	
	if(delivery == '0') {
		jQuery('#jam_delivery').html('Delivery 2-3 days');
	} else {
		jQuery('#jam_delivery').html('In stock');
	};
	
	var inStock = jQuery('#cart_status h1').html();
	if (inStock == 'Products marked with *** are not available in the desired quantity or not in stock!') {
		jQuery('#cart_status h1').html('Items dispatched in 2-3 days')
	};

	//INPUT STYLES
	jQuery('input[type="button"]').addClass('buttons');
	jQuery('input[type="submit"]').addClass('buttons');
	jQuery('input[type="text"]').addClass('text');
	jQuery('input[type="password"]').addClass('text');
	
	//AJAX
	
	
	if($('body').hasClass('category')) {
		$('body').prepend('<div class="message"></div>');
		var msg = $('.message');
		$.ajax({
			type: 'GET',
			url: '/rss.php',
			data: {key: "value"},
			dataType: "html",
			success: function(html){
				$('#jam_right_column').addClass('latest_releases');
				$('.latest_releases').html('<div id="lounge_feed" class="box"></div>');
				
				$(html).find('item').filter(function(index) {
					return index % 3 == 2;
				}).each(function() {
					var description = $('description',this).text();
					var title = $('title',this).text();
					var link = $('guid',this).text();
					$('#lounge_feed').append('<div class="new_release"><a title="' + title + '" href="' + link + '">' + description + '</a></div>');
				});
				
				$('div.new_release').each(function() {
					$(this).truncate({max_length: 80,more: '',less: ''});
				})
				
			},
			error: function(req,error) {
	          msg.html(' (error!)');
	          msg.addClass('error');
	          if(error === 'error'){error = req.statusText;}
	          var errormsg = 'There was a communication error: '+error;
	          msg.html(errormsg)
			},
			complete: function() {
				
			}
		});		
	}
});


