
(function($){
//Encloses and protects $, and all other defined symbols. attachement to BN object inside is link to outer world.
var updateTooltips = function(updateType){
	 $('td.functionalLink span').each(function(){
		 $(this).hoverCopyFrom('#toolTip'+$(this).text());		 
	});
}
$(function() {
iSection = new BN.FormUtil.InputSection('#orderTable','tr.inputLine','#bulkEntryTemplate','#titleCount');
iSection.setControlDetails('searchall','<td class="functionalLink"><span class="searchItemGroup" onclick="Bulk.doSearch(iSection.getIndex(this))">Search</span></td>','abc',null,null,null);
iSection.doOnUpdate(updateTooltips);
iSection.initialize();
iSection.displayAllControls();
//updateTooltips();

$('.bulkOrderHelpTrigger').click(function(){
	var o=new $.Overlay({
		heading:'What is an ISBN or UPC?',
		useHeading:1
	});
	o.set.content('<div class="copy">'+$('.bulkOrderHelp').html()+'</div>');
	o.set.width(500);
	o.open();
	$('.overlayClose',o.element).click(function(){
		o.close();
		o.remove();
	});
});

$('.addNewInput').click(function(){
	iSection.newGroup();
});

Bulk={};




Bulk.widget=new $.SearchWidget({
			heading: "Find a book",
			cbf:'Bulk.widget.displayResults',
			productTypes:["Books","DigAudio", "DVD", "Music", "Video_Games", "Toys_Games", "Home_Gifts"],
			add:function(e) {
				e.preventDefault(e);
				var grp;
				var first = Bulk.widget.firstAdd;
				var clickValues = $(e.target).attr('id').split("_");
				var ean = clickValues[1];
				var title = $(e.target).parents('tr').find('span.title').text();
				if(!(first)){
					var found = false;
					while(grp=iSection.getGroup(++Bulk.widget.start)){
						if(grp.testEmpty()){
							found=true;							
							break;
						}						
					}
					if(!found){
						grp = iSection.newGroup();
					}
				}else{
					var grp = iSection.getGroup(Bulk.widget.start);
				}
				grp.addNewValue('title',title);
				grp.addNewValue('isbn',ean);
				grp.populate();
				grp.removeControl('searchall');
				Bulk.widget.firstAdd=false;
			}
		});
Bulk.widget.defaultDisplay =Bulk.widget.displayResults;
Bulk.widget.displayResults = function(rsp){
	Bulk.widget.defaultDisplay(rsp);
	$('.sw-add').once('addBook').hoverCopyFrom('#toolTipSearchAdd');
}

Bulk.doSearch=function(x){
	Bulk.widget.start=x;
	Bulk.widget.firstAdd=true;	
	Bulk.widget.addItems();
	var curr=iSection.getGroup(x);
	curr.setValues();
	var fill=(curr.getValue('isbn'+x))?curr.getValue('isbn'+x):curr.getValue('title'+x);
	if(fill){
		$('#searchWidget-value').get(0).value=fill;
		$('#searchWidget-search').click();
	}	
}

});

})(jQuery);
