/*
*
*	Nectar utils
*
*/

if (NECTAR === undefined){
	var NECTAR = {};
}

NECTAR.stripNonDigits = function(element) { 
	
	//Passing in an element is optional. When called from an event handler, 'this' will refer to the clicked/pressed element instead.
	
	var userentered = element.value || this.value;  
	var re = /\D/g;
	if (userentered.match(re)){
		this.value = userentered.replace(re, "");
	}	
};


NECTAR.trunc = function(items, maxwords){
	
	//adds 'show more' link to items with text longer than maxwords
	
	var group = items;		//items you want to truncate (array)
	var max = maxwords;		//max number of words to display
	
	var i = group.length;
	while (i--){
		var words = group[i].innerHTML.split(/[\s]+/);
		var len = words.length;
		if (len > max){
			var visiblewords = words.slice(0, max);
			var hiddenwords = words.slice(max, len);
			group[i].innerHTML = visiblewords.join(" ") + ' <span style="display: none;">' + hiddenwords.join(" ") + '</span> ( ... <a href="#" class="trunctoggle">more</a> )';
		}
	}
	
	$('a.trunctoggle').toggle(
		function (){
			$(this).text('less').prev('span').show();
		},
		function (){
			$(this).text('more').prev('span').hide();
		}
	);
};


NECTAR.getPopularProducts = function(retailer, numberofproducts){
	var ret = retailer;					//retailer 'popular products' name
	var num = numberofproducts || 15;	//number of popular products to display (optional, default is 15)
										
	$.ajax({
	url : "/dynamic/shoppingPopup/shopping/search?partner_wl_path=/VENDA/nectar/cse/retailer_products/" + ret + "&count=" + num,
	success : function (data) {
			$("#popularproducts").html('<li id="popularintro">The products shown on this page are subject to the points exceptions that apply to each retailer. Please check the exceptions before making your purchase by looking under the &ldquo;Important information&rdquo; tab.</li>' + data);
			NECTAR.trunc($('#popularproducts p.price'),30);
	}
	});
};


//GOOGLE EVENT TRACKING
NECTAR.event = function(obj, cam, pid){
		var _obj = obj;			//jquery object
		var _cam = cam;			//Campaign name
		var _pid = pid || "";	//Panel ID
					
		var _cat = "CAM: " + _cam;
		var _pg = "PG: " + document.location.pathname;
		var _ad = "AD:";
		
		if(_pid){
			_ad += " " + _pid + "/";
		}
		
		_ad += _obj.text().replace(/^\s+|\s+$/,'');
		
		var imgs = _obj.find('img');
		if (imgs.length){
			_ad += " " + imgs.attr('alt') + " image";
		}
		
		if (_obj.attr('href').match(/http:\/\//)){
			_ad += " outbound";
		}
		
		pageTracker._trackEvent(_cat, _pg, _ad);
		
};

