var COUPON = {
	selected: [],
	init:function() {
		$('COUPONS').select('li').each(function(coupon) {
			var couponSelect = new Element('span');
			coupon.insert(couponSelect);
		});
		Event.observe('COUPONS',"mouseup",COUPON.upEvent);
			
		var printLink = new Element('a',{'href':'javascript:void(0);','class':'printCoupon noprint'}).update('print');
		$('COUPONS').insert({'top':printLink});
		
		var selectLink = new Element('a',{'href':'javascript:void(0);','class':'unselectAll noprint'}).update('unselect all');
		$('COUPONS').insert({'top':selectLink});
		
		var selectLink = new Element('a',{'href':'javascript:void(0);','class':'selectAll noprint'}).update('select all');
		$('COUPONS').insert({'top':selectLink});
		
		var message = new Element('div',{'class':'couponMessage noprint'});
		$('COUPONS').insert({'top':message});
	},
	upEvent:function(event) {
		$('COUPONS').down('div.couponMessage').update('');
		var target_el = event.element();
		switch (target_el.tagName) {
		case 'IMG' :
			COUPON.toggle(target_el.next('span'));
			break;
		case 'SPAN' :
			COUPON.toggle(target_el);
			break;
		case 'A' :
			if (target_el.hasClassName('printCoupon')) {
				COUPON.print();
			} else if (target_el.hasClassName('selectAll')) {
				$('COUPONS').select('li').each(function(coupon) {
					coupon.down('span').addClassName('selected');
				});
			} else if (target_el.hasClassName('unselectAll')) {
				$('COUPONS').select('li').each(function(coupon) {
					coupon.down('span').removeClassName('selected');
				});
			} 
			break;
		}
	},
	print:function() {
		var hasSelected = false;
		$('COUPONS').select('li').each(function(coupon) {
			coupon.addClassName('noprint');
			if (coupon.down('span').hasClassName('selected')) {
				coupon.removeClassName('noprint');
				hasSelected = true;
			}
		});
		
		if (hasSelected) {
			$('COUPONS').select('li').each(function(coupon) {
				coupon.down('span').removeClassName('selected');
			});
			print();
		} else {
			$('COUPONS').down('div.couponMessage').update('No coupons are selected.');
		}
	},
	printWin:function(id) {
		var couponWin = window.open('coupon/index.php?id=' + id,'couponWin','height=432,width=270');
		couponWin.focus();
	},
	toggle:function(target_el) {
		if (target_el.hasClassName('selected')) {
			target_el.removeClassName('selected');
		} else {
			target_el.addClassName('selected');
		}
	}
}
Event.observe(window,'load',COUPON.init);
