if (typeof jQuery == 'undefined') {
    (function() {
        var url     = document.location.href;
        var baseurl = url.substring(0, url.indexOf("/", url.indexOf("/", 8)+1 ));

        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.async = false;
        script.src = baseurl + '/nemo/jquery/jquery.js';
        script.onload = nemo_main; // Run nemo_main() once loaded
        script.onreadystatechange = function () { // Same thing but for IE
          if (this.readyState == 'complete' || this.readyState == 'loaded') nemo_main();
        }

        var s = document.getElementsByTagName('script')[0];
        s.parentNode.insertBefore(script, s);
    })();
}
else {
    nemo_main();
}

var nemo = {

    editor: null,
    styleSheets: null,
    toolbar_opened: false,
    contextPath: null,
    language: null,
    requestedResource: null,
    logged: false,
    
    modified : false,

    toolbar_height: function () {
        return $(".nemo_toolbar").height();
    },

    toolbar_toogle: function () {
        if (nemo.toolbar_opened) {
            nemo.toolbar_close();
        } else {
            nemo.toolbar_open();
        }
    },

    toolbar_open: function () {
        $(".nemo_toolbar").animate({top:'0px'}, 200, function () {
            nemo.toolbar_opened = true;
        });
    },

    toolbar_close: function () {
        $("#nemo_navigation_location").hide();
        $(".nemo_toolbar").animate({top:'-200px'}, 200, function () {
            nemo.toolbar_opened = false;
        });
    },

    replaceDiv: function (div)
    {
        nemo.killEditor();
        
        var ckOpts = {
            sharedSpaces: {
                top : 'nemo_editor_toolbar',
                bottom : 'nemo_editor_location'
            },
            removePlugins: 'maximize,resize',
            filebrowserBrowseUrl: nemo.contextPath + '/--editor/browser',
            filebrowserImageBrowseUrl: nemo.contextPath + '/--editor/browser?type=image',
            filebrowserWindowWidth: '930',
            filebrowserWindowHeight: '600',
            width:div.offsetWidth,
            height:div.offsetHeight,
            extraPlugins : 'autogrow',
            autoGrow_minHeight:20,
            enterMode : CKEDITOR.ENTER_BR,
            shiftEnterMode: CKEDITOR.ENTER_P,
            contentsCss: nemo.styleSheets,
            toolbarCanCollapse: false,
            toolbar : 'MyToolbar',
            toolbar_MyToolbar :
            [
                ['Source'],
                ['Cut','Copy','Paste','PasteText','PasteFromWord'],
                ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat','ShowBlocks'],['Link','Unlink','Anchor'],
                ['Image','Flash','Table','HorizontalRule','SpecialChar'],
                '/',
                ['NumberedList','BulletedList','-','Outdent','Indent'],
                ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
                ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
                ['Styles', 'Format','Font','FontSize','TextColor','BGColor']
            ]
        };
        
        if (typeof ckStyles != 'undefined'){
            
            ckOpts.stylesSet = ckStyles;   
        }        

        nemo.editor = CKEDITOR.replace (div, ckOpts);

        CKEDITOR.on("instanceReady", function(event)
        {
            var editor = event.editor;

            //webkit not redraw iframe correctly when editor's width is < 310px (300px iframe + 10px paddings)
            if (CKEDITOR.env.webkit) {// && parseInt(editor.config.width) < 310) {
                var iframe = document.getElementById('cke_contents_' + editor.name).firstChild;
                iframe.style.display = 'none';
                iframe.style.display = 'block';
            }

            editor.focus();
        });
    },

    onEditorClicked: function (ev)
    {
        var element = ev.target;
        
        while (element != null) {
            
            var className = element.className;
            var nodeName = element.nodeName.toLowerCase();
            
            if (className && (nodeName == 'div' && className.indexOf('nemo_editor') != -1)) {
                 nemo.replaceDiv(element);
                 return false;
            }

            if (className && (className.indexOf('nemo_') == 0 || className.indexOf('cke_') == 0)) {
                return true;
            }

            element = element.parentNode;
        }

        nemo.killEditor();
        
        return true;
    },

    killEditor: function ()
    {
        if (nemo.editor != null) {
            
            if (nemo.editor.checkDirty()){
                
                nemo.modified = true;
            }
            
            nemo.editor.destroy();
            nemo.editor = null;
        }
    },

    initCSS: function () {

        if (!nemo.styleSheets) {
            nemo.styleSheets = [];
            for (var i = 0; i < document.styleSheets.length; i++) {
                var ss = document.styleSheets[i].href;
                if (ss) {
                    nemo.styleSheets.push(ss);
                }
            }
        }
    },
    
    initToolbar: function () {

        if (!nemo.logged) return;

        if ($(".nemo_toolbar").length > 0) return;
        
        $("body").append('<div class="nemo_opener">...</div>' +
                          '<div class="nemo_toolbar">' +
                           '<div class="nemo_actions">' +
                            '<span class="nemo_left_actions">' +
                             '<span class="nemo_action"><a href="javascript:nemo.navigation();">Arborescence...</a></span>' +
                             '<span class="nemo_action"><a href="javascript:nemo.translation();">Traductions...</a></span>' +
                            '</span>' +
                            '<span class="nemo_right_actions">' +
                             '<span class="nemo_action nemo_save"><a href="javascript:nemo.save();">Sauvegarde</a></span>' +
                             '<span class="nemo_action"><a href="javascript:nemo.logout();">Déconnection</a></span>' +
                            '</span>' +
                           '</div>' +
                          '<div style="clear:both"></div>' +
                          '<div id="nemo_editor_toolbar"></div>' +
                          '<div id="nemo_editor_location"></div>' +
                          '<div id="nemo_navigation_location"></div>' +
                          '<form id="nemo_logout" method="post"><input type="hidden" name="nemo_logout" value="true"/></form>' +
                         '</div>');
    },

    save: function () {

        nemo.killEditor();
        
        var data = {};

        data.language = nemo.language;
        data.path = nemo.requestedResource;
        data.editors = [];

        $("div.nemo_editor").each(function() {
            var id = $(this).attr('id');
            var html = $(this).html();
            var code = id.substring ("nemo_editor_".length, id.length);
            var editor = {};

            editor.code = code;
            editor.content = html;
            editor.isStatic = ($(this).hasClass('nemo_editor_static')) ? 1 : 0;

            data.editors.push (editor);
        });


        
        $.post(nemo.contextPath  + '/--editor/save', data, function (){
            
            $("span.nemo_save").fadeOut(250, function () {
                $("span.nemo_save").fadeIn(250, function () {
                    $("span.nemo_save").fadeOut(250, function () {
                        $("span.nemo_save").fadeIn(250);
                    });
                });
            });
            
            nemo.modified = false;
        })
    },

    logout: function () {
        $("#nemo_logout").submit();
    },

    login: function () {
        $("#nemo_user form").submit();
    },

    navigation: function () {
        
        
        if (!$("#nemo_navigation_location").is(":visible")){
            
            $("#nemo_navigation_location").load(nemo.contextPath  + '/--navigation', {path: nemo.requestedResource});
        }
        
        $("#nemo_navigation_location").toggle();
    },

    translation: function () {
        alert("Interface non disponible");
    }
};


function nemo_main(){

    $(function(){

        nemo.initToolbar();
        nemo.initCSS();

        if (nemo.logged) {

            $(".nemo_opener,.nemo_toolbar").bind("dragstart selectstart", function(ev) {
                ev.stopPropagation();
                ev.preventDefault();
                return false;
            });

            $(".nemo_opener").click (function(ev) {
                nemo.toolbar_toogle();
            })

            $(document).click(nemo.onEditorClicked);
            $(window).bind('beforeunload', function(){ 
                
                if (nemo.modified){
                    
                    return "Attention ! vous n'avez pas sauvegardés vos modifications, voulez-vous vraiment quitter cette page ?"
                }
            })
        }

        $("#nemo_user img").click(function () {
            $("#nemo_user").toggleClass("opened");
        });
    });
}

