﻿var notepad = {
    contentid: 0,
    minwords: 2,
    url: '/web/notepad.aspx',
    urlpad: { 'it-IT': '/servizi/notepad.html', 'en-US': '/services/notepad.html' },
    filter: '.content',
    iconnotepad: '#notepadicon',
    divnotepad: '#notepad ',
    divlist: '.notepad',
    noteids: [],
    selection: '',
    removing: '',
    onstage: false,
    mouse_y: 0,
    mouse_x: 0,
    orig: [],
    icon: '<span id="notepadicon" style="display:none;margin: -20px 0pt 0pt 10px; position: absolute; width: 25px; height: 29px; cursor: pointer;" ><a href="#" onclick="notepad.show();return false;"><img border="0" src="/includes/img/notepad.png"></a></span>',

    form: '<div id="notepad" style="display:none;">' +
            '<div class="left-column-top">&#160;</div>' +
            '<div class="text">' +
                '<a title="' + lang[idlang].chiudi + '" href="#" onclick="notepad.close();" class="right close">' + lang[idlang].chiudi + '</a>' +
                '<h2>' + lang[idlang].aggiungiappunti + '</h2>' +
                '<p>' + lang[idlang].page + ': <b></b>' +
                '<p><textarea spellcheck="false" cols="50" rows="10"></textarea></p>' +
                '<p><input type="button" value="' + lang[idlang].aggiungi + '" onclick="notepad.add();notepad.close();"></p>' +
                '<div class="clear"></div>' +
            '</div>' +
            '<div class="left-column-bottom">&nbsp;</div>' +
            '</div>',
    notepad: function (o) {
        //o.href = this.urlpad[idlang];
    },
    init: function (cntid) {
        // just add the icon, we'll add the form later.
        if (cntid > 0) {
            $('body').append(this.icon);
            this.contentid = cntid;
            var contentarea = $(notepad.filter + " *");
            for (var oid, i = 0; (elem = contentarea[i]); i++) {
                elem.onmouseup = notepad.mouseup;
                elem.onmousedown = notepad.mousedown;
            }

            //window.onblur = notepad.iconAutoHide();
            document.onmousedown = notepad.mousedown;
            document.onmouseup = notepad.mouseup;
        }
    },
    // on mouse down, hide icon.
    mousedown: function (e) {
        notepad.updateMouseCoords(e);
        if (window.getSelection && e.target.toString().indexOf("HTMLImageElement") != -1) { // Moz
            setTimeout('notepad.iconHide()', 200);
        } else {
            setTimeout('notepad.iconHide()', 10);
        }
    },
    // on mouse up we show the icon
    mouseup: function (e) {
        notepad.updateMouseCoords(e);
        var str = notepad.getSelection();
        if (str.length == 0 || notepad.selection == str) return;
        notepad.selection = str; // Moz & Opera
        setTimeout('notepad.iconShow()', 10);
    },
    // avoid hiding the icon if there's a selection
    iconHide: function () {
        try {
            var str = this.getSelection();
            if (str.length != 0) return;
            $(this.iconnotepad).hide();
            window.status = "";
        }
        catch (ex) { }
    },
    // force hide
    iconDoHide: function () {
        try {
            $(this.iconnotepad).hide();
        }
        catch (ex) { }
    },
    // auto hide icon after 1 sec
    iconAutoHide: function () {
        try {
            setTimeout('notepad.iconDoHide()', 1000);
        }
        catch (ex) { }
    },
    // show icon near the mouse pointer
    iconShow: function () {
        var o = $(this.iconnotepad);
        if (o.is(':visible')) return;
        $(o).animate({ left: this.mouse_x + "px", top: this.mouse_y + "px" }, 1);
        o.show();
    },

    // form close: destroy the form.
    close: function () {
        $(this.divnotepad).remove();
        this.onstage = false;
    },

    add: function () {
        var sessionid = $.cookie("s") || '';

        var params = { 'action': 'a',
            'output': 'JSON',
            'note': $(this.divnotepad + ' textarea').val().replace(/\n/g, '<br>'),
            'contentid': this.contentid,
            'sessionid': sessionid,
            'r': Math.random()
        };
        $.post(this.url, params,
            function (data) {
                flash.show('notice', lang[idlang].appuntosalvato);
                $.cookie("s", data.Table[0].s, { path: '/' });
            }, "json");
    },
    update: function (id) {
        var sessionid = $.cookie("s") || '';
        var params = { 'action': 'u',
            'output': 'JSON',
            'note': $('#textarea' + id).val().replace(/\n/g, '<br>'),
            'notepadid': id,
            'contentid': 0,
            'sessionid': sessionid,
            'r': Math.random()
        };
        $.post(this.url, params, function (data) {
            var id = data.Table[0].id;
            var note = $('li#notepadcnt' + id + ' .note').html(data.Table[0].note.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
            $('li#notepadcnt' + id + ' span').show();
            flash.show('notice', lang[idlang].appuntoaggiornato);
        }, "json");
    },
    remove: function (id) {
        var sessionid = $.cookie("s") || '';
        var params = { 'action': 'd',
            'output': 'JSON',
            'notepadid': id,
            'contentid': 0,
            'sessionid': sessionid,
            'r': Math.random()
        };
        if (confirm(lang[idlang].eliminaappunto)) {
            $.getJSON(this.url, params,
                function (data) {
                    flash.show('notice', lang[idlang].appuntoeliminato);
                    notepad.removing = '#notepadcnt' + data.Table[0].id;
                    $(notepad.removing).slideUp('fast', function () { $(notepad.removing).remove(); notepad.removing = ''; });
                });
        }
    },
    list: function (output) {
        var sessionid = $.cookie("s") || '';
        var params = { 'action': 'a',
            'output': 'JSON',
            'contentid': '0',
            'sessionid': sessionid,
            'r': Math.random()
        };
        $.getJSON(this.url, params,
                    function (data) {
                        var str = [];
                        for (var i = 0; i < data.Table.length; i++) {
                            if (data.Table[i].id) {
                                notepad.noteids.push(data.Table[i].id);
                                str.push('<li id="notepadcnt' + data.Table[i].id + '"><a href="' + data.Table[i].u + '" target="_blank"><b>' + data.Table[i].t.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>') + '</b></a> <div class="note">' + data.Table[i].note.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>') + '</div> <span class="right"><a href="#" onclick="notepad.edit(' + data.Table[i].id + ');return false;">' + lang[idlang].modifica + '</a>|<a href="#" onclick="notepad.remove(' + data.Table[i].id + ');return false;">' + lang[idlang].rimuovi + '</a></span></li>');
                            }
                        }
                        if (str.length > 0) {
                            $(notepad.divlist).html(str.join('\n'));
                            $('div.empty').hide();
                        }
                        else {
                            $('div.empty').show();
                            $('div.full').hide();
                        }
                    });
    },
    edit: function (id) {
        var li = $('li#notepadcnt' + id);
        var orig = $('li#notepadcnt' + id + ' .note').html();
        this.orig['li#notepadcnt' + id] = orig;
        var note = orig.replace(/<br>/g, '\n');
        $('li#notepadcnt' + id + ' span').hide();
        var editor = '<textarea id="textarea' + id + '" spellcheck="false" cols="50" rows="10">' + note + '</textarea><br><input type="button" value="' + lang[idlang].aggiorna + '" onclick="notepad.update(' + id + ');notepad.close();"> o <a href="#" onclick="notepad.canceledit(' + id + ');return false;" class="cancel">' + lang[idlang].annulla + '</a>';
        $('li#notepadcnt' + id + ' .note').html(editor);
    },
    canceledit: function (id) {
        var li = $('li#notepadcnt' + id);
        var note = this.orig['li#notepadcnt' + id];
        $('li#notepadcnt' + id + ' span').show();
        $('li#notepadcnt' + id + ' .note').html(note);
    },
    send: function () {
        var wnd = window.open('/invia-notepad.aspx?id=' + $.cookie("s") + '&l=' + idlang, 'notepad', 'menubar=1,resizable=1,width=550,height=450')
        wnd.focus();
    },
    // show form
    show: function () {
        if (!this.onstage) {
            $('body').append(this.form);
            this.onstage = true;
        }
        $(this.divnotepad + ' textarea').html('"' + this.selection + '"\n');
        $(this.divnotepad + ' b').html(document.title);
        $(this.divnotepad).show();
        document.getElementById(notepad.divnotepad.replace('#', '').replace(' ', '')).style.left = notepad.mouse_x + "px";
        document.getElementById(notepad.divnotepad.replace('#', '').replace(' ', '')).style.top = notepad.mouse_y + "px";
        $(this.divnotepad + ' textarea').focus();
    },
    // get selection
    getSelection: function () {
        var str = new String("");
        if (window.getSelection) {   // Moz & Safari
            if (navigator.appVersion.indexOf("Safari") != -1) { // Safari
                str = window.getSelection() + "";
            } else { // Moz
                str = window.getSelection().toString();
            }
        } else if (document.selection && document.selection.createRange) { // IE
            var range = document.selection.createRange();
            str = range.text.toString();
        }
        if (str.split(' ').length < this.minwords + 1)
            str = '';
        return str;
    },
    // update mouse coordinates
    updateMouseCoords: function (e) {
        if (!e) var e = window.event;
        if (e.pageX || e.pageY) {
            this.mouse_x = e.pageX - 15;
            this.mouse_y = e.pageY - 15;
        } else if (e.clientX || e.clientY) {
            this.mouse_x = e.clientX + document.documentElement.scrollLeft - 15;
            this.mouse_y = e.clientY + document.documentElement.scrollTop - 15;
        }
    }
};
