/*
 * Favorisweb.net
 * by Capweb.biz
 */

var siteThemes = {
    'path': 'images/high/'
};

var dragboxList = {
    'Sortables': false
};

var site_regex = {
    'mail':         /^[\\+a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,4}$/i,
    'pseudo':       /^[ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ\w\.\-@]{3,100}$/,
    'password':     /^[\w\.\-@]{6,200}$/,
    'newGroupName': /^[ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ\w\s\.\-@,;:!\?=#\\\/\(\)&"'\[\]\{\}\|\+\*\%]{1,15}$/,
    'newLinkName':  /^[ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ\w\s\.\-@,;:!\?=#\\\/\(\)&"'\[\]\{\}\|\+\*\%]{1,25}$/,
    'newLink':      /^((http|https|ftp):\/\/)?([-\w\.]+)+(\.[a-z]{2,4})?(:\d+)?(\/([-,\w/_\.]*(\?\S+)?)?)?$/i
};

var displayTime = function(){
    var Digital = new Date();
    var hours   = Digital.getHours();
    var minutes = Digital.getMinutes();
    var seconds = Digital.getSeconds();

    if( minutes <= 9) minutes = '0' + minutes;
    if( seconds <= 9) seconds = '0' + seconds;

    $("heure").set('html', hours + ':' + minutes + ':' + seconds);
};

var getThemeImagesList = function(){

    if( !$defined(siteThemes[theme]) )
    {
        new Request.JSON({
            'url':  'ss_ajax/getThemeImagesList.php',
            'data': new Hash({
                'theme':    theme,
                'path':     siteThemes.path
            }).toQueryString(),
            'onSuccess': function(responseJSON){
                dbug.log('responseJSON : %o', responseJSON);

                siteThemes[theme] = {};
                siteThemes[theme].images = responseJSON.images;

                randThemeImage.run();
            },
            'onFailure': function(xhr){

            }
        }).send();
    }
    else
    {
        randThemeImage.run();
    }
};

var periodicalRandThemeImage;
var randThemeImage = function(){
    periodicalRandThemeImage = $clear(periodicalRandThemeImage);
    if( $('imgTheme') && $defined(theme) ) $('imgTheme').set('src', siteThemes.path + theme + '/' + siteThemes[theme].images.getRandom());
    periodicalRandThemeImage = randThemeImage.periodical(refreshDelay*1000);
};

var checkFormNew = function(){
    var pseudo  = $('new_pseudo').getProperty('value').clean();
    var mail    = $('new_mail').getProperty('value').clean();
    var pwd1    = $('new_password1').getProperty('value').clean();
    var pwd2    = $('new_password2').getProperty('value').clean();

    var check = true;

    if( mail == '' || !mail.match( site_regex.mail ) )
    {
        check = false;
        $('new_mail').highlight('#ffffff','#fe0101');
    }
    
    if( pseudo == '' || !pseudo.match( site_regex.pseudo ) )
    {
        check = false;
        $('new_pseudo').highlight('#ffffff','#fe0101');
    }

    if( pwd1 == '' || !pwd1.match( site_regex.password ) )
    {
        check = false;
        $('new_password1').highlight('#ffffff','#fe0101');
    }

    if( pwd1 != pwd2 || pwd2 == '' || !pwd2.match( site_regex.password ) )
    {
        check = false;
        $('new_password2').highlight('#ffffff','#fe0101');
    }

    return check;
};

var checkFormLogin = function(){
    var mail        = $('login_mail').getProperty('value').clean();
    var password    = $('login_password').getProperty('value').clean();

    var check = true;

    if( mail == '' || !mail.match( site_regex.mail ) )
    {
        check = false;
        $('login_mail').highlight('#ffffff','#fe0101');
    }

    if( password == '' || !password.match( site_regex.password) )
    {
        check = false;
        $('login_password').highlight('#ffffff','#fe0101');
    }

    return check;
};

var addGroup = function(){
    var addGroupBox = new Facebox({
        'id':           'addGroupBoxWindow',
        'title':        'Nouveau groupe',
        'url':          'ss_ajax/window_addGroup.php',
        'ajaxDelay':    400,
        'submitValue':  'Créer',
        'submitFunction': function(e){
            var newGroupName = $('newGroupName').getProperty('value').clean();

            if( newGroupName != '' && newGroupName.match( site_regex.newGroupName) )
            {
                createNewGroup.run([ newGroupName ]);
                addGroupBox.close();
            }
            else
            {
                $('newGroupName').highlight('#ffffff','#fe0101');
            }
        }
    });
    addGroupBox.show();
};

var createNewGroup = function(groupName){
    dbug.log('createNewGroup : %o', groupName);

    new Request.JSON({
        'url':  'ss_ajax/setNewGroup.php',
        'data': new Hash({
            'title':    groupName
        }).toQueryString(),
        'onSuccess': function(responseJSON){
            dbug.log('responseJSON : %o', responseJSON);
            if( responseJSON.success )
            {
                buildDragbox.run([ responseJSON.id, groupName, 1 ]);
            }
            else
            {
                // TODO
            }
        },
        'onFailure': function(xhr){
            // TODO
        }
    }).send();
};

var buildDragbox = function(id, title, column){

    var dragbox = new Element('div', {
        'id':       'dragbox' + id,
        'class':    'contentBox'
    }).store('id_group', id).grab( new Element('div', {
        'class': 'dragableBar'
    }).grab( new Element('table', {
        'cellpadding':  '0',
        'cellspacing':  '0',
        'border':       '0',
        'class':        'light',
        'events': {
            'mouseover': function(){
                $(this).getElements("img[class~=edit], img[class~=delete]").removeClass('opacity30').addClass('opacity100');
            },
            'mouseout': function(){
                $(this).getElements("img[class~=edit], img[class~=delete]").removeClass('opacity100').addClass('opacity30');
            }
        }
    }).grab( new Element('tbody', {
    }).grab( new Element('tr', {
    }).grab( new Element('td', {
        'class': 'puce'
    }).grab( new Element('img', {
        'class':    'puce',
        'src':      'images/puce_right.gif'
    }) ) ).grab( new Element('td', {
        'class': 'title'
    }).grab( new Element('div', {
        'class':    'title',
        'html':     title
    }) ) ).grab( new Element('td', {
        'class': 'edit'
    }).grab( new Element('img', {
        'class':    'edit opacity30',
        'src':      'images/server_edit.png',
        'alt':      'Editer',
        'title':    'Editer',
        'events': {
            'click': function(){
                manageDragbox.run([ id ]);
            }
        }
    }) ) ).grab( new Element('td', {
        'class': 'delete'
    }).grab( new Element('img', {
        'class':    'delete opacity30',
        'src':      'images/server_delete.png',
        'alt':      'Supprimer',
        'title':    'Supprimer',
        'events': {
            'click': function(){
                deleteDragbox.run([ id ]);
            }
        }
    }) ) ) ) ) ) ).grab( new Element('div', {
        'class': 'contentLink'
    }) ).inject( $('column' + column) );

    // store
    dragboxList[id] = {
        'title': title,
        'links': []
    };

    // make sortables
    dragboxList.Sortables.addItems(dragbox);

    return true;
};

var deleteDragbox = function(id){
    dbug.log('deleteDragbox... %o', id);
    var deleteDragboxBox = new Facebox({
        'id':       'deleteDragboxBoxWindow',
        'title':    'Confirmation de suppression',
        'url':      'ss_ajax/window_deleteDragbox.php',
        'requestData': new Hash({
            'id': id
        }),
        'ajaxDelay':    400,
        'width':        450,
        'submitValue':  'Valider',
        'submitFunction': function(e){
            dbug.log('deleteDragbox submit button click...');

            new Request.JSON({
                'url':  'ss_ajax/setDeleteGroup.php',
                'data': new Hash({
                    'id_group': id
                }).toQueryString(),
                'onSuccess': function(responseJSON){
                    dbug.log('responseJSON : %o', responseJSON);
                    if( responseJSON.success )
                    {
                        dragboxList.Sortables.removeItems( $('dragbox' + id) );
                        $('dragbox' + id).destroy();
                    }
                    else
                    {
                        // TODO
                    }
                },
                'onFailure': function(xhr){
                    // TODO
                }
            }).send();

            deleteDragboxBox.close();
        }
    });
    deleteDragboxBox.show();
};

var manageDragbox = function(id){
    dbug.log('manageDragbox... %o', id);
    var manageDragboxBox = new Facebox({
        'id':       'manageDragboxBoxWindow',
        'title':    'Gérer ce groupe',
        'url':      'ss_ajax/window_manageDragbox.php',
        'requestData': new Hash({
            'id': id
        }),
        'ajaxDelay':    400,
        'width':        500,
        'submitValue':  'Valider',
        'submitFunction': function(e){
            dbug.log('manageDragbox submit button click...');

            dbug.log('manageBox : %o', manageBox);

            var data = {
                'id_group':         id,
                'modifyGroupName':  $('modifyGroupName').getProperty('value').clean(),
                'delete':           manageBox.toBeDeleted,
                'modify':           [],
                'create':           []
            };

            if( ! data.modifyGroupName.match( site_regex.newGroupName) )
            {
                $('modifyGroupName').highlight('#ffffff','#fe0101').focus();
                return false;
            }

            var checkValidity = {
                'linkName': true,
                'link':     true
            };

            if( manageBox.Accordion )
            {
                // set elements position
                $$("ul#accordion li div.element").each(function(el,index){
                    $(el).store('link_position', index);
                });

                manageBox.Accordion.elements.each(function(el, index){
                    var linkName = false, link = false, position, id_link;

                    $try(function(){ linkName   = $(el).getElement("input[name=linkName]").getProperty('value').clean();    });
                    $try(function(){ link       = $(el).getElement("input[name=link]").getProperty('value').clean();        });
                    $try(function(){ id_link    = $(el).retrieve('id_link');                                                });
                    $try(function(){ position   = $(el).retrieve('link_position');                                          });

                    if( linkName && link && checkValidity.linkName && checkValidity.link )
                    {
                        if( ! linkName.match(site_regex.newLinkName) )  checkValidity.linkName = false;
                        if( ! link.match(site_regex.newLink) )          checkValidity.link = false;

                        if( !checkValidity.linkName || !checkValidity.link )
                        {
                            dbug.log('manageBox.Accordion : %o', manageBox.Accordion);

                            var delay = 0;

                            if( manageBox.Accordion.to[index].height[0].value == 0 && manageBox.Accordion.to[index].opacity[0].value == 0 )
                            {
                                manageBox.Accordion.display(index);
                                delay = 500;
                            }

                            (function(){
                                if( !checkValidity.linkName )   $(el).getElement("input[name=linkName]").highlight('#ffffff','#fe0101');
                                if( !checkValidity.link )       $(el).getElement("input[name=link]").highlight('#ffffff','#fe0101');
                            }).delay(delay);

//                            return false;
                        }
                        else
                        {
                            if( !id_link )
                            {
                                data.create.push({
                                    'linkName': linkName,
                                    'link':     link,
                                    'position': position
                                });
                            }
                            else
                            {
                                data.modify.push({
                                    'id_link':  id_link,
                                    'linkName': linkName,
                                    'link':     link,
                                    'position': position
                                });
                            }
                        }
                    }
                });
            }

            if( checkValidity.linkName && checkValidity.link )
            {
                dbug.log('data OK : %o', data);

                new Request.JSON({
                    'url':  'ss_ajax/setModifyGroup.php',
                    'data': new Hash({
                        'json': JSON.encode(data)
                    }).toQueryString(),
                    'onSuccess': function(responseJSON){
                        dbug.log('responseJSON : %o', responseJSON);
                        if( responseJSON.success )
                        {
                            // update title
                            if( responseJSON.result.updateGroupName ) $('dragbox' + id).getElement("div.title").set('html', data.modifyGroupName);

                            // clean store
                            dragboxList[id].links = [];

                            // empty box links
                            $('dragbox' + id).getElement("div.contentLink").empty();

                            // rebuild links list
                            responseJSON.links.each(function(link){
                                insertBoxLink.run([ id, link.id_link, link.name, link.link ]);
                            });
                        }
                        else
                        {
                            // TODO
                        }
                    },
                    'onFailure': function(xhr){
                        // TODO
                    }
                }).send();

                manageDragboxBox.close();
            }
        }
    });
    manageDragboxBox.show();
};

var updateAllPosition = function(){
    dbug.log('updateAllPosition...');

    var data = [];

    ['1','2','3','4'].each(function(col){
        $$("td#column" + col + " div.contentBox").each(function(box,index){
            var id_group = $(box).retrieve('id_group');
//            dbug.log("id_group : %o", id_group);
            data.push({
                'id_group': id_group,
                'column':   col,
                'position': index
            });
        });
    });

    new Request.JSON({
        'url':  'ss_ajax/setPositionGroups.php',
        'data': new Hash({
            'json': JSON.encode(data)
        }).toQueryString(),
        'onSuccess': function(responseJSON){
            dbug.log('responseJSON : %o', responseJSON);
            if( responseJSON.success )
            {
                // ok
            }
            else
            {
                // TODO
            }
        },
        'onFailure': function(xhr){
            // TODO
        }
    }).send();
};

var managePreferences = function(){
    dbug.log('managePreferences...');
};

var getUserGroupsLinks = function(){
    dbug.log('getUserGroupsLinks...');

    new Request.JSON({
        'url': 'ss_ajax/getUserGroupsLinks.php',
        'onSuccess': function(responseJSON){
            dbug.log('responseJSON : %o', responseJSON);
            if( responseJSON.success )
            {
                responseJSON.result.each(function(box){
                    if( buildDragbox.run([ box.id_group, box.title, box.column ]) )
                    {
                        box.links.each(function(link){
                            insertBoxLink.run([ box.id_group, link.id_link, link.name, link.link ]);
                        });
                    }
                });
            }
            else
            {
                // TODO
            }
        },
        'onFailure': function(xhr){
            // TODO
        }
    }).send();
};

var insertBoxLink = function(id_group, id_link, name, link){
    dbug.log('add link : %o %o %o', id_link, name, link);

    new Element('img', {
        'src':      'images/external_link.png',
        'alt':      'Ouvrir dans une nouvelle fenêtre',
        'title':    'Ouvrir dans une nouvelle fenêtre',
        'events': {
            'click': function(){
                window.open( $(this).getNext("a").getProperty('href') , '_blank');
            }
        }
    }).inject( $('dragbox' + id_group).getElement("div.contentLink") );
    new Element('a', {
        'href': link.match(/^(http|https|ftp):\/\//i) ? link : 'http://' + link,
        'html': name
    }).inject( $('dragbox' + id_group).getElement("div.contentLink") );

    // store
    dragboxList[id_group].links.push({
        'id_link':  id_link,
        'name':     name,
        'link':     link
    });
};

window.addEvent('domready',function(){

    if( !domain.contains('favorisweb') ) dbug.enable();

    // time
    displayTime.periodical(1000);

    // manage theme
    getThemeImagesList.run();

    // get groups and links
    getUserGroupsLinks.run();

    dragboxList.Sortables = new Sortables('.colContainer', {
        'handle':   '.dragableBar',
        'opacity':  0.7,
        'onStart': function(el,clone){
            dbug.log('onStart : %o %o', el, clone);
            $$("td.colContainer").addClass('zoneDrop');
        },
        'onSort': function(el,clone){
            dbug.log('onSort : %o %o', el, clone);
            $(el).store('requirePositionUpdate', true);
        },
        'onComplete': function(el){
            dbug.log('onComplete : %o', el);
            $$("td.colContainer").removeClass('zoneDrop');
            if( $defined($(el).retrieve('requirePositionUpdate')) && $(el).retrieve('requirePositionUpdate') == true ) updateAllPosition.run();
            $(el).eliminate('requirePositionUpdate');
        }
    });

    $$("div.dragableBar table").each(function(el){
        // drag bar mouseover
        $(el).addEvents({
            'mouseover': function(){
                $(this).getElement("img[class~=edit]").removeClass('opacity30').addClass('opacity100');
            },
            'mouseout': function(){
                $(this).getElement("img[class~=edit]").removeClass('opacity100').addClass('opacity30');
            }
        });

        // edit click
        $(el).getElement("img[class~=edit]").addEvent('click', function(){
            manageDragbox.run();
        });
    });
});

