﻿/// <reference path="protoaculous.1.8.1.min.js" />

function check(name) {
    var _name = name.toString().split('_')[2];
    var input = $$('.' + _name)[0];

    Element.removeClassName(input, 'ok');
    Element.removeClassName(input, 'error');
    Element.addClassName(input, 'working');

    input.title = 'Vérification...';
}

function checkresult(result)
{
    var name = result.toString().split(' ')[0];
    var result = result.toString().split(' ')[1];
    var _name = name.toString().split('_')[2];
    var input = $$('.' + _name)[0];

    Element.removeClassName(input, 'working');

    var m_invalid;
    var m_used;
    var m_valid;

    switch (_name) {
        case 'username':
            m_invalid = 'Ce nom d\'utilisateur est invalide';
            m_used = 'Ce nom d\'utilisateur est déjà utilisé par un autre compte';
            m_valid = 'Ce nom d\'utilisateur est disponible';
            break;
        case 'email':
            m_invalid = 'Cette adresse email est invalide';
            m_used = 'Cette adresse email est déjà utilisée pour un autre compte';
            m_valid = 'Cette adresse email est valide';
            break;
    }

    switch (result)
    {
        case "-1":
            Element.removeClassName(input, 'ok');
            Element.addClassName(input, 'error');
            input.title = m_invalid;
            break;
        case "0":
            Element.removeClassName(input, 'ok');
            Element.addClassName(input, 'error');
            input.title = 'pas ok';
            input.title = m_used;
            break;
        case "1":
            Element.removeClassName(input, 'error');
            Element.addClassName(input, 'ok');
            input.title = m_valid;
            break;
    }
}

function addModuleHandles()
{
    $A($$('.cote .module h1, .cote .module h2')).each(function(e) { 
        var p= e.parentNode;
    
        if (p.id!=null && p.id!='')
        {
            var i = new Element('img', { 'class':'handle' });
           
            i.onclick = function() { toggleModuleHandle(this); };
            i.src = '/images/icons/empty.gif';
                        
            if (p.hasClassName('onlytitle')) {
                i.className = 'sprite-icon sprite-bullet_arrow_down handle';
                if (p.id.substr(p.id.length-2,2)!='ot') { p.id = p.id + 'ot'; }
            } else {
                i.className = 'sprite-icon sprite-bullet_arrow_up handle';
            }
            
            e.appendChild(i);
        }   
    });
}

function toggleModuleHandle(e)
{
    if (e.className.indexOf('bullet_arrow_up',0)>0) { e.className = 'sprite-icon sprite-bullet_arrow_down handle'; }
    else if (e.className.indexOf('bullet_arrow_down',0)>0) { e.className = 'sprite-icon sprite-bullet_arrow_up handle'; }
    
    var parent = e.parentNode.parentNode;

    if (parent.hasClassName('onlytitle')) {
        parent.removeClassName('onlytitle');
        
        if (parent.id.substr(parent.id.length-2,2)=='ot')
            parent.id = parent.id.substr(0,parent.id.length-2);
    } else {
        parent.addClassName('onlytitle');
        
        if (parent.id.substr(parent.id.length-2,2)!='ot')
            parent.id = parent.id + 'ot';
    }
    
    setDroppable();
    UpdateMinorityBoard();
}

function CreateFriends() {
    Sortable.create("friends", { dropOnEmpty: true, containment: ["friends"], constraint: false, onUpdate: UpdateFriends, handle: 'friendhandler' });
}

function setDroppable()
{
    Sortable.create('colgauche',{tag:'div',dropOnEmpty:true,containment:["colgauche","coldroite"],handle:'title',constraint:false,hoverclass:'hover',onChange:checkEmpty,onUpdate:UpdateMinorityBoard});
    Sortable.create('coldroite',{tag:'div',dropOnEmpty:true,containment:["coldroite","colgauche"],handle:'title',constraint:false,hoverclass:'hover',onChange:checkEmpty,onUpdate:UpdateMinorityBoard});

    checkEmpty();
}

function checkEmpty()
{
    if ($('colgauche').hasClassName('empty') && $$('#colgauche div').size()>0) {
        $('colgauche').removeClassName('empty');
        $('centre').removeClassName('fillleft');
    } else if ($$('#colgauche div').size()==0) {
        $('colgauche').addClassName('empty');
        $('centre').addClassName('fillleft');
    }
   
    if ($('coldroite').hasClassName('empty') && $$('#coldroite div').size()>0) {
        $('coldroite').removeClassName('empty');
        $('centre').removeClassName('fillright');
    } else if ($$('#coldroite div').size()==0) {
        $('coldroite').addClassName('empty');
        $('centre').addClassName('fillright');
    }
}

function changeTheme(color) {
    new Ajax.Request('/Async.ashx?action=update&what=theme&where=local&value=' + color + '&t=' + Math.random(), { method: 'post' });
    $('currstyle').href = '/css/' + color + '.css';
}

var ajaxTabs = {
    loadIn: function (url, id) {
        new Ajax.Updater(id, url, { method: 'get' });
    },
    active: function (tab, css, url, id) {
        $$(css).each(function (item) { $(item).removeClassName('active'); });
        $(tab).addClassName('active');
        $(id).update('Chargement');
        ajaxTabs.loadIn(url, id);
        return false;
    }
}

// Wollyhood Async System
//
// Rights verifications are perform on server side ;)

// Wollyhood Async Messaging System

var Messaging = {
    removeMessage: function(id) {
        var m = $(id);
        var ms = null;

        if (m.nextSiblings()[0] != null) { if (m.nextSiblings()[0].hasClassName('messageseparator')) { ms = m.nextSiblings()[0]; }; }

        new Effect.Fade(m, { afterFinish: function() {
            if (m != null) { m.remove(); }
            if (ms != null) { ms.remove(); }

            switch (CurrentType) {
                case 'received':
                    Messaging.refreshReceivedMessages(null);
                    Messaging.refreshReceivedPager(null);
                    break;
                case 'saved':
                    Messaging.refreshSavedMessages(null);
                    Messaging.refreshSavedPager(null);
                    break;
                case 'sent':
                    Messaging.refreshSentMessages(null);
                    Messaging.refreshSentPager(null);
                    break;
            }
        }
        });
    },
    createMessage: function(What, Options) {
        var tpl;

        switch (Options.MessageImage) {
            case "mail_send":
                Options.MessageAlt = "Nouveau";
                break;
            case "mail_down":
                Options.MessageAlt = "Répondu";
                break;
            default:
                Options.MessageAlt = "Message";
                break;
        }

        switch (What) {
            case 'received':
                tpl = new Template('<div id="msg_#{MessageId}" class="message"><img src="/images/icons/empty.gif" id="imessage_#{MessageId}" class="sprite-icon sprite-#{MessageImage}" alt="#{MessageAlt}" title="#{MessageAlt}" /> Message de&nbsp;<a href="/minorityreport/#{FromUserId}/default.aspx">#{FromUserName}</a> reçu il y a #{ReceivedSince} <a href="/minorityboard/answer/#{FromUserId}/#{MessageId}/default.aspx" id="answer_#{MessageId}" title="Répondre"><img src="/images/icons/empty.gif" class="sprite-icon sprite-mail_write" alt="Répondre" title="Répondre" /></a> <img src="/images/icons/empty.gif" id="save_#{MessageId}" class="sprite-icon sprite-mail_add" style="cursor:pointer;" alt="Enregistrer" title="Enregistrer" onclick="WebForm_DoCallback(\'ctl00\',\'r_msg_save #{MessageId}\',Messaging.removeMessage(\'msg_#{MessageId}\'),null,null,false)" /> <img src="/images/icons/empty.gif" id="delete_#{MessageId}" class="sprite-icon sprite-mail_exclude" style="cursor:pointer;" alt="Supprimer" title="Supprimer" onclick="WebForm_DoCallback(\'ctl00\',\'r_msg_delete #{MessageId}\',Messaging.removeMessage(\'msg_#{MessageId}\'),null,null,false)" /><br /><br /><div id="msg_text_#{MessageId}" class="#{MessageType}">#{MessageText}</div></div>');
                break;
            case 'saved':
                tpl = new Template('<div id="msg_#{MessageId}" class="message"><img src="/images/icons/empty.gif" id="imessage_#{MessageId}" class="sprite-icon sprite-#{MessageImage}" alt="#{MessageAlt}" title="#{MessageAlt}" /> Message de&nbsp;<a href="/minorityreport/#{FromUserId}/default.aspx">#{FromUserName}</a> reçu il y a #{ReceivedSince} <a href="/minorityboard/answer/#{FromUserId}/#{MessageId}/default.aspx" id="answer_#{MessageId}" title="Répondre"><img src="/images/icons/empty.gif" class="sprite-icon sprite-mail_write" alt="Répondre" title="Répondre" /></a> <img src="/images/icons/empty.gif" id="delete_#{MessageId}" class="sprite-icon sprite-mail_exclude" style="cursor:pointer;" alt="Supprimer" title="Supprimer" onclick="WebForm_DoCallback(\'ctl00\',\'r_msg_delete #{MessageId}\',Messaging.removeMessage(\'msg_#{MessageId}\'),null,null,false)" /><br /><br /><div id="msg_text_#{MessageId}" class="#{MessageType}">#{MessageText}</div></div>');
                break;
            case 'sent':
                tpl = new Template('<div id="msg_#{MessageId}" class="message"><img src="/images/icons/empty.gif" id="imessage_#{MessageId}" class="sprite-icon sprite-#{MessageImage}" alt="#{MessageAlt}" title="#{MessageAlt}" /> Message pour&nbsp;<a href="/minorityreport/#{ToUserId}/default.aspx">#{ToUserName}</a> envoyé il y a #{SentSince} <img src="/images/icons/empty.gif" id="delete_#{MessageId}" class="sprite-icon sprite-mail_exclude" style="cursor:pointer;" alt="Supprimer" title="Supprimer" onclick="WebForm_DoCallback(\'ctl00\',\'s_msg_delete #{MessageId}\',Messaging.removeMessage(\'msg_#{MessageId}\'),null,null,false)" /><br /><br /><div id="msg_text_#{MessageId}" class="#{MessageType}">#{MessageText}</div></div>');
                break;
        }
        return tpl.evaluate(Options);
    },
    refreshMessages: function(What, Page) {
        if (Page == null) Page = CurrentPage;

        new Ajax.Request('/Async.ashx?action=get&what=' + What + 'messages&where=local&value=' + Page + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) {
            var msgs = transport.responseText.evalJSON(true);
            var dmsgs = $('msgs');

            if (msgs.size() == 0) {
                dmsgs.innerHTML = '<span style=\"color:gray;\">Vous n\'avez aucun message</span>';
                dmsgs.removeClassName('module');
            } else {
                dmsgs.addClassName('module');
                dmsgs.innerHTML = '';
                msgs.each(function(msg) { dmsgs.innerHTML = dmsgs.innerHTML + '<div class="messageseparator par15"><hr /></div>' + Messaging.createMessage(What, msg); });
                if ($$('#msgs .messageseparator')[0] != null) $$('#msgs .messageseparator')[0].remove();
            }
        }
        });
    },
    refreshPager: function(What, Page) {
        if (Page == null) Page = CurrentPage;
        new Ajax.Request('/Async.ashx?action=get&what=' + What + 'pager&where=local&value=' + Page + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) { $('msgs_pager').innerHTML = transport.responseText; } });
    },
    refreshReceivedMessagesCount: function() {
        new Ajax.Request('/Async.ashx?action=get&what=receivedmessages&where=local&value=count&t=' + Math.random(), { method: 'post', onSuccess: function(transport) {
            $('messages_count').innerHTML = transport.responseText;
        }
        });
    },
    refreshReceivedMessages: function(Page) { this.refreshMessages('received', Page); this.refreshReceivedMessagesCount(); },
    refreshReceivedPager: function(Page) { this.refreshPager('received', Page); },
    refreshSavedMessages: function(Page) { this.refreshMessages('saved', Page); },
    refreshSavedPager: function(Page) { this.refreshPager('saved', Page); },
    refreshSentMessages: function(Page) { this.refreshMessages('sent', Page); },
    refreshSentPager: function(Page) { this.refreshPager('sent', Page); }
}

// Wollyhood Async Articles System

var Articles = {
    editable: function(Content,ArticleId,aEdit,controls) {
    new Ajax.WhInPlaceEditor($(Content), '/Async.ashx?action=update&what=article&where=' + ArticleId, { externalControl: $(aEdit), controlsLocation: $(controls), cancelText: 'Annuler', okText: 'Valider', savingText: 'Enregistrement en cours...', externalControlOnly: true, okControl: 'link', loadTextURL: '/Async.ashx?action=get&what=unformatedarticle&where=' + ArticleId, mceCall: createEditor, ajaxOptions: { method: 'post'} })
    }
}

// Wollyhood Async History System

var History = {
    remove: function(guid, item) {
        if (confirm('Êtes-vous certain de vouloir supprimer cet événement ?')) {

            new Ajax.Request('/Async.ashx?action=delete&what=history&where=' + guid + '&t=' + Math.random(), { method: 'post' });

            var i = $(item);

            if (i != null) {
                i.parentNode.parentNode.remove();
            }
        }
    },
    mouseOver: function(item) {
        if (item)
            $(item).parentNode.parentNode.addClassName('hightlight');
    },
    mouseOut: function(item) {
        if (item)
            $(item).parentNode.parentNode.removeClassName('hightlight');
    }
}

// Wollyhood Async Comment System

var Comment = {
    Articles: {
        editable: function(Comment, fromUserId, ArticleId, commentNum, aEdit, controls, cancel) {
            if ($(aEdit)) {
		new Ajax.WhInPlaceEditor($(Comment), '/Async.ashx?action=update&what=comment&where=a,' + fromUserId + ',' + ArticleId + ',' + commentNum, { externalControl: $(aEdit), secondCancelControl: cancel, controlsLocation: $(controls), cancelText: 'Annuler', okText: 'Valider', savingText: 'Enregistrement en cours...', externalControlOnly: true, controlsLocationBefore: true, okControl: 'link', loadTextURL: '/Async.ashx?action=get&what=unformatedarticlecomment&where=' + ArticleId + ',' + fromUserId + ',' + commentNum, ajaxOptions: { method: 'post'} })
            }
	},

        stupid: function(dComment, fromUserId, ArticleId, commentNum) {
            if (confirm("Êtes-vous certain de vouloir supprimer ce commentaire ?")) {
                new Ajax.Request('/Async.ashx?action=stupid&what=comment&where=a,' + fromUserId + ',' + ArticleId + ',' + commentNum, { method: 'post' });

                $(dComment).className = 'bubble bubble-moderate';
                $$('#' + dComment + ' .controls').first().remove();
                $$('#' + dComment + ' blockquote').first().update('<p>Commentaire supprimé par un modérateur</p>');
                return true;
            }
            return false;
        }
    },
    Movies: {
        editable: function(Comment, fromUserId, MovieId, commentNum, aEdit, controls, cancel) {
	    if ($(aEdit)) {
            	new Ajax.WhInPlaceEditor($(Comment), '/Async.ashx?action=update&what=comment&where=m,' + fromUserId + ',' + MovieId + ',' + commentNum, { externalControl: $(aEdit), secondCancelControl: cancel, controlsLocation: $(controls), cancelText: 'Annuler', okText: 'Valider', savingText: 'Enregistrement en cours...', externalControlOnly: true, controlsLocationBefore: true, okControl: 'link', loadTextURL: '/Async.ashx?action=get&what=unformatedmoviecomment&where=' + MovieId + ',' + fromUserId + ',' + commentNum, ajaxOptions: { method: 'post'} })
       	    }
	},

        stupid: function(dComment, fromUserId, MovieId, commentNum) {
            if (confirm("Êtes-vous certain de vouloir supprimer ce commentaire ?")) {
                new Ajax.Request('/Async.ashx?action=stupid&what=comment&where=m,' + fromUserId + ',' + MovieId + ',' + commentNum, { method: 'post' });

                $(dComment).className = 'bubble bubble-moderate';
                $$('#' + dComment + ' .controls').first().remove();
                $$('#' + dComment + ' blockquote').first().update('<p>Commentaire supprimé par un modérateur</p>');
                return true;
            }
            return false;
        },
        positive: function(lVote, fromUserId, MovieId, commentNum) {
            new Ajax.Request('/Async.ashx?action=positive&what=comment&where=m,' + fromUserId + ',' + MovieId + ',' + commentNum + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) {
                $(lVote).innerHTML = transport.responseText;
            }
            });
        },
        negative: function(lVote, fromUserId, MovieId, commentNum) {
            new Ajax.Request('/Async.ashx?action=negative&what=comment&where=m,' + fromUserId + ',' + MovieId + ',' + commentNum + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) {
                $(lVote).innerHTML = transport.responseText;
            }
            });
        }
    },
    Sagas: {
        editable: function(Comment, fromUserId, SagaId, commentNum, aEdit, controls, cancel) {
            if ($(aEdit)) {
		new Ajax.WhInPlaceEditor($(Comment), '/Async.ashx?action=update&what=comment&where=s,' + fromUserId + ',' + SagaId + ',' + commentNum, { externalControl: $(aEdit), secondCancelControl: cancel, controlsLocation: $(controls), cancelText: 'Annuler', okText: 'Valider', savingText: 'Enregistrement en cours...', externalControlOnly: true, controlsLocationBefore: true, okControl: 'link', loadTextURL: '/Async.ashx?action=get&what=unformatedsagacomment&where=' + SagaId + ',' + fromUserId + ',' + commentNum, ajaxOptions: { method: 'post'} })
            }
	},

        stupid: function(dComment, fromUserId, SagaId, commentNum) {
            if (confirm("Êtes-vous certain de vouloir supprimer ce commentaire ?")) {
                new Ajax.Request('/Async.ashx?action=stupid&what=comment&where=s,' + fromUserId + ',' + SagaId + ',' + commentNum, { method: 'post' });

                $(dComment).className = 'bubble bubble-moderate';
                $$('#' + dComment + ' .controls').first().remove();
                $$('#' + dComment + ' blockquote').first().update('<p>Commentaire supprimé par un modérateur</p>');
                return true;
            }
            return false;
        }
    },
    Users: {
        editable: function(Comment, fromUserId, toUserId, commentNum, aEdit, nBefore, controls, cancel) {
            if ($(aEdit)) {
		new Ajax.WhInPlaceEditor($(Comment), '/Async.ashx?action=update&what=comment&where=u,' + fromUserId + ',' + toUserId + ',' + commentNum, { externalControl: $(aEdit), secondCancelControl: cancel, controlsLocation: $(controls), cancelText: 'Annuler', okText: 'Valider', savingText: 'Enregistrement en cours...', externalControlOnly: true, controlsLocationBefore: true, okControl: 'link', loadTextURL: '/Async.ashx?action=get&what=unformatedusercomment&where=' + toUserId + ',' + fromUserId + ',' + commentNum, ajaxOptions: { method: 'post'} })
            }
	},

        publish: function(dComment, fromUserId, toUserId, commentNum) {
            new Ajax.Request('/Async.ashx?action=accept&what=comment&where=u,' + fromUserId + ',' + toUserId + ',' + commentNum, { method: 'post' });

            $(dComment).className = 'bubble';
            $$('#' + dComment + ' .controls').first().remove();
        },
        refuse: function(dComment, fromUserId, toUserId, commentNum) {
            if (confirm("Êtes-vous certain de vouloir refuser ce commentaire ?")) {
                new Ajax.Request('/Async.ashx?action=refuse&what=comment&where=u,' + fromUserId + ',' + toUserId + ',' + commentNum, { method: 'post' });

                new Effect.Fade($(dComment), { afterFinish: function() { $(dComment).remove(); } });
            }
        },
        stupid: function(dComment, fromUserId, toUserId, commentNum) {
            if (confirm("Êtes-vous certain de vouloir supprimer ce commentaire ?")) {
                new Ajax.Request('/Async.ashx?action=stupid&what=comment&where=u,' + fromUserId + ',' + toUserId + ',' + commentNum, { method: 'post' });

                $(dComment).className = 'bubble bubble-moderate';
                $$('#' + dComment + ' .controls').first().remove();
                $$('#' + dComment + ' blockquote').first().update('<p>Commentaire supprimé par un modérateur</p>');
                return true;
            }
            return false;
        }
    }
};

// Wollyhood Async Movie handler
var Movie = {
    add: function(MovieId) {
        new Ajax.Request('/Async.ashx?action=add&what=movie&where=' + MovieId, { method: 'post' });
    },
    setrate: function(rate) {
        setTimeout(function() {
            if ($('movie_rate') != null) {
                var rate = new Ajax.Request('/Async.ashx?action=rate&what=movie&where=' + currentMovieId + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) {
                    var movie_rate = new Control.Rating('movie_rate', { value: transport.responseText, rated: true });
                }
                });
            }
            if ($('movie_rate_count') != null) {
                var rateCount = new Ajax.Request('/Async.ashx?action=rate&what=movie&where=' + currentMovieId + '&value=count&t=' + Math.random(), { method: 'post', onSuccess: function(transport) {
                    $('movie_rate_count').update(transport.responseText);
                }
                });
            }
        }, 1250);
    },
    createSeasonSeen: function(MovieId, SeasonId) {
        var cMovie = $('movie_' + MovieId + '_' + SeasonId);

        cMovie.observe('click', function() {
            if (!cMovie.checked) {
                new Ajax.Request('/Async.ashx?action=add&what=movie&where=unseenseason&value=' + MovieId + '_' + SeasonId + '&t=' + Math.random(), { method: 'post' });
            } else {
                new Ajax.Request('/Async.ashx?action=add&what=movie&where=seenseason&value=' + MovieId + '_' + SeasonId + '&t=' + Math.random(), { method: 'post' });
            }
        });
    },
    createSeen: function(MovieId) {
        var uMovie = $('movie_' + MovieId + '_seenby');
        var dMovie = uMovie.parentNode.parentNode;
        var aMovie = $('movie_' + MovieId + '_actions');
        var aMovieSeen = $('movie_' + MovieId + '_actions_seen');
        var aMovieWish = $('movie_' + MovieId + '_actions_wish');

        aMovie.hide();

        aMovieSeen.observe('click', function() {
            dMovie.stopObserving('mouseover');
            dMovie.stopObserving('mouseout');

            new Ajax.Request('/Async.ashx?action=add&what=movie&where=seen&value=' + MovieId + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) { uMovie.innerHTML = transport.responseText; } });
            aMovie.remove();
        });

        if (aMovieWish != null) {
            aMovieWish.observe('click', function() {
                new Ajax.Request('/Async.ashx?action=add&what=movie&where=wish&value=' + MovieId + '&t=' + Math.random(), { method: 'post' });

                aMovieWish.remove();
            });
        }

        Event.observe(dMovie, 'mouseover', function() { aMovie.show(); });
        Event.observe(dMovie, 'mouseout', function() { aMovie.hide(); });
    },
    pSeen: function(MovieId, item) {
        new Ajax.Request('/Async.ashx?action=add&what=movie&where=seen&value=' + MovieId + '&t=' + Math.random(), { method: 'post', onSuccess: function(transport) { if (item != null) { $(item).removeClassName('sprite-user_add'); $(item).addClassName('sprite-accept'); window.setTimeout(function() { $(item).remove(); }, 2000); } } });
    }
};

// Wollyhood Async Director manager
var Directors = {
    exist: function(idHidden, DirectorName) {
        var Directors = $(idHidden).value.split();

        for (var i = 0; i < Directors.length; i++) {
            if (Directors[i] == DirectorName)
                return true;
        }
        return false;
    },
    remove: function(idUl, idHidden, DirectorName) {
        var Directors = $(idHidden).value.split('#');

        for (var i = 0; i < Directors.length; i++) {
            if (Directors[i] == DirectorName)
                Directors.splice(i, 1);
        }

        $(idHidden).value = Directors.length > 1 ? Directors.join('#') : (Directors.length == 0 ? '' : Directors[0]);

        var lis = $(idUl).childElements();
        for (var j = 0; j < lis.size(); j++) {
            if (lis[j].innerText==DirectorName) {
                lis[j].remove();
                break;
            }
        }

        if (Directors.length == 0)
            $(idUl).style.display = 'none';
    },
    manager: function(idUl, idAutoComplete, idIndicator, idInput, idHidden, idAdd) {
        // Autocomplete
        new Ajax.Autocompleter(idInput, idAutoComplete, '/AutoComplete.ashx', { method: 'post', paramName: "moviesDirectors", minChars: 1, indicator: idIndicator, frequency: 0.4 });

        $(idInput).observe('keypress', function(e) {
            if (e.keyCode == Event.KEY_RETURN) {
                var DirectorName = $(idInput).value.replace(/^\s+|\s+$/g, "");
                if (DirectorName.length > 1 && !Directors.exist(idHidden, DirectorName)) {
                    if ($(idHidden).value == '' || $(idHidden).value == '#')
                        $(idHidden).value = DirectorName;
                    else
                        $(idHidden).value += '#' + DirectorName;

                    var img = new Element('img', { 'src': '/images/icons/cross-small.png', 'title': 'Supprimer', 'alt': 'Supprimer' });
                    var a = new Element('a').update(img); a.observe('click', function(e) { Directors.remove(idUl, idHidden, DirectorName); });
                    var li = new Element('li').insert(DirectorName).insert(a);
                    $(idUl).insert(li);

                    $(idUl).style.display = 'block';
                }
                $(idInput).value = '';
                return false;
            }
        });

        // Add event
        $(idAdd).observe('click', function(e) {
            var DirectorName = $(idInput).value.replace(/^\s+|\s+$/g, "");
            if (DirectorName.length > 1 && !Tags.exist(idHidden, DirectorName)) {
                if ($(idHidden).value == '' || $(idHidden).value == '#')
                    $(idHidden).value = DirectorName;
                else
                    $(idHidden).value += '#' + DirectorName;

                var img = new Element('img', { 'src': '/images/icons/cross-small.png', 'title': 'Supprimer', 'alt': 'Supprimer' });
                var a = new Element('a').update(img); a.observe('click', function(e) { Directors.remove(idUl, idHidden, DirectorName); });
                var li = new Element('li').insert(DirectorName).insert(a);
                $(idUl).insert(li);

                $(idUl).style.display = 'block';
            }
            $(idInput).value = '';
            return false;
        });
    }
};

// Wollyhood Async Tags manager
var Tags = {
    exist: function(idHidden, tagName) {
        var tags = $(idHidden).value.split();

        for (var i = 0; i < tags.length; i++) {
            if (tags[i] == tagName)
                return true;
        }
        return false;
    },
    remove: function(idUl, idHidden, tagName) {
        var tags = $(idHidden).value.split('#');

        for (var i = 0; i < tags.length; i++) {
            if (tags[i] == tagName)
                tags.splice(i, 1);
        }

        $(idHidden).value = tags.length > 1 ? tags.join('#') : (tags.length == 0 ? '' : tags[0]);

        var lis = $(idUl).childElements();
        for (var j = 0; j < lis.size(); j++) {
            if (lis[j].innerText==tagName) {
                lis[j].remove();
                break;
            }
        }

        if (tags.length == 0)
            $(idUl).style.display = 'none';
    },
    manager: function(idUl, idAutoComplete, idIndicator, idInput, idHidden, idAdd) {
        // Autocomplete
        new Ajax.Autocompleter(idInput, idAutoComplete, '/AutoComplete.ashx', { method: 'post', paramName: "moviestags", minChars: 1, indicator: idIndicator, frequency: 0.4 });

        $(idInput).observe('keypress', function(e) {
            if (e.keyCode == Event.KEY_RETURN) {
                var tagName = $(idInput).value.replace(/^\s+|\s+$/g, "").toLowerCase();
                if (tagName.length > 1 && !Tags.exist(idHidden, tagName)) {
                    if ($(idHidden).value == '' || $(idHidden).value == '#')
                        $(idHidden).value = tagName;
                    else
                        $(idHidden).value += '#' + tagName;

                    var img = new Element('img', { 'src': '/images/icons/cross-small.png', 'title': 'Supprimer', 'alt': 'Supprimer' });
                    var a = new Element('a').update(img); a.observe('click', function(e) { Tags.remove(idUl, idHidden, tagName); });
                    var li = new Element('li').insert(tagName).insert(a);
                    $(idUl).insert(li);

                    $(idUl).style.display = 'block';
                }
                $(idInput).value = '';
                return false;
            } 
        });

        // Add event
        $(idAdd).observe('click', function(e) {
            var tagName = $(idInput).value.replace(/^\s+|\s+$/g, "").toLowerCase();
            if (tagName.length > 1 && !Tags.exist(idHidden, tagName)) {
                if ($(idHidden).value == '' || $(idHidden).value == '#')
                    $(idHidden).value = tagName;
                else
                    $(idHidden).value += '#' + tagName;

                var img = new Element('img', { 'src': '/images/icons/cross-small.png', 'title': 'Supprimer', 'alt': 'Supprimer' });
                var a = new Element('a').update(img); a.observe('click', function(e) { Tags.remove(idUl, idHidden, tagName); });
                var li = new Element('li').insert(tagName).insert(a);
                $(idUl).insert(li);

                $(idUl).style.display = 'block';
            }
            $(idInput).value = '';
            return false;
        });
    }
};
