var SearchResults = Class.create();
SearchResults.prototype = {
	store_id:36,
	search_id:0,
	search_string:'',
	category_offset:0,
	product_offset:0,
	cart_page:'/qs/cart.php',
	school_store_id:34,
	related_ids:$H(),

	initialize: function(options) {
		this.results = new Array();
		if (options!=null){
		  this.store_id=options.store_id;
		  this.search_id=options.search_id;
		  this.search_string=options.search_string;
		  this.category_offset=options.category_offset;
		  this.product_offset=options.product_offset;
		  this.cart_page=options.cart_page;
		  this.related_ids=$H(options.related_ids);
		}
	},

	get_isbn_10: function(isbn_13) {
		if (isbn_13.length != 13 || isbn_13.substring(0, 3) != '978') {
			return '';
		}
		var isbn_10 = isbn_13.substring(3, 12);
		var total = 0;
		for (i=0; i<9; i++) {
			total += (i+1) * parseInt(isbn_10.charAt(i));
		}
		var check_digit = total % 11;
		if (check_digit == 10) {
			check_digit = 'X';
		}
		
		return '' + isbn_10 + check_digit;
	},
	
	get_isbn_13: function(isbn_10) {
		if (isbn_10.length != 10) {
			return '';
		}
		var isbn_13 = '978' + isbn_10.substring(0, isbn_10.length-1);
		var total = 0;
		for (i=0; i<12; i++) {
			total += (i % 2 * 2 + 1) * parseInt(isbn_13.charAt(i));
		}
		var check_digit = 10 - total % 10;
		if (check_digit > 9) {
			check_digit = 0;
		}
		
		return '' + isbn_13 + check_digit;
	},
	
	insert: function(obj) {
		var product_isbn = obj.product_isbn;
		obj.total_sold = (+obj.total_sold);
		if (product_isbn == undefined) {
			return false;
		}
		obj.isbn_10 = this.get_isbn_10(obj.product_isbn);
	
		var found = false;
		this.results.each(function(s) {
			if (s[0].product_isbn == obj.product_isbn) {
				s[0].total_sold += obj.total_sold;
				s[s.size()] = obj;
				found = true;
			}
		});
		if (!found) {
			this.results[this.results.size()] = [ obj ];
		}
	},
	
	setRelated: function(related) { this.related = related; },

	sort: function(field) {
		var results = this.results;
		switch(field){
			case 'B':	// best sellers
				results = this.results.sortBy(function(s){return (+s[0].total_sold)}).reverse();
				break;
			case 'E':	// published date
				results = this.results.sortBy(function(s){return s[0].pub_date}).reverse();
				break;
			case 'T':	// title
				results = this.results.sortBy(function(s){return s[0].title.toLowerCase()});
				break;
		}
		return results;
	},

	updateCartForm: function(product, inventory, quantity) {
		if ($('product_id') == null || this.results.size() < 1) {
			$('status_message').update('Cannot add to cart.').scrollTo();
			return false;
		}
		$('product_id').value = product;
		$('inventory_id').value = inventory;
		$('quantity').value = quantity;
		$('status_message').update('Adding to cart...').scrollTo();
		new Ajax.Updater('status_message', this.cart_page, {parameters: $('cart_form').serialize(true)});
	},
	
	getResults: function(target, sort_order) {
		if ($(target) == null || this.results.size() < 1) return false;

		t_title = new Template(
			'<form id="cart_form" method="post">' +
			'<input type="hidden" name="store_id" value="'+this.store_id+'"' +
			'<input type="hidden" name="search_id" value="'+this.search_id+'">' +
			'<input type="hidden" name="search_string" value="'+this.search_string+'">' +
			'<input type="hidden" name="category_offset" value="'+this.category_offset+'">' +
			'<input type="hidden" name="product_offset" value="'+this.product_offset+'">' +
			'<input type="hidden" name="category_id" value="#{category_id}">' +
			'<input type="hidden" id="product_id" name="product_id" value="">' +
			'<input type="hidden" id="inventory_id" name="inventory_id" value="">' +
			'<input type="hidden" id="quantity" name="quantity" value="">' +
			'<input type="hidden" name="redir" value="ajax">' +
			'<table width="100%" style="background-color:#ddd;"><tbody class="text"><tr><th align="right">Title:</th><td colspan="3" style="font-size:larger">#{title}</td><th align="right">Edition:</th><td>#{edition}</td></tr>' +
			'<tr><th align="right">Author:</th><td colspan="3">#{author}</td><th align="right">Pub Date:</th><td>#{pub_year}</td></tr>' + 
			'<tr><th align="right">ISBN:</th><td>#{isbn_10}</td><th align="right">ISBN-13:</th><td width="110">#{product_isbn}&nbsp;</td><th align="right">Publisher:</th><td>#{publisher}</td></tr>' +
			'<tr><td colspan="6"><table width="100%" align="center" style="background-color:#fff;"><tbody class="text"><tr valign="bottom"><th>Condition</th><th>ISBN</th><th>Price</th><th>Available<br>On-Hand</th><th>Qty</th><th>Add to<br>Cart</th></tr>'
		);
		t_row = new Template(
			'<tr style="text-align:center;background-color:#{background};"><td><a target="_blank" href="/qs/page/sm/3410/1348/#{store_id}" title="Book Condition Chart">#{condition}</a></td><td>#{sku_isbn}</td><td>#{price}</td><td>#{quantity}</td><td><input id="quantity_#{inventory_id}" size="2"></td><td><input type="button" value="Add" onClick="if (search_results.updateCartForm(#{product_id},#{inventory_id},$F(\'quantity_#{inventory_id}\'))) this.form.submit();"></td></tr>'
		);
		t_supplementary = new Template(
			'<tr><td colspan="2"><a target="_blank" href="/search/?p=#{related_ids}">Supplementary Materials</a></td></tr>'
		);
		t_foot = new Template(
			'<tr height="10"></tr>' +
			'<tr><td colspan="6">Not all our inventory is listed online. If you need more copies than currently Available On-Hand</td></tr>'+
			'<tr><td colspan="6">please enter the total quantity that you need in your cart. We\'ll check for additional stock and</td></tr>'+
			'<tr><td colspan="6">contact you.</td></tr>' +
			'<tr><td colspan="6" style="font-size:larger"><strong>PRICES and AVAILABILITY of all items are subject to verification.</strong></td></tr>'+
			'</tbody></table></td></tr></tbody></table><br>' +
			'</form>'
		);

		var result_str = '';
		var results = this.sort((sort_order) ? sort_order : 'B');
		if (results.length < 2) {
			$$('.tr_sort').invoke('hide');
		}
		results.each((function(s) {
			result_str += t_title.evaluate(s[0]);
			s.each((function(t) {
				t.store_id=this.store_id;
				t.background = '#fff';
				if (t.quantity > 0 && (t.condition == 'Near New' || t.condition == 'Used')) {
					t.background = '#bfb';
				}
				if (t.quantity > 200) {t.quantity = '200+';}

				result_str += t_row.evaluate(t);
			}).bind(this));
			var suppl_arr  = this.related_ids.get(s[0].product_id);
			if (this.store_id == this.school_store_id && suppl_arr) {
				result_str += t_supplementary.evaluate({related_ids:suppl_arr.join(',')});
			}
			result_str += t_foot.evaluate('');
		}).bind(this));
		
		$(target).update(result_str);
		return this.results.length;
	},
	
	debug: function(results) {
		var str = '';
		results.each(function(s, idx) {
			str += idx +': '+ s[0].name + '<br>';
			s.each(function(t) {
				str += '...';
				if (t.product_isbn.endsWith('U')) {
					str += 'USED';
				} else if (t.product_isbn.endsWith('F')) {
					str += 'FAIR';
				} else if (t.product_isbn.endsWith('P')) {
					str += 'PASSABLE';
				} else if (t.product_isbn.endsWith('N')) {
					str += 'NEAR NEW';
				} else {
					str += 'NEW';
				}
				str += ' ('+t.product_isbn+')<br>';
			});
		});
		$("debug_msg").update(str);
	}
};


