if(!Contes) { var Contes = {}; }

/************************************
 *          Multicheckbox           *
 ************************************/

Contes.Multicheckbox = Class.create({
    
    options: $H({
        'max' : false
    }),
    
    initialize: function(element, options) {
        this.options.update(options);
        this.el = $(element);
        this.checkboxes = this.el.select('input');
        this.checkboxes.each(function(b){
            b.observe('click', function(e) {
                this.validate();
            }.bind(this));
        }, this);
        this.validate();
    },
    
    validate: function() {
        var count = 0;
        this.checkboxes.each(function(b){
            if(b.checked) {
                count++;
            }
        });
        if(this.options.get('max') && count >= this.options.get('max')) {
            this.lock();
        } else {
            this.unlock();
        }
    },
    
    lock: function() {
        this.el.addClassName('locked');
        this.checkboxes.each(function(b){
            if(!b.checked) {
                b.disable();
            }
        });
    },
    
    unlock: function() {
        this.el.removeClassName('locked');
        this.checkboxes.each(function(b){
            b.enable();
        });
    }
});

/************************************
 *          BlackAndWhite           *
 ************************************/
 
Contes.BlackAndWhite = Class.create({
    initialize: function(checkElt, coloristElt) {
		this.checkbox = $(checkElt);
		this.colorists = $(coloristElt);
		this.toggleColorists();
		
		this.checkbox.observe('click', this.toggleColorists.bind(this));
	},
	
	toggleColorists: function(e) {
		if (this.checkbox.checked) {
			this.colorists.hide();
		} else {
			this.colorists.show();
		}
	}
});


/************************************
 *          Autocomplete            *
 ************************************/

Contes.Autocomplete = Class.create({
    
    options: $H({
        'loadingText' : 'Loading...'
    }),
    
    initialize: function(element, hidden, url, options) {
        this.options.update(options);
        this.el = $(element).writeAttribute('autocomplete', 'off');
        this.el.observe('keydown', this.process.bind(this));
        this.el.observe('keyup', this.search.bind(this));
        this.el.observe('blur', this.select.bind(this));
        this.hidden = $(hidden);
        this.url = url;
        this.result = new Element('div');
        this.result.addClassName('autocomplete-result')
                   .setStyle({display : 'none', position : 'absolute'});
		this.el.insert({'after': this.result});
    },
    
    process: function(e)
    {
        if(this.resultShown) {
            switch(e.keyCode){
              case Event.KEY_UP: return this.move('up');
              case Event.KEY_DOWN: return this.move('down');
              case Event.KEY_TAB:
              case Event.KEY_RETURN:
                e.stop();
                this.select(); 
                return false;
                break;
              case Event.KEY_ESC: return this.unselect();
            }
        }
    },
    
    search: function(e) {
        switch(e.keyCode) {
            case Event.KEY_UP: 
            case Event.KEY_DOWN:
            case Event.KEY_RIGHT:
            case Event.KEY_LEFT:
            case Event.KEY_TAB:
            case Event.KEY_RETURN:
            case Event.KEY_ESC: 
                break;
            default:
                if(this.el.value == '') return this.reset();
                new Ajax.Request(this.url, {
                        method: 'get',
                        parameters: {'q': this.el.value},
                        onLoading: function(transport) {
                            this.result.update('<ul>'+this.options.get('loadingText')+'</ul>');
                            this.show();
                        }.bind(this),
                        onSuccess: function(transport) {
                            this.reset();
                            this.feed(transport.responseText);
                            if(this.result.innerHTML) this.show();
                        }.bind(this)
                    });
        }
    },
    
    feed: function(response) {
        this.result.innerHTML = response;
        this.result.select('li').each(function(el){
            el.observe('click', this.select.bind(this));
            el.observe('mouseover', function(e){
                this.focus(e.element());
            }.bind(this));
        }, this);
    },
    
    reset: function() {
        this.hide();
    },
    
    show: function() {
        if(!this.resultShown) {
            this.resultShown = true;
            this.result.setStyle({ display : 'block'});
        }
        this.focus(this.result.select('li')[0]);
    },
    
    hide: function() {
        this.resultShown = false;
        this.result.innerHTML = '';
        this.result.setStyle({'display': 'none'});
    },
    
    focus: function(element)
    {
        if(this.current) this.current.removeClassName('highlighted');
        this.current = $(element).addClassName('highlighted');
    },
    
    move: function(direction) {
        if(!this.resultShown) return false;
        if(this.current) this.focus(this.current[(direction == 'up' ? 'previous' : 'next')]());
        return this;
    },
    
    unselect: function()
    {
        this.current = null;
        this.hidden.value='';
        this.hide();
    },
    
    select: function()
    {
        if(this.current) {
            this.hidden.value = this.current.id;
            this.el.value = this.current.innerHTML;
            this.current = null;
			this.hide();
			if(this.onSelect) { this.onSelect();}
        } else {
			this.hide();
		}
        return false
    }
});

/************************************
 *          Textboxlist             *
 ************************************/

Contes.Textboxlist = Class.create({
    
	initialize: function(element, name, url, options) {
        this.el = $(element);
		this.el.addClassName('textboxlist');
        this.url = url;
		this.name = name;
		this.initBoxes();
		this.createAutocomplete();
    },
    
	initBoxes: function()
	{
		this.el.select('li').each(function(d){
            var hidden = this.createHidden();
            hidden.value = d.id;
            var box = this.createBox(d.innerHTML, hidden);
            this.el.insert(box);
        }, this);
	},
		
    select: function() {
        var box = this.createBox(this.input.value, this.hidden);
		this.autocomplete.replace(box);
		this.createAutocomplete();
		this.input.focus();
    },
	
    createAutocomplete: function() {			
			this.autocomplete = new Element('span', {'class': 'autocomplete textboxlist-input', style: 'float:left;'});
			
			this.input = new Element('input', {type: 'text'});
			this.autocomplete.insert(this.input);
			
			this.hidden = this.createHidden();
			this.autocomplete.insert(this.hidden);
			
			var tmp = new Contes.Autocomplete(this.input, this.hidden, this.url);
			tmp.onSelect = this.select.bind(this);
			this.el.insert(this.autocomplete);
    },
    
	createHidden: function() {
		var hiddenName = this.name + '[]';
		var hidden = new Element('input', {type: 'hidden', name: hiddenName});
		return hidden;
	},
	
	createBox: function(caption, hidden) {
		var box = new Element('span', {style:'float:left;'});
		box.addClassName('textboxlist-box');
		
		var x = new Element('span');
		x.insert('X').addClassName('textboxlist-close').setStyle({cursor: 'pointer'});
		x.observe('click', this.closeBox);
		
		box.insert(caption)
		   .insert(hidden)
		   .insert(x);
		return box;
	},
	
	closeBox: function(e) {
		e.element().up('.textboxlist-box').remove();
	}
});

/************************************
 *              Date                *
 ************************************/

Contes.Date = Class.create({
    
    years: {first: 1900, last: 2010},
    
    months: $A([
        {id: 1, value : 'janvier'},
        {id: 2, value : 'février'},
        {id: 3, value : 'mars'},
        {id: 4, value : 'avril'},
        {id: 5, value : 'mai'},
        {id: 6, value : 'juin'},
        {id: 7, value : 'juillet'},
        {id: 8, value : 'aout'},
        {id: 9, value : 'septembre'},
        {id: 10, value : 'octobre'},
        {id: 11, value : 'novembre'},
        {id: 12, value : 'decembre'}
    ]),
    
    initialize: function(element) {
        var el = $(element);
        this.initDate = new Date(el.value);
        this.el = new Element('div', {'class': 'date'});
        this.el.id = el.id;
		Element.replace(el, this.el);
        this.build();
        
        var name = el.name ? el.name : el.id;
        this.day.name   = name + '[day]';
        this.month.name = name + '[month]';
        this.year.name  = name + '[year]';
    },
    
    build: function(){
        this.day = this.createSelect(this.list(1,this.nbrOfDays()));
        this.day.value = this.initDate.getDate();
        this.el.insert(this.day);
        
        this.month = this.createSelect(this.months);
        this.month.observe('change', this.updateDays.bind(this));
        this.month.value = this.initDate.getMonth() + 1;
        this.el.insert(this.month);
        
        this.year = this.createSelect(this.list(this.years.first,this.years.last));
        this.year.observe('change', this.updateDays.bind(this));
        this.year.value = this.initDate.getFullYear();
        this.el.insert(this.year);
    },
    
    updateDays: function(){
        var currentDay = this.day.value;
        var currentNbrOfDays = this.day.length;
        var nbrOfDays = this.nbrOfDays(this.month.value, this.year.value);
        if (currentNbrOfDays != nbrOfDays) {
            this.createOptions(this.day.update(''), this.list(1, nbrOfDays));
            this.day.value = currentDay;
        }
    },
    
    createSelect: function(data) {
        var select = new Element('select');
        this.createOptions(select, data);
        return select;
    },
    
    createOptions: function(select, data) {
        data.each(function(data){
            var option = new Element('option');
            option.value = data.id;
            option.insert(data.value);
            select.insert(option);
        }, select);
        return select;
    },
    
    list: function(min, max) {
        data = $A();
        $R(min, max).each(function(i){
            data.push({'id': i, 'value' : i});
        }, data);
        return data;
    },
    
    nbrOfDays: function(month, year) {
        if (!month) { return 31; }
        switch (month) {
            case '4':
            case '6':
            case '9':
            case '11':
                return 30;
                break;
            case '2':
                if(!year) return 29;
                return (year % 4 == 0) ? (year % 100 == 0)  ? (year % 1000 == 0) 
                                       ? 29  : 28 : 29 : 28; 
                break;
            default:
                return 31;
                break;
        }
    }
});

/************************************
 *            AjaxAction            *
 ************************************/
Contes.AjaxAction = Class.create({
    defaults: {
        loadingMessage : 'En cours ...',
        successMessage : 'OK',
        errorMessage    : 'Oups ! Une erreur s\'est produite. Veuillez réessayer plus tard.'
    },
    
    initialize: function(element, message, options) {
        this.el = $(element);
        this.disabled = false;
        this.message = $(message);
        this.options = $H(this.defaults).merge(options);
        this.el.observe('click', this.onClick.bind(this));
    },
    
    disable: function() {
        this.disabled = true;
        if (!this.el.hasClassName('btn-disabled')) {
            this.el.addClassName('btn-disabled');
        }
    },
    
    enable: function() {
        this.disable = false;
        if (this.el.hasClassName('btn-disabled')) {
            this.removeClassName('btn-disabled');
        }
    },
    
    onClick: function(e) {
        e.stop();
        if (!this.disabled) {
            this.disable();
            new Ajax.Request(this.el.getAttribute('href'), {
                parameters: {
                    'request_uri': window.location.href
                },
                
                onLoading : function(transport) {
                    this.createMessage(this.options.get('loadingMessage'), 'info');
                }.bind(this),
                
                onSuccess : function(transport) {
                    var data = transport.responseJSON;
                    if (Object.isUndefined(data)) {
                        this.createMessage(this.options.get('errorMessage'), 'error');
                    } else {
                        if (data.message) {
                            this.createMessage(data.message, 'success');
                        }
                        
                        if (data.button) {
                            var holder = new Element('div');
                            holder.insert(data.button);
                            var new_element = holder.firstDescendant();
                            this.el.replace(new_element);
                            this.el = $(new_element);
                            this.el.observe('click', this.onClick.bind(this));
                            this.disabled = false;
                        }
                        
                        if (data.text) {
                            this.el.replace(data.text);
                        }
                        
                        if (data.event) {
                            var evt = data.event.evalJSON();
                            this.el.fire(evt.name, evt.memo);
                        }
                    }
                    this.enable();
                }.bind(this),
                
                onFailure : function(transport) {
                    switch (transport.status) {
                        // unauthorized
                        case 401:
                            var data = transport.responseJSON;
                            if(data.redirect) {
                                window.location = data.redirect;
                            }
                            break;
                            
                        default:
                            this.createMessage(this.options.get('errorMessage'), 'error');
                            break;
                    }
                }.bind(this)
            });
        }
    },
    
    createMessage: function(text, level) {
        level = level ? level : 'info';
        Contes.updateMessage(text, level);
    }
});

/************************************
 *              List                *
 ************************************/
Contes.List = Class.create({
    defaults: {
        selectors: {
            'list' : 'ms-list',
            'listItem' : 'ms-list-item',
            'listItemAlternate' : 'alternate-row'
        }
    },
    
    initialize: function (element, options) {
        this.el = $(element);
        this.options = $H(this.defaults).merge(options);
        this.selectors = this.options.get('selectors');
        this.build();
        
        document.observe('activity:created', function(e) { this.prepend(e.memo.activity); }.bind(this));
        document.observe('activity:updated', function(e) { this.append(e.memo.activity); }.bind(this));
        document.observe('item:deleted', this.deleteAction.bind(this));
    },
    
    getListItems: function() {
        var itemSelector = '.' + this.selectors.listItem;
        return this.el.select(itemSelector);
    },
    
    build: function() {
        var $i = 0;
        this.getListItems().each(function(element) {
            var listItem = new Contes.ListItem(element);
        }, this);
    },
    
    insert: function(position, item) {
        var div = new Element('div').update(item);
        var that = this;
        div.select('.' + this.selectors.listItem).each(function(element) {
            var listItem = new Contes.ListItem(element);
            listItem.el.hide();
            new Insertion[position](that.el, listItem.el);
            new Effect.Appear(listItem.el, {duration: 0.3});
        });
        
        var A = $(document.body);
        A.select('.ms-list-noitem').each(function(element) {
            element.hide();
        });
        this.el.show();
    },
    
    deleteAction: function(e) {
        var id = e.memo.item;
        var item = $("item_"+id);
        new Effect.Fade(item, {duration: 0.3});
    }
 });
 
Contes.List.prototype.append = Contes.List.prototype.insert.curry('Bottom');
Contes.List.prototype.prepend = Contes.List.prototype.insert.curry('Top');

Contes.ListUpdater = Class.create({
    selectors: {
        'updater' : 'ms-list-updater',
        'noitem' : 'ms-list-updater-noitem'
    },
    
    initialize: function (element) {
        this.el = $(element);
        this.page = 2;
        var A = this.el.down('.' + this.selectors.updater);
        if (A) {
            this.list_updater = A;
            this.list_updater.observe('click', this.update.bind(this));
        }
    },
    
    update: function(e) {
        e.stop();

        var url = this.list_updater.readAttribute('href');
        new Ajax.Request(url, {
            parameters: {'page' : this.page},
            onFailure: this.onUpdateFailure.bind(this),
            onSuccess: this.onUpdateSuccess.bind(this)
        });
    },
    
    onUpdateFailure: function(e) {
        var A = this.el.down('.' + this.selectors.updater);
        var B = this.el.down('.' + this.selectors.noitem);
        
        if (A) {
            this.list_updater = A;
            this.list_updater.hide();
        }
        
        if (B) {
            this.list_updater_noitem = B;
            this.list_updater_noitem.show();
        }
    },
    
    onUpdateSuccess: function(e) {
        this.page++;
        this.el.fire('activity:updated', {activity: e.responseText});
    }
 });
 
 Contes.PaginateUpdater = Class.create({
	initialize: function (div_elt) {
		this.divElt = $(div_elt);
		this.initPaginate();
	},
	
	initPaginate: function() {
		this.paginateElt = this.divElt.down('.pagination');
		if (this.paginateElt) {
			this.paginateElt.observe('click', this.update.bind(this));
		}
	},
	
	update: function(e) {
        e.stop();
		
		this.element = Event.element(e);
        this.url = this.element.readAttribute('href');
		
		if (this.url) {
			new Ajax.Request(this.url, {
				onFailure: this.onUpdateFailure.bind(this),
				onSuccess: this.onUpdateSuccess.bind(this)
			});
		}
    },
    
    onUpdateFailure: function(e) {
        
    },
    
    onUpdateSuccess: function(e) {
		this.divElt.update(e.responseText);
		this.initPaginate();
    }
 });

 Contes.ActivityUpdater = Class.create({
    selectors: {
        'updater' : 'ms-list-updater',
        'noitem' : 'ms-list-updater-noitem'
    },
    
    initialize: function (element) {
        this.el = $(element);
		
        var A = this.el.down('.' + this.selectors.updater);
        if (A) {
            this.list_updater = A;
            this.list_updater.observe('click', this.update.bind(this));
        }
    },
    
    update: function(e) {
        e.stop();
		var lastActivity = $('activity_list').childElements().last();
		var activityDate = lastActivity.readAttribute('activityDate');
		
        var url = this.list_updater.readAttribute('href');
        new Ajax.Request(url, {
            parameters: {'lastDate' : activityDate},
            onFailure: this.onUpdateFailure.bind(this),
            onSuccess: this.onUpdateSuccess.bind(this)
        });
    },
    
    onUpdateFailure: function(e) {
        var A = this.el.down('.' + this.selectors.updater);
        var B = this.el.down('.' + this.selectors.noitem);
        
        if (A) {
            this.list_updater = A;
            this.list_updater.hide();
        }
        
        if (B) {
            this.list_updater_noitem = B;
            this.list_updater_noitem.show();
        }
    },
    
    onUpdateSuccess: function(e) {
        this.el.fire('activity:updated', {activity: e.responseText});
    }
 });
/************************************
 *            List  Item            *
 ************************************/
 Contes.ListItem = Class.create({
    selectors: {
        'btnDelete' : 'ms-list-item-btn-delete',
        'btnEdit' : 'ms-list-item-btn-edit',
        'btnReply' : 'btn-auto-reply',
        'isPrivate' : 'ms-private-item',
        'focus' : 'highlighted'
    },
    
    messages: {
        'confirmDelete' : "Confirmez-vous la suppression ?"
    },
    
    initialize: function(element) {
        this.el = $(element);
        this.el.observe('mouseover', this.onFocusIn.bind(this));
        this.el.observe('mouseout', this.onFocusOut.bind(this));
        var A = this.el.down('.' + this.selectors.btnDelete);
        if (A) {
            this.btnDelete = A;
            this.btnDelete.observe('click', this.deleteAction.bind(this));
        }
        /** reply-to*/
        var B = this.el.down('.' + this.selectors.btnReply);
        var D = this.el.readAttribute('class').match(this.selectors.isPrivate);
        
        if (B) {
            this.btnReply = B;
            this.btnReply.observe('click', function(e) {
                e.stop();
                var C = this.el.readAttribute('class').match(/u-([A-Za-z0-9_\-\.]+)/);
				var privacy = false;
				if(D) {
					privacy = true;
				}
                e.element().fire('activity:reply-to', {'user': C[1], 'privacy': privacy});
            }.bind(this));
        }
    },
    
    onFocusIn: function (e) {
        if (!this.el.hasClassName(this.selectors.focus)) {
            this.el.addClassName(this.selectors.focus)
        }
    },
    
    onFocusOut: function (e) {
        if (this.el.hasClassName(this.selectors.focus)) {
            this.el.removeClassName(this.selectors.focus)
        }
    },
    
    deleteAction: function(e) {
        e.stop();
        if (confirm(this.messages.confirmDelete)) {
            var urlAction = this.btnDelete.getAttribute('href');
            new Ajax.Request(urlAction, {
                onSuccess : this.onDeleteSuccess.bind(this)
            });
        }
    },
    
    onDeleteSuccess: function(e) {
        new Effect.Fade(this.el, {duration: 0.3});
    }
 });

/************************************
 *            Shoutbox              *
 ************************************/
Contes.Shoutbox = Class.create({
    
    messages: {
        hint: 'Exprimez vous !',
        validationError: "Le message est limité à :maxChar caractères"
    },
    
    initialize: function(element) {
        this.el = $(element);
        this.maxChar = 800;
        this.collapsed = true;
        this.animating = false;
        this.initMessageBox();
        this.initSubmitBtn();
        this.initPrivacyCheckbox();
        this.initForm();   
        document.observe('click', function(e){
            if (!e.element().up('#shoutbox')) {
                this.collapse();
            }
        }.bind(this));
        
        document.observe('activity:reply-to', function(e){
            A = e.memo.user;
            this.expand();
            this.privacyCheckbox.checked = false;
            this.messageBox.value = '@' + A + ' ' + this.messageBox.value.replace(RegExp("@" + A + " ?","i"), "");
            if (e.memo.privacy) {
				this.privacyCheckbox.checked = true;
			}
			this.messageBox.focus();
        }.bind(this));
    },
    
    initForm: function () {
        this.form = $('shoutbox_form')
        this.form.observe('submit', this.onSubmit.bind(this));
    },
    
    initMessageBox: function() {
        this.messageBox = this.el.down('#message');
        this.messageBox.observe('focus', this.expand.bind(this));
        if(!this.messageBox.value) {
            this.messageBox.value = this.messages.hint;
            this.messageBox.addClassName('ms-messageBox-inactive');
        }
        //this.messageBox.observe('keydown', this.onKeyDown.bind(this));
        this.messageBox.observe('keyup', this.onKeyUp.bind(this));
        var B = this.messages.validationError.replace(':maxChar', this.maxChar);
        this.messageBox.isNotValid = function() {
            var A = $('message_field');
            if (!A.down('.validation-error')) {
                A.insert(new Element('div', {'class': 'validation-error'}).update(B));   
            }
        }
        this.messageBox.isValid = function() {
            var A = $('message_field');
            if (A.down('.validation-error')) {
                A.down('.validation-error').remove();
            }
        }
    },
    
    initSubmitBtn: function() {
        this.submitBtn = this.el.down('#shoutbox_submit');
        this.submitBtn.hide();
        this.submitBtn.inactivate = function() {
            this.disabled = true;
            this.addClassName('btn-disabled'); 
        }
        this.submitBtn.isEnabled = function() {
            this.disabled = false;
            this.removeClassName('btn-disabled'); 
        }
        this.submitBtn.inactivate();
    },
    
    initPrivacyCheckbox: function() {
        this.privacyCheckboxField = this.el.down('#private_field');
        this.privacyCheckbox = this.el.down('#private');
        this.privacyCheckboxField.hide();
    },
    
    onKeyDown: function(e) {
        switch(e.keyCode) {
            case Event.KEY_UP: 
            case Event.KEY_DOWN:
            case Event.KEY_RIGHT:
            case Event.KEY_LEFT:
            case Event.KEY_TAB:
            case Event.KEY_ENTER:
            case Event.KEY_BACKSPACE:
            case Event.KEY_DELETE:
            case Event.KEY_ESC: 
                break;
            default:
                if(this.messageBox.value.length >= this.maxChar) {
                    e.stop();
                    this.messageBox.isNotValid();
                }
                break;
        }
    },
    
    onKeyUp: function(e) {
        var A = this.messageBox.value.length;
        if(A > 0 && A <= this.maxChar) {
            this.submitBtn.isEnabled();
            this.messageBox.isValid();
        } else {
            this.submitBtn.inactivate();
            if (A) {this.messageBox.isNotValid();}
            else {this.messageBox.isValid();}
        }
    },
    
    onSubmit: function(e) {
        e.stop();
        this.form.request({onSuccess: this.onMessageCreated.bind(this)})
        this.submitBtn.inactivate();
    },
    
    onMessageCreated: function(transport) {
        this.el.fire('activity:created', {activity: transport.responseText});
        this.messageBox.value = this.messages.hint;
        this.messageBox.addClassName('ms-messageBox-inactive');
    },
    
    collapse: function() {
        if(!this.collapsed && !this.animating) {
            this.collapsed = true;
            this.animating = true;
            new Effect.Scale(this.messageBox, 50, {duration: 0.3, scaleX: false, scaleContent: false, afterFinish: this.onMessageCollapsed.bind(this)});
        }
    },
    
    expand: function() {
        if (this.messageBox.value == this.messages.hint) {
            this.messageBox.value = '';
            this.messageBox.removeClassName('ms-messageBox-inactive');
        }
        
        if (this.collapsed && !this.animating) {
            this.collapsed = false;
            this.animating = true;
            new Effect.Scale(this.messageBox, 200, {duration: 0.3, scaleX: false, scaleContent: false, afterFinish: this.onMessageExpanded.bind(this)});
        }
    },
    
    onMessageExpanded: function() {
        this.animating = false;
        this.submitBtn.show();
        this.privacyCheckboxField.show();
    },
    
    onMessageCollapsed: function() {
        this.animating = false;
        this.submitBtn.hide();
        this.privacyCheckboxField.hide();
        if (!this.messageBox.value) {
            this.messageBox.addClassName('ms-messageBox-inactive');
            this.messageBox.value = this.messages.hint;
        }
    }
});
 
/************************************
 *          Starbox                 *
 ************************************/
 Contes.Starbox = Class.create({
    defaults: $H({
        max: 5,
        interval: 16
    }),
 
    initialize: function(element, rating, options) {
        this.el = $(element);
        this.rating = rating;
        this.options = this.defaults.merge(options);
        this.max = this.options.get('max');
        this.interval = this.options.get('interval');
        this.width = this.max * this.interval;
        this.create();
    },
    
    create: function()
    {
        this.el.addClassName('starbox');
        this.el.setStyle({
            position: 'relative',
            top: '0px',
            left: '0px',
            width: this.width + 'px',
            height: this.interval + 'px',
            overflow: 'hidden'
        });
        
        this.colorbar = new Element('div', {'class': 'color-bar'});
        this.colorbar.setStyle({
            position: 'absolute',
            'z-index': 100,
            width: this.width + 'px',
            height: this.interval + 'px',
            top: '0px',
            left: this.colorbarPosition(this.rating) + 'px'
        });
        this.el.insert(this.colorbar);
        
        this.stars = new Element('div', {'class': 'stars'});
        this.stars.setStyle({
            position: 'relative',
            width: this.width + 'px',
            height: this.interval + 'px',
            top: '0px',
            left: '0px',
            overflow: 'hidden'
        });
        
        for (i = 0; i < this.max; i++) {
            var star = new Element('div', {'class': 'star'});
            star.setStyle({
                position: 'absolute',
                'z-index': 101,
                width: this.interval + 'px',
                height: this.interval + 'px',
                top: '0px',
                left: i * this.interval + 'px'
            });
            this.stars.insert(star);
        }
        this.el.insert(this.stars);
    },
    
    colorbarPosition: function (rating) {
        return this.interval * (rating - this.max);
    }
 });
 
/************************************
 *        Navigation Menu           *
 ************************************/
 Contes.Navmenu = Class.create({
    
    initialize: function (element) {
        this.el = $(element);
        this.el.observe('mouseover', this.manage.bind(this));
        this.currentList = null;
    },
    
    manage: function(e) {
        targetEl = e.element();
        if(menuList = targetEl.up('.ms-menu-list')) {
            this.currentList = menuList;
            menuList.addClassName('on');
            menuList.observe('mouseout', this.close.curry(menuList))
        }
    },
    
    close: function(menuList) {
        menuList.removeClassName('on');
    }
    
 });
 
 /************************************
 *             Filters               *
 ************************************/
 Contes.AlbumFilters = Class.create({

    initialize: function (element) {
        this.el = $(element);
		this.advancedFilters = $('list_advanced_filters');
		this.advancedToggleBtn = $('toggle_advanced_filters');
		this.orders = $('list_orders');
		this.categories = $('list_categories');
		
        this.orders.observe('change', function(e) { $('list_options_form').submit(); });
		this.categories.observe('change', function(e) { $('list_options_form').submit(); });
		this.advancedToggleBtn.observe('click', this.toggleFilters.bind(this));
    },
    
	toggleFilters: function (e) {
		this.advancedFilters.toggle();
		//this.advancedToggleBtn.innerHTML = this.advancedFilters.visible ? 'Recherche avancée <<' : 'Recherche avancée >>';
	}
 });
 
 Contes.MemberFilters = Class.create({

    initialize: function (element) {
        this.el = $(element);
		this.orders = $('list_orders');
        this.search_btn = $('search_btn');
		
        this.orders.observe('change', function(e) { $('list_options_form').submit(); });
		this.search_btn.observe('click', function(e) { $('list_options_form').submit(); });
    }
 });
 
 /************************************
 *             Updaters              *
 ************************************/
 Contes.PreviewList = Class.create({
	
	initialize: function(element, url) {
		this.el = $(element);
        this.url = url;
		this.spinner = new Element('div', {'class': 'ms-spinner'});
		this.spinner.hide();
		this.el.update(this.spinner);
		new Effect.Appear(this.spinner);
		
		new Ajax.Request(this.url, {
			
			method: 'get',
			
			onSuccess: function(transport) {
				var div = new Element('div', {'style': 'zoom: 1;'}).update(transport.responseText);
				div.hide();
				new Effect.Appear(div);
				this.el.update(div);
			}.bind(this)
			
		});
	}
	
 });
 
 Contes.PreviewUpdater = Class.create({

    initialize: function (element, url) {
        this.el = $(element);
        this.url = url;
		
		new Ajax.Request(this.url, {
			method: 'get',
			onSuccess: function(transport) {
				var div = new Element('div').update(transport.responseText);
				if (div.select('li').size() > 0) {
					this.el.show();
                    div.hide();
                    this.el.insert(div);
                    new Effect.Appear(div);
				}
			}.bind(this)
		});
    }
 });
 
Contes.iframeSwitch = function (element) {
    //find flash content container and grab contents
    //(should only be object and embed tags)
    var container = $(element);
    var c = container.innerHTML;

    //get the size from the object element
    var object = container.down('embed');
    var d = object.getDimensions();
    var x = d.width;
    var y = d.height;

    //create the iframe element, hidden for now
    var frame = new Element('iframe', {
        id:'swf_content_frame',
        frameborder:'0',
        marginwidth:'0',
        marginheight:'0',
        scrolling:'no',
        style: 'display: block; z-index: 1; width: ' + x + 'px; height: ' + y + 'px;'
    });

    //attach the iframe to the document and remove the
    //old flash container element
    container.insert({'after': frame});
    container.remove();

    //set the size, open the iframe, and insert
    //the flash content.
    frame.contentDocument.open();
    frame.contentDocument.write(c);
    frame.contentDocument.close();
};

Element.addMethods('button', {
    activate: function (element) {
        element = $(element);
        element.disabled = false;
        element.removeClassName('btn-disabled');
    },
    inactivate: function(element) {
        element = $(element);
        element.disabled = true;
        element.addClassName('btn-disabled');
    }
});

/************************************
 *	          MessageBox            *
 ************************************/
Contes.updateMessage = function(msg, level) {
	var lvl = level || 'info';
	$(document.body).fire('message:update', {'message': msg, 'level': lvl});
 };
 
Contes.MessageBox = Class.create({

	initialize: function(element) {
		this.box = $(element);
		this.content = this.box.down('.ms-box-message-content');
		this.displayed = false;
		this.animating = false;
		document.observe('message:update', function(e) {
			if (e.memo.message) {
				var level = e.memo.level || 'info';
				this.update(e.memo.message, level);
			}
		}.bind(this));
	},
	
	show: function() {
		if (!this.displayed) {
			this.animating = true;
			Effect.SlideDown(this.box, { duration: 0.5, afterFinish: this.onEffectEnd.bind(this), queue: 'end'});
		}
	},
	
	hide: function() {
		if (this.displayed) {
			if (this.autoclose) {
				this.autoclose.stop();
			}
			this.animating = true;
			Effect.SlideUp(this.box, { duration: 0.5, afterFinish: this.onEffectEnd.bind(this), queue: 'end'});
		}
	},
	
	onEffectEnd: function() {
		this.animating = false;
		this.displayed = !this.displayed;
	},
	
	update: function(message, level){
		this.content.update(message);
		if (level) {
			this.content.className = 'ms-box-message-content';
			this.content.addClassName('ms-message-' + level);
			this.content.insert({'top': new Element('span', {'class' : 'ms-message-icon ms-icon-mini ms-icon-' + level})});
		}
		if (!this.displayed && !this.animating) { this.show(); }
		if (this.autoclose) { this.autoclose.stop(); }
		this.autoclose = new PeriodicalExecuter(this.hide.bind(this), 3);
	}
 });

/************************************
 *	          TextEditor           *
************************************/
Contes.Editor = Class.create({
	initialize: function () {
		var LinkSelectionHelper = {
			promptLinkSelection: function() {
				if (this.linkSelected()) {
				if (confirm("Retirer le lien?"))
					this.unlinkSelection();
				} else {
					var value = prompt("Entrer une URL", "http://");
					if (value)
						this.linkSelection(value);
				}
			}
		}
		
		WysiHat.Editor.include(LinkSelectionHelper);
		
		document.observe('dom:loaded', function() {
			var editor = WysiHat.Editor.attach('body');
			var toolbar = new WysiHat.Toolbar(editor);
			
			toolbar.addButtonSet(WysiHat.Toolbar.ButtonSets.Basic);
			
			// toolbar.addButton({name:'strikethrough', label: 's'});
			
			// toolbar.addButton({name:'insertunorderedlist', label: 'ul'});
			// toolbar.addButton({name:'insertorderedlist', label: 'ol'});
			
			// toolbar.addButton({name:'justifyleft', label: 'left'});
			// toolbar.addButton({name:'justifyright', label: 'right'});
			// toolbar.addButton({name:'justifycenter', label: 'center'});
			// toolbar.addButton({name:'justifyfull', label: 'justify'});
			
			// toolbar.addButton({name:'increasefontsize', label: 'A'});
			// toolbar.addButton({name:'decreasefontsize', label: 'a'});
			
			// toolbar.addButton({name:'indent', label: '=>'});
			// toolbar.addButton({name:'outdent', label: '<='});
			
			toolbar.addButton({
				label: "Lien",
				handler: function(editor) { return editor.promptLinkSelection(); }
			});
			
			toolbar.addButton({
				label: "Image",
				handler: function(editor) {
					var value = prompt("Entrer une URL", "http://");
					if (value) {
						// if (Prototype.Browser.IE && document.selection) {
							// theSelection = document.selection;
							// theRange = theSelection.createRange();
							// theRange.collapse(false);
							// theRange.pasteHTML("<img src=\"" + value + "\" />");
						// } else {
							document.getElementById("body_editor").focus();
							editor.insertImage(value);
						// }
					}
				}
			});
			
			document.observe('form:submit', function(e){
				editor.save();
			});
		});
    }
});

/************************************
*	           Slideshow            *
 ************************************/
Contes.Slideshow = Class.create({
	
	defaults: {
		'autoplay': 5
	},
	
	selectors: {
		'viewer'  : 'ms-slideshow-viewer',
		'menu'    : 'ms-slideshow-menu',
		'toggle'  : 'ms-slideshow-toggle',
		'active'  : 'ms-slideshow-toggle-active',
		'content' : 'ms-slideshow-content',
		'selector' : 'ms-slideshow-selector'
	},
	
	initialize: function(element) {
		this.el = $(element);
		this.play = true;
		var that = this;
		this.el.observe('mouseenter', function(e){ that.play = false;});
		this.el.observe('mouseleave', function(e){ that.play = true;});
		this.toggleHeight = Math.round(this.el.getHeight() / this.el.select('.' + this.selectors.toggle).length);
		
		new PeriodicalExecuter(this.autoplay.bind(this), this.defaults.autoplay);
		
		this.viewer = this.el.down('.' + this.selectors.viewer);
		this.selector = this.el.down('.' + this.selectors.selector);
		
		this.currentSlide = false;
		
		this.el.select('.' + this.selectors.toggle).each(function(item){
			item.observe('mouseenter', function(e) {this.activate(item)}.bind(this));
		}, this);
		
		this.activate(this.el.down('.' + this.selectors.toggle));
	},
	
	autoplay: function(){
		if(!this.play) return false;
		
		if(!this.currentToggle) {
			var nextToggle = this.el.down('.' + this.selectors.toggle);
		} else {
			var nextToggle = this.currentToggle.next('.' + this.selectors.toggle);
			if(!nextToggle) {
				var nextToggle = this.el.down('.' + this.selectors.toggle);
			}
		}
		
		this.activate(nextToggle);
	},
	
	activate: function(toggleEl) {
		
		var effects = [];
		var options = {duration: 0.1, sync: true};
		
		if(this.currentToggle) {
			this.currentToggle.removeClassName(this.selectors.active);
		}
		var targetSlide = toggleEl.down('.' + this.selectors.content);
		var id = targetSlide.id.match(/slide_([0-9]+)/)[1];
		
		this.currentToggle = toggleEl;
		this.currentToggle.addClassName(this.selectors.active);	
		
		if  (Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6) {   
		//Cette ligne évite le décalage du pointeur du slideshow de 3px sous IE6
		this.selector.setStyle({'top': (id-1)*(this.toggleHeight-3) + 'px'});
		}
		else {
		this.selector.setStyle({'top': (id-1)*this.toggleHeight + 'px'});
		}
		this.selector.show();
		
		if(this.currentSlide) {
			this.oldSlide = this.currentSlide;
			effects.push(
				new Effect.Fade(this.oldSlide, options)
			);
		}
		
		this.currentSlide = new Element('div', {'style' : 'display: none; position: absolute;'});
		this.currentSlide.update(targetSlide.innerHTML);
		
		effects.push(
			new Effect.Appear(this.currentSlide, options)
		);
		this.viewer.insert(this.currentSlide);
		new Effect.Parallel(effects, {afterFinish: function(e){ 
			if(this.oldSlide) {
				this.oldSlide.remove();
			}
		}.bind(this)});
	}
 });

Contes.ConfirmAction = function(element, message) {
	var el = $(element);
	
	if (el) {
		el.observe('click', function (e) {
			if (!confirm(message)) {
				e.stop();
			}
		});
	}
};

/*************************************
*	     Close Iframe Link           *
 *************************************/
Contes.closeIframeLink =  function (url) {
	var links = $('page_content').getElementsBySelector('a');
	links.each(function(item){
		var urlReplace = url + "?redirect="+encodeURI(item.readAttribute('href'));
		item.writeAttribute('href',urlReplace);	
	   }	
	);
  }


/*************************************
*	     		 Selection           *
 *************************************/

Contes.Selection = Class.create({
	
	//define all the div'ids used in the function
	selectors: {
	'mainImage'  	   : 'selection_image',
	'selectionText'    : 'selection_text',
	'selectionList'    : 'selection_list',
	'descriptionAlbum' : 'description_album'
	},
	
	initialize: function(element) {
		this.el = $(element);
		
		this.mainImage = $('selection_image').getElementsBySelector('img').first();
		this.albumDescription = $('description_album');
		
		//We get the default selection parameters
		this.defaultSelectionImageUrl = this.mainImage.readAttribute('src');
		this.defaultSelectionDescription = $(this.selectors.selectionText).getElementsBySelector('div').first().innerHTML;
		
		this.selectionElementList = $(this.selectors.selectionList).select('.album-preview-item');
		this.mainImage.writeAttribute('src',this.defaultSelectionImageUrl);
		this.albumDescription.innerHTML = this.defaultSelectionDescription;
		
		this.selectionElementList.each(function(item){item.observe('mouseover', this.switchAlbumView.bind(this))}, this);
		//$('selection_list').observe('mouseout', this.switchDefaultAlbumView.bind(this));
	},
	
	switchAlbumView : function(e) {
		this.currentItemAlbum = e.element().up('.album-preview-item');
		if (!this.currentItemAlbum) this.currentItemAlbum = this.selectionElementList.first();
		var C = this.currentItemAlbum.readAttribute('class').match(/a-([0-9]+)/);
		albumId = C[1];
		var D = this.currentItemAlbum.readAttribute('name').match(/b-([0-9]+)/);
		imageId = D[1];
		imageLink = this.mainImage.readAttribute('src');
		positionLastSlash=imageLink.lastIndexOf('/');
		newLink=imageLink.truncate(positionLastSlash,'')+"/"+albumId+"-"+imageId+"-large.jpg";
		//we switch the picture
		this.mainImage.writeAttribute('src',newLink);	
		$('description_album').innerHTML = $('description_album_'+albumId).innerHTML;
		document.observe('mousemove', this.switchDefaultAlbumView.bind(this));
	},
	
	switchDefaultAlbumView : function(e) {
		if (!e.element().up('#selection_list')){
		document.stopObserving('mousemove');
		//Par défaut on affiche la couverture de l'album 1
		this.mainImage.writeAttribute('src',this.defaultSelectionImageUrl);
		this.albumDescription.innerHTML = this.defaultSelectionDescription;
		this.switchedDefault = true;
		}
	}
});



Contes.Didactitiel = Class.create({
	
	initialize: function(element) {
	this.el = $(element);
	this.picturesDidactitiel = $(element).immediateDescendants();
	this.picturesDidactitiel.each(function(item){
		item.observe('mouseout',function(e){
				var newClass = e.element().readAttribute('class').sub("-hover","");
				e.element().writeAttribute('class',newClass);
			}.bind(this));
		item.observe('mouseover',function(e){
			if (!e.element().readAttribute('class').endsWith('hover')){
				e.element().writeAttribute('class',e.element().readAttribute('class') + "-hover");
			}			
			}.bind(this));
	   }.bind(this) );
	  
	}
	
});

Contes.DidactitielShow = Class.create({
	
	constant: {
	'vitesse'  	   : 1,
	'authorPosition' : 0,
	'readerPosition' : -920,
	'criticPosition' : -1840
	},
	
	initialize: function(element) {
	this.el = $(element);
		var anchor = window.location.hash.substring(1,window.location.hash.length);
		if (anchor){
			switch (anchor) {
			case 'author':
				$('didacticiel_content').setStyle({left : this.constant.authorPosition + "px"});
				$('author_button').setStyle({color : '#AFD520'});
			break;
			case 'critic':
				$('didacticiel_content').setStyle({left : this.constant.criticPosition + "px"});
				$('critic_button').setStyle({color : '#AFD520'});
			break;
			case 'reader':
				$('didacticiel_content').setStyle({left : this.constant.readerPosition + "px"});
				$('reader_button').setStyle({color : '#AFD520'});
			break;
			}
		}
		else
		{
			$('didacticiel_content').setStyle({left : this.constant.readerPosition + "px"});
			$('reader_button').setStyle({color : '#AFD520'});
		}
		$('author_button').observe('click',this.moveTo.bind(this));		
		$('reader_button').observe('click',this.moveTo.bind(this));
		$('critic_button').observe('click',this.moveTo.bind(this));	
	},
	
	moveTo : function(e) {
		switch (e.element().readAttribute('id')) {
				case 'author_button' :
					this.positionToGo = this.constant.authorPosition;
				break;
				case 'reader_button' :
					this.positionToGo = this.constant.readerPosition;
				break;
				case 'critic_button' :
					this.positionToGo = this.constant.criticPosition;
				break;	
			}
		new Effect.Move('didacticiel_content', { x: this.positionToGo, y: 0, mode: 'absolute',beforeStart: this.colorButton.bind(this)});
	},
	
	colorButton : function(e) {
		
		$('critic_button').setStyle({color : 'white'});
		$('reader_button').setStyle({color : 'white'});
		$('author_button').setStyle({color : 'white'});
		
		switch (this.positionToGo){
			case this.constant.authorPosition :
				$('author_button').setStyle({color : '#AFD520'});
			break;
				
			case this.constant.readerPosition :
				$('reader_button').setStyle({color : '#AFD520'});
			break;
				
			case this.constant.criticPosition :
				$('critic_button').setStyle({color : '#AFD520'});
			break;	
		}
	}
});








