/*
Script: Classim.js
    DOM Scripting for Tennis-Classim.net.

Tennis-Classim Copyright:
    Copyright (c) 2001-2009 Helix, <http://www.tennis-classim.net/>
*/

var Classim = {};

Classim.Const = {
    Palmares2010Url: '/fft/palmares/{0}',
    Palmares2009Url: '/fft/palmares/{0}/2009',
    SearchUrl:       'http://www.fft.fr/palmares/bdd/recherche_licencies/liste_licencies.asp?LICENCE={0}'
};

String.format = function(format){
    var args = Array.prototype.slice.call(arguments, 1);
    return format.replace(/\{(\d+)\}/g, function(m, i){
        return args[i];
    });
};

var PopupLicence = new Class({

    initialize: function(element) {
        element.addEvent('click', function(e) {
            var popup = $('popupLicence') || new Element('div', {
                'id': 'popupLicence', 
                'class': 'popup-licence'
            }).setStyle('display', 'none').inject(document.body);

            var licence = (this.href && this.href.match('[0-9]{7}'));
            if (!licence) return;

            var pos = this.getPosition();
            popup.setStyles({left: (pos.x) + 'px', top: (pos.y + (Browser.Engine.trident ? 20 : 15)) + 'px'});

            var contentHtml = '';
            contentHtml += '<ul class="submenu">';
            if (this.hasClass('dropdown')) {
                contentHtml += '<li><a class="classim" href="' + this.href + '">Palmarès classim 2010</a></li>';
            }
            if (licence) {
               contentHtml += '<li><a href="' + String.format(Classim.Const.Palmares2010Url, licence) + '">Palmarès officiel 2010</a></li>';
               contentHtml += '<li><a href="' + String.format(Classim.Const.Palmares2009Url, licence) + '">Palmarès archive 2009</a></li>';
            } else {
                contentHtml += '<li><span>Veuillez renseigner le n° de licence</span></li>';
            }

            contentHtml += '</ul>';
            popup.innerHTML = contentHtml;
            popup.style.display = (popup.style.display == 'none') ? '' : 'none';

            // Attach events
            var links = popup.getElements('a');
            for (var i = 0, l = links.length; i < l; i++) {
                links[i].addEvent('click', function(e){
                    Classim.openSqueezeBox(this);
                    e.stop();
                });
            }
            e.stop();
         });

        document.addEvent('mouseup', this.hide.bindWithEvent(this));
    },

    hide: function(e) {
        if (e.rightClick) return true;
        var popup = $('popupLicence');
        if (popup) popup.style.display = 'none';
    }
});

Classim.openSqueezeBox = function(el){
    var height = Window.getSize().y * 0.9;
    var width  = Window.getSize().x * 0.9;
    SqueezeBox.fromElement(el, {handler: 'iframe', size: {x: width, y: height}});
}


var LicenceUpdater = new Class({

    initialize: function(element) {
        this.element = $(element);
        if (!this.element) return;

        this.linkButton = new Element('a', { 
            'href': 'javascript:void(0)', 
            'title': 'Cliquez pour compléter les données automatiquement à partir du site de la FFT',
            'text': 'Compléter',
            'class': 'autocomplete',
            'hidefocus': 'hidefocus',
            'events': {
                'click': this.onButtonClicked.bindWithEvent(this)
            }
        }).inject(element, 'after');

        this.message = new Element('span', {'id': 'autocomplete-message'}).inject(this.linkButton, 'after');
        this.request = new Request.JSON({ 
            url: '/ajax/licence/infos',
            method: 'get',
            link: 'cancel',
            onRequest: this.onRequest.bind(this),
            onSuccess: this.onSuccess.bind(this),
            onFailure: this.onFailure.bind(this),
            onComplete: this.onComplete.bind(this)
        });
    },

    onButtonClicked: function(e) {
        var licence = this.element.value;
        if (licence.match(/^[0-9]{7}[A-Za-z]?$/)) {
            this.request.send('licence=' + licence);
        } else {
            this.linkButton.addClass('warning');
            this.message.set('text', 'saisissez un numéro de licence valide (7 chiffres + 1 lettre)').yellowFade();
        }
        e.stop();
    },

    onRequest: function() {
        this.linkButton.removeClass('warning').addClass('loading');
    },

    onComplete: function() {
        this.linkButton.removeClass('loading');
    },

    onSuccess: function(response) { // JSON
        if (!response.error) {
            var map = {
                'advLastName': 'nom',
                'advFirstName': 'prenom',
                'advLicence': 'licence',
                'advNais': 'nais',
                'advClub': 'club',
                'advClt': 'clt'
            };
            for (var elementId in map) {
                var name = map[elementId];
                if (response.infos[name]){
                    var el = $(elementId);
                    el.value = response.infos[name];
                    if (!Browser.Engine.trident) {
                        el.yellowFade(); // ie has issues with optgroup selects
                    }
                }
            }
            this.message.set('html', 'données complétées pour ce <a href="' + String.format(Classim.Const.SearchUrl, this.element.value) + '" target="_blank">numéro de licence</a>').yellowFade();

        } else {
            var msg = 'Aucune info disponible pour ce numéro de licence.';
            if (response.error.code == 503) {
                msg = 'Service momentanément indisponible. Réessayer ultérieurement.';
            } else if (response.error.code == 504) {
                msg = 'Le service n\'a pas répondu.';
            }
            this.linkButton.addClass('warning');
            this.message.set('html', msg).yellowFade();
        }
    },

    onFailure: function() {
        this.linkButton.addClass('warning');
        this.message.set('text', 'Données non disponibles. Veuillez réessayer ultérieurement.').yellowFade();
        this.onComplete();
    }
});


Classim.DomReady = {

    // Initialize external links
    initExternalLinks: function() {
        var links = $$('a');
        for (var i = 0, l = links.length; i < l; i++) { 
            var lnk = links[i];
            if (lnk.href && lnk.rel == 'external') { 
                lnk.target = '_blank'; 
            }
            if (lnk.hasClass('boxed')) {
                lnk.addEvent('click', function(e) {
                    Classim.openSqueezeBox(this);
                    return false; 
                });
            } else if (lnk.hasClass('popup-licence')){
                new PopupLicence(lnk);
            }
        }
    },

    // Initialize rollover images
    initRolloverImages: function() {
        $$('img.rollover').each(function(img){
            img.addEvent('mouseover',  function(e) { this.src = this.src.replace(/(\.[^.]+)$/, '_over$1'); });
            img.addEvent('mouseleave', function(e) { this.src = this.src.replace(/_over/, ''); });
        });
    },

    // Initialize yellow fade
    initYellowFade: function() {
        var fade = $('fade');
        if (fade) {
            fade.yellowFade();
        }
        $$('p.error.fade').yellowFade('#FFFF9C', '#FFFFE0');
        $$('p.success.fade').yellowFade('#FFFF9C', '#DFD');
    },

    // Initialize tooltips
    initTips: function(){
        var tips = new Tips($$('img.tooltip'), {
            //initialize:function() {
                //this.fx = new Fx.Tween(this.toolTip, 'opacity', {duration: 500,  'link': 'chain'}).set(0);
            //},
            onShow: function(toolTip) { toolTip.fade('in'); },
            onHide: function(toolTip) { toolTip.fade('out'); }
        });
    },

    initSaisonEdit: function(){
        $$('.saison .edit').each(function(el){
            el.addEvent('click', function(e){
                e.stop();
                window.location.href = '/saison/' + this.get('-data-saison') + '/edit';
            });
        });
    }
};


Element.implement({

    yellowFade: function(colorStart, colorEnd) {
        if (colorStart == undefined) colorStart = '#FFFF9C';
        if (colorEnd == undefined) colorEnd = '#FFFFFF';

        var fx = new Fx.Tween(this, {'property': 'background-color', 'duration': 500,  'link': 'chain'});
        fx.start(colorStart).chain(function(){
            fx.start(colorEnd)
        });
    }

});


//---------------------------------------------------------------------------------------

var Win = {
    open: function(url) {
        var features = "left=0,top=0,width=" + Window.getSize().x + ",height=600,location=0,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=0";
        var childWindow = window.open(url, 'Classim', features);
        childWindow.focus();
    }
}

function CheckLogin(form) {
    //if ($('login').value.trim() == '' || $('password').value.trim() == '') {
        //return false;
    //}
    form.submit.disabled = true;
    return true;
}


var Toggle = {};
Toggle.display = function(el) {
    el = document.getElementById(el);
    el.style.display = (el.style.display != "none") ? "none" : "";
}

// Preload images
//var preload = [];
//preload['edit'] = new Image();
//preload['edit'].src = "/images/icon-edit_over.gif";



window.addEvent('domready', function() {
    for (var property in Classim.DomReady) {
        Classim.DomReady[property]();
    }
    new LicenceUpdater('advLicence');
});
