var Logger = {
	debug: function(text, indicator) {
		if	(window.console) { console.log((indicator||'>> ') + text); }
	}
};

function debug(text, indicator) {
	Logger.debug(text, indicator);
}

/* Message */
var AdminMessage = {};
AdminMessage.Base = new Class({
	options: {
		image: '/images/plus.gif',
		title: '',
		text: '',
		duration: 3
	},
	initialize: function(image) {
		Logger.debug('Message init');
		this.image = new Asset.image(image, { onload: this.create.bind(this) });
		return this.show.bind(this);
	},
	create: function() {
		Logger.debug('Message create');
		this.i = 0;

		this.image.setStyles({
			'position':'absolute',
			'right':'10px', 
			'display':'block'
		}).setOpacity(0).injectInside($(document.body));
		
		this.block = new Element('div').set({
			'class': 'message-notif',
			'styles': {
				'position': 'absolute',
				'z-index':'999',
				'right':'10px', 
				'display':'block',
				'width': '280px'
			}
		}).setOpacity(0).injectInside($(document.body));
		
		new Element('img', {
			'src': this.options.image,
			'styles': {
				'float':'left',
				'margin':'12px',
				'width': '50px',
				'height': '50px'
			}
		}).injectInside(this.block);
		
		new Element('h3').injectInside(this.block);
		new Element('p').injectInside(this.block);
	},
	show: function(options) {
		options = $merge(this.options, options);
		
		var elements = $A([this.image.clone(), this.block.clone()]);
		elements.each(function(e, i) {
			e.injectInside($(document.body));
			if (i) {
				e.getFirst().setProperty('src', options.image).getNext().set({'text': options.title}).getNext().set({'text': options.text});
			}
		});

		delta = window.getScrollTop()+10+(this.i*83);
		
		new Fx.Elements(elements).set({
			'0': {'top':delta+'px'},
			'1': {'top':delta+'px'}
		});

		new Fx.Elements(elements, {duration:400}).start({
			'0': { 'opacity': 0.7 }, 
			'1': { 'opacity': 1 }
		});
		this.i++;
		this.hide.delay(this.options.duration*1000, this, [elements]);
	},
	hide: function(elements) {
		Logger.debug('Message hide');
		
		new Fx.Elements(elements, {duration:400}).start({
			'0': { 'opacity': 0 }, 
			'1': { 'opacity': 0 } 
		});
		this.i--;
	}
});

/* Message for the front office */

var Message = {	
	create: function() {
		Logger.debug('Message init');
		var alreadyExisting = true;
						
		// create the div in case some feature needs it to display a message
		if ($('application-message-anchor')) {
			alreadyExisting = false;
			var div = new Element('div', { 'id': 'application-message' });
			var p = new Element('p', { 'class': 'notice', 'html': '' });
			p.inject(div);
			div.inject($('application-message-anchor'), 'after');
			$('application-message-anchor').dispose();						
		}
		
		var el = $('application-message');
						
		// add fx 
		var fx = new Fx.Slide(el, { duration: 400 });
		if (!alreadyExisting) fx.hide();
		el.store('fx', fx);
	},
	
	show: function(msg, cssClass, delay) {
		Logger.debug('Message show');
		var el = $('application-message');
		var fx = el.retrieve('fx');
		
		el.getElement('p').set('html', msg);
		el.getElement('p').set('class', cssClass);
		fx.slideIn().chain(function() { Message.hide(delay); });
	},
	
	hide: function(delay) {
		delay = delay || 7000;
		Logger.debug('Message hide');
		var el = $('application-message');
		var fx = el.retrieve('fx');
		
		(function() { fx.slideOut(); }).delay(delay);
	}
};

/* custom ajax requests */

Request.FRONT = new Class({
	Extends: Request.JSON,
	options: {
		data: {},
		messageDelay: 5000,
		errorMessageDelay: 7000,
		onFailure: function() {
			alert('Server error');
		}
	},
	initialize: function(options){
		this.parent(options);
		switch ($type(this.options.data)) {
			case 'string': this.options.data += "&" + Hash.toQueryString(SienerToken); break;
			case 'hash': case 'object': $extend(this.options.data, SienerToken); break;
		}		
	},
	success: function(text) { 
		this.parent(text);
		if (this.response.json.error) 
			Message.show(this.response.json.error, 'error', this.options.errorMessageDelay);
		else
			if (this.response.json.notice) Message.show(this.response.json.notice, 'notice');
	},
	send: function(options) {
		var data = options;			
		
		switch ($type(data)) {
			case 'element': case 'string': data = Hash.toQueryString(SienerToken) + "&" + $(data).toQueryString(); break;
			case 'hash': case 'object': data = { 'data': $merge(SienerToken, data) }; break;
		}
		this.parent(data);
	}
});

// inspired by http://refactormycode.com/codes/85-rails-like-number_to_currency-formatting
// and enhanced thanks to mootools
function numberToCurrency(number, format) {
  var match, defaultFormat, property, integerPart, fractionalPart;
	
  match = number.toString().match(/([\+\-]?[0-9]*)(.[0-9]+)?/);

  if (!match) return;

  defaultFormat = { precision: 2, unit: "$", separator: ".", delimiter : ",", format: "{u}{n}" };
	
  format = format || {};
  for (property in defaultFormat)
    if (typeof format[property] === "undefined")
      format[property] = defaultFormat[property];
	
  integerPart = match[1].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1" + format.delimiter);
  fractionalPart = ((match[2] == undefined ? "" : match[2].toString()) + "000000000000").substr(1, format.precision);

  return format.format.substitute({ u: format.unit, n: integerPart + ( format.precision > 0 ? format.separator + fractionalPart : "") });
}