// standard events
window.addEvent('domready', function() {

// OTREASURES - ajax search (google style)
var coupon_search = $('coupon_search');
var output = $('coupon_search_output');

if ( coupon_search && output ) {
	// timer
	var cso_timeout;

	// focus was lost
	coupon_search.addEvent('blur', function(e) {
		cso_timeout = setTimeout("$('coupon_search_output').setStyle('display','none')", 500);
	});

	// focus was gained
	coupon_search.addEvent('focus', function(e) {
		clearTimeout(cso_timeout);
		if ( output.innerHTML != '' )
			output.setStyle('display','block');
	});

	// key was pressed
	coupon_search.addEvent('keyup', function(e) {
		// check if there are no chars, if none, hide the box again
		if ( coupon_search.value.length == 0 )
			output.setStyle('display','none');
		else {
			output.setStyle('display','block');
        }

		// setup the url
		var url = tres.url+'/page/coupons_ajax?search=' + encodeURIComponent(coupon_search.value);

		// perform the ajax
		new Ajax(url, {
				 wait: false,
				 method: 'get',
				 update: output
		}).request();

    });
}

// OTREASURES - autotab for home_act_code module
var home_act_codes = $$('.home_act_code');
if ( home_act_codes && home_act_codes.length > 0 ) {
	home_act_codes.each(function(el, idx) {
		el.addEvent('keyup', function(e) {
			// grab id number
			id = el.id;
			id = id.substring(1);
			id = parseInt(id);
			id++;
			// grab the next element
			if ( id <= 9 && el.value.length == 1 ) {
				new_el = 'c'+id;
				new_el = $(new_el);
				if ( new_el )
					new_el.focus();
			}
		});

		el.addEvent('focus', function(e) {
			el.select(1,1);
		});
	});

}

// OTREASURES - mydeals
var mydeal_buttons = $$('.mydeals_button');
if ( mydeal_buttons && mydeal_buttons.length > 0 ) {
	mydeal_buttons.each(function(el, idx) {
		el.addEvent('click', function() {
			var coupon_id = parseInt(el.id.substr(2));
			if ( el.hasClass('mydeals_button_off') ) {
				// url
				var url = tres.url+'page/favourites/?ajax=add_deal&coupon_id='+coupon_id;

				// ajax
				new Ajax(url, {
						 method: 'get'
				}).request();

				// perform 'add from my deals'
				el.removeClass('mydeals_button_off');
				el.addClass('mydeals_button_on');
				el.title = 'Remove from my favourites';
			} else {
				// url
				var url = tres.url+'page/favourites/?ajax=remove_deal&coupon_id='+coupon_id;

				// ajax
				new Ajax(url, {
						 method: 'get'
				}).request();

				// perform 'remove to my deals'
				el.removeClass('mydeals_button_on');
				el.addClass('mydeals_button_off');
				el.title = 'Add to my favourites';
			}
		});
	});
}
});

